epiq 1.8.2 → 1.8.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/gui/main.js +3896 -1229
- package/dist/index.js +85 -77
- package/dist/mcp.js +83 -60
- package/package.json +1 -1
package/dist/mcp.js
CHANGED
|
@@ -1,75 +1,98 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
2
|
+
var Rv=Object.defineProperty;var h=(e,t)=>()=>(e&&(t=e(e=0)),t);var cr=(e,t)=>{for(var n in t)Rv(e,n,{get:t[n],enumerable:!0})};var rl={};cr(rl,{failed:()=>a,isFail:()=>d,isSuccess:()=>Dt,resultStatuses:()=>tn,succeeded:()=>l});var tn,a,l,d,Dt,R=h(()=>{"use strict";tn={Success:"success",Fail:"fail"},a=e=>({status:tn.Fail,message:e,value:null}),l=(e,t)=>({status:tn.Success,message:e,value:t}),d=e=>e.status==="fail",Dt=e=>e.status==="success"});var al={};cr(al,{ACTOR_ID_ENV:()=>lr,ACTOR_NAME_ENV:()=>gt,applyActorNameArgument:()=>na,deriveActorId:()=>il,isValidUserId:()=>vs,isValidUserName:()=>ur,resolveEnvActor:()=>ta});import Nv from"node:crypto";var gt,lr,sl,Cv,ea,vs,ur,vo,il,ta,na,Un=h(()=>{"use strict";R();gt="EPIQ_USER_NAME",lr="EPIQ_USER_ID",sl="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Cv=26,ea=80,vs=e=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(e),ur=e=>e.trim().length>0&&e.length<=ea,vo=e=>e.trim().toLowerCase(),il=e=>{let t=Nv.createHash("sha256").update(`epiq:actor:${vo(e)}`).digest(),n="";for(let o=0;o<Cv;o++)n+=sl[(t[o]??0)%sl.length];return n},ta=(e,t=process.env)=>{let n=(t[gt]??"").trim(),o=(t[lr]??"").trim();return n?ur(n)?!o&&e.userId&&e.userName&&vo(e.userName)===vo(n)?l("Actor override names the configured user",{userId:e.userId,userName:e.userName}):o&&!vs(o)?a(`${lr} must be 26 characters of Crockford base32`):o&&e.userId&&o===e.userId?a(`${lr} is the configured user's own id; using it under a different name would rename them on the board`):l("Resolved actor from environment",{userId:o||il(n),userName:o?n:vo(n)}):a(`${gt} must be 1-${ea} characters of text`):o?a(`${lr} is set without ${gt}`):l("No actor override",null)},na=(e,t,n=process.env)=>{let o=e.trim();if(!ur(o))return a(`${t} must be 1-${ea} characters of text`);let r=(n[gt]??"").trim();return r&&vo(r)!==vo(o)?a(`${t} names ${o}, but ${gt} names ${r}`):(r||(n[gt]=o),l("Applied actor name argument",r||o))}});var oa,dl=h(()=>{"use strict";oa="1.8.3"});var cl={};cr(cl,{parseMcpArgs:()=>wv});var Av,wv,ll=h(()=>{"use strict";dl();Av=`epiq-mcp ${oa}
|
|
3
|
+
|
|
4
|
+
Usage: epiq-mcp [name]
|
|
5
|
+
|
|
6
|
+
name the board identity this server writes under, e.g. claude/peter
|
|
7
|
+
(equivalent to setting EPIQ_USER_NAME)
|
|
8
|
+
|
|
9
|
+
Options:
|
|
10
|
+
-v, --version print the version
|
|
11
|
+
-h, --help print this help
|
|
12
|
+
`,wv=e=>{if(e.length>1)return{kind:"error",message:`Expected at most one name argument, got ${e.length}`};let t=e[0];return t===void 0?{kind:"none"}:t==="--version"||t==="-v"?{kind:"print",text:`${oa}
|
|
13
|
+
`}:t==="--help"||t==="-h"?{kind:"print",text:Av}:t.startsWith("-")?{kind:"error",message:`Unknown option ${t}; expected a name, e.g. epiq-mcp claude/peter`}:{kind:"name",name:t}}});import{decodeTime as ul}from"ulid";var ys,mr,He,pr,ml,$n,Ke=h(()=>{"use strict";R();ys=1440*60*1e3,mr=(e,t=Date.now())=>e>t+ys?t:e,He=e=>mr(ul(e)),pr=e=>{let t=Date.now()+ys,n=e.find(r=>r!==null&&r<=t)??null;if(n===null)return[...e];let o=null;return e.map(r=>{if(r===null)return null;let s=r<=t?r:o??n;return o=s,s})},ml=e=>{try{return l("Decoded date",new Date(He(e)))}catch(t){return a("Decoding failed + "+t.message)}},$n=e=>{if(!e?.id)return null;try{return ul(e.id)}catch{return null}}});var bs,it,pl,Ft=h(()=>{"use strict";R();bs="removed",it=(e,t)=>{let n=e.find(o=>o.context===t);return n!==void 0?l("Found node",n):a("Unable to find node in breadcrumb")},pl=["png","jpg","gif","webp"]});function ra(e){return e.context===V.WORKSPACE}function P(e){return e.context===V.TICKET}function fl(e){return e.context===V.TEXT}function at(e){return e.context===V.FIELD}function fr(e){return e.context===V.FIELD_LIST}var V,Sn,gr,hr,K=h(()=>{"use strict";V={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};Sn=e=>e.context===V.SWIMLANE,gr=e=>e.context===V.BOARD,hr=e=>e.context===V.COMMENT});var b,pe=h(()=>{"use strict";b={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"}});var gl=h(()=>{"use strict";jn()});import hl from"string-width";function xs(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}var Hn,Tv,sa,kv,ia,fe,dt=h(()=>{"use strict";Hn=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Tv=/\u001B\[[0-9;]*m/,sa="\x1B[0m",kv=e=>[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(e)].map(({segment:t})=>t),ia=(e,t)=>{if(t<=0)return"";if(hl(e)<=t)return e;if(t<=3)return"...".slice(0,t);let o=t-3,r="",s=0,i=!1;for(let c of e.split(/(\u001B\[[0-9;]*m)/))if(c!==""){if(Tv.test(c)){r+=c,i=c!==sa&&c!=="\x1B[m";continue}for(let u of kv(c)){let m=hl(u);if(s+m>o)return`${r}...${i?sa:""}`;r+=u,s+=m}}return`${r}...${i?sa:""}`},fe=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim()});var vl,yl,bl=h(()=>{"use strict";vl=e=>{let t=new Map;for(let n of e)for(let o=1;o<=n.length;o++){let r=n.slice(0,o),s=t.get(r);s?s.push(n):t.set(r,[n])}return t},yl=(e,t)=>t?e.get(t)??[]:[]});var xl,Mv,Il,El=h(()=>{"use strict";dt();bl();xl=new WeakMap,Mv=e=>{let t=xl.get(e);return t||(t=vl(e),xl.set(e,t)),t},Il=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let o=t.toLowerCase();return yl(Mv(e),o).filter(s=>xs(o,s)>=n)}});var Pv,Sl,Lv,Rl=h(()=>{"use strict";dt();El();Pv={hint:"",hints:[],overlap:0,remainder:""},Sl=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},o)=>{if(n||e==="")return Pv;let r=Il({wordList:o,inputToMatch:e,overlapThreshold:1});return Lv(t,r)},Lv=(e,t)=>{let n=t[0]??"",o=xs(e.toLowerCase(),n.toLowerCase()),[r,s]=n.split(":"),i=o<(r??"").length,c=!!s,p=(c&&i?r:n)+(c&&i?":":" "),f=p.slice(o);return{hint:p,hints:t,overlap:o,remainder:f}}});import{useSyncExternalStore as VR}from"react";var Is,Dv,Fv,Ie,ht,We=h(()=>{"use strict";Is={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},Dv=new Set,Fv=()=>{for(let e of Dv)e()},Ie=()=>Is,ht=e=>(Is={...Is,...e},Fv(),Is)});function Nl(e){return!e||!Ov.test(e)?a(`Invalid hex rank: ${e}`):l("Converted rank to bigint",BigInt("0x"+e))}function vt(e,t=vr){if(e<0n)return a("Negative rank not allowed");let n=e.toString(16);return l("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function qe(e,t){if(!e&&!t)return vt(_t/2n,vr);let n=e?Nl(e):l("Resolved lower bound",0n);if(d(n))return n;let o=t?Nl(t):l("Resolved upper bound",_t);if(d(o))return o;let r=n.value,s=o.value;if(s<=r)return a("Neighbouring ranks leave no space between them");let i=(r+s)/2n;return i===r||i===s?a("No rank space available between neighbors"):vt(i,vr)}function Cl(e){if(e<=0)return l("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let o=0;o<e;o++){let r=_t*BigInt(o+1)/(t+1n),s=vt(r,vr);if(d(s))return s;n.push(s.value)}return l("Resolved evenly spaced ranks",n)}var vr,_v,_t,Ov,yo=h(()=>{"use strict";R();vr=24n,_v=vr*4n,_t=(1n<<_v)-1n,Ov=/^[0-9a-f]+$/});import{ulid as Bv}from"ulid";var aa,Al=h(()=>{"use strict";R();yt();yo();aa=(e,t)=>{let n=ge(e),o=Cl(n.length);if(d(o))return o;let r={};for(let s=0;s<n.length;s++){let i=n[s],c=o.value[s];if(!i||!c)return a("Unable to assign rebalance rank");r[i.id]=c}return l("Created rebalance event",{id:Bv(),action:"rebalance.children",payload:{parent:e,ranks:r},...t})}});import yr from"node:fs";import{ulid as Uv}from"ulid";import{z as Es}from"zod";var $v,jv,Ss,Ot,br,wl,nn=h(()=>{"use strict";R();ae();$v="__epiq_state__",jv=Es.object({projectId:Es.string().min(1),stateBranch:Es.string().min(1),createdAt:Es.iso.datetime()}),Ss=()=>({projectId:Uv(),stateBranch:$v,createdAt:new Date().toISOString()}),Ot=e=>{let t=Rs(e);if(!yr.existsSync(t))return a("Missing .epiq/project.json");try{let n=yr.readFileSync(t,"utf8"),o=JSON.parse(n),r=jv.safeParse(o);return r.success?l("Read project.json",r.data):a(`Invalid .epiq/project.json: ${r.error.issues.map(s=>`${s.path.join(".")}: ${s.message}`).join(", ")}`)}catch(n){return a(n instanceof Error?`Failed to read .epiq/project.json: ${n.message}`:"Failed to read .epiq/project.json")}},br=e=>{let t=Ot(e);return d(t)?a(t.message):l("Read projectId",t.value.projectId)},wl=({repoRoot:e,fileContents:t})=>{let n=Wn(e),o=Rs(e);try{if(yr.mkdirSync(n,{recursive:!0}),yr.existsSync(o)){let r=Ot(e);return d(r)?a(r.message):l("Project already initialized",null)}return yr.writeFileSync(o,JSON.stringify(t,null,2)+`
|
|
14
|
+
`,"utf8"),l("Created project.json",null)}catch(r){return a(r instanceof Error?`Failed to initialize project: ${r.message}`:"Failed to initialize project")}}});import Hv from"node:os";import Wv from"node:path";var Tt,on,Ns=h(()=>{"use strict";Tt=".epiq-global",on=()=>process.env.EPIQ_GLOBAL_DIR??Wv.join(Hv.homedir(),Tt)});var da,Tl=h(()=>{"use strict";R();da=(e,t)=>{let n=new Map,o=t??((...s)=>JSON.stringify(s)),r=((...s)=>{let i=o(...s);if(!n.has(i)){let c=e(...s).then(u=>(d(u)&&n.delete(i),u));n.set(i,c)}return n.get(i)});return r.clear=()=>n.clear(),r}});var ye,Cs=h(()=>{"use strict";ct();ye={stage:({cwd:e,pathspec:t,ignoreRemoval:n=!1})=>W({args:["add",...n?["--ignore-removal"]:[],...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1,pathspec:o})=>W({args:["commit","--no-verify",...n?["--allow-empty"]:[],"-m",t,...o?.length?["--",...o]:[]],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>W({args:["fetch",t,`+refs/heads/${n}:refs/remotes/${t}/${n}`],cwd:e}),rebaseOnto:({cwd:e,ref:t})=>W({args:["-c","rebase.autoStash=true","rebase",t],cwd:e}),checkout:({cwd:e,branch:t})=>W({args:["checkout",t],cwd:e}),push:({cwd:e,remote:t,branch:n,setUpstream:o=!1})=>{let r=t&&n?["push","--no-verify",...o?["-u"]:[],t,n]:["push","--no-verify"];return W({args:r,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>W({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>W({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>W({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>W({args:["worktree","prune"],cwd:e})}});var Bt,bt,bo=h(()=>{"use strict";nn();R();ae();Bt=e=>{let t=Me(e);if(d(t))return a("Unable to resolve epiq project root");let n=Ot(t.value);return d(n)?a("Unable to read project.json"):l("Resolved state branch",n.value.stateBranch)},bt="origin"});import{spawn as Ml}from"node:child_process";import rn from"node:fs";import sn from"node:path";var ca,qv,Gv,zv,Vv,Pl,Ll,Dl,W,Be,la,xo,ua,Kv,As,qn,ma,ws,xr,Fl,pa,Ts,_l,Ol,Bl,Yv,Xv,Jv,Qv,Zv,kl,Ir,ey,Er,Ul,$l,jl,Hl,ct=h(()=>{"use strict";R();Cs();bo();ca=1e4,qv=12e4,Gv=new Set(["fetch","push","pull","clone","ls-remote","rebase","checkout","worktree"]),zv=e=>{let t=e.find((n,o)=>!n.startsWith("-")&&e[o-1]!=="-c");return t&&Gv.has(t)?qv:ca},Vv=()=>{let e=process.platform==="win32"?["git.exe","git"]:["git"];for(let t of(process.env.PATH??"").split(sn.delimiter))if(t)for(let n of e){let o=sn.join(t,n);try{if(!rn.statSync(o).isFile())continue;return rn.accessSync(o,rn.constants.X_OK),o}catch{continue}}return"git"},Pl=Vv(),Ll={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo",GIT_SSH_COMMAND:process.env.GIT_SSH_COMMAND??"ssh -o BatchMode=yes -o ConnectTimeout=10"},Dl=({args:e,cwd:t,allowFail:n})=>new Promise(o=>{if(!rn.existsSync(t)){let f=`Git cwd does not exist: ${t}`;if(n){o({stdout:"",stderr:f,exitCode:1});return}o(a(f));return}let r=Ml(Pl,e,{cwd:t,stdio:["ignore","pipe","pipe"],env:Ll}),s=!1,i="",c="",u=f=>{s||(s=!0,clearTimeout(p),o(f))},m=zv(e),p=setTimeout(()=>{r.kill("SIGTERM");let f=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${m}ms`].join(`
|
|
15
|
+
`);u(n?{stdout:i,stderr:f,exitCode:124}:a(f))},m);r.stdout.setEncoding("utf8"),r.stderr.setEncoding("utf8"),r.stdout.on("data",f=>{i+=f}),r.stderr.on("data",f=>{c+=f}),r.on("error",f=>{if(n){u({stdout:i,stderr:f.message,exitCode:1});return}u(a([`git ${e.join(" ")}`,`cwd=${t}`,f.message].join(`
|
|
16
|
+
`)))}),r.on("close",f=>{let y=f??1;if(n){u({stdout:i,stderr:c,exitCode:y});return}if(y!==0){u(a([`git ${e.join(" ")}`,c.trim()||i.trim()||"Git command failed"].filter(Boolean).join(`
|
|
17
|
+
`)));return}u(l("Git command succeeded",{stdout:i,stderr:c,exitCode:y}))})}),W=({args:e,cwd:t})=>Dl({args:e,cwd:t,allowFail:!1}),Be=({args:e,cwd:t})=>Dl({args:e,cwd:t,allowFail:!0}),la=(e,t)=>new Promise(n=>{if(e.length===0){n(l("No blobs to read",new Map));return}let o=Ml(Pl,["cat-file","--batch"],{cwd:t,stdio:["pipe","pipe","pipe"],env:Ll}),r=[],s="",i=!1,c=m=>{i||(i=!0,clearTimeout(u),n(m))},u=setTimeout(()=>{o.kill("SIGTERM"),c(a(`git cat-file --batch timed out after ${ca}ms`))},ca);o.stdout.on("data",m=>r.push(m)),o.stderr.setEncoding("utf8"),o.stderr.on("data",m=>{s+=m}),o.on("error",m=>c(a(m.message))),o.on("close",m=>{if(m!==0){c(a(`git cat-file --batch exited ${m}${s?`
|
|
18
|
+
${s}`:""}`));return}let p=Buffer.concat(r),f=new Map,y=0;for(let I of e){let S=p.indexOf(10,y);if(S===-1){c(a(`git cat-file --batch output ended before a header for ${I}`));return}let A=p.toString("utf8",y,S);y=S+1;let w=/^[0-9a-f]{4,64} \S+ (\d+)$/.exec(A);if(!w||!w[1]){c(a(`Unexpected git cat-file --batch header: "${A}"`));return}let k=Number(w[1]);f.set(I,p.toString("utf8",y,y+k)),y+=k+1}c(l("Read blobs",f))}),o.stdin.write(e.join(`
|
|
19
|
+
`)+`
|
|
20
|
+
`),o.stdin.end()}),xo=async({cwd:e,message:t,pathspec:n})=>{let o=await ye.commit({cwd:e,message:t,pathspec:n});if(d(o))return a(`Failed to create commit
|
|
21
|
+
${o.message}`);let r=await W({args:["rev-parse","HEAD"],cwd:e});return d(r)?a(`Commit created, but failed to read HEAD SHA
|
|
22
|
+
${r.message}`):l("Created commit and resolved SHA",r.value.stdout.trim())},ua=async e=>{let t=await W({cwd:e,args:["rev-parse","--git-dir"]});if(d(t))return a(t.message);let n=t.value.stdout.trim();return l("Resolved git dir",sn.isAbsolute(n)?n:sn.resolve(e,n))},Kv=async e=>{let t=await ua(e);if(d(t))return a(t.message);let n=t.value,o={MERGE_HEAD:"merge in progress"};for(let[s,i]of Object.entries(o))if(rn.existsSync(sn.join(n,s)))return l("Checked for in-progress Git operation",i);let r={"rebase-merge":"rebase in progress","rebase-apply":"rebase in progress"};for(let[s,i]of Object.entries(r))if(rn.existsSync(sn.join(n,s)))return l("Checked for in-progress Git operation",i);return l("Checked for in-progress Git operation",null)},As=async e=>{let t=await Kv(e);return d(t)?a(t.message):l("Checked for in-progress Git operation",t.value!==null)},qn=async({repoRoot:e})=>{let n=(await Be({args:["remote","get-url",bt],cwd:e})).exitCode===0;return l(`Checked remote ${n}`,n)},ma=async({repoRoot:e,branch:t})=>{let n=await Be({args:["ls-remote","--heads",bt,t],cwd:e});return n.exitCode!==0?a(n.stderr.trim()||`Unable to inspect remote branch ${bt}/${t}`):l("Checked remote branch",n.stdout.trim().length>0)},ws=async({repoRoot:e,branch:t})=>{let n=await Be({args:["show-ref","--verify","--quiet",`refs/heads/${t}`],cwd:e});return n.exitCode===0?l("Local branch exists",!0):n.exitCode===1?l("Local branch missing",!1):a(n.stderr.trim()||`Unable to inspect branch ${t}`)},xr=e=>{try{return rn.realpathSync.native(e)}catch{return sn.resolve(e)}},Fl=async({repoRoot:e,worktreeRoot:t})=>{let n=await W({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return a(n.message);let o=xr(t),r=n.value.stdout.split(`
|
|
23
|
+
`).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(xr).includes(o);return l("Checked worktree registration",r)},pa=async e=>{let t=await Be({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return l("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},Ts=async e=>{let t=await W({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return d(t)?a(t.message):l("Resolved current branch",t.value.stdout.trim())},_l=async e=>{let t=await W({args:["rev-parse","--short","HEAD"],cwd:e});return d(t)?a(t.message):l("Resolved short HEAD sha",t.value.stdout.trim())},Ol=e=>e.includes("fetch first")||e.includes("non-fast-forward"),Bl=async e=>{let t=await Be({cwd:e,args:["rev-parse","--absolute-git-dir"]});if(t.exitCode!==0)return!1;let n=t.stdout.trim();return n?rn.existsSync(sn.join(n,"rebase-merge"))||rn.existsSync(sn.join(n,"rebase-apply")):!1},Yv=3,Xv=120,Jv=e=>new Promise(t=>setTimeout(t,e)),Qv=async(e,t)=>{let n=await ye.rebaseOnto({cwd:e,ref:t});for(let o=1;o<Yv;o+=1){if(!d(n)||await Bl(e))return n;await Jv(Xv),n=await ye.rebaseOnto({cwd:e,ref:t})}return n},Zv=async e=>{if(!await Bl(e))return l("No rebase to abort",!1);let t=await Be({cwd:e,args:["rebase","--abort"]});return t.exitCode!==0?a(`Failed to abort the rebase in progress at ${e}
|
|
24
|
+
${t.stderr.trim()}`):l("Aborted stale rebase",!0)},kl=async e=>{let t=await Be({args:["rev-parse","HEAD"],cwd:e});return t.exitCode===0?t.stdout.trim():null},Ir=e=>/could not resolve host/i.test(e)||/connection refused|connection timed out|operation timed out/i.test(e)||/network is unreachable|no route to host/i.test(e)||/failed to connect to/i.test(e),ey=e=>e.includes("couldn't find remote ref")||e.includes("Could not find remote branch"),Er=async({cwd:e,branch:t})=>{let n=await Zv(e);if(d(n))return a(n.message);let o=await kl(e),r=await ye.fetch({cwd:e,remote:bt,branch:t});if(d(r))return ey(r.message)?l("Remote branch missing, skipped pull",!1):a(`Failed to fetch ${t}
|
|
25
|
+
${r.message}`);let s=await Qv(e,`${bt}/${t}`);if(d(s))return a(`Failed during rebase
|
|
26
|
+
${s.message}`);let i=await kl(e),c=o!==null&&i!==null&&o!==i;return l(c?"Pulled with rebase":"Already up to date",c)},Ul=async e=>{let t=await Be({args:["rev-list","--count","@{u}..HEAD"],cwd:e});return t.exitCode!==0?l("No upstream to compare against",!1):l("Compared against upstream",Number(t.stdout.trim())>0)},$l=async e=>{let t=await Be({args:["status","--porcelain","--untracked-files=all"],cwd:e});return t.exitCode!==0?a(t.stderr.trim()||"Unable to inspect the worktree for changes"):l("Inspected worktree for changes",t.stdout.trim().length>0)},jl=async(e,t)=>{let n=await Be({args:["diff","--cached","--quiet",...t?.length?["--",...t]:[]],cwd:e});return n.exitCode===0?l("No staged changes",!1):n.exitCode===1?l("Has staged changes",!0):a(n.stderr.trim()||"Unable to inspect staged changes")},Hl=async e=>{let t=await Ts(e);return d(t)?a(t.message):l("Checked detached HEAD state",t.value==="HEAD")}});import Rn from"node:fs";import Ye from"node:path";var Gl,zl,Vl,Kl,ks,be,ty,Wl,Sr,Ms,Yl,ny,oy,fa,ga,ql,Xl,Jl,lt,HN,Xe=h(()=>{"use strict";nn();R();Ns();ae();Tl();xt();ct();Gl="4b825dc642cb6eb9a060e54bf8d69288fbee4904",zl=e=>Ye.join(Ge,an,e),Vl=()=>Ye.join(Ge,ha),Kl=on,ks=()=>Ye.join(Kl(),"worktrees"),be=({repoRoot:e})=>{let t=br(e);return d(t)?a(t.message):l("Resolved state branch root",Ye.join(ks(),t.value))},ty=e=>Ye.join(e,Ge),Wl=e=>Ye.join(ty(e),an),Sr=e=>{try{return Rn.mkdirSync(e,{recursive:!0}),l("Ensured directory",void 0)}catch(t){return a(t instanceof Error?t.message:String(t))}},Ms=()=>{let e=Kl(),t=ks(),n=!Rn.existsSync(e)||!Rn.existsSync(t),o=Sr(e);if(d(o))return a(`Ensure epiq home failed.
|
|
27
|
+
`+o.message);let r=Sr(t);return d(r)?a(`Ensure worktrees dir failed.
|
|
28
|
+
`+r.message):l("Ensured epiq storage",n)},Yl=e=>{Rn.existsSync(e)&&(J.debug("[sync] remove path",e),Rn.rmSync(e,{recursive:!0,force:!0}))},ny=`*.jsonl merge=union
|
|
29
|
+
`,oy=`*~pending*.jsonl
|
|
30
|
+
`,fa=()=>Ye.join(Ge,an,".gitattributes"),ga=()=>Ye.join(Ge,an,".gitignore"),ql=(e,t)=>{try{Rn.readFileSync(e,"utf8")!==t&&Rn.writeFileSync(e,t)}catch{Rn.writeFileSync(e,t)}},Xl=(e,t)=>{for(let n of[Wl(e),Wl(t)]){let o=Sr(n);if(d(o))return a(o.message)}return ql(Ye.join(t,fa()),ny),ql(Ye.join(t,ga()),oy),l("Ensured state branch",void 0)},Jl=async e=>{let t=await W({args:["ls-tree","--name-only","HEAD"],cwd:e});if(d(t))return a(`ensure state branch is storage only failed
|
|
15
31
|
`+t.message);let o=t.value.stdout.trim().split(`
|
|
16
|
-
`).filter(Boolean).filter(
|
|
17
|
-
${r.message}`);let s=await
|
|
18
|
-
`);if(n[n.length-1]===""&&n.pop(),t<=
|
|
32
|
+
`).filter(Boolean).filter(i=>i!==Ge);if(o.length===0)return l("State branch is storage-only",!1);let r=await W({args:["rm","-r","--ignore-unmatch","--",...o],cwd:e});if(d(r))return a(`Failed to clean storage branch
|
|
33
|
+
${r.message}`);let s=await xo({cwd:e,message:"[epiq:repair-storage-branch]",pathspec:o});return d(s)?a(s.message):l("Cleaned storage branch",!0)},lt=da(async(e=process.cwd())=>{let t=await W({args:["rev-parse","--show-toplevel"],cwd:e});return d(t)?a("Not inside a Git repository"):l("Resolved repo root",t.value.stdout.trim())},e=>Ye.resolve(e)),HN=da(async e=>{let t=await W({args:["rev-parse","--git-dir"],cwd:e});if(d(t))return a(t.message);let n=t.value.stdout.trim(),o=Ye.isAbsolute(n)?n:Ye.join(e,n);return l("Resolved git dir",o)},e=>Ye.resolve(e))});import Rr from"node:fs";import Ut from"node:path";var YN,Ge,an,ha,ry,Wn,Rs,kt,Ps,Ql,sy,Nr,Ls,iy,Me,Zl,$t,ae=h(()=>{"use strict";R();Xe();Ns();YN=process.env.IS_LOCAL==="true",Ge=".epiq",an="events",ha="media",ry="project.json",Wn=e=>Ut.join(e,Ge),Rs=e=>Ut.join(Wn(e),ry),kt=e=>Ut.join(Wn(e),an),Ps=e=>Ut.join(Wn(e),ha),Ql=e=>Ut.join(e,Ge),sy=e=>{let t=Ut.join(e,Ge);return Rr.existsSync(t)&&Rr.statSync(t).isDirectory()},Nr=e=>{let t=Rs(e);return Rr.existsSync(t)&&Rr.statSync(t).isFile()},Ls=e=>{let t=Ut.resolve(e);for(;;){if(sy(t))return l("Resolved closest .epiq root",t);let n=Ut.dirname(t);if(n===t)return a("No .epiq directory found in any parent");t=n}},iy="No .epiq/project.json found in any parent",Me=e=>{let t=Ut.resolve(e);for(;;){if(Nr(t))return l("Resolved closest epiq project root",t);let n=Ut.dirname(t);if(n===t)return a(iy);t=n}},Zl=e=>{let t=kt(e);try{return Rr.mkdirSync(t,{recursive:!0}),l("Resolved events dir",t)}catch(n){return a(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}},$t=async()=>{let e=await lt(process.cwd());if(d(e))return e;let t=be({repoRoot:e.value});return d(t)?t:l("Resolved persist root",t.value)}});import Mt from"fs";import Ia from"path";import ay from"util";function uy(e){if(!Mt.existsSync(e))return;let t=Mt.statSync(e).size,n=ly(e,Ea).split(`
|
|
34
|
+
`);if(n[n.length-1]===""&&n.pop(),t<=Ea&&n.length<=eu)return;let o=n.slice(-eu).join(`
|
|
19
35
|
`)+`
|
|
20
|
-
`;
|
|
21
|
-
`;try{
|
|
22
|
-
`);return d===-1?"":s.slice(d+1)}finally{At.closeSync(o)}};Th=e=>{if(e.length<=Hi)return e;let t=e.length-Hi;return`${e.slice(0,Hi)} \u2026 [${t} more chars]`};Gi=()=>sl()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",X={info(...e){let t=Gi();(t==="info"||t==="debug")&&qi("[Info]",e,!1)},debug(...e){Gi()==="debug"&&qi("[Debug]",e,!0)},error(...e){let t=Gi();if(t==="error"||t==="info"||t==="debug"){let o=e.some(r=>r instanceof Error)?void 0:new Error().stack;qi("[Error]",[...e,o].filter(Boolean),!1)}}};globalThis.logger=X});var le,uo=h(()=>{"use strict";le={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments",ATTACHMENTS:"Attachments"}});var j,dr,st=h(()=>{"use strict";j=e=>e.slice(-7).toUpperCase(),dr=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?j(e).includes(n):!0}});var Te,On=h(()=>{"use strict";V();st();Te={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:z.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,o,r=!1)=>({id:e,title:t,rank:o,isDeleted:!1,props:{ref:j(e)},context:z.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:r,log:[]}),swimlane:(e,t,n,o)=>({id:e,title:t,rank:o,isDeleted:!1,props:{},context:z.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:o,props:r={},childRenderAxis:s="horizontal",isVirtual:d=!1})=>({id:e,title:t,rank:o,isDeleted:!1,props:r,context:z.FIELD,childRenderAxis:s,parentNodeId:n,readonly:!1,log:[],isVirtual:d}),fieldList:({id:e,name:t,parentNodeId:n,rank:o,childRenderAxis:r="horizontal",isVirtual:s=!1})=>({id:e,title:t,rank:o,isDeleted:!1,props:{},context:z.FIELD_LIST,childRenderAxis:r,parentNodeId:n,readonly:!1,log:[],isVirtual:s}),ticket:(e,t,n,o)=>({id:e,title:t,rank:o,isDeleted:!1,props:{ref:j(e)},context:z.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:o,readonly:r=!0,isVirtual:s=!0})=>({id:e,title:t,rank:o,isDeleted:!1,props:{},context:z.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:r,log:[],isVirtual:s}),comment:({id:e,name:t,parentNodeId:n,rank:o,props:r={},readonly:s=!0,isVirtual:d=!0})=>({id:e,title:t,rank:o,isDeleted:!1,props:r,context:z.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:d})}});var Mh,fe,fs,Jt=h(()=>{"use strict";Mh=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[fe,fs]=Mh});function hn(e,t=!1){let n=Bh[e.action];if(!n)return i(`Unknown event action "${e.action}", likely created by a newer epiq version. Evt id: ${e.id}`);if(!vt()&&e.action!=="init.workspace")return D(`${e.action} arrived before the workspace was initialized`,e);if(e.action==="init.workspace"&&Ge){if(Ge.genesisApplied)return D("the workspace is already initialized",e);Ge.genesisApplied=!0}let o;try{o=n(e)}catch(s){return D(`threw while materializing (${s instanceof Error?s.message:String(s)})`,e)}if(a(o))return o;let r=_h(e,t);return r||o}var Ki,D,lr,Un,$n,il,al,kh,Ph,Yi,Lh,Dh,Ge,Fh,_h,cr,Bh,Qt,Zt=h(()=>{"use strict";ht();V();R();uo();te();On();M();Xi();Jt();Ki=(e,t)=>i(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),D=(e,t)=>({...Ki(e,t),convergence:!0}),lr=e=>a(e)&&e.convergence===!0,Un=e=>{let t=e.filter(a);return{fatal:t.filter(n=>!lr(n)),skipped:t.filter(lr)}},$n=e=>{e.length!==0&&X.info(`Skipped ${e.length} event(s) that could not be applied to this state: ${e.map(t=>t.message).join("; ")}`)},il=e=>{let t=I.getNode(e);if(!t||!k(t)||t.isDeleted)return null;let n=hs(t);return a(n)?n:null},al=e=>{if(!vs())return null;for(let t of e){let n=il(t);if(n)return n;let o=g().nodes[t]?.parentNodeId;if(!o)continue;let r=il(o);if(r)return r}return null},kh=(e,t)=>{let n=I.getNode(e);n&&I.updateNode({...n,log:[...n.log??[],t]})},Ph=e=>{let t=[e],n=g().nodes[e]?.parentNodeId;return n&&t.push(n),t},Yi=e=>{switch(e.action){case"add.issue.comment":case"edit.issue.comment":case"delete.issue.comment":case"add.issue.attachment":case"delete.issue.attachment":return[e.payload.issue];case"delete.node":case"edit.description":return Ph(e.payload.id);case"init.workspace":case"add.workspace":case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"edit.title":case"lock.node":case"move.node":case"close.issue":case"reopen.issue":case"add.issue.tag":case"remove.issue.tag":case"add.issue.assignee":case"remove.issue.assignee":return[e.payload.id];case"rebalance.children":return Object.keys(e.payload.ranks);case"create.tag":case"tombstone.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"link.contributor.user":default:return[]}},Lh=e=>{Re(t=>({...t,eventLog:[...t.eventLog,e]}))},Dh=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?Ki("Invalid user ID format",e):l("Valid user",null)},Ge=null,Fh=e=>{for(let[t,n]of e.nodeLog){let o=I.getNode(t);o&&I.updateNode({...o,log:[...o.log??[],...n]})}return e.appLog.length>0&&Re(t=>({...t,eventLog:[...t.eventLog,...e.appLog]})),al([...e.virtualNodeIds])},_h=(e,t)=>{let n=Dh(e);if(a(n))return n;let o=[...new Set(Yi(e))];if(Ge){for(let s of o){if(!t){let d=Ge.nodeLog.get(s);d?d.push(e):Ge.nodeLog.set(s,[e])}if(vs()){Ge.virtualNodeIds.add(s);let d=g().nodes[s]?.parentNodeId;d&&Ge.virtualNodeIds.add(d)}}return t||Ge.appLog.push(e),null}t||(o.forEach(s=>kh(s,e)),Lh(e));let r=al(o);return r||null},cr=(e,t,n)=>I.getNode(e)?D(`a node with id ${e} already exists`,n):t===e?D("a node cannot be its own parent",n):null,Bh={"init.workspace":e=>{let{id:t,name:n,rank:o}=e.payload,r=Te.workspace(t,n,o),s=ur(r);if(a(s))return Ki(s.message,e);let d=I.createNode(r);return a(d)?D(d.message??"Failed to initialize workspace",e):ki(d.value)?l("Workspace initialized",{action:e.action,result:d.value}):i("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:o}=e.payload,r=cr(t,void 0,e);if(r)return r;let s=I.createNode(Te.workspace(t,n,o));return a(s)?D(s.message??"Failed to add workspace",e):ki(s.value)?l("Added workspace",{action:e.action,result:s.value}):i("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:o,rank:r}=e.payload,s=cr(t,o,e);if(s)return s;let d=I.createNode(Te.board(t,n,o,r));return a(d)?D(d.message??"Unable to create board",e):Jo(d.value)?l("Added board",{action:e.action,result:d.value}):i("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:o,rank:r}=e.payload,s=cr(t,o,e);if(s)return s;let d=I.createNode(Te.swimlane(t,n,o,r));return a(d)?D(d.message??"Unable to create swimlane",e):pn(d.value)?l("Added swimlane",{action:e.action,result:d.value}):i("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:o,rank:r}=e.payload,s=cr(t,o,e);if(s)return s;let d=I.createNode(Te.ticket(t,n,o,r));return a(d)?D(d.message??"Unable to create issue",e):k(d.value)?l("Added issue",{action:e.action,result:d.value}):i("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:o,val:r,rank:s}=e.payload,d=cr(t,o,e);if(d)return d;let c=I.createNode(Te.field({id:t,name:n,parentNodeId:o,rank:s,props:{value:r},childRenderAxis:n.includes(le.DESCRIPTION)?"vertical":"horizontal"}));return a(c)?D(c.message??`Unable to create field: ${n}`,e):nt(c.value)?l("Added field",{action:e.action,result:c.value}):i("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!I.getNode(t))return D(`Unable to locate node with id ${t}`,e);let r=I.renameNode(t,n);return a(r)?D(r.message??"Unable to edit title",e):l("Edited title",{action:e.action,result:r.value})},"delete.node":e=>{let{id:t}=e.payload,n=I.tombstoneNode(t);return a(n)?D(n.message??"Unable to delete node",e):l("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,o=I.createTag({id:t,name:n});return a(o)?D(o.message??"Unable to create tag",e):l("Tag added",{action:e.action,result:o.value})},"tombstone.tag":e=>{let{id:t}=e.payload,n=I.tombstoneTag(t);return a(n)?D(n.message??"Unable to delete tag",e):l("Tag tombstoned",{action:e.action,result:n.value})},"restore.tag":e=>{let{id:t,name:n}=e.payload,o=I.restoreTag(t,n);return a(o)?D(o.message??"Unable to restore tag",e):l("Tag restored",{action:e.action,result:o.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,o=I.createContributor({id:t,name:n});return a(o)?D(o.message??"Unable to create contributor",e):l("Contributor created",{action:e.action,result:o.value})},"rename.contributor":e=>{let{id:t,name:n}=e.payload,o=I.renameContributor(t,n);return a(o)?D(o.message??"Unable to rename contributor",e):l("Contributor renamed",{action:e.action,result:o.value})},"tombstone.contributor":e=>{let{id:t}=e.payload,n=I.tombstoneContributor(t);return a(n)?D(n.message??"Unable to remove contributor",e):l("Contributor tombstoned",{action:e.action,result:n.value})},"restore.contributor":e=>{let{id:t,name:n}=e.payload,o=I.restoreContributor(t,n);return a(o)?D(o.message??"Unable to restore contributor",e):l("Contributor restored",{action:e.action,result:o.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,o=I.tag(t,n);return a(o)?D(o.message??"Unable to tag issue",e):l("Issue tagged",{action:e.action,result:{tag:n}})},"remove.issue.tag":e=>{let{id:t,tag:n}=e.payload,o=I.untag(t,n);return a(o)?D(o.message??"Unable to untag issue",e):l("Issue untagged",{action:e.action,result:{tag:n}})},"add.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,o=I.assign(t,n);return a(o)?D(o.message??"Unable to assign issue",e):l("Assigned successfully",{action:e.action,result:{assignee:n}})},"remove.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,o=I.unassign(t,n);return a(o)?D(o.message??"Unable to unassign issue",e):l("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:o}=e.payload,r=I.moveNodeToRank({id:t,parentId:n,rank:o});return a(r)?D(r.message??"Failed to move node",e):l("Moved node",{action:e.action,result:r.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,o=I.editValue(t,n);return a(o)?D(o.message??"Unable to edit description",e):l("Set node value",{action:e.action,result:o.value})},"close.issue":e=>{let{id:t,parent:n,rank:o}=e.payload,r=I.getNode(t);if(!r)return D("Unable to locate issue",e);if(!k(r))return D("Can only close issues",e);let s=I.getNode(fe);if(!s)return D("Unable to locate target swimlane",e);if(n!==s.id)return D("Close target must be closed swimlane",e);let d=I.moveNodeToRank({id:t,parentId:n,rank:o});return a(d)?D(d.message??"Unable to close issue",e):l("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:o}=e.payload,r=I.getNode(t);if(!r)return D("Unable to locate issue",e);if(!k(r))return D("Can only reopen issues",e);let s=I.getNode(fe);if(!s)return D("Unable to locate closed swimlane",e);if(n===s.id)return D("Cannot reopen issue into closed swimlane",e);if(!I.getNode(n))return D("Reopen parent no longer exists",e);let c=I.moveNodeToRank({id:t,parentId:n,rank:o});return a(c)?D(c.message??"Unable to reopen issue",e):l("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=I.lockNode(t);return a(n)?D(n.message??"Unable to lock node",e):l("Node locked",{action:e.action,result:n.value})},"rebalance.children":e=>{let{parent:t,ranks:n}=e.payload;for(let[o,r]of Object.entries(n)){let s=I.getNode(o);if(!s)return D(`Unable to locate node ${o}`,e);if(s.parentNodeId!==t)return D(`Node ${o} is not child of ${t}`,e);let d=I.updateNode({...s,rank:r});if(a(d))return D(d.message??"Unable to rebalance child",e)}return l("Rebalanced children",{action:e.action,result:{parent:t}})},"add.issue.comment":e=>{let{id:t,issue:n,author:o,md:r}=e.payload,s=I.createComment({id:t,issue:n,authorId:o,authorName:I.getContributor(o)?.name??"Unknown",md:r,deleted:!1});return a(s)?D(s.message??"Unable to add comment",e):l("Comment added",{action:e.action,result:{id:t,issue:n,author:o,md:r}})},"edit.issue.comment":e=>{let{id:t,issue:n,md:o}=e.payload,r=I.getComment(t);if(!r)return D("Unable to locate comment",e);if(r.issue!==n)return D("Comment does not belong to issue",e);let s=I.editComment(t,o);return a(s)?D(s.message??"Unable to edit comment",e):l("Comment edited",{action:e.action,result:{id:t,issue:n,md:o}})},"delete.issue.comment":e=>{let{id:t,issue:n}=e.payload,o=I.getComment(t);if(!o)return D("Unable to locate comment",e);if(o.issue!==n)return D("Comment does not belong to issue",e);let r=I.deleteComment(t);return a(r)?D(r.message??"Unable to delete comment",e):l("Comment deleted",{action:e.action,result:{id:t,issue:n}})},"add.issue.attachment":e=>{let{id:t,issue:n,hash:o,ext:r,name:s,bytes:d}=e.payload,c=I.createAttachment({id:t,issue:n,hash:o,ext:r,name:s,bytes:d,deleted:!1});return a(c)?D(c.message??"Unable to add attachment",e):l("Attachment added",{action:e.action,result:{id:t,issue:n,hash:o}})},"delete.issue.attachment":e=>{let{id:t,issue:n}=e.payload,o=I.getAttachment(t);if(!o)return D("Unable to locate attachment",e);if(o.issue!==n)return D("Attachment does not belong to issue",e);let r=I.deleteAttachment(t);return a(r)?D(r.message??"Unable to delete attachment",e):l("Attachment deleted",{action:e.action,result:{id:t,issue:n}})},"link.contributor.user":e=>{let{contributor:t}=e.payload,n=I.linkUserId({contributorId:t,userId:e.userId});return a(n)?D(n.message??"Unable to link contributor",e):l("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};Qt=e=>{let t=dl(()=>{let n=Ge===null;n&&(Ge={appLog:[],nodeLog:new Map,virtualNodeIds:new Set,genesisApplied:!1});try{let o=e.map(r=>hn(r));if(n&&Ge){let r=Fh(Ge);if(r)return e.map(()=>r)}return o}finally{n&&(Ge=null)}});return a(t)?e.map(()=>i(t.message)):t.value}});var Ji,cl=h(()=>{"use strict";Ji=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/\.jsonl/g,"-jsonl").replace(/^-+|-+$/g,"")||"unknown"});import{existsSync as Oh,readdirSync as Uh,statSync as $h}from"node:fs";import jh from"node:path";var jn,ll,Qi,vn,ul,ml,pl,mr=h(()=>{"use strict";ae();jn=e=>{let t=Bn(e);return Oh(t)?Uh(t).filter(n=>n.endsWith(".jsonl")).sort().map(n=>{let{size:o,mtimeMs:r}=$h(jh.join(t,n));return`${n}:${o}:${r}`}).join("|"):"none"},ll=e=>new Map(e.split("|").filter(Boolean).map(t=>{let n=t.indexOf(":");return[t.slice(0,n),t.slice(n+1)]})),Qi=(e,t,n)=>{let o=ll(t),r=jn(e),s=ll(r);for(let[d,c]of s)if(d!==n&&o.get(d)!==c)return null;for(let d of o.keys())if(d!==n&&!s.has(d))return null;return r},vn=null,ul=e=>vn&&vn.root===e?vn.signature:null,ml=(e,t)=>{vn={root:e,signature:t}},pl=(e,t)=>{if(!vn||vn.root!==e)return;let n=Qi(e,vn.signature,t);vn=n===null?null:{root:e,signature:n}}});var Hh,Wh,gl,fl,Zi=h(()=>{"use strict";Hh=["init.workspace","add.workspace","add.board","add.swimlane","add.issue","add.field","edit.title","delete.node","create.tag","tombstone.tag","restore.tag","create.contributor","rename.contributor","tombstone.contributor","restore.contributor","add.issue.assignee","remove.issue.assignee","add.issue.tag","remove.issue.tag","move.node","edit.description","add.issue.comment","edit.issue.comment","delete.issue.comment","add.issue.attachment","delete.issue.attachment","close.issue","reopen.issue","lock.node","rebalance.children","link.contributor.user"],Wh=new Set(Hh),gl=e=>Wh.has(e),fl=e=>({action:e.action,payload:e.payload})});import{z as G}from"zod";var H,Ct,yn,ys,ea,qh,hl,vl=h(()=>{"use strict";R();H=G.string().min(1),Ct=G.string(),yn=G.string(),ys=G.looseObject({id:H}),ea=G.looseObject({id:H,name:Ct,parent:H,rank:yn}),qh={"init.workspace":G.looseObject({id:H,name:Ct,rank:yn}),"add.workspace":G.looseObject({id:H,name:Ct,rank:yn}),"add.board":ea,"add.swimlane":ea,"add.issue":ea,"add.field":G.looseObject({id:H,name:Ct,parent:H,rank:yn}),"edit.title":G.looseObject({id:H,name:Ct}),"delete.node":ys,"lock.node":ys,"move.node":G.looseObject({id:H,parent:H,rank:yn}),"edit.description":G.looseObject({id:H,md:G.string()}),"close.issue":G.looseObject({id:H,parent:H,rank:yn}),"reopen.issue":G.looseObject({id:H,parent:H,rank:yn}),"create.tag":G.looseObject({id:H,name:Ct}),"tombstone.tag":ys,"restore.tag":G.looseObject({id:H,name:Ct}),"create.contributor":G.looseObject({id:H,name:Ct}),"rename.contributor":G.looseObject({id:H,name:Ct}),"tombstone.contributor":ys,"restore.contributor":G.looseObject({id:H,name:Ct}),"link.contributor.user":G.looseObject({contributor:H}),"add.issue.assignee":G.looseObject({id:H,assignee:H}),"remove.issue.assignee":G.looseObject({id:H,assignee:H}),"add.issue.tag":G.looseObject({id:H,tag:H}),"remove.issue.tag":G.looseObject({id:H,tag:H}),"add.issue.comment":G.looseObject({id:H,issue:H,md:G.string()}),"edit.issue.comment":G.looseObject({id:H,issue:H,md:G.string()}),"delete.issue.comment":G.looseObject({id:H,issue:H}),"add.issue.attachment":G.looseObject({id:H,issue:H,hash:G.string().min(1),ext:G.string().min(1),name:Ct,bytes:G.number()}),"delete.issue.attachment":G.looseObject({id:H,issue:H}),"rebalance.children":G.looseObject({parent:H,ranks:G.record(G.string(),yn)})},hl=(e,t)=>{let o=qh[e].safeParse(t);return o.success?l("Payload is readable",void 0):i(`${e}: ${o.error.issues.map(r=>`${r.path.join(".")||"payload"} ${r.message}`).join(", ")}`)}});import Is from"node:fs";import xs from"node:path";import{decodeTime as Gh}from"ulid";import{z as ta}from"zod";function pr(e,t){let n=Bn(e),o=jn(e);if(!Is.existsSync(n))return l("No events found",[]);let r=Is.readdirSync(n).filter(c=>c.endsWith(".jsonl")).map(c=>xs.join(n,c)),s=[];for(let c of r){let u=ev(c,t);if(a(u))return i(u.message);s.push(...u.value)}let d=nv(s);return en={root:e,signature:o,edge:d.at(-1)?.id?.[0]??null},l("All events loaded",d)}function yt(e){let t=[],n=pr(e,t);if(a(n))return i(n.message);let o=oa(n.value,t);return a(o)?i(o.message):(tv=t,l("Loaded merged events",{events:o.value,unreadable:t}))}function ra(e){let t=pr(e);return a(t)?i(t.message):l("Loaded event actors",t.value.map(({userId:n,userName:o})=>({userId:n,userName:o})))}function Hn(e){let t=yt(e);return a(t)?i(t.message):l("Loaded merged events",t.value.events)}function sa(e,t){let n=pr(e);if(a(n))return i(n.message);let{appliedEvents:o,unappliedEvents:r}=ov(n.value,t),s=oa(o);if(a(s))return i(s.message);let d=oa(r);return a(d)?i(d.message):l("Loaded merged events before time",{appliedEvents:s.value,unappliedEvents:d.value})}function yl(e=process.cwd()){let t=jn(e);if(en&&en.root===e&&en.signature===t)return l("Loaded edge reference, unchanged",en.edge);let n=pr(e);return a(n)?i(n.message):l("Loaded edge reference",n.value.at(-1)?.id?.[0]??null)}function bl(e,t,n){if(!en||en.root!==e)return;let o=Qi(e,en.signature,t);en=o===null?null:{root:e,signature:o,edge:n}}function ia(e){let t=pr(e);if(a(t))return i(t.message);let n=Il(t.value);return l("Loaded effective event times",new Map(t.value.map((o,r)=>[o.id[0],n[r]??null])))}var zh,bs,Vh,Kh,Yh,Xh,Jh,Qh,Zh,oa,ev,tv,en,na,nv,Il,ov,bt=h(()=>{"use strict";ht();R();ae();mr();et();Zi();Se();vl();zh=ta.object({userId:ta.string().min(1).default("unknown"),userName:ta.string().min(1).default("unknown")}),bs=e=>{let t=Object.entries(e).filter(([r])=>r!=="id"&&r!=="v"&&r!=="userId"&&r!=="userName");if(t.length!==1)return null;let n=t[0]?.[1];if(typeof n!="object"||n===null)return null;let o=n.id;return typeof o=="string"&&o.length>0?o:null},Vh=/^[0-9a-hjkmnp-tv-z]{26}$/i,Kh=e=>Vh.test(e)?e.toUpperCase():e,Yh=e=>{let t=xs.basename(e,".jsonl"),n=t.indexOf("."),o=n===-1?t:t.slice(0,n),r=n===-1?void 0:t.slice(n+1),s=zh.safeParse({userId:Kh(o),userName:r});return s.success?l("Parsed event file actor",s.data):i(`Invalid event file name ${xs.basename(e)}: ${s.error.issues.map(d=>d.path.join(".")||d.message).join(", ")}`)},Xh=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?i(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?i("Invalid persisted event: action key is missing or invalid"):l("Resolved persisted action",t[0])},Jh=(e,t)=>t in e,Qh=({id:e,action:t,payload:n,userId:o,userName:r})=>({id:e,action:t,payload:n,userId:o,userName:r}),Zh=e=>{let{userId:t,userName:n,...o}=e,r=Xh(o);if(a(r))return i(r.message);let s=r.value,d=e.id?.[0];return d?Jh(o,s)?l("Decoded persisted event",Qh({id:d,action:s,payload:o[s],userId:t,userName:n})):i(`Persisted event is missing payload for action: ${s}`):i("Persisted event is missing id")},oa=(e,t)=>{let n=[],o=new Map,r=new Map;for(let s of e){if(!El(s.v)){r.set(s.v,(r.get(s.v)??0)+1),t?.push({eventId:s.id[0],reason:"unsupported-schema-version",detail:`v${s.v}`,targetNodeId:bs(s)});continue}let d=Zh(s);if(a(d)){t?.push({eventId:s.id[0],reason:"invalid-payload",detail:d.message,targetNodeId:bs(s)});continue}let c=d.value.action;if(!gl(c)){o.set(c,(o.get(c)??0)+1),t?.push({eventId:s.id[0],reason:"unknown-action",detail:c,targetNodeId:bs(s)});continue}let u=hl(c,d.value.payload);if(a(u)){t?.push({eventId:s.id[0],reason:"invalid-payload",detail:u.message,targetNodeId:bs(s)});continue}n.push(d.value)}if(o.size>0){let s=[...o.entries()].map(([d,c])=>`${d} (x${c})`).join(", ");X.info(`Skipped events with unknown actions, likely created by a newer epiq version: ${s}. Upgrade to apply them.`)}if(r.size>0){let s=[...r.entries()].map(([d,c])=>`v${d} (x${c})`).join(", ");X.info(`Skipped events with unsupported schema versions, created by a newer epiq version: ${s}. Upgrade to apply them.`)}return l("Decoded reconstructed events",n)},ev=(e,t)=>{if(!Is.existsSync(e))return l("Event file missing",[]);let n=Yh(e);if(a(n))return i(n.message);let o=Is.readFileSync(e,"utf8"),r=[],s=xs.basename(e),d=(c,u)=>{t?.push({eventId:null,reason:"corrupt-line",detail:`${s}:${c} (${u})`,targetNodeId:null})};for(let[c,u]of o.split(`
|
|
23
|
-
`)
|
|
24
|
-
`,"utf8"),n&&(n.current=c);let p=Sl.basename(s.value);return bl(t,p,c),pl(t,p),l("Event persisted",{path:s.value,entry:m.value})}catch(r){let s=r instanceof Error?r.message:"Unknown persist error";return i(`Failed to persist event: ${s}`)}}var Nl,Rl,av,dv,cv,Al,lv,uv,xl,mv,pv,El,gv,ne,qn,fv,hv,Se=h(()=>{"use strict";ht();Mn();R();Be();ae();cl();et();bt();mr();Zi();Nl=1,Rl=iv(),av=0xffffffffffff,dv=Zr,cv=e=>{let t=Date.now(),n;try{n=sv(e)}catch{return t}return n>=av?t:n>t+dv?(X.error("[persist] edge id is too far in the future; seeding from the wall clock instead",{edgeRef:e,edgeTime:n,now:t}),t):Math.max(t,n+1)},Al=Wn.tuple([Wn.string().min(1),Wn.string().min(1).nullable()]),lv=Wn.looseObject({v:Wn.literal(Nl),id:Al}),uv=Wn.looseObject({v:Wn.number().int().positive(),id:Al}),xl=e=>{let t=uv.safeParse(e);return t.success?l("Parsed persisted event envelope",t.data):i(`Invalid persisted event envelope: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},mv=[1],pv=new Set(mv),El=e=>pv.has(e),gv=e=>{let t=lv.safeParse(e);return t.success?l("Parsed persisted event",t.data):i(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},ne=()=>{let{userName:e,userId:t}=Ie();return e?t?Qr(t)?Vo(e)?l("Successfully resolved actor ID",{userId:t,userName:e}):i("Invalid user name in config"):i("Invalid user ID in config"):i("User ID not configured"):i("User name not configured")},qn=({userId:e,userName:t})=>`${Ji(e)}.${Ji(t)}.jsonl`,fv=(e,{userId:t,userName:n})=>{let o=qn({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(o))return i(`Invalid event log file name: ${o}`);let s=Sl.join(Bn(e),o);return l("Successfully resolved event log path",s)},hv=(e,t)=>{let n={[e.action]:e.payload,v:Nl,id:t};return gv(n)}});import{ulid as vv}from"ulid";function Cl(e,t,n){let o=aa(t,n);if(a(o))return i(o.message);let r={...e,id:o.value[0]},s=hn(r);if(s.status!==Vt.Success)return s;let d=Es({event:r,rootDir:t,edge:n,id:o.value});return a(d)?d:s}function L(e,t){if(e.length===0||!e[0])return i("No events provided");if(g().readOnly)return i(g().readOnlyReason??"Cannot change the board while time travelling");let n={},o=yv(e[0],t,n);if(a(o))return o;let r=e.map(d=>Cl(d,t,n)),s=r.filter(a);return s.length>0?i("Materialize and persist failed: "+s.map(d=>d.message).join(", ")):l("Materialization succeeded",r.map(d=>d.value))}var yv,xe=h(()=>{"use strict";R();te();M();Zt();Se();yv=(e,t,n)=>{if(e.action==="create.contributor"||e.action==="rename.contributor")return l("Contributor write already in flight",void 0);let o=I.getContributor(e.userId),r={id:vv(),action:o?"rename.contributor":"create.contributor",payload:{id:e.userId,name:e.userName},userId:e.userId,userName:e.userName};if(o&&(o.tombstoned||o.name===e.userName))return l("Contributor name is current",void 0);let s=Cl(r,t,n);return a(s)?i(s.message):l("Contributor name recorded",void 0)}});var Gn,da,wl=h(()=>{"use strict";st();Gn=e=>e.trim().toLocaleLowerCase(),da=(e,t)=>Gn(e).includes(Gn(t))});var bv,Iv,Tl,Ml,xv,Ev,kl,Pl=h(()=>{"use strict";M();st();wl();bv=e=>{let{tags:t}=g();return(e.props.tags??[]).map(n=>t[n]).filter(n=>n!==void 0&&!n.tombstoned).map(n=>n.name)},Iv=e=>{let{contributors:t}=g();return(e.props.assignees??[]).map(n=>{let o=t[n];return o?o.name:void 0}).filter(n=>!!n)},Tl=null,Ml=new Map,xv=()=>{let e=g().eventLog??[];if(e===Tl)return Ml;let t=new Map;for(let n of e){if(!n.userId)continue;let o=n.payload;for(let r of[o.id,o.issue]){if(typeof r!="string")continue;let s=t.get(r)??new Set;s.add(n.userId),t.set(r,s)}}return Tl=e,Ml=t,t},Ev=e=>{let{contributors:t}=g(),n=xv().get(e.id);return n?[...n].map(o=>t[o]?.name).filter(o=>!!o):[]},kl=(e,t)=>{let n=Gn(t.value);if(!n)return!0;switch(t.target){case"title":return da(e.title??"",n);case"description":return da(e.props.description??"",n);case"tag":return bv(e).map(Gn).some(r=>r.includes(n));case"assignee":return Iv(e).map(Gn).some(r=>r.includes(n));case"actor":return Ev(e).map(Gn).some(r=>r.includes(n));case"ref":return dr(e.id,t.value);default:return!0}}});var Ll,Rv,Dl,Fl,ca=h(()=>{"use strict";V();Pl();Ll=(e,t)=>e.rank.localeCompare(t.rank),Rv=(e,t)=>!!e&&!e.isDeleted&&e.parentNodeId===t,Dl=(e,t)=>Object.values(e).filter(n=>Rv(n,t)).sort(Ll),Fl=(e,t)=>{let n={};for(let o of Object.values(e)){if(k(o)&&t.length>0&&!t.every(s=>kl(o,s))||!o.parentNodeId||o.isDeleted)continue;let r=n[o.parentNodeId];r?r.push(o):n[o.parentNodeId]=[o]}for(let o of Object.keys(n))n[o].sort(Ll);return n}});var _l,Rs,ge,Bl,Ol,Dt,bn,pt=h(()=>{"use strict";_c();xe();R();M();ca();ao();_l=e=>Rs(ge(e),{at:"end"}),Rs=(e,t={at:"end"})=>{let n=r=>a(r)?l("Rank space exhausted",{rank:"",needsRebalance:!0}):l("Resolved rank",{rank:r.value,needsRebalance:!1});if(e.length===0)return n(Oe(void 0,void 0));let o=()=>n(Oe(e[e.length-1]?.rank,void 0));switch(t.at){case"start":{let r=e[0];return r?n(Oe(void 0,r.rank)):i("Unable to resolve first sibling")}case"end":{let r=e[e.length-1];return r?n(Oe(r.rank,void 0)):i("Unable to resolve last sibling")}case"before":{let r=Bl(e,t.sibling),s=r<0?void 0:e[r];if(!s)return o();let d=r>0?e[r-1]:void 0;return n(Oe(d?.rank,s.rank))}case"after":{let r=Bl(e,t.sibling),s=r<0?void 0:e[r];if(!s)return o();let d=r<e.length-1?e[r+1]:void 0;return n(Oe(s.rank,d?.rank))}}},ge=e=>{let t=g();if(!Ul()&&t.filters.length===0){let n=t.renderedChildrenIndex[e];if(n)return n}return Dl(t.nodes,e)},Bl=(e,t)=>e.findIndex(n=>n.id===t),Ol=(e,t,n={at:"end"})=>Rs(ge(t).filter(o=>o.id!==e),n),Dt=(e,t,n,o,r)=>{let s=Ol(t,e,n);if(a(s))return s;if(!s.value.needsRebalance)return l("Resolved rank",s.value.rank);let d=Di(e,o);if(a(d))return d;let c=L([d.value],r);if(a(c))return c;let u=Ol(t,e,n);return a(u)?u:u.value.needsRebalance?i("Rank rebalance failed to create space"):l("Resolved rank after rebalance",u.value.rank)},bn=(e,t,n)=>{let o=_l(e);if(a(o))return o;if(!o.value.needsRebalance)return l("Resolved rank",o.value.rank);let r=Di(e,t);if(a(r))return r;let s=L([r.value],n);if(a(s))return s;let d=_l(e);return a(d)?d:d.value.needsRebalance?i("Rank rebalance failed to create space"):l("Resolved rank after rebalance",d.value.rank)}});var U,$l,jl,it=h(()=>{"use strict";M();U={exit(){process.exit(0)},enterChildNode(){let e=g(),t=e.contextNode,n=Math.max(0,e.selectedIndex),o=oe(t.id),r=o[n];r&&(t.context==="FIELD"&&o.length===0||r.context==="COMMENT"||r.context==="TEXT"||U.navigate({contextNode:r,selectedIndex:oe(r.id).length?0:-1}))},enterParentNode(){let{contextNode:e,nodes:t}=g();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let o=oe(n.id),r=o.findIndex(({id:d})=>d===e.id),s=o.length===0?-1:r>=0?r:0;U.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>$l(1),navigateToPreviousItem:()=>$l(-1),navigateToNextContainer:()=>jl(1),navigateToPreviousContainer:()=>jl(-1),navigate:({contextNode:e,selectedIndex:t})=>{E({contextNodeId:e.id,selectedIndex:t})}},$l=e=>{let{selectedIndex:t,contextNode:n}=g(),o=oe(n.id).length;if(o===0)return;let s=(Math.max(0,t)+e+o)%o;U.navigate({selectedIndex:s,contextNode:n})},jl=e=>{let{contextNode:t,nodes:n,selectedIndex:o}=g();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let r=n[t.parentNodeId];if(!r)return;let s=oe(r.id),d=s.findIndex(x=>x.id===t.id);if(d<0)return;let c=s.at(d+e)??s.at(0);if(!c)return;let u=oe(c.id),m=Math.max(0,u.length-1),p=Math.min(Math.max(0,o),m),f=u.length?p:-1;U.navigate({contextNode:c,selectedIndex:f})}});var Wl,ql,Sv,Ss,Gl,Hl,Nv,zl,Vl=h(()=>{"use strict";V();R();pt();M();it();Wl=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),ql=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=g();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},Sv=e=>{let t=g().nodes[e];return!!t&&!t.isDeleted&&nt(t)&&t.childRenderAxis==="vertical"},Ss=(e,t)=>{let{nodes:n}=g(),o=n[e];if(!o||o.isDeleted)return!1;let r=ge(o.id);return U.navigate({contextNode:o,selectedIndex:Wl(t,r.length)}),!0},Gl=e=>{let{nodes:t}=g(),n=t[e];if(!n||n.isDeleted)return!1;let o=n.parentNodeId;if(!o)return Ss(n.id,0);let r=t[o];if(!r||r.isDeleted)return!1;let d=ge(r.id).findIndex(c=>c.id===n.id);return d>=0?(U.navigate({contextNode:r,selectedIndex:d}),!0):Gl(r.id)},Hl=e=>{let{nodes:t}=g(),n=e,o=new Set;for(;n&&!o.has(n);){if(o.add(n),Gl(n))return!0;n=t[n]?.parentNodeId}return!1},Nv=e=>{if(!e)return!1;let t=g().nodes[e];return!!t&&!t.isDeleted},zl=e=>{let{nodes:t,rootNodeId:n}=g();if(Sv(e.contextNodeId)&&Ss(e.contextNodeId,e.selectedIndex))return l("Restored navigation inside text container",null);if(Nv(e.selectedNodeId)&&e.selectedNodeId&&Hl(e.selectedNodeId))return l("Restored navigation to selected node or ancestor",null);if(Ss(e.contextNodeId,e.selectedIndex))return l("Restored navigation to previous container",null);if(e.parentNodeId&&Ss(e.parentNodeId,e.selectedIndex))return l("Restored navigation to previous parent",null);if(Hl(e.contextNodeId))return l("Restored navigation to previous container or ancestor",null);let o=t[n];if(!o||o.isDeleted)return i("Unable to restore navigation");let r=ge(o.id);return U.navigate({contextNode:o,selectedIndex:Wl(e.selectedIndex,r.length)}),l("Restored navigation to root",null)}});import{monotonicFactory as Av,ulid as Ft}from"ulid";function Cv(){let e=$e();if(a(e))return i("Unable to boot. State not initialized");let t=e.value,n=Object.values(t.nodes).find(s=>s.context==="WORKSPACE");if(!n)return i("No workspace found in event log");let[o]=oe(n.id),[r]=o?oe(o.id):[];if(r){let s=t.renderedChildrenIndex?.[r.id]??[];return l("Resolved boot nav target",{contextNode:r,selectedIndex:s.length>0?0:-1})}else return o?l("Resolved boot nav target",{contextNode:o,selectedIndex:0}):l("Resolved boot nav target",{contextNode:n,selectedIndex:0})}function wv(){let e=Cv();return a(e)?e:U.navigate(e.value)}function Kl({userId:e,userName:t}){let n=gr(),o=gr(),r=gr(),s=gr(),d=gr(),c=Oe(void 0,void 0);if(a(c))return c;let u=Oe(void 0,void 0);if(a(u))return u;let m=Oe(u.value,void 0);if(a(m))return m;let p=Oe(void 0,void 0);if(a(p))return p;let f=Oe(p.value,void 0);if(a(f))return f;let x=Oe(f.value,void 0);if(a(x))return x;let S=Oe(void 0,void 0);return a(S)?S:l("Created default events",[{id:Ft(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:c.value}},{id:Ft(),userId:e,userName:t,action:"create.contributor",payload:{id:e,name:t}},{id:Ft(),userId:e,userName:t,action:"add.board",payload:{id:o,name:"Default",parent:n,rank:u.value}},{id:Ft(),userId:e,userName:t,action:"add.swimlane",payload:{id:r,name:"Todo",parent:o,rank:p.value}},{id:Ft(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"In progress",parent:o,rank:f.value}},{id:Ft(),userId:e,userName:t,action:"add.swimlane",payload:{id:d,name:"Done",parent:o,rank:x.value}},{id:Ft(),userId:e,userName:t,action:"add.board",payload:{id:fs,name:"Closed",parent:n,rank:m.value}},{id:Ft(),userId:e,userName:t,action:"add.swimlane",payload:{id:fe,name:"Closed",parent:fs,rank:S.value}},{id:Ft(),userId:e,userName:t,action:"lock.node",payload:{id:fs}},{id:Ft(),userId:e,userName:t,action:"lock.node",payload:{id:fe}}])}function _t(e,t=[]){if(Tv())return l("Skipped boot while checked out at a historical point",null);if(!e.length){let s=Te.workspace("temporary-uninitialized-workspace","Workspace","a0"),d=ur(s);return a(d)?d:(E({hasProjectDefinition:!1,mode:y.DEFAULT}),l("Booted uninitialized workspace placeholder",null))}if(!e.some(s=>s.action==="init.workspace"))return i("Initialized Epiq project has no workspace init event");let n=Qt(e),{fatal:o,skipped:r}=Un(n);return o.length>0?i(`Materializing failed:
|
|
36
|
+
`;Mt.writeFileSync(e,o,"utf8")}function ba(e,t,n=!1){let o=cy();if(!o)return;let r=my(ay.format(...t)),s=new Date,c=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${r}
|
|
37
|
+
`;try{Mt.mkdirSync(Ia.dirname(o),{recursive:!0}),Mt.appendFileSync(o,c,"utf8"),ya++,(ya>=dy||Mt.statSync(o).size>Ea)&&(ya=0,uy(o))}catch{}}var eu,Ea,va,dy,ya,tu,cy,ly,my,xa,J,xt=h(()=>{"use strict";R();ae();eu=500,Ea=4*1024*1024,va=16*1024,dy=50,ya=0,tu=()=>process.env.EPIQ_MCP==="true",cy=()=>{let e=process.cwd(),t=Ls(e);return d(t)?tu()?Ia.join(on(),"epiq-mcp.log"):void 0:Ia.join(t.value,Ge,"log","epiq.log")},ly=(e,t)=>{let n=Mt.statSync(e).size;if(n<=t)return Mt.readFileSync(e,"utf8");let o=Mt.openSync(e,"r");try{let r=Buffer.alloc(t);Mt.readSync(o,r,0,t,n-t);let s=r.toString("utf8"),i=s.indexOf(`
|
|
38
|
+
`);return i===-1?"":s.slice(i+1)}finally{Mt.closeSync(o)}};my=e=>{if(e.length<=va)return e;let t=e.length-va;return`${e.slice(0,va)} \u2026 [${t} more chars]`};xa=()=>tu()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",J={info(...e){let t=xa();(t==="info"||t==="debug")&&ba("[Info]",e,!1)},debug(...e){xa()==="debug"&&ba("[Debug]",e,!0)},error(...e){let t=xa();if(t==="error"||t==="info"||t==="debug"){let o=e.some(r=>r instanceof Error)?void 0:new Error().stack;ba("[Error]",[...e,o].filter(Boolean),!1)}}};globalThis.logger=J});var ue,Io=h(()=>{"use strict";ue={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments",ATTACHMENTS:"Attachments"}});var j,Cr,Je=h(()=>{"use strict";j=e=>e.slice(-7).toUpperCase(),Cr=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?j(e).includes(n):!0}});var Pe,Gn=h(()=>{"use strict";K();Je();Pe={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:V.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,o,r=!1)=>({id:e,title:t,rank:o,isDeleted:!1,props:{ref:j(e)},context:V.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:r,log:[]}),swimlane:(e,t,n,o)=>({id:e,title:t,rank:o,isDeleted:!1,props:{},context:V.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:o,props:r={},childRenderAxis:s="horizontal",isVirtual:i=!1})=>({id:e,title:t,rank:o,isDeleted:!1,props:r,context:V.FIELD,childRenderAxis:s,parentNodeId:n,readonly:!1,log:[],isVirtual:i}),fieldList:({id:e,name:t,parentNodeId:n,rank:o,childRenderAxis:r="horizontal",isVirtual:s=!1})=>({id:e,title:t,rank:o,isDeleted:!1,props:{},context:V.FIELD_LIST,childRenderAxis:r,parentNodeId:n,readonly:!1,log:[],isVirtual:s}),ticket:(e,t,n,o)=>({id:e,title:t,rank:o,isDeleted:!1,props:{ref:j(e)},context:V.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:o,readonly:r=!0,isVirtual:s=!0})=>({id:e,title:t,rank:o,isDeleted:!1,props:{},context:V.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:r,log:[],isVirtual:s}),comment:({id:e,name:t,parentNodeId:n,rank:o,props:r={},readonly:s=!0,isVirtual:i=!0})=>({id:e,title:t,rank:o,isDeleted:!1,props:r,context:V.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:i})}});var py,he,Ds,dn=h(()=>{"use strict";py=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[he,Ds]=py});function Nn(e,t=!1){let n=xy[e.action];if(!n)return a(`Unknown event action "${e.action}", likely created by a newer epiq version. Evt id: ${e.id}`);if(!It()&&e.action!=="init.workspace")return F(`${e.action} arrived before the workspace was initialized`,e);if(e.action==="init.workspace"&&Qe){if(Qe.genesisApplied)return F("the workspace is already initialized",e);Qe.genesisApplied=!0}let o;try{o=n(e)}catch(s){return F(`threw while materializing (${s instanceof Error?s.message:String(s)})`,e)}if(d(o))return o;let r=by(e,t);return r||o}var Sa,F,wr,zn,Vn,nu,ou,fy,gy,Ra,hy,vy,Qe,yy,by,Ar,xy,cn,ln=h(()=>{"use strict";xt();K();R();Io();ne();Gn();M();Na();dn();Sa=(e,t)=>a(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),F=(e,t)=>({...Sa(e,t),convergence:!0}),wr=e=>d(e)&&e.convergence===!0,zn=e=>{let t=e.filter(d);return{fatal:t.filter(n=>!wr(n)),skipped:t.filter(wr)}},Vn=e=>{e.length!==0&&J.info(`Skipped ${e.length} event(s) that could not be applied to this state: ${e.map(t=>t.message).join("; ")}`)},nu=e=>{let t=E.getNode(e);if(!t||!P(t)||t.isDeleted)return null;let n=Fs(t);return d(n)?n:null},ou=e=>{if(!_s())return null;for(let t of e){let n=nu(t);if(n)return n;let o=g().nodes[t]?.parentNodeId;if(!o)continue;let r=nu(o);if(r)return r}return null},fy=(e,t)=>{let n=E.getNode(e);n&&E.updateNode({...n,log:[...n.log??[],t]})},gy=e=>{let t=[e],n=g().nodes[e]?.parentNodeId;return n&&t.push(n),t},Ra=e=>{switch(e.action){case"add.issue.comment":case"edit.issue.comment":case"delete.issue.comment":case"add.issue.attachment":case"delete.issue.attachment":return[e.payload.issue];case"delete.node":case"edit.description":return gy(e.payload.id);case"init.workspace":case"add.workspace":case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"edit.title":case"lock.node":case"move.node":case"close.issue":case"reopen.issue":case"add.issue.tag":case"remove.issue.tag":case"add.issue.assignee":case"remove.issue.assignee":return[e.payload.id];case"rebalance.children":return Object.keys(e.payload.ranks);case"create.tag":case"tombstone.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"link.contributor.user":default:return[]}},hy=e=>{Ne(t=>({...t,eventLog:[...t.eventLog,e]}))},vy=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?Sa("Invalid user ID format",e):l("Valid user",null)},Qe=null,yy=e=>{for(let[t,n]of e.nodeLog){let o=E.getNode(t);o&&E.updateNode({...o,log:[...o.log??[],...n]})}return e.appLog.length>0&&Ne(t=>({...t,eventLog:[...t.eventLog,...e.appLog]})),ou([...e.virtualNodeIds])},by=(e,t)=>{let n=vy(e);if(d(n))return n;let o=[...new Set(Ra(e))];if(Qe){for(let s of o){if(!t){let i=Qe.nodeLog.get(s);i?i.push(e):Qe.nodeLog.set(s,[e])}if(_s()){Qe.virtualNodeIds.add(s);let i=g().nodes[s]?.parentNodeId;i&&Qe.virtualNodeIds.add(i)}}return t||Qe.appLog.push(e),null}t||(o.forEach(s=>fy(s,e)),hy(e));let r=ou(o);return r||null},Ar=(e,t,n)=>E.getNode(e)?F(`a node with id ${e} already exists`,n):t===e?F("a node cannot be its own parent",n):null,xy={"init.workspace":e=>{let{id:t,name:n,rank:o}=e.payload,r=Pe.workspace(t,n,o),s=Tr(r);if(d(s))return Sa(s.message,e);let i=E.createNode(r);return d(i)?F(i.message??"Failed to initialize workspace",e):ra(i.value)?l("Workspace initialized",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:o}=e.payload,r=Ar(t,void 0,e);if(r)return r;let s=E.createNode(Pe.workspace(t,n,o));return d(s)?F(s.message??"Failed to add workspace",e):ra(s.value)?l("Added workspace",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:o,rank:r}=e.payload,s=Ar(t,o,e);if(s)return s;let i=E.createNode(Pe.board(t,n,o,r));return d(i)?F(i.message??"Unable to create board",e):gr(i.value)?l("Added board",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:o,rank:r}=e.payload,s=Ar(t,o,e);if(s)return s;let i=E.createNode(Pe.swimlane(t,n,o,r));return d(i)?F(i.message??"Unable to create swimlane",e):Sn(i.value)?l("Added swimlane",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:o,rank:r}=e.payload,s=Ar(t,o,e);if(s)return s;let i=E.createNode(Pe.ticket(t,n,o,r));return d(i)?F(i.message??"Unable to create issue",e):P(i.value)?l("Added issue",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:o,val:r,rank:s}=e.payload,i=Ar(t,o,e);if(i)return i;let c=E.createNode(Pe.field({id:t,name:n,parentNodeId:o,rank:s,props:{value:r},childRenderAxis:n.includes(ue.DESCRIPTION)?"vertical":"horizontal"}));return d(c)?F(c.message??`Unable to create field: ${n}`,e):at(c.value)?l("Added field",{action:e.action,result:c.value}):a("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!E.getNode(t))return F(`Unable to locate node with id ${t}`,e);let r=E.renameNode(t,n);return d(r)?F(r.message??"Unable to edit title",e):l("Edited title",{action:e.action,result:r.value})},"delete.node":e=>{let{id:t}=e.payload,n=E.tombstoneNode(t);return d(n)?F(n.message??"Unable to delete node",e):l("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,o=E.createTag({id:t,name:n});return d(o)?F(o.message??"Unable to create tag",e):l("Tag added",{action:e.action,result:o.value})},"tombstone.tag":e=>{let{id:t}=e.payload,n=E.tombstoneTag(t);return d(n)?F(n.message??"Unable to delete tag",e):l("Tag tombstoned",{action:e.action,result:n.value})},"restore.tag":e=>{let{id:t,name:n}=e.payload,o=E.restoreTag(t,n);return d(o)?F(o.message??"Unable to restore tag",e):l("Tag restored",{action:e.action,result:o.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,o=E.createContributor({id:t,name:n});return d(o)?F(o.message??"Unable to create contributor",e):l("Contributor created",{action:e.action,result:o.value})},"rename.contributor":e=>{let{id:t,name:n}=e.payload,o=E.renameContributor(t,n);return d(o)?F(o.message??"Unable to rename contributor",e):l("Contributor renamed",{action:e.action,result:o.value})},"tombstone.contributor":e=>{let{id:t}=e.payload,n=E.tombstoneContributor(t);return d(n)?F(n.message??"Unable to remove contributor",e):l("Contributor tombstoned",{action:e.action,result:n.value})},"restore.contributor":e=>{let{id:t,name:n}=e.payload,o=E.restoreContributor(t,n);return d(o)?F(o.message??"Unable to restore contributor",e):l("Contributor restored",{action:e.action,result:o.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,o=E.tag(t,n);return d(o)?F(o.message??"Unable to tag issue",e):l("Issue tagged",{action:e.action,result:{tag:n}})},"remove.issue.tag":e=>{let{id:t,tag:n}=e.payload,o=E.untag(t,n);return d(o)?F(o.message??"Unable to untag issue",e):l("Issue untagged",{action:e.action,result:{tag:n}})},"add.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,o=E.assign(t,n);return d(o)?F(o.message??"Unable to assign issue",e):l("Assigned successfully",{action:e.action,result:{assignee:n}})},"remove.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,o=E.unassign(t,n);return d(o)?F(o.message??"Unable to unassign issue",e):l("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:o}=e.payload,r=E.moveNodeToRank({id:t,parentId:n,rank:o});return d(r)?F(r.message??"Failed to move node",e):l("Moved node",{action:e.action,result:r.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,o=E.editValue(t,n);return d(o)?F(o.message??"Unable to edit description",e):l("Set node value",{action:e.action,result:o.value})},"close.issue":e=>{let{id:t,parent:n,rank:o}=e.payload,r=E.getNode(t);if(!r)return F("Unable to locate issue",e);if(!P(r))return F("Can only close issues",e);let s=E.getNode(he);if(!s)return F("Unable to locate target swimlane",e);if(n!==s.id)return F("Close target must be closed swimlane",e);let i=E.moveNodeToRank({id:t,parentId:n,rank:o});return d(i)?F(i.message??"Unable to close issue",e):l("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:o}=e.payload,r=E.getNode(t);if(!r)return F("Unable to locate issue",e);if(!P(r))return F("Can only reopen issues",e);let s=E.getNode(he);if(!s)return F("Unable to locate closed swimlane",e);if(n===s.id)return F("Cannot reopen issue into closed swimlane",e);if(!E.getNode(n))return F("Reopen parent no longer exists",e);let c=E.moveNodeToRank({id:t,parentId:n,rank:o});return d(c)?F(c.message??"Unable to reopen issue",e):l("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=E.lockNode(t);return d(n)?F(n.message??"Unable to lock node",e):l("Node locked",{action:e.action,result:n.value})},"rebalance.children":e=>{let{parent:t,ranks:n}=e.payload;for(let[o,r]of Object.entries(n)){let s=E.getNode(o);if(!s)return F(`Unable to locate node ${o}`,e);if(s.parentNodeId!==t)return F(`Node ${o} is not child of ${t}`,e);let i=E.updateNode({...s,rank:r});if(d(i))return F(i.message??"Unable to rebalance child",e)}return l("Rebalanced children",{action:e.action,result:{parent:t}})},"add.issue.comment":e=>{let{id:t,issue:n,author:o,md:r}=e.payload,s=E.createComment({id:t,issue:n,authorId:o,authorName:E.getContributor(o)?.name??"Unknown",md:r,deleted:!1});return d(s)?F(s.message??"Unable to add comment",e):l("Comment added",{action:e.action,result:{id:t,issue:n,author:o,md:r}})},"edit.issue.comment":e=>{let{id:t,issue:n,md:o}=e.payload,r=E.getComment(t);if(!r)return F("Unable to locate comment",e);if(r.issue!==n)return F("Comment does not belong to issue",e);let s=E.editComment(t,o);return d(s)?F(s.message??"Unable to edit comment",e):l("Comment edited",{action:e.action,result:{id:t,issue:n,md:o}})},"delete.issue.comment":e=>{let{id:t,issue:n}=e.payload,o=E.getComment(t);if(!o)return F("Unable to locate comment",e);if(o.issue!==n)return F("Comment does not belong to issue",e);let r=E.deleteComment(t);return d(r)?F(r.message??"Unable to delete comment",e):l("Comment deleted",{action:e.action,result:{id:t,issue:n}})},"add.issue.attachment":e=>{let{id:t,issue:n,hash:o,ext:r,name:s,bytes:i}=e.payload,c=E.createAttachment({id:t,issue:n,hash:o,ext:r,name:s,bytes:i,deleted:!1});return d(c)?F(c.message??"Unable to add attachment",e):l("Attachment added",{action:e.action,result:{id:t,issue:n,hash:o}})},"delete.issue.attachment":e=>{let{id:t,issue:n}=e.payload,o=E.getAttachment(t);if(!o)return F("Unable to locate attachment",e);if(o.issue!==n)return F("Attachment does not belong to issue",e);let r=E.deleteAttachment(t);return d(r)?F(r.message??"Unable to delete attachment",e):l("Attachment deleted",{action:e.action,result:{id:t,issue:n}})},"link.contributor.user":e=>{let{contributor:t}=e.payload,n=E.linkUserId({contributorId:t,userId:e.userId});return d(n)?F(n.message??"Unable to link contributor",e):l("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};cn=e=>{let t=ru(()=>{let n=Qe===null;n&&(Qe={appLog:[],nodeLog:new Map,virtualNodeIds:new Set,genesisApplied:!1});try{let o=e.map(r=>Nn(r));if(n&&Qe){let r=yy(Qe);if(r)return e.map(()=>r)}return o}finally{n&&(Qe=null)}});return d(t)?e.map(()=>a(t.message)):t.value}});var Ca,su=h(()=>{"use strict";Ca=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/\.jsonl/g,"-jsonl").replace(/^-+|-+$/g,"")||"unknown"});import Ee from"node:fs";import Kn from"node:path";import{ulid as Iy}from"ulid";var Bs,Aa,au,du,wa,cu,lu,Us,uu,Ey,Sy,mu,Ry,pu,Ny,fu,Cy,Os,iu,$s,Yn=h(()=>{"use strict";R();ae();Bs="~pending",Aa=/~pending(-[0-9a-z]+)*$/i,au=/-f(\d+)$/,du=e=>{let t=e.indexOf(".");return t===-1?`${e}${Bs}`:e.slice(0,t)+Bs+e.slice(t)},wa=e=>{let t=e.indexOf(".");return t===-1?[e,""]:[e.slice(0,t),e.slice(t)]},cu=e=>{let[t,n]=wa(e);return Aa.test(t)?t.replace(Aa,"")+n:null},lu=e=>e.replace(Aa,""),Us=e=>e.endsWith(".jsonl")&&cu(e)!==null,uu=e=>{let[t]=wa(e),n=au.exec(t);return n&&Us(e)?Number(n[1]):null},Ey=e=>du(e).replace(Bs,`${Bs}-${Iy().toLowerCase()}`),Sy=(e,t)=>{let[n,o]=wa(e);return`${n.replace(au,"")}-f${t}${o}`},mu=(e,t)=>Kn.join(kt(e),du(t)),Ry=(e,t)=>Math.max(0,Ee.statSync(e).size-(uu(t)??0)),pu=e=>{let t=kt(e);try{return Ee.existsSync(t)?Ee.readdirSync(t).filter(Us).some(n=>Ry(Kn.join(t,n),n)>0):!1}catch{return!0}},Ny=3,fu=(e,t)=>{for(let n=1;;n++){let o=Ee.openSync(e,"a"),r;try{Ee.writeSync(o,t),r=Ee.fstatSync(o).ino}finally{Ee.closeSync(o)}let s;try{s=Ee.statSync(e).ino}catch{s=null}if(s===r||n>=Ny)return}},Cy=e=>{let t;try{t=Ee.openSync(e,"r")}catch{return!0}try{let{size:n}=Ee.fstatSync(t);if(n===0)return!0;let o=Buffer.alloc(1);return Ee.readSync(t,o,0,1,n-1),o[0]===10}finally{Ee.closeSync(t)}},Os=10,iu=(e,t,n=!1)=>{let o=n?t.length:t.lastIndexOf(Os)+1;if(o===0)return{bytes:0,lines:0};let r=t.subarray(0,o);if(r.toString("utf8").trim().length===0)return{bytes:o,lines:0};Ee.appendFileSync(e,Buffer.concat([Buffer.from(Cy(e)?"":`
|
|
39
|
+
`),r,Buffer.from(r[r.length-1]===Os?"":`
|
|
40
|
+
`)]));let s=0;for(let i of r)i===Os&&s++;return r[r.length-1]!==Os&&s++,{bytes:o,lines:s}},$s=(e,t)=>{let n=kt(e);if(!Ee.existsSync(n))return l("No events directory",0);try{let o=Ee.readdirSync(n).filter(i=>cu(i)===t),r=Kn.join(n,t),s=0;for(let i of o){let c=uu(i);if(c!==null){let f=Kn.join(n,i),y=Ee.readFileSync(f).subarray(c);s+=iu(r,y,!0).lines,Ee.rmSync(f,{force:!0});continue}let u=/~pending-/i.test(i)?i:Ey(t),m=Kn.join(n,u);u!==i&&Ee.renameSync(Kn.join(n,i),m);let p=iu(r,Ee.readFileSync(m));s+=p.lines,Ee.renameSync(m,Kn.join(n,Sy(u,p.bytes)))}return l("Folded pending logs",s)}catch(o){return a(`Unable to fold pending event logs in ${n}: ${o instanceof Error?o.message:String(o)}`)}}});import{existsSync as Ay,readdirSync as wy,statSync as Ty}from"node:fs";import ky from"node:path";var Xn,gu,Ta,Cn,hu,vu,yu,kr=h(()=>{"use strict";ae();Xn=e=>{let t=kt(e);return Ay(t)?wy(t).filter(n=>n.endsWith(".jsonl")).sort().map(n=>{let{size:o,mtimeMs:r}=Ty(ky.join(t,n));return`${n}:${o}:${r}`}).join("|"):"none"},gu=e=>new Map(e.split("|").filter(Boolean).map(t=>{let n=t.indexOf(":");return[t.slice(0,n),t.slice(n+1)]})),Ta=(e,t,n)=>{let o=gu(t),r=Xn(e),s=gu(r);for(let[i,c]of s)if(i!==n&&o.get(i)!==c)return null;for(let i of o.keys())if(i!==n&&!s.has(i))return null;return r},Cn=null,hu=e=>Cn&&Cn.root===e?Cn.signature:null,vu=(e,t)=>{Cn={root:e,signature:t}},yu=(e,t)=>{if(!Cn||Cn.root!==e)return;let n=Ta(e,Cn.signature,t);Cn=n===null?null:{root:e,signature:n}}});var My,Py,bu,xu,ka=h(()=>{"use strict";My=["init.workspace","add.workspace","add.board","add.swimlane","add.issue","add.field","edit.title","delete.node","create.tag","tombstone.tag","restore.tag","create.contributor","rename.contributor","tombstone.contributor","restore.contributor","add.issue.assignee","remove.issue.assignee","add.issue.tag","remove.issue.tag","move.node","edit.description","add.issue.comment","edit.issue.comment","delete.issue.comment","add.issue.attachment","delete.issue.attachment","close.issue","reopen.issue","lock.node","rebalance.children","link.contributor.user"],Py=new Set(My),bu=e=>Py.has(e),xu=e=>({action:e.action,payload:e.payload})});import{z}from"zod";var q,Pt,An,js,Ma,Ly,Iu,Eu=h(()=>{"use strict";R();q=z.string().min(1),Pt=z.string(),An=z.string(),js=z.looseObject({id:q}),Ma=z.looseObject({id:q,name:Pt,parent:q,rank:An}),Ly={"init.workspace":z.looseObject({id:q,name:Pt,rank:An}),"add.workspace":z.looseObject({id:q,name:Pt,rank:An}),"add.board":Ma,"add.swimlane":Ma,"add.issue":Ma,"add.field":z.looseObject({id:q,name:Pt,parent:q,rank:An}),"edit.title":z.looseObject({id:q,name:Pt}),"delete.node":js,"lock.node":js,"move.node":z.looseObject({id:q,parent:q,rank:An}),"edit.description":z.looseObject({id:q,md:z.string()}),"close.issue":z.looseObject({id:q,parent:q,rank:An}),"reopen.issue":z.looseObject({id:q,parent:q,rank:An}),"create.tag":z.looseObject({id:q,name:Pt}),"tombstone.tag":js,"restore.tag":z.looseObject({id:q,name:Pt}),"create.contributor":z.looseObject({id:q,name:Pt}),"rename.contributor":z.looseObject({id:q,name:Pt}),"tombstone.contributor":js,"restore.contributor":z.looseObject({id:q,name:Pt}),"link.contributor.user":z.looseObject({contributor:q}),"add.issue.assignee":z.looseObject({id:q,assignee:q}),"remove.issue.assignee":z.looseObject({id:q,assignee:q}),"add.issue.tag":z.looseObject({id:q,tag:q}),"remove.issue.tag":z.looseObject({id:q,tag:q}),"add.issue.comment":z.looseObject({id:q,issue:q,md:z.string()}),"edit.issue.comment":z.looseObject({id:q,issue:q,md:z.string()}),"delete.issue.comment":z.looseObject({id:q,issue:q}),"add.issue.attachment":z.looseObject({id:q,issue:q,hash:z.string().min(1),ext:z.string().min(1),name:Pt,bytes:z.number()}),"delete.issue.attachment":z.looseObject({id:q,issue:q}),"rebalance.children":z.looseObject({parent:q,ranks:z.record(z.string(),An)})},Iu=(e,t)=>{let o=Ly[e].safeParse(t);return o.success?l("Payload is readable",void 0):a(`${e}: ${o.error.issues.map(r=>`${r.path.join(".")||"payload"} ${r.message}`).join(", ")}`)}});import Ws from"node:fs";import qs from"node:path";import{decodeTime as Dy}from"ulid";import{z as Pa}from"zod";function Mr(e,t){let n=kt(e),o=Xn(e);if(!Ws.existsSync(n))return l("No events found",[]);let r=Ws.readdirSync(n).filter(c=>c.endsWith(".jsonl")).map(c=>qs.join(n,c)),s=[];for(let c of r){let u=Wy(c,t);if(d(u))return a(u.message);s.push(...u.value)}let i=qy(s);return un={root:e,signature:o,edge:i.at(-1)?.id?.[0]??null},l("All events loaded",i)}function Et(e){let t=[],n=Mr(e,t);if(d(n))return a(n.message);let o=Da(n.value,t);return d(o)?a(o.message):l("Loaded merged events",{events:o.value,unreadable:t})}function Fa(e){let t=Mr(e);return d(t)?a(t.message):l("Loaded event actors",t.value.map(({userId:n,userName:o})=>({userId:n,userName:o})))}function Jn(e){let t=Et(e);return d(t)?a(t.message):l("Loaded merged events",t.value.events)}function _a(e,t){let n=Mr(e);if(d(n))return a(n.message);let{appliedEvents:o,unappliedEvents:r}=Gy(n.value,t),s=Da(o);if(d(s))return a(s.message);let i=Da(r);return d(i)?a(i.message):l("Loaded merged events before time",{appliedEvents:s.value,unappliedEvents:i.value})}function Su(e=process.cwd()){let t=Xn(e);if(un&&un.root===e&&un.signature===t)return l("Loaded edge reference, unchanged",un.edge);let n=Mr(e);return d(n)?a(n.message):l("Loaded edge reference",n.value.at(-1)?.id?.[0]??null)}function Ru(e,t,n){if(!un||un.root!==e)return;let o=Ta(e,un.signature,t);un=o===null?null:{root:e,signature:o,edge:n}}function Oa(e){let t=Mr(e);if(d(t))return a(t.message);let n=Nu(t.value);return l("Loaded effective event times",new Map(t.value.map((o,r)=>[o.id[0],n[r]??null])))}var Fy,Hs,_y,Oy,By,Uy,$y,jy,Hy,Da,Wy,un,La,qy,Nu,Gy,St=h(()=>{"use strict";xt();R();ae();kr();Ke();ka();Ce();Eu();Yn();Fy=Pa.object({userId:Pa.string().min(1).default("unknown"),userName:Pa.string().min(1).default("unknown")}),Hs=e=>{let t=Object.entries(e).filter(([r])=>r!=="id"&&r!=="v"&&r!=="userId"&&r!=="userName");if(t.length!==1)return null;let n=t[0]?.[1];if(typeof n!="object"||n===null)return null;let o=n.id;return typeof o=="string"&&o.length>0?o:null},_y=/^[0-9a-hjkmnp-tv-z]{26}$/i,Oy=e=>_y.test(e)?e.toUpperCase():e,By=e=>{let t=qs.basename(e,".jsonl"),n=t.indexOf("."),o=lu(n===-1?t:t.slice(0,n)),r=n===-1?void 0:t.slice(n+1),s=Fy.safeParse({userId:Oy(o),userName:r});return s.success?l("Parsed event file actor",s.data):a(`Invalid event file name ${qs.basename(e)}: ${s.error.issues.map(i=>i.path.join(".")||i.message).join(", ")}`)},Uy=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?a(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?a("Invalid persisted event: action key is missing or invalid"):l("Resolved persisted action",t[0])},$y=(e,t)=>t in e,jy=({id:e,action:t,payload:n,userId:o,userName:r})=>({id:e,action:t,payload:n,userId:o,userName:r}),Hy=e=>{let{userId:t,userName:n,...o}=e,r=Uy(o);if(d(r))return a(r.message);let s=r.value,i=e.id?.[0];return i?$y(o,s)?l("Decoded persisted event",jy({id:i,action:s,payload:o[s],userId:t,userName:n})):a(`Persisted event is missing payload for action: ${s}`):a("Persisted event is missing id")},Da=(e,t)=>{let n=[],o=new Map,r=new Map;for(let s of e){if(!Au(s.v)){r.set(s.v,(r.get(s.v)??0)+1),t?.push({eventId:s.id[0],reason:"unsupported-schema-version",detail:`v${s.v}`,targetNodeId:Hs(s)});continue}let i=Hy(s);if(d(i)){t?.push({eventId:s.id[0],reason:"invalid-payload",detail:i.message,targetNodeId:Hs(s)});continue}let c=i.value.action;if(!bu(c)){o.set(c,(o.get(c)??0)+1),t?.push({eventId:s.id[0],reason:"unknown-action",detail:c,targetNodeId:Hs(s)});continue}let u=Iu(c,i.value.payload);if(d(u)){t?.push({eventId:s.id[0],reason:"invalid-payload",detail:u.message,targetNodeId:Hs(s)});continue}n.push(i.value)}if(o.size>0){let s=[...o.entries()].map(([i,c])=>`${i} (x${c})`).join(", ");J.info(`Skipped events with unknown actions, likely created by a newer epiq version: ${s}. Upgrade to apply them.`)}if(r.size>0){let s=[...r.entries()].map(([i,c])=>`v${i} (x${c})`).join(", ");J.info(`Skipped events with unsupported schema versions, created by a newer epiq version: ${s}. Upgrade to apply them.`)}return l("Decoded reconstructed events",n)},Wy=(e,t)=>{if(!Ws.existsSync(e))return l("Event file missing",[]);let n=By(e);if(d(n))return a(n.message);let o=Ws.readFileSync(e,"utf8"),r=[],s=qs.basename(e),i=(c,u)=>{t?.push({eventId:null,reason:"corrupt-line",detail:`${s}:${c} (${u})`,targetNodeId:null})};for(let[c,u]of o.split(`
|
|
41
|
+
`).entries()){let m=u.trim();if(!m)continue;let p;try{p=JSON.parse(m)}catch{i(c+1,"invalid JSON");continue}let f=Cu(p);if(d(f)){i(c+1,f.message);continue}r.push({...f.value,userId:n.value.userId,userName:n.value.userName})}return l("Parsed persisted events file",r)};un=null;La=(e,t)=>{let n=e.id[0].localeCompare(t.id[0]);return n!==0?n:JSON.stringify(e).localeCompare(JSON.stringify(t))},qy=e=>{let t=new Map,n=new Map;for(let m of e){let p=m.id[0],f=m.id[1]??null;t.set(p,m);let y=n.get(f)??[];y.push(m),n.set(f,y)}for(let m of n.values())m.sort(La);let o=[],r=new Set,s=m=>{let p=[m];for(;p.length>0;){let f=p.pop(),y=f.id[0];if(r.has(y))continue;o.push(f),r.add(y);let I=n.get(y)??[];for(let S=I.length-1;S>=0;S--)p.push(I[S])}},i=(n.get(null)??[]).filter(m=>{let p=Object.keys(m).filter(f=>f!=="id"&&f!=="v"&&f!=="userId"&&f!=="userName");return p.length===1&&p[0]==="init.workspace"});for(let m of i)s(m);let c=e.filter(m=>{let p=m.id[0],f=m.id[1]??null;return r.has(p)?!1:f===null||!t.has(f)}).sort(La);for(let m of c)s(m);let u=e.filter(m=>!r.has(m.id[0])).sort(La);for(let m of u)s(m);return o},Nu=e=>pr(e.map(t=>{try{return Dy(t.id[0])}catch{return null}}));Gy=(e,t)=>{let n=new Set,o=[],r=[],s=Nu(e);for(let i=0;i<e.length;i++){let c=e[i],u=c.id[0],m=c.id[1],p=s[i]??null;!(p!==null&&p<t)||m&&n.has(m)?(n.add(u),r.push(c)):o.push(c)}return{appliedEvents:o,unappliedEvents:r}}});import Ba from"node:path";import{decodeTime as zy,monotonicFactory as Vy}from"ulid";import{z as Qn}from"zod";function Ua(e,t){let n;if(t&&t.current!==void 0)n=t.current;else{let r=Su(e);if(d(r))return a(r.message);n=r.value}let o=n?wu(Xy(n)):wu();return l("Minted event id",[o,n])}function Gs({event:e,rootDir:t,edge:n,id:o}){try{let r=Zl(t);if(d(r))return r;let s=nb(t,{userId:e.userId,userName:e.userName});if(d(s))return s;let i=l("Resolved pending event log path",mu(t,Ba.basename(s.value))),c=o?l("Minted event id",o):Ua(t,n);if(d(c))return a(c.message);let[u,m]=c.value,p=ob(xu(e),[u,m]);if(d(p))return a(p.message);fu(i.value,`${JSON.stringify(p.value)}
|
|
42
|
+
`),n&&(n.current=u);let f=Ba.basename(i.value);return Ru(t,f,u),yu(t,f),l("Event persisted",{path:i.value,entry:p.value})}catch(r){let s=r instanceof Error?r.message:"Unknown persist error";return a(`Failed to persist event: ${s}`)}}var Tu,wu,Ky,Yy,Xy,ku,Jy,Qy,Cu,Zy,eb,Au,tb,oe,Zn,nb,ob,Ce=h(()=>{"use strict";xt();Un();R();We();ae();su();Ke();Yn();St();kr();ka();Tu=1,wu=Vy(),Ky=0xffffffffffff,Yy=ys,Xy=e=>{let t=Date.now(),n;try{n=zy(e)}catch{return t}return n>=Ky?t:n>t+Yy?(J.error("[persist] edge id is too far in the future; seeding from the wall clock instead",{edgeRef:e,edgeTime:n,now:t}),t):Math.max(t,n+1)},ku=Qn.tuple([Qn.string().min(1),Qn.string().min(1).nullable()]),Jy=Qn.looseObject({v:Qn.literal(Tu),id:ku}),Qy=Qn.looseObject({v:Qn.number().int().positive(),id:ku}),Cu=e=>{let t=Qy.safeParse(e);return t.success?l("Parsed persisted event envelope",t.data):a(`Invalid persisted event envelope: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},Zy=[1],eb=new Set(Zy),Au=e=>eb.has(e),tb=e=>{let t=Jy.safeParse(e);return t.success?l("Parsed persisted event",t.data):a(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},oe=()=>{let{userName:e,userId:t}=Ie();return e?t?vs(t)?ur(e)?l("Successfully resolved actor ID",{userId:t,userName:e}):a("Invalid user name in config"):a("Invalid user ID in config"):a("User ID not configured"):a("User name not configured")},Zn=({userId:e,userName:t})=>`${Ca(e)}.${Ca(t)}.jsonl`,nb=(e,{userId:t,userName:n})=>{let o=Zn({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(o))return a(`Invalid event log file name: ${o}`);let s=Ba.join(kt(e),o);return l("Successfully resolved event log path",s)},ob=(e,t)=>{let n={[e.action]:e.payload,v:Tu,id:t};return tb(n)}});import{ulid as rb}from"ulid";function Mu(e,t,n){let o=Ua(t,n);if(d(o))return a(o.message);let r={...e,id:o.value[0]},s=Nn(r);if(s.status!==tn.Success)return s;let i=Gs({event:r,rootDir:t,edge:n,id:o.value});return d(i)?i:s}function L(e,t){if(e.length===0||!e[0])return a("No events provided");if(g().readOnly)return a(g().readOnlyReason??"Cannot change the board while time travelling");let n={},o=sb(e[0],t,n);if(d(o))return o;let r=e.map(i=>Mu(i,t,n)),s=r.filter(d);return s.length>0?a("Materialize and persist failed: "+s.map(i=>i.message).join(", ")):l("Materialization succeeded",r.map(i=>i.value))}var sb,Se=h(()=>{"use strict";R();ne();M();ln();Ce();sb=(e,t,n)=>{if(e.action==="create.contributor"||e.action==="rename.contributor")return l("Contributor write already in flight",void 0);let o=E.getContributor(e.userId),r={id:rb(),action:o?"rename.contributor":"create.contributor",payload:{id:e.userId,name:e.userName},userId:e.userId,userName:e.userName};if(o&&(o.tombstoned||o.name===e.userName))return l("Contributor name is current",void 0);let s=Mu(r,t,n);return d(s)?a(s.message):l("Contributor name recorded",void 0)}});var eo,$a,Pu=h(()=>{"use strict";Je();eo=e=>e.trim().toLocaleLowerCase(),$a=(e,t)=>eo(e).includes(eo(t))});var ib,ab,Lu,Du,db,cb,Fu,_u=h(()=>{"use strict";M();Je();Pu();ib=e=>{let{tags:t}=g();return(e.props.tags??[]).map(n=>t[n]).filter(n=>n!==void 0&&!n.tombstoned).map(n=>n.name)},ab=e=>{let{contributors:t}=g();return(e.props.assignees??[]).map(n=>{let o=t[n];return o?o.name:void 0}).filter(n=>!!n)},Lu=null,Du=new Map,db=()=>{let e=g().eventLog??[];if(e===Lu)return Du;let t=new Map;for(let n of e){if(!n.userId)continue;let o=n.payload;for(let r of[o.id,o.issue]){if(typeof r!="string")continue;let s=t.get(r)??new Set;s.add(n.userId),t.set(r,s)}}return Lu=e,Du=t,t},cb=e=>{let{contributors:t}=g(),n=db().get(e.id);return n?[...n].map(o=>t[o]?.name).filter(o=>!!o):[]},Fu=(e,t)=>{let n=eo(t.value);if(!n)return!0;switch(t.target){case"title":return $a(e.title??"",n);case"description":return $a(e.props.description??"",n);case"tag":return ib(e).map(eo).some(r=>r.includes(n));case"assignee":return ab(e).map(eo).some(r=>r.includes(n));case"actor":return cb(e).map(eo).some(r=>r.includes(n));case"ref":return Cr(e.id,t.value);default:return!0}}});var Ou,lb,Bu,Uu,ja=h(()=>{"use strict";K();_u();Ou=(e,t)=>e.rank.localeCompare(t.rank),lb=(e,t)=>!!e&&!e.isDeleted&&e.parentNodeId===t,Bu=(e,t)=>Object.values(e).filter(n=>lb(n,t)).sort(Ou),Uu=(e,t)=>{let n={};for(let o of Object.values(e)){if(P(o)&&t.length>0&&!t.every(s=>Fu(o,s))||!o.parentNodeId||o.isDeleted)continue;let r=n[o.parentNodeId];r?r.push(o):n[o.parentNodeId]=[o]}for(let o of Object.keys(n))n[o].sort(Ou);return n}});var $u,zs,ge,ju,Hu,jt,wn,yt=h(()=>{"use strict";Al();Se();R();M();ja();yo();$u=e=>zs(ge(e),{at:"end"}),zs=(e,t={at:"end"})=>{let n=r=>d(r)?l("Rank space exhausted",{rank:"",needsRebalance:!0}):l("Resolved rank",{rank:r.value,needsRebalance:!1});if(e.length===0)return n(qe(void 0,void 0));let o=()=>n(qe(e[e.length-1]?.rank,void 0));switch(t.at){case"start":{let r=e[0];return r?n(qe(void 0,r.rank)):a("Unable to resolve first sibling")}case"end":{let r=e[e.length-1];return r?n(qe(r.rank,void 0)):a("Unable to resolve last sibling")}case"before":{let r=ju(e,t.sibling),s=r<0?void 0:e[r];if(!s)return o();let i=r>0?e[r-1]:void 0;return n(qe(i?.rank,s.rank))}case"after":{let r=ju(e,t.sibling),s=r<0?void 0:e[r];if(!s)return o();let i=r<e.length-1?e[r+1]:void 0;return n(qe(s.rank,i?.rank))}}},ge=e=>{let t=g();if(!Wu()&&t.filters.length===0){let n=t.renderedChildrenIndex[e];if(n)return n}return Bu(t.nodes,e)},ju=(e,t)=>e.findIndex(n=>n.id===t),Hu=(e,t,n={at:"end"})=>zs(ge(t).filter(o=>o.id!==e),n),jt=(e,t,n,o,r)=>{let s=Hu(t,e,n);if(d(s))return s;if(!s.value.needsRebalance)return l("Resolved rank",s.value.rank);let i=aa(e,o);if(d(i))return i;let c=L([i.value],r);if(d(c))return c;let u=Hu(t,e,n);return d(u)?u:u.value.needsRebalance?a("Rank rebalance failed to create space"):l("Resolved rank after rebalance",u.value.rank)},wn=(e,t,n)=>{let o=$u(e);if(d(o))return o;if(!o.value.needsRebalance)return l("Resolved rank",o.value.rank);let r=aa(e,t);if(d(r))return r;let s=L([r.value],n);if(d(s))return s;let i=$u(e);return d(i)?i:i.value.needsRebalance?a("Rank rebalance failed to create space"):l("Resolved rank after rebalance",i.value.rank)}});var U,qu,Gu,ut=h(()=>{"use strict";M();U={exit(){process.exit(0)},enterChildNode(){let e=g(),t=e.contextNode,n=Math.max(0,e.selectedIndex),o=se(t.id),r=o[n];r&&(t.context==="FIELD"&&o.length===0||r.context==="COMMENT"||r.context==="TEXT"||U.navigate({contextNode:r,selectedIndex:se(r.id).length?0:-1}))},enterParentNode(){let{contextNode:e,nodes:t}=g();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let o=se(n.id),r=o.findIndex(({id:i})=>i===e.id),s=o.length===0?-1:r>=0?r:0;U.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>qu(1),navigateToPreviousItem:()=>qu(-1),navigateToNextContainer:()=>Gu(1),navigateToPreviousContainer:()=>Gu(-1),navigate:({contextNode:e,selectedIndex:t})=>{N({contextNodeId:e.id,selectedIndex:t})}},qu=e=>{let{selectedIndex:t,contextNode:n}=g(),o=se(n.id).length;if(o===0)return;let s=(Math.max(0,t)+e+o)%o;U.navigate({selectedIndex:s,contextNode:n})},Gu=e=>{let{contextNode:t,nodes:n,selectedIndex:o}=g();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let r=n[t.parentNodeId];if(!r)return;let s=se(r.id),i=s.findIndex(y=>y.id===t.id);if(i<0)return;let c=s.at(i+e)??s.at(0);if(!c)return;let u=se(c.id),m=Math.max(0,u.length-1),p=Math.min(Math.max(0,o),m),f=u.length?p:-1;U.navigate({contextNode:c,selectedIndex:f})}});var Vu,Ku,ub,Vs,Yu,zu,mb,Xu,Ju=h(()=>{"use strict";K();R();yt();M();ut();Vu=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),Ku=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=g();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},ub=e=>{let t=g().nodes[e];return!!t&&!t.isDeleted&&at(t)&&t.childRenderAxis==="vertical"},Vs=(e,t)=>{let{nodes:n}=g(),o=n[e];if(!o||o.isDeleted)return!1;let r=ge(o.id);return U.navigate({contextNode:o,selectedIndex:Vu(t,r.length)}),!0},Yu=e=>{let{nodes:t}=g(),n=t[e];if(!n||n.isDeleted)return!1;let o=n.parentNodeId;if(!o)return Vs(n.id,0);let r=t[o];if(!r||r.isDeleted)return!1;let i=ge(r.id).findIndex(c=>c.id===n.id);return i>=0?(U.navigate({contextNode:r,selectedIndex:i}),!0):Yu(r.id)},zu=e=>{let{nodes:t}=g(),n=e,o=new Set;for(;n&&!o.has(n);){if(o.add(n),Yu(n))return!0;n=t[n]?.parentNodeId}return!1},mb=e=>{if(!e)return!1;let t=g().nodes[e];return!!t&&!t.isDeleted},Xu=e=>{let{nodes:t,rootNodeId:n}=g();if(ub(e.contextNodeId)&&Vs(e.contextNodeId,e.selectedIndex))return l("Restored navigation inside text container",null);if(mb(e.selectedNodeId)&&e.selectedNodeId&&zu(e.selectedNodeId))return l("Restored navigation to selected node or ancestor",null);if(Vs(e.contextNodeId,e.selectedIndex))return l("Restored navigation to previous container",null);if(e.parentNodeId&&Vs(e.parentNodeId,e.selectedIndex))return l("Restored navigation to previous parent",null);if(zu(e.contextNodeId))return l("Restored navigation to previous container or ancestor",null);let o=t[n];if(!o||o.isDeleted)return a("Unable to restore navigation");let r=ge(o.id);return U.navigate({contextNode:o,selectedIndex:Vu(e.selectedIndex,r.length)}),l("Restored navigation to root",null)}});import{monotonicFactory as pb,ulid as Ht}from"ulid";function fb(){let e=ze();if(d(e))return a("Unable to boot. State not initialized");let t=e.value,n=Object.values(t.nodes).find(s=>s.context==="WORKSPACE");if(!n)return a("No workspace found in event log");let[o]=se(n.id),[r]=o?se(o.id):[];if(r){let s=t.renderedChildrenIndex?.[r.id]??[];return l("Resolved boot nav target",{contextNode:r,selectedIndex:s.length>0?0:-1})}else return o?l("Resolved boot nav target",{contextNode:o,selectedIndex:0}):l("Resolved boot nav target",{contextNode:n,selectedIndex:0})}function gb(){let e=fb();return d(e)?e:U.navigate(e.value)}function Qu({userId:e,userName:t}){let n=Pr(),o=Pr(),r=Pr(),s=Pr(),i=Pr(),c=qe(void 0,void 0);if(d(c))return c;let u=qe(void 0,void 0);if(d(u))return u;let m=qe(u.value,void 0);if(d(m))return m;let p=qe(void 0,void 0);if(d(p))return p;let f=qe(p.value,void 0);if(d(f))return f;let y=qe(f.value,void 0);if(d(y))return y;let I=qe(void 0,void 0);return d(I)?I:l("Created default events",[{id:Ht(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:c.value}},{id:Ht(),userId:e,userName:t,action:"create.contributor",payload:{id:e,name:t}},{id:Ht(),userId:e,userName:t,action:"add.board",payload:{id:o,name:"Default",parent:n,rank:u.value}},{id:Ht(),userId:e,userName:t,action:"add.swimlane",payload:{id:r,name:"Todo",parent:o,rank:p.value}},{id:Ht(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"In progress",parent:o,rank:f.value}},{id:Ht(),userId:e,userName:t,action:"add.swimlane",payload:{id:i,name:"Done",parent:o,rank:y.value}},{id:Ht(),userId:e,userName:t,action:"add.board",payload:{id:Ds,name:"Closed",parent:n,rank:m.value}},{id:Ht(),userId:e,userName:t,action:"add.swimlane",payload:{id:he,name:"Closed",parent:Ds,rank:I.value}},{id:Ht(),userId:e,userName:t,action:"lock.node",payload:{id:Ds}},{id:Ht(),userId:e,userName:t,action:"lock.node",payload:{id:he}}])}function Wt(e,t=[]){if(hb())return l("Skipped boot while checked out at a historical point",null);if(!e.length){let s=Pe.workspace("temporary-uninitialized-workspace","Workspace","a0"),i=Tr(s);return d(i)?i:(N({hasProjectDefinition:!1,mode:b.DEFAULT}),l("Booted uninitialized workspace placeholder",null))}if(!e.some(s=>s.action==="init.workspace"))return a("Initialized Epiq project has no workspace init event");let n=cn(e),{fatal:o,skipped:r}=zn(n);return o.length>0?a(`Materializing failed:
|
|
25
43
|
${o.map(s=>s.message).join(`
|
|
26
|
-
`)}`):(
|
|
27
|
-
`).filter(t=>t.trim().length>0),
|
|
28
|
-
`);
|
|
44
|
+
`)}`):(Vn(r),gb(),N({hasProjectDefinition:!0}),vb(t),l("State booted successfully",null))}var Pr,hb,vb,to=h(()=>{"use strict";xt();ut();pe();R();Gn();M();yo();ln();dn();Pr=pb();hb=()=>{let e=ze();if(d(e))return!1;let{timeMode:t}=e.value;return t==="peek"||t==="replay"},vb=e=>{if(e.length===0)return;let t=e.filter(o=>o.reason==="corrupt-line"||o.reason==="invalid-payload"),n=e.filter(o=>o.reason==="unsupported-schema-version"||o.reason==="unknown-action");if(n.length>0){let o=[...new Set(n.map(r=>r.detail))].join(", ");J.info(`This build cannot read ${n.length} event(s) in the log (${o}). They are skipped, so anything they changed may be out of date until you upgrade.`)}if(t.length>0){let o=[...new Set(t.map(r=>r.detail))].join(", ");J.info(`Skipped ${t.length} corrupt line(s) in the event log (${o}). The rest of the board loaded normally; those events are unrecoverable.`)}}});import{WebSocket as yb}from"ws";var bb,Zu,em=h(()=>{"use strict";bb=new Set,Zu=e=>{let t=JSON.stringify(e);for(let n of bb)n.readyState===yb.OPEN&&n.send(t)}});var Ks,Eo,no,Ha,Ys,Re,Lr=h(()=>{"use strict";em();R();M();Ks=e=>{It()&&(N({syncStatus:e}),Zu({type:"sync-status",payload:e}))},Eo=(e="Syncing...")=>{Ks({status:"syncing",msg:e})},no=(e="Synced")=>{Ks({status:"synced",msg:e})},Ha=e=>{Ks({status:"failed",msg:e})},Ys=e=>{Ks({status:"offline",msg:e})},Re=e=>(Ha(e),a(e))});var So,tm,re,Xs=h(()=>{"use strict";R();So=(e,t)=>(logger.error(`[boot:${e}] ${t}`),a(`[boot:${e}] ${t}`)),tm=e=>{if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}},re=(e,t)=>(d(t)&&logger.info(`[${e}]:failed`,t.message),t)});import qt from"node:fs";import Dr from"node:path";var Ro,nm,om,rm,xb,sm,Ib,Eb,im,Wa=h(()=>{"use strict";ct();R();Yn();ae();Ro=e=>e.split(`
|
|
45
|
+
`).filter(t=>t.trim().length>0),nm=e=>{let t=Dr.join(e,Ge,an);try{if(!qt.existsSync(t))return l("No events directory",[]);let n=qt.readdirSync(t).filter(o=>o.endsWith(".jsonl")).filter(o=>Ro(qt.readFileSync(Dr.join(t,o),"utf8")).length>0);return l("Looked for stranded event logs",n)}catch(n){return a(`Unable to check ${t} for event logs before deleting it: ${n instanceof Error?n.message:String(n)}`)}},om=e=>Dr.join(e,Ge,an),rm=e=>{let t=om(e),n=new Map;try{if(!qt.existsSync(t))return n;for(let o of qt.readdirSync(t))o.endsWith(".jsonl")&&(Us(o)||n.set(o,Ro(qt.readFileSync(Dr.join(t,o),"utf8"))))}catch{return n}return n},xb=e=>{try{let t=JSON.parse(e);return typeof t=="object"&&t!==null}catch{return!1}},sm=(e,t)=>{if(t.size===0)return[];let n=om(e),o=[];for(let[r,s]of t){if(s.length===0)continue;let i=Dr.join(n,r);try{let c=qt.existsSync(i)?qt.readFileSync(i,"utf8"):null,u=new Set(c===null?[]:Ro(c)),m=s.filter(f=>!u.has(f)).filter(xb);if(m.length===0)continue;qt.mkdirSync(n,{recursive:!0});let p=c!==null&&c.length>0&&!c.endsWith(`
|
|
46
|
+
`);qt.appendFileSync(i,`${p?`
|
|
29
47
|
`:""}${m.join(`
|
|
30
48
|
`)}
|
|
31
|
-
`,"utf8"),o.push(`${r} (${m.length})`)}catch{continue}}return o},
|
|
32
|
-
`),
|
|
33
|
-
`));
|
|
34
|
-
${n.message}`);let o=n.value.stdout.trim(),r=await
|
|
35
|
-
${r.message}`):l("Created state branch",!0)},
|
|
36
|
-
`+n.message);if(n.value)return l("Local state branch already exists",!1);let o=await
|
|
37
|
-
`+o.message);let r=o.value,s=r?await
|
|
38
|
-
`+s.message);let
|
|
39
|
-
${c.message}`)}if(
|
|
40
|
-
${c.message}`):l("Created local state branch from remote",!0)}return
|
|
41
|
-
`),r=null;for(let s of o){if(s.startsWith("worktree ")){r=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&r)return l("Found worktree for branch",r)}return l("No worktree found for branch",null)},
|
|
42
|
-
`+o.message);if(
|
|
43
|
-
`));
|
|
44
|
-
${r.message}`):l("Created state branch worktree",!0)},
|
|
45
|
-
`));
|
|
46
|
-
${m.message}`)}if(s&&!
|
|
47
|
-
${u.message}`)}let
|
|
48
|
-
${u.message}`)}return
|
|
49
|
-
${r.message}`):l("Checked out state branch",!0)},
|
|
50
|
-
${c.message}`);let u=await ye.setUpstream({cwd:t,branch:s,upstream:`${
|
|
51
|
-
${u.message}`):l("Configured state branch upstream",!0)},
|
|
52
|
-
${s.message}`):l("Staged state branch event file",n)},
|
|
53
|
-
${o.message}`):l("Staged state branch media files",t)},
|
|
54
|
-
${n.message}`):l("Staged event log
|
|
55
|
-
`+o.message):
|
|
56
|
-
${s.message}`);let d=!`${s.value.stdout}${s.value.stderr}`.includes("Everything up-to-date");return l(d?"Pushed state branch":"Remote already up to date",d)},du=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let o=!1,r=kt(e);if(a(r))return r;let s=r.value,d=[ms(),await pa({repoRoot:e,stateBranchName:s}),await Kn({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await $v({stateBranchRoot:t,stateBranchName:s}),await tl(t),n?await jv({stateBranchRoot:t,repoRoot:e}):l("Skipped state branch upstream bootstrap",!1)];for(let c of d){if(a(c))return i(c.message);o=o||!!c.value}return l(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",o)}});import Ts from"node:fs";import fa from"node:os";import Hv from"node:path";var Wv,cu,qv,Gv,zv,uu,ga,lu,Vv,Ms,ha=h(()=>{"use strict";R();Nt();ht();Wv="epiq-sync.lock",cu=600*1e3,qv=e=>{try{let t=JSON.parse(e);return typeof t.pid!="number"||typeof t.hostname!="string"||typeof t.startedAt!="number"||typeof t.operation!="string"?null:t}catch{return null}},Gv=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},zv=e=>e&&(e.hostname!==fa.hostname()||Gv(e.pid))?Date.now()-e.startedAt>cu:!0,uu=e=>`${e.operation} (pid ${e.pid} on ${e.hostname}, started ${new Date(e.startedAt).toISOString()})`,ga=e=>{try{return qv(Ts.readFileSync(e,"utf8"))}catch{return null}},lu=(e,t)=>{let n={pid:process.pid,hostname:fa.hostname(),startedAt:Date.now(),operation:t};try{return Ts.writeFileSync(e,JSON.stringify(n),{flag:"wx"}),!0}catch{return!1}},Vv=async({worktreeRoot:e,operation:t})=>{let n=await _i(e);if(a(n))return i(n.message);let o=Hv.join(n.value,Wv),r=()=>{try{let c=ga(o);c&&c.pid===process.pid&&Ts.rmSync(o)}catch{}};if(lu(o,t))return l("Acquired sync lock",{acquired:!0,release:r});let s=ga(o);if(!zv(s))return l("Sync lock is held",{acquired:!1,heldBy:s});X.info(`Breaking an abandoned sync lock: ${s?uu(s):"unreadable lock file"}`);try{Ts.rmSync(o,{force:!0})}catch{}if(lu(o,t))return l("Acquired sync lock after breaking a stale one",{acquired:!0,release:r});let d=ga(o);return l("Sync lock taken by another process",{acquired:!1,heldBy:d??{pid:-1,hostname:fa.hostname(),startedAt:Date.now(),operation:"unknown"}})},Ms=async({worktreeRoot:e,operation:t,fn:n})=>{let o=await Vv({worktreeRoot:e,operation:t});if(a(o))return i(o.message);if(!o.value.acquired)return X.info(`Skipping ${t}: the state worktree is held by ${uu(o.value.heldBy)}`),l("State worktree is held by another process",null);let{release:r}=o.value;try{return l("Ran under the sync lock",await n())}finally{r()}}});import Kv from"node:fs";var Yv,Xv,va,mu,ya,ks,Ps=h(()=>{"use strict";R();fr();Cs();co();We();Nt();br();ua();ha();Yv=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=re("getRepoRootDir",await rt(e));if(a(n))return i(n.message);let o=n.value;logger.debug("[sync] repo root",o);let r=re("getStateBranchRoot",ve({repoRoot:o}));if(a(r))return i(r.message);let s=r.value;logger.debug("[sync] state branch root",s),logger.debug("[sync] bootstrapping state branch storage",{repoRoot:o,stateBranchRoot:s,ensureUpstream:t});let d=re("bootstrapStateBranchStorage",await du({repoRoot:o,stateBranchRoot:s,ensureUpstream:t}));if(a(d))return i(d.message);logger.debug("[sync] bootstrap result",{bootstrapped:d.value,stateBranchRoot:s}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:s});let c=re("hasInProgressGitOperation(stateBranchRoot)",await ds(s));if(a(c))return i(c.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:c.value}),c.value)return logger.info("[sync] state branch git operation in progress"),i("Cannot sync while a git operation is in progress in the state branch");logger.debug("[sync] ensuring state branch layout",{repoRoot:o,stateBranchRoot:s});let u=re("ensureStateBranchLayout",el(o,s));return a(u)?i(u.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:o,stateBranchRoot:s,bootstrapped:d.value}),l("Sync preconditions satisfied",{repoRoot:o,stateBranchRoot:s,bootstrapped:d.value}))},Xv=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{logger.debug("[sync] committing own event file from state branch",{ownEventFileName:n,stateBranchRoot:t}),logger.debug("[sync] staging own event file",{stateBranchRoot:t,ownEventFileName:n});let o=re("stageStateBranchOwnEventFile",await ws({stateBranchRoot:t,eventFileName:n}));if(a(o))return i(o.message);let r=re("stageStateBranchMediaFiles",await su({stateBranchRoot:t}));if(a(r))return i(r.message);let s=re("stageStateBranchEventAttributes",await iu({stateBranchRoot:t}));if(a(s))return i(s.message);let d=[o.value,r.value,s.value].filter(m=>m!==null);if(d.length===0)return l("Nothing to stage",{createdCommit:!1});let c=re("hasStagedChanges(after stage)",await zc(t,d));if(a(c))return i(c.message);if(logger.debug("[sync] state branch change check after stage result",{changed:c.value}),!c.value)return logger.info("[sync] no own event file changes to commit"),l("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let u=re("createStateBranchSyncCommit",await au({repoRoot:e,stateBranchRoot:t,pathspec:d}));return a(u)?i(u.message):(logger.debug("[sync] created sync commit",u.value),l("Committed own event file",{createdCommit:!0,commitSha:u.value}))},va=(e,t="offline")=>{let n=e.createdCommit?`Committed locally, ${t}`:t==="offline"?"Offline":"No remote";return As(n),l(n,{...e,pulled:!1,pushed:!1,offline:!0})},mu=async({cwd:e=process.cwd(),ownEventFileName:t})=>{if(logger.debug("[sync] syncEpiqWithRemote:start",{cwd:e,ownEventFileName:t}),t.includes("/")||t.includes("\\"))return logger.error("[sync] invalid own event file name: contains path separator",{ownEventFileName:t}),i("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return logger.error("[sync] invalid own event file name: missing .jsonl suffix",{ownEventFileName:t}),i("Own event file must end with .jsonl");mo();let n=re("ensureSyncReady",await Yv({cwd:e,ensureUpstream:!0}));if(a(n))return Ee(n.message);let{repoRoot:o,stateBranchRoot:r,bootstrapped:s}=n.value,d=re("isDetachedHead(stateBranchRoot)",await Vc(r));if(a(d))return Ee(d.message);if(logger.debug("[sync] detached state branch check result",{detached:d.value}),d.value)return Ee("Cannot run :sync while the state branch is in detached HEAD state");let c=!1,u,m=!1,p=!1,f=re("getStateBranch",kt(o));if(a(f))return Ee(f.message);let x=f.value;logger.debug("[sync] resolved state branch",{stateBranch:x,stateBranchRoot:r});let S=re("commitOwnEventFileToStateBranch",await Xv({repoRoot:o,stateBranchRoot:r,ownEventFileName:t}));if(a(S))return Ee(S.message);c=S.value.createdCommit,u=S.value.commitSha;let A=re("hasRemote",await _n({repoRoot:r}));if(a(A))return Ee(A.message);if(!A.value)return va({repoRoot:o,stateBranchRoot:r,createdCommit:c,commitSha:u,bootstrapped:s},"no remote");let P=re("pullBranchRebaseIfPresent",await rr({cwd:r,branch:x}));if(a(P))return or(P.message)?va({repoRoot:o,stateBranchRoot:r,createdCommit:c,commitSha:u,bootstrapped:s}):Ee(P.message);m=P.value;let T=re("isAheadOfUpstream",await qc(r));if(a(T))return Ee(T.message);if(c||s||T.value){logger.info("[sync] pushing state branch",{createdCommit:c,bootstrapped:s,stateBranchRoot:r});let w=re("pushStateBranch",await yr({stateBranchRoot:r,repoRoot:o}));if(a(w)&&Wc(w.message)){let _=re("pullBranchRebaseIfPresent(retry)",await rr({cwd:r,branch:x}));if(a(_))return Ee(_.message);m=m||_.value,w=re("pushStateBranch(retry)",await yr({stateBranchRoot:r,repoRoot:o}))}if(a(w))return or(w.message)?va({repoRoot:o,stateBranchRoot:r,createdCommit:c,commitSha:u,bootstrapped:s}):Ee(w.message);p=w.value}if(c){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:r});let w=re("git rev-parse HEAD",await q({args:["rev-parse","HEAD"],cwd:r}));if(a(w))return Ee(w.message);u=w.value.stdout.trim(),logger.debug("[sync] final sync commit sha",u)}return Vn(p?"Synced and pushed":m||c?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),l("Synced event logs with state branch",{repoRoot:o,stateBranchRoot:r,createdCommit:c,commitSha:u,pulled:m,pushed:p,bootstrapped:s,offline:!1})},ya=async(e,t)=>{let n=eu(e);try{return await t()}finally{let o=tu(e,n);o.length>0&&logger.error(`[sync] restored event log lines git dropped from the worktree: ${o.join(", ")}`)}},ks=async e=>{let t=e.cwd??process.cwd(),n=await rt(t);if(a(n))return Ee(n.message);let o=ve({repoRoot:n.value});if(a(o))return Ee(o.message);let r=o.value;if(!Kv.existsSync(r))return mu(e);let s=await Ms({worktreeRoot:r,operation:"sync",fn:()=>ya(r,()=>mu(e))});return a(s)?Ee(s.message):s.value===null?l("Another process is syncing this board",{repoRoot:n.value,stateBranchRoot:r,createdCommit:!1,pulled:!1,pushed:!1,bootstrapped:!1,offline:!1,skipped:!0}):s.value}});var Ot,Ls,Jv,ba,pu,Ds=h(()=>{"use strict";Vl();zn();bt();Se();me();R();M();fr();Cs();Ps();Ot=null,Ls=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!Ot,currentStatus:g().syncStatus?.status,currentMessage:g().syncStatus?.msg}),Ot)return logger.debug("[sync] syncAndReloadState joining existing promise"),Ot;logger.debug("[sync] syncAndReloadState creating promise"),Ot=Jv();try{let e=await Ot;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!a(e),message:(a(e),e.message),statusAfterResolve:g().syncStatus?.status,statusMessageAfterResolve:g().syncStatus?.msg}),a(e)&&g().syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),E({syncStatus:{msg:e.message,status:"failed"}})),e}catch(e){let t=e instanceof Error?e.message:String(e);return logger.error("[sync] syncAndReloadState promise threw",{message:t,error:e}),Ot||i(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:g().syncStatus?.status,statusMessageBeforeClear:g().syncStatus?.msg}),Ot=null}},Jv=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:g().mode,syncStatus:g().syncStatus});let e=pu();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:g().mode,message:e.message,syncStatus:g().syncStatus}),e;if(Ot)return Ot;logger.debug("[sync] syncAndReloadState:start");let t=re("resolveActorId",ne());if(a(t)||!t.value)return logger.info("[sync] unable to resolve actor id",{message:a(t)?t.message:"Missing actor id"}),i("Unable to resolve event log path");E({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:g().syncStatus});let n=qn(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let o=re("syncEpiqWithRemote",await ks({ownEventFileName:n}));if(logger.debug("[sync] syncEpiqWithRemote:result",{success:!a(o),message:(a(o),o.message)}),a(o))return logger.error("[sync] syncAndReloadState:sync failed",o.message),E({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:g().syncStatus}),Ee(`Unable to sync state. ${o.message}`);let{stateBranchRoot:r,offline:s}=o.value,d=ba(r);return a(d)?d:(E({hasProjectDefinition:!0,syncStatus:s?{msg:"Committed locally, offline",status:"offline"}:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:g().syncStatus}),l("Synced",!0))},ba=e=>{logger.debug("[sync] loading merged events after sync",{stateBranchRoot:e});let t=re("loadMergedEvents",yt(e));if(logger.debug("[sync] loadMergedEvents:result",{success:!a(t),message:(a(t),t.message),count:a(t)?void 0:t.value.events.length}),a(t))return E({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:g().syncStatus}),i(`Unable to load events. ${t.message}`);logger.debug("[sync] loaded merged events after sync",{count:t.value.events.length});let n=pu();if(n)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:g().mode,message:n.message,syncStatus:g().syncStatus}),n;let o=ql(),r=g().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:o,selectedNodeId:g().selectedNode?.id,contextNodeId:g().contextNode?.id,selectedNodeIsVirtual:g().selectedNode?.isVirtual,contextNodeIsVirtual:g().contextNode?.isVirtual}),!g().selectedNode?.isVirtual&&!g().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:t.value.events.length});let d=re("bootStateFromEventLog",_t(t.value.events,t.value.unreadable));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!a(d),message:(a(d),d.message)}),a(d))return E({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:g().syncStatus}),i(`Unable to boot synced state. ${d.message}`)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:g().selectedNode?.isVirtual,contextNodeIsVirtual:g().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),E({filters:r}),logger.debug("[sync] restoreNavigationAnchor:start");let s=re("restoreNavigationAnchor",zl(o));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!a(s),message:a(s)?s.message:"Navigation restored",selectedNodeId:g().selectedNode?.id,contextNodeId:g().contextNode?.id}),a(s)?(E({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:g().syncStatus}),s):l("Reloaded state from event log",null)},pu=()=>g().mode===y.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:g().mode,syncStatus:g().syncStatus}),E({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),i("Will not re-materialize if not in default mode, to not lose edit data"))});var fo,gu,fu,Ia,xa,Ir,Ea,Qv,hu,Zv,vu,Fs=h(()=>{"use strict";R();Be();M();Ds();fo=3e3,gu=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<fo?null:t},fu=0,xa=!1,Ir=!1,Ea=()=>{if(xa)return!0;let e=$e();return a(e)?!1:e.value.syncStatus.status==="syncing"},Qv=()=>{let e=Ie().autoSyncIntervalMs??1e4,t=Date.now()-fu;return Math.max(0,e-t)},hu=()=>{Ia||(Ia=setTimeout(async()=>{if(Ia=void 0,!!vt()){if(Ea()){Ir=!0;return}Ir=!1,await Zv()}},Qv()))},Zv=async()=>{if(g().readOnly||g().timeMode==="peek"||g().timeMode==="replay")return i("Cannot auto-sync while peeking");if(!vt())return i("Cannot auto-sync before state is initialized");if(Ea())return Ir=!0,i("Sync already in progress");xa=!0,fu=Date.now(),E({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await Ls()}finally{xa=!1,Ir&&hu()}},vu=()=>{vt()&&(Ir=!0,!Ea()&&hu())}});import xr from"node:fs";import Er from"node:path";import{z as ho}from"zod";var _s,ey,ty,ny,bu,Iu,yu,xu,Eu,Ru,oy,Bs,Rr,vo=h(()=>{"use strict";R();Yt();is();ae();_s="recent-projects.json",ey=20,ty=ho.object({projectId:ho.string().min(1),root:ho.string().min(1),lastOpenedAt:ho.number().finite()}),ny=ho.object({projects:ho.array(ty)}),bu=()=>Er.join(Xt(),_s),Iu=e=>Er.basename(e)||e,yu=e=>{let t=Er.resolve(e);try{return xr.realpathSync(t)}catch{return t}},xu=(e,t)=>t.lastOpenedAt-e.lastOpenedAt,Eu=e=>{if(!ar(e.root))return!1;let t=tr(e.root);return!a(t)&&t.value===e.projectId},Ru=()=>{let e=bu();if(!xr.existsSync(e))return l("No recent projects recorded",[]);let t;try{t=JSON.parse(xr.readFileSync(e,"utf8"))}catch(o){return i(`Invalid ${_s}: ${o instanceof Error?o.message:String(o)}`)}let n=ny.safeParse(t);return n.success?l("Read recent projects",n.data.projects):i(`Invalid ${_s} shape: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},oy=e=>{let t=bu();try{xr.mkdirSync(Er.dirname(t),{recursive:!0}),xr.writeFileSync(t,JSON.stringify({projects:e},null,2)+`
|
|
57
|
-
`,"utf8")}catch(n){return i(`Unable to write ${_s}: ${n instanceof Error?n.message:String(n)}`)}return l("Recorded recent project",e)},Bs=({exclude:e}={})=>{let t=Ru();if(a(t))return t;let n=e===void 0?null:yu(e);return l("Listed recent projects",t.value.filter(o=>n===null||yu(o.root)!==n).filter(Eu).sort(xu))},Rr=({root:e,now:t=Date.now()})=>{let n=Er.resolve(e),o=tr(n);if(a(o))return i(o.message);let r=o.value,s=Ru(),d=a(s)?[]:s.value,c=[{projectId:r,root:n,lastOpenedAt:t},...d.filter(u=>u.projectId!==r&&u.root!==n)].filter(Eu).sort(xu).slice(0,ey);return oy(c)}});var Os,Su,Nu,Au,Sr=h(()=>{"use strict";R();Yt();Be();ae();Os=()=>{let e=Ie(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),o=e.autoSync===!0||e.autoSync===!1;return{isSetupDone:n&&t&&o,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:o}},Su=()=>{let e=Ue(process.cwd());if(a(e))return!1;let t=Kt(e.value);return wt(t)},Nu=e=>e===!0?"on":e===!1?"off":null,Au=e=>e==="on"?!0:e==="off"?!1:null});var Fe,C,je=h(()=>{"use strict";Fe={bg:"#1a1b26",fg:"#c8d3ff",grayDark:"#3a3e54",gray:"#46507a",grayLight:"#969bb5",cyan:"#88d5ee",cyanSoft:"#8fe6fb",blue:"#5b8cff",magenta:"#a78bfa",magentaSoft:"#c4b5fd",green:"#8fdc8c",yellow:"#f1c27d",red:"#ff7a90",white:"#ffffff"},C={accent:Fe.cyan,accent2:Fe.magenta,primary:Fe.white,secondary:Fe.grayDark,secondary2:Fe.grayLight,gray:Fe.gray,green:Fe.green,yellow:Fe.yellow,red:Fe.red}});var N,yo,Us=h(()=>{"use strict";je();N={red:Fe.red,yellow:Fe.yellow,green:Fe.green,blue:Fe.blue,magenta:Fe.magenta,cyan:Fe.cyan},yo={urgent:N.red,critical:N.red,important:N.red,blocker:N.red,asap:N.red,immediate:N.red,fail:N.red,failure:N.red,broken:N.red,bug:N.red,error:N.red,incident:N.red,outage:N.red,production:N.red,crash:N.red,security:N.red,warning:N.yellow,warn:N.yellow,risky:N.yellow,risk:N.yellow,attention:N.yellow,pending:N.yellow,review:N.yellow,"needs-review":N.yellow,qa:N.yellow,testing:N.yellow,test:N.yellow,validate:N.yellow,verification:N.yellow,staging:N.yellow,check:N.yellow,"follow-up":N.yellow,followup:N.yellow,waiting:N.yellow,blocked:N.yellow,hold:N.yellow,done:N.green,complete:N.green,completed:N.green,success:N.green,ok:N.green,stable:N.green,resolved:N.green,fixed:N.green,closed:N.green,merged:N.green,released:N.green,deployed:N.green,approved:N.green,verified:N.green,working:N.green,healthy:N.green,pass:N.green,passing:N.green,info:N.blue,information:N.blue,note:N.blue,docs:N.blue,documentation:N.blue,doc:N.blue,guide:N.blue,help:N.blue,explanation:N.blue,detail:N.blue,details:N.blue,context:N.blue,design:N.blue,discussion:N.blue,proposal:N.blue,idea:N.blue,feature:N.magenta,enhancement:N.magenta,improvement:N.magenta,refactor:N.magenta,refactoring:N.magenta,cleanup:N.magenta,optimize:N.magenta,optimization:N.magenta,perf:N.magenta,performance:N.magenta,upgrade:N.magenta,migration:N.magenta,modernize:N.magenta,debt:N.magenta,todo:N.cyan,next:N.cyan,planned:N.cyan,plan:N.cyan,future:N.cyan,backlog:N.cyan,investigate:N.cyan,explore:N.cyan,prototype:N.cyan}});var ry,sy,In,xn,$s,js,Nr=h(()=>{"use strict";V();R();te();M();ry=e=>e.props.tags??[],sy=e=>e.props.assignees??[],In=e=>ry(e).map(t=>I.getTag(t)).filter(t=>!!t),xn=e=>sy(e).map(t=>I.getContributor(t)).filter(t=>!!t),$s=()=>{let{breadCrumb:e,selectedNode:t}=g(),n=[...e,t].find(o=>o?.context==="TICKET");return!n||!k(n)?i("Invalid untag target"):l("Retrieved tags from ticket in breadcrumb",In(n))},js=()=>{let{breadCrumb:e,selectedNode:t}=g(),n=[...e,t].find(o=>o?.context==="TICKET");return!n||!k(n)?i("Invalid unassign target"):l("Retrieved assignees from ticket in breadcrumb",xn(n))}});var b,Yn=h(()=>{"use strict";b={PALETTE:"?",EXIT:"exit",INIT:"init",OPEN:"open",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",REPLAY:"replay",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",COMMENT:"comment",CONFIG:"config",EDIT:"edit",YANK:"yank",SYNC:"sync",EXPORT:"export",NONE:""}});var iy,ay,dy,cy,ly,Xn,Cu,Hs,Ws,wu,uy,Ra,Ar=h(()=>{"use strict";iy=/^(\d+)(h|d|w|mo|y)$/,ay=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,dy=({year:e,month:t,day:n,hour:o=0,minute:r=0})=>{let s=new Date(e,t-1,n,o,r);return s.getFullYear()===e&&s.getMonth()===t-1&&s.getDate()===n&&s.getHours()===o&&s.getMinutes()===r},cy=(e,t=new Date)=>{let n=e.match(iy);if(!n)return null;let[,o,r]=n,s=Number(o);if(!Number.isInteger(s)||s<=0)return null;let d=new Date(t);switch(r){case"h":return d.setHours(d.getHours()-s),d;case"d":return d.setDate(d.getDate()-s),d;case"w":return d.setDate(d.getDate()-s*7),d;case"mo":return d.setMonth(d.getMonth()-s),d;case"y":return d.setFullYear(d.getFullYear()-s),d;default:return null}},ly=e=>{let t=e.match(ay);if(!t)return null;let[,n,o,r,s,d]=t,c=Number(n),u=Number(o),m=Number(r),p=s?Number(s):0,f=d?Number(d):0;return dy({year:c,month:u,day:m,hour:p,minute:f})?new Date(c,u-1,m,p,f):null},Xn=e=>{let t=e.trim().toLowerCase();return cy(t)??ly(t)},Cu=/^(\d+)(s|m)?$/,Hs=e=>{let t=e.trim().toLowerCase().match(Cu);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},Ws=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),o=n.length>0&&Cu.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:o}},wu=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,uy=[{unit:"h",from:1,to:24},{unit:"d",from:1,to:7},{unit:"w",from:1,to:52},{unit:"mo",from:1,to:12},{unit:"y",from:1,to:5}],Ra=(e=uy)=>{let t=[];for(let{unit:n,from:o,to:r}of e)for(let s=o;s<=r;s++)t.push(`${s}${n}`);return t}});var my,he,at,Ne,py,gy,Na,Aa,ku,Jn,qs,Sa,Tu,fy,hy,Cr,Mu,vy,yy,Ca,by,Ae,nn=h(()=>{"use strict";Fs();vo();R();Sr();Jt();V();te();M();Us();Nr();Yn();Ar();my=["BOARD","TICKET","SWIMLANE","COMMENT"],he={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",LOG_LEVEL:"logLevel"},at={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},Ne={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},py=[he.EDITOR,he.VIEW,he.USERNAME,he.AUTOSYNC,he.SYNC_DEBOUNCE_MS,he.ATTACHMENT_MAX_KB,he.LOG_LEVEL],gy=(e=g().selectedNode?.context)=>{switch(e){case"TICKET":return[at.TITLE,at.DESCRIPTION];case"BOARD":case"SWIMLANE":return[at.TITLE];case"COMMENT":return[at.COMMENT];default:return[]}},Na=[String(fo),"5000","15000","30000","60000"],Aa=["250","500","1000"],ku=["10s","20s","30s","45s"],Jn=[b.EXIT,b.SYNC,b.HELP,b.EXPORT,b.CONFIG,b.YANK],qs=[b.NEW,b.EDIT,b.DELETE,b.MOVE],Sa=[b.TAG,b.UNTAG,b.ASSIGN,b.UNASSIGN,b.CLOSE_ISSUE,b.RE_OPEN_ISSUE,b.EDIT,b.COMMENT],Tu=[b.FILTER,b.PEEK,b.REPLAY],fy={WORKSPACE:[...Jn,...qs],BOARD:[...Tu,...Jn,...qs],SWIMLANE:[...Tu,...Jn,...qs],TICKET:[...Jn,...qs,...Sa],FIELD:[...Jn,...Sa],FIELD_LIST:[...Jn,...Sa],TEXT:[...Jn],COMMENT:[b.EDIT,b.DELETE,b.YANK]},hy=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Cr=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&k(n)),Mu=e=>e.parentNodeId===fe,vy=({selectedNode:e,breadCrumb:t})=>{let n=gy(e?.context);return Cr({breadCrumb:t,selectedNode:e})?n.includes(at.DESCRIPTION)?n:[...n,at.DESCRIPTION]:n},yy=({selectedNode:e,breadCrumb:t})=>{let n=Cr({breadCrumb:t,selectedNode:e});return n?[Ne.REF,Ne.TITLE,...n.props?.description?.trim()?[Ne.DESCRIPTION]:[],...In(n).length>0?[Ne.TAGS]:[],...xn(n).length>0?[Ne.ASSIGNEES]:[]]:e?[Ne.REF,Ne.TITLE]:[]},Ca=()=>{let e=Bs({exclude:process.cwd()});return a(e)?[]:[...e.value.map((t,n)=>String(n+1)),...e.value.map(t=>t.root)]},by=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:o}=Os();if(!o)return[b.HELP,b.CONFIG];if(!Su())return[b.HELP,b.INIT,b.OPEN];if(t)return[b.HELP,b.PEEK,b.REPLAY,b.EXPORT,b.CONFIG,b.YANK];let r=e?.context,s=r&&my.includes(r),d=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?fy[u]:[]))],c=Cr({breadCrumb:n,selectedNode:e});return d.filter(u=>u===b.MOVE?!1:u===b.YANK?!!(c??e):u===b.EDIT?s||!!c:u===b.DELETE?s:u===b.UNTAG?!!(c&&In(c).length>0):u===b.UNASSIGN?!!(c&&xn(c).length>0):u===b.RE_OPEN_ISSUE?!!(c&&Mu(c)):u===b.CLOSE_ISSUE?!!(c&&!Mu(c)):!0)},Ae=(e,{contextNode:t,selectedNode:n,readOnly:o,breadCrumb:r}=g())=>{let s=t.context??"WORKSPACE";return{[b.NONE]:by({breadCrumb:r,readOnly:o,selectedNode:n}),[b.EXIT]:["confirm"],[b.EXPORT]:[],[b.SYNC]:[],[b.INIT]:[],[b.OPEN]:e===b.OPEN?Ca():[],[b.HELP]:[],[b.PEEK]:[...Ra(),"now","prev","next"],[b.REPLAY]:[...Ra()],[b.EDIT]:vy({selectedNode:n,breadCrumb:r}),[b.YANK]:yy({selectedNode:n,breadCrumb:r}),[b.COMMENT]:[],[b.DELETE]:["confirm"],[b.RE_OPEN_ISSUE]:["confirm"],[b.CLOSE_ISSUE]:["confirm"],[b.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[b.FILTER]:["tag","assignee","actor","description","title","ref","clear"],[b.TAG]:[...new Set([...Object.keys(yo),...I.getExistingTags()])],[b.UNTAG]:[...$s()?.value?.map(({name:c})=>c)??[]],[b.UNASSIGN]:[...js()?.value?.map(({name:c})=>c)??[]],[b.ASSIGN]:I.getExistingAssignees(),[b.NEW]:hy(s),[b.CONFIG]:[...py]}[e]??[]}});var Pu,Lu=h(()=>{"use strict";Pu=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"]});import{accessSync as Iy,copyFileSync as xy,existsSync as Gs,mkdirSync as Du,readdirSync as Fu,readFileSync as Ey,renameSync as Ry,rmSync as Sy,statSync as _u,unlinkSync as Ny,writeFileSync as Ay}from"node:fs";import bo from"node:path";var wa,ze,zs=h(()=>{"use strict";wa=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",ze={writeToFile:(e,t)=>{try{let n=bo.dirname(e);Gs(n)||Du(n,{recursive:!0});let o=typeof t=="string"?t:JSON.stringify(t,null,2);Ay(e,o,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return Ey(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=ze.readFile(e);return t===null?null:JSON.parse(t)}catch(t){return logger.error(`Failed to read JSON at ${e}:`,t),null}},dirExists:e=>{try{return Gs(e)&&_u(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await Iy(e),!0}catch{return!1}},mkDir:e=>Du(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=bo.parse(t);for(;;){let o=bo.join(t,e);try{if(Gs(o)&&_u(o).isDirectory())return o}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=bo.dirname(t)}return null},readFirstJSON(e){try{if(!ze.dirExists(e))return null;let t=Fu(e).filter(o=>o.endsWith(".json")).sort()[0];if(!t)return null;let n=bo.join(e,t);return ze.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return ze.dirExists(e)?Fu(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{Ny(e)}catch(t){(!wa(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{Sy(e,{recursive:!0,force:!0})}catch(t){(!wa(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(bo.dirname(t)),!n?.overwrite&&Gs(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{Ry(e,t)}catch(o){if(wa(o)&&o.code==="EXDEV"){xy(e,t),this.rmFile(e);return}throw o}}}});import Cy from"node:path";import{z as on}from"zod";var wy,Bu,Ty,Ou,Ta,Ma,My,Io,Uu,Ve,wr,Ut=h(()=>{"use strict";Mn();ae();R();zs();wy={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},Bu=on.object({logLevel:on.enum(["info","error","debug"]),preferredEditor:on.string().optional(),userName:on.string().optional(),userId:on.string().optional(),autoSync:on.boolean().nullable().optional(),autoSyncDebounceMs:on.number().optional(),attachmentMaxKb:on.number().optional(),viewMode:on.enum(["dense","wide"]).optional()}).partial(),Ty="config.json",Ou=Xt,Ta=()=>Cy.join(Ou(),Ty),Ma=()=>{try{return ze.mkDir(Ou()),l(`Ensured ~/${St} exists`,null)}catch{return i(`Unable to create ~/${St}`)}},My=e=>{let t;try{t=JSON.parse(e)}catch{return i(`Invalid ~/${St}/config.json JSON`)}let n=Bu.safeParse(t??{});return n.success?l("Parsed config",n.data):i(`Invalid ~/${St}/config.json shape: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},Io=()=>{let e=Ma();if(a(e))return i(e.message);let t=Ta(),n=ze.readFile(t);return n==null||n.trim()===""?l("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):My(n)},Uu=e=>{let t=Ma();if(a(t))return i(t.message);let n=Bu.safeParse(e);if(!n.success)return i(`Invalid config: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`);let o=Ta();try{return ze.writeToFile(o,JSON.stringify(n.data,null,2)+`
|
|
58
|
-
`),l("Config written",null)}catch{return i(`Unable to write ~/${St}/config.json`)}},Ve=e=>{let t=Io();if(a(t))return i("Failed to read existing config");let n={...t.value,...e};return Uu(n)},wr=()=>{let e=Ta(),t=Ma();if(a(t))return i(`Unable to create ~/${St}`);if(!(ze.readFile(e)!==null)){let A=Uu(wy);if(a(A))throw new Error(`Unable to create ~/${St}/config.json`)}let o=Io();if(a(o))throw new Error(o.message||"Unable to load settings");let{preferredEditor:r,userName:s,userId:d,autoSync:c,autoSyncDebounceMs:u,attachmentMaxKb:m,logLevel:p,viewMode:f}=o.value,x=wi({userId:d,userName:s});if(a(x))return i(x.message);let S=x.value??{userId:d,userName:s};return!S.userName||!S.userId?i(`User name or ID not configured in ~/${St}/config.json`):(process.env.EPIQ_LOG_LEVEL=p,l("successfully loaded settings",{logLevel:p??"debug",preferredEditor:r??"",userName:S.userName,userId:S.userId,autoSync:c??!1,autoSyncIntervalMs:u??1e4,attachmentMaxKb:m??null,viewMode:f??"dense"}))}});var $u,ju,ka,Hu=h(()=>{"use strict";$u="/media/",ju=e=>`${$u}${e}`,ka=(e,t)=>`})`});import ky from"node:crypto";import Pa from"node:fs";import Py from"node:path";var rn,xo,Ly,Dy,Fy,Wu,Eo=h(()=>{"use strict";Tt();R();ae();Hu();rn=500,xo=(e,t)=>`${e}.${t}`,Ly=e=>e.length>=8&&e.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))?l("Sniffed image type","png"):e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?l("Sniffed image type","jpg"):e.length>=6&&(e.subarray(0,6).equals(Buffer.from("GIF87a","ascii"))||e.subarray(0,6).equals(Buffer.from("GIF89a","ascii")))?l("Sniffed image type","gif"):e.length>=12&&e.subarray(0,4).equals(Buffer.from("RIFF","ascii"))&&e.subarray(8,12).equals(Buffer.from("WEBP","ascii"))?l("Sniffed image type","webp"):i(`Unsupported image format. Allowed: ${Ec.join(", ")}`),Dy=e=>ky.createHash("sha256").update(e).digest("hex"),Fy=(e,t=rn)=>{if(e.length===0)return i("Attachment is empty");if(e.length>t*1024)return i(`Attachment exceeds the ${t} KB size cap (${Math.ceil(e.length/1024)} KB)`);let n=Ly(e);return a(n)?n:l("Validated attachment data",{hash:Dy(e),ext:n.value,bytes:e.length})},Wu=(e,t,n=rn)=>{let o=Fy(t,n);if(a(o))return o;let r=ps(e),s=Py.join(r,xo(o.value.hash,o.value.ext));try{Pa.existsSync(s)||(Pa.mkdirSync(r,{recursive:!0}),Pa.writeFileSync(s,t))}catch(d){return i(`Unable to write attachment blob: ${d instanceof Error?d.message:String(d)}`)}return l("Wrote attachment blob",o.value)}});import _y from"zod";var Tr,Mr,qu,La=h(()=>{"use strict";Ut();Eo();me();R();de();Be();M();Tr=50,Mr=5e3,qu=()=>{let e=ie().commandMeta.inputString,t=_y.coerce.number().int().min(Tr).max(Mr).safeParse(e);if(!t.success)return i(`Attachment size cap must be ${Tr}-${Mr} KB (default ${rn})`);let n=Ve({attachmentMaxKb:t.data});return a(n)?n:(ut({attachmentMaxKb:t.data}),E({mode:y.DEFAULT}),l(`Attachment size cap set to ${t.data} KB`,null))}});import Gu from"chalk";var Fa,zu,Da,Vu,By,Oy,Ku,Uy,$y,kr,Ce,Yu,Xu,Vs,jy,Hy,Ks,dt=h(()=>{"use strict";Us();Fa={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},zu=(e,t,n)=>Math.max(t,Math.min(n,e)),Da=(e,t,n)=>e+(t-e)*n,Vu=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},By=e=>e.toLowerCase().trim(),Oy=(e,t,n)=>{let o=t/100,r=n/100,s=(1-Math.abs(2*r-1))*o,d=e/60,c=s*(1-Math.abs(d%2-1)),u=0,m=0,p=0;d>=0&&d<1?(u=s,m=c):d>=1&&d<2?(u=c,m=s):d>=2&&d<3?(m=s,p=c):d>=3&&d<4?(m=c,p=s):d>=4&&d<5?(u=c,p=s):(u=s,p=c);let f=r-s/2;return[Math.round((u+f)*255),Math.round((m+f)*255),Math.round((p+f)*255)]},Ku=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,Uy=(e,t,n)=>{let o=zu(n,0,1);return[Math.round(Da(e[0],t[0],o)),Math.round(Da(e[1],t[1],o)),Math.round(Da(e[2],t[2],o))]},$y=(e,t,n)=>Uy(e,t,n),kr=e=>{let t=Vu(e)%360,n=Oy(t,Fa.stringColor.saturation,Fa.stringColor.lightness);return Ku(n)},Ce=(e,t=yo)=>{let n=By(e??"");return n&&t[n]?t[n]:kr(n)},Yu=e=>{let t=Fa.gradient.stops,n=zu(e,0,1);if(t.length===0)return[0,0,0];if(t.length===1)return t[0];let o=t.length-1,r=n*o,s=Math.min(Math.floor(r),o-1),d=r-s;return $y(t[s],t[s+1],d)},Xu=e=>Ku(Yu(e)),Vs=e=>Vu(e.toLowerCase().trim())/4294967295,jy=e=>{let t=Vs(e);return Yu(t)},Hy=e=>{let[t,n,o]=jy(e);return{normal:r=>Gu.bgRgb(t,n,o).black(r),cursor:r=>Gu.bgRgb(t,n,o).white.bold(r)}},Ks=e=>Hy(e).normal(` ${e} `)});var Ke,sn=h(()=>{"use strict";Ke=(e,t,n)=>t.length>n?`${e} cannot exceed ${n} characters (got ${t.length})`:null});import{createHash as Wy}from"node:crypto";var qy,Gy,Me,Ro=h(()=>{"use strict";qy="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Gy=e=>{let t=Wy("sha256").update(e).digest(),n=0n;for(let r=0;r<16;r++)n=n<<8n|BigInt(t[r]);let o="";for(let r=0;r<26;r++){let s=BigInt((25-r)*5);o+=qy[Number(n>>s&31n)]}return o},Me=(e,t)=>Gy(`${e}:virtual:${t}`)});import Ju from"chalk";var ce,ke,De,Qu=h(()=>{"use strict";dt();je();ce=e=>Ju.dim(e),ke=e=>Ju.hex(C.primary)(e),De=({prefix:e="",wordList:t,postfix:n="",noOfHints:o=100,inputString:r,minLengthForHints:s=1})=>{let d=r.trim();if(d.length<s)return"";let p=[...t.filter(Boolean).filter(f=>f.startsWith(d))].sort((f,x)=>Vs(f)-Vs(x)).slice(0,o).map(f=>Ks(f)).join(" ");return p?`${ce(e)}${p}${ce(n)}`:""}});var En,Ys=h(()=>{"use strict";En={None:"none",Invalid:"invalid",Valid:"valid"}});import tm from"chalk";var zy,Zu,ue,Z,W,No,em,Xs,_a,Vy,So,Ky,Yy,Xy,Jy,Qy,nm,om=h(()=>{"use strict";Fs();Sr();Lu();et();Tt();R();te();Be();La();Eo();M();dt();sn();Nr();Ro();Qu();Yn();Ys();nn();Ar();zy=["BOARD","TICKET","SWIMLANE"],Zu=()=>{let e=g().selectedNode;if(!e?.context)return W({message:ce("Missing target context")});if(zy.includes(e.context))return Z();if(e.parentNodeId){let t=g().nodes[e.parentNodeId];if(t?.id===Me(t?.parentNodeId??"","comments"))return Z()}return W({message:ce("Command not available in this context")})},ue="<ENTER> to confirm",Z=(e="",t=[])=>({message:ce(e),validity:En.Valid,completionWordList:t}),W=({message:e,completionWordList:t=[]})=>({validity:En.Invalid,message:e,completionWordList:t}),No=e=>e.length===0,em=(e,t)=>{let n=tt(g().breadCrumb,"BOARD");if(a(n))return W({message:ke("Command is not applicable in this context")});let o=xc(n.value.id);return a(o)?W({message:ke(`Unable to ${t}: board id is not a valid ULID`)}):wu({date:e,horizonDate:o.value})?null:W({message:ke(`nothing to ${t} before ${o.value.toISOString().slice(0,16).replace("T"," ")}`)})},Xs=e=>` ${tm.hex("#000").bgHex(Ce(e))(` ${e} `)} `,_a=({modifier:e})=>{let t="confirm";return e===t?Z(ue):W({message:No(e)?ce("if you are certain, enter ")+Ks(t):"",completionWordList:[t]})},Vy=({list:e,hint:t,onValue:n})=>({modifier:o,inputString:r})=>e.includes(o)?r.trim().length<1?W({message:ce(n)}):Z():W({message:No(o)?t:"",completionWordList:[...e]}),So=({hint:e,onOk:t})=>({modifier:n,inputString:o})=>No(n)&&No(o)?W({message:e,completionWordList:[]}):Z(t??ue),Ky=({modifier:e,inputString:t})=>{let n=Ca();return!No(e)||!No(t)?Z(ue):W({message:n.length?ce("number from the list, or a path"):ce("path to an epiq project"),completionWordList:n})},Yy=({modifier:e,inputString:t})=>{let n=Ae(b.CONFIG);if(!n.includes(e))return W({message:De({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case he.EDITOR:{let o=[...Pu];return t.trim()?o.includes(t.trim())?Z(ue):W({message:De({prefix:"editors: ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o}):W({message:De({prefix:"editors: ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o})}case he.VIEW:{let o=["dense","wide"];return o.includes(t.trim())?Z(ue):W({message:De({prefix:"view... ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o})}case he.USERNAME:return t.trim()?Z(ue):W({message:ke("Enter a user name. Saved in ")+tm.bgBlack("~/.epiq-global/config.json")});case he.LOG_LEVEL:{let o=["debug","error","info"],r=t.trim();return o.includes(r)?Z(ue):W({message:De({prefix:"one of: ",wordList:[...o],inputString:r,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...o]})}case he.AUTOSYNC:{let o=["on","off"],r=Ie().autoSync;if(!o.includes(t.trim())){let s=Nu(r);return W({message:De({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:o,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:o})}return Z(ue)}case he.ATTACHMENT_MAX_KB:{let o=Ie().attachmentMaxKb,r=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(r)||r<Tr||r>Mr){let s=De({prefix:" examples: ",wordList:Aa,minLengthForHints:0,inputString:t});return W({message:ke(`provide a size cap in KB (${Tr}-${Mr}). current: ${o??rn} KB.`)+s,completionWordList:Aa})}return Z(ue)}case he.SYNC_DEBOUNCE_MS:{let o=Ie().autoSyncIntervalMs,r=gu(t);if(!t.trim()||r===null||r<fo){let s=De({prefix:" examples: ",wordList:Na,minLengthForHints:0,inputString:t});return W({message:ke(`provide duration above ${fo}ms. current duration: ${o}ms.`)+s,completionWordList:Na})}return Z(ue)}default:return W({message:ke("Unknown config option"),completionWordList:n})}},Xy=({modifier:e,inputString:t})=>{let n=Ae(b.EDIT);if(!n.length)return W({message:ke("Command not available in this context")});if(!n.includes(e)){let o=De({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return W({message:o||ke("Unknown edit option"),completionWordList:n})}switch(e){case at.COMMENT:return t.trim()?Z(ue):W({message:ce("write a comment...")});case at.TITLE:return Z(ue);case at.DESCRIPTION:{let{preferredEditor:o}=Ie();return o?Z(ce("<ENTER> to edit in ")+o):W({message:"No editor selected"})}default:return W({message:ke("Unknown edit option"),completionWordList:n})}},Jy=({modifier:e})=>{let t=Ae(b.YANK);return t.length?t.includes(e)?Z(ue+ce(" and copy to clipboard")):W({message:De({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):W({message:ke("Nothing selected to copy from")})},Qy={[b.EXPORT]:()=>Z(ue+ce(", and create export markdown file")),[b.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return Z(ue);let n={message:ce("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},o=t||e.inputString.trim(),r=Xn(o);if(!o||!r)return W(n);let s=em(r,"peek");return s||Z(ue)},[b.REPLAY]:e=>{let{dateInput:t,durationInput:n}=Ws(e.modifier,e.inputString),o={message:ce("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},r=Xn(t);if(!t||!r)return W(o);let s=em(r,"replay");return s||(n&&Hs(n)===null?W({message:ke("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):Z("<ENTER> to replay board history",n?ku:[]))},[b.EXIT]:()=>Z(ue+ce(" and exit the application")),[b.INIT]:()=>Z(ue),[b.OPEN]:Ky,[b.PALETTE]:()=>Z(ue),[b.FILTER]:e=>{if(e.modifier==="clear")return Z(ue);let t=s=>Ae(b.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return W({message:De({wordList:Ae(b.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:Ae(b.FILTER)});let n=Object.values(g().tags).map(s=>s.name),o=Object.values(g().contributors).map(s=>s.name),r=e.modifier==="tag"?n:e.modifier==="assignee"?o:[];return e.inputString?r.length&&!r.includes(e.inputString.trim())?W({message:De({prefix:`existing ${e.modifier}s... `,wordList:r,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:r}):Z():W({message:De({prefix:"one of... ",wordList:r,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:r})},[b.NONE]:e=>{let t=Ae(b.NONE);return W({message:De({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[b.NEW]:e=>Vy({list:Ae(b.NEW),hint:De({wordList:Ae(b.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[b.HELP]:()=>Z(ue),[b.EDIT]:Xy,[b.COMMENT]:e=>{let t=So({hint:ce(`write a comment (max ${4e3} char)...`),onOk:ce(`(${e.inputString.length}/${4e3})`)})(e);return t.validity===En.Invalid?t:e.inputString.length>4e3?Z(ke("max input exceeded")):t},[b.CONFIG]:Yy,[b.YANK]:Jy,[b.DELETE]:e=>{let t=Zu();return t.validity==="invalid"?t:_a(e)},[b.CLOSE_ISSUE]:e=>_a(e),[b.RE_OPEN_ISSUE]:e=>_a(e),[b.MOVE]:e=>{let t=Zu();return t.validity==="invalid"?t:So({hint:De({prefix:"hey hacker! These commands are blocked for you... ",wordList:Ae(b.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[b.TAG]:e=>{let n=I.getExistingTags().slice(0,10).map(Xs).join("");return So({hint:n.length?ce("create tag or reuse:")+n+ce(""):ce("create tag ...")})(e)},[b.UNTAG]:e=>{let t=$s();if(a(t))return W({message:ke("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:o})=>o).map(Xs).slice(0,10);return n.length?So({hint:ce(" ... ")+n.join("")})(e):W({message:ke("Issue has no tags"),completionWordList:[]})},[b.ASSIGN]:e=>{let t=I.getExistingAssignees().map(Xs).slice(0,10);return So({hint:ce("assignees... ")+t.join("")})(e)},[b.UNASSIGN]:e=>{let t=js();if(a(t))return W({message:ke("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:o})=>o).map(Xs).slice(0,10);return n.length?So({hint:ce("remove assignee... ")+n.join("")})(e):W({message:ke("Issue has no assignees"),completionWordList:[]})},[b.SYNC]:()=>Z(ue)},nm=Object.fromEntries(Object.entries(Qy).map(([e,t])=>[e,{validate:(n,o,r)=>t({modifier:o,command:n,inputString:r})}]))});var Js,rm=h(()=>{"use strict";Js=["add","fix","bug","log","run","api","cli","ui","ux","test","mock","stub","sync","hash","sign","fork","push","pull","lock","warn","leak","hang","node","seed","lint","edit","save","load","read","send","drop","swap","wrap","port","host","role","user","auth","flag","diff","perf","docs","todo","task","team","epic","spec","remove","update","change","improve","enhance","refactor","rewrite","redesign","implement","build","create","delete","rename","migrate","upgrade","downgrade","revert","rollback","restore","replace","deprecate","cleanup","simplify","optimize","stabilize","harden","document","clarify","investigate","debug","reproduce","triage","mitigate","remediate","resolve","escalate","verify","validate","benchmark","profile","audit","monitor","instrument","configure","provision","deploy","release","publish","integrate","automate","support","enable","disable","prevent","handle","ensure","prioritize","estimate","schedule","track","install","uninstall","enforce","expose","extract","inject","override","extend","customize","localize","translate","redirect","forward","dispatch","broadcast","subscribe","unsubscribe","register","allocate","reserve","persist","retrieve","archive","expire","refresh","reload","reset","recover","replay","retry","scaffold","bootstrap","finalize","terminate","suspend","resume","cancel","abort","notify","alert","trigger","debounce","frontend","backend","fullstack","infrastructure","architecture","integration","application","environment","framework","platform","service","component","module","gateway","pipeline","container","orchestrator","middleware","endpoint","interface","database","datastore","cache","queue","scheduler","worker","daemon","runtime","library","package","plugin","extension","webhook","microservice","monolith","repository","namespace","cluster","sandbox","tenant","dashboard","console","portal","client","server","browser","mobile","desktop","kernel","driver","protocol","schema","migration","fixture","template","snippet","config","manifest","bundle","exception","incident","defect","regression","degradation","malfunction","instability","intermittent","workaround","failure","outage","crash","freeze","corruption","inconsistency","severity","criticality","diagnostics","analysis","blocker","flaky","timeout","mismatch","misconfiguration","boundary","overflow","underflow","panic","stacktrace","breakage","breaking","oversight","ambiguity","discrepancy","anomaly","authorize","authenticate","confidentiality","availability","accessibility","reliability","compliance","governance","encrypt","decrypt","integrity","traceability","accountability","protection","privileges","permissions","sanitize","escape","vulnerability","exposure","secrets","credentials","certificate","session","cookie","identity","tokenization","rotation","scanning","hardening","threat","exploit","payload","injection","phishing","breach","dependency","orchestrate","synchronize","compatibility","incompatibility","interoperability","observability","telemetry","discovery","registration","coordination","distribution","isolation","virtualization","networking","routing","proxy","firewall","balancer","failover","topology","replica","shard","region","capacity","quota","metrics","logging","tracing","alerting","monitoring","heartbeat","liveness","rollover","serialize","deserialize","initialize","instantiate","propagate","aggregate","consolidate","normalize","standardize","transform","reconcile","correlate","index","partition","enrich","filter","stream","batch","parse","encode","decode","compress","decompress","deduplicate","paginate","query","ingest","export","import","backup","snapshot","mapping","record","dataset","metadata","checksum","rollup","lookup","cursor","truncate","concurrency","parallelism","contention","deadlock","throttle","backpressure","fragmentation","saturation","exhaustion","replicate","redundancy","obsolescence","starvation","overload","latency","throughput","scalability","bottleneck","memoize","prefetch","warmup","autoscale","horizontal","vertical","elasticity","recursion","allocation","leakage","garbage","collection","pooling","buffering","caching","eviction","staleness","modularize","encapsulate","abstraction","extensibility","configurability","maintainability","recoverability","readability","testability","debuggability","reusability","simplicity","consistency","linting","formatting","typecheck","coverage","tooling","scaffolding","boilerplate","technical","cleanliness","naming","comments","docstring","testing","unittest","mocking","stubbing","assertion","smoke","sanity","fuzzing","flakiness","harness","scenario","baseline","performance","functionality","requirement","recommendation","improvement","enhancement","description","acceptance","criteria","deliverable","milestone","iteration","backlog","roadmap","followup","hotfix","patch","changelog","rollout","feature","spike","proposal","specification","priority","sprint","story","subtask","assignee","reviewer","reproduction","context","expected","actual","impact","workflow","version","tracking","discussion","decision","tradeoff","feedback","approval","planning","breakdown","scoping"]});var Zy,eb,tb,nb,ob,sm,im,am,dm=h(()=>{"use strict";R();M();rm();Zy=3,eb=new Set(["the","and","for","are","but","not","you","all","any","can","was","one","our","out","use","this","that","with","have","from","will","your","they","them","then","than","when","what","were","been","into","should","would","could","about"]),tb=e=>{let t=[];for(let n of Object.values(e.nodes)){n.title&&t.push(n.title);let o=n.props;typeof o.description=="string"&&t.push(o.description),typeof o.value=="string"&&t.push(o.value)}for(let n of Object.values(e.tags))t.push(n.name);for(let n of Object.values(e.contributors))t.push(n.name);for(let n of Object.values(e.comments))t.push(n.md);return t},nb=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=Zy&&!eb.has(t)&&!/^\d+$/.test(t)),ob=e=>{let t=new Map;for(let s of tb(e))for(let d of nb(s))t.set(d,(t.get(d)??0)+1);let n=[...t.entries()].sort((s,d)=>d[1]-s[1]||s[0].localeCompare(d[0])).map(([s])=>s),o=new Set(n),r=Js.filter(s=>!o.has(s));return[...n,...r]},sm=Js,im=-1,am=()=>{let e=$e();if(a(e))return Js;let t=e.value,n=t.eventLog.length;return n!==im&&(sm=ob(t),im=n),sm}});var cm,lm,Ba=h(()=>{"use strict";Lc();nn();Yn();om();dm();M();me();cm=e=>Object.values(b).includes(e),lm=(e,t)=>{let n=e.command??"",{modifier:o,target:r,inputString:s}=e,{message:d,validity:c,completionWordList:u}=nm[n].validate(n,o,s),m=n!==b.PEEK&&n!==b.REPLAY,p=r==="command"||r==="modifier"?Ae(n):m?am():[],{mode:f}=g(),x=f===y.COMMAND_LINE?d??"":"",S=[...u,...p];return{validity:c,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:x,autoCompletion:t?Pc(e,S):{hint:"",hints:[],remainder:"",overlap:0}}}});var um,rb,sb,ib,mm=h(()=>{"use strict";Ba();nn();um=e=>{let t=e.trimStart(),n=sb(t),o=n[0]??"",r=n[1]??"",s=/\s$/.test(e),d=ib(e),c=cm(o)?o:null,u=c!==null,m=o!=="",p=c?Ae(c)??[]:[],f=c&&p.includes(r)?r:"",x="word";n.length===0||n.length===1&&!s?x="command":(n.length===1&&s||n.length===2&&!s)&&(x="modifier");let S=s?"":d,A=rb(t,c,f);return{raw:e,trimmedStart:t,words:n,firstWord:o,lastWord:d,hasCommand:m,command:c,isCommandKeyword:u,isLastWordCompleted:s,modifier:f,target:x,inputToMatch:S,inputString:A}},rb=(e,t,n)=>{let o=e;return t&&o.startsWith(t)&&(o=o.slice(t.length)),o=o.replace(/^\s+/,""),n&&o.startsWith(n)&&(o=o.slice(n.length),o=o.replace(/^\s+/,"")),o},sb=e=>e.trim()?e.trim().split(/\s+/):[],ib=e=>e.trimEnd().split(/\s+/).at(-1)??""});import{useSyncExternalStore as AT}from"react";var Ao,Oa,Co,ab,pm,$t,Pr,Ua,$a,gm,fm,Qs,hm,ee,vm,ym,bm,ie,Zs,de=h(()=>{"use strict";Ba();mm();R();Ys();Ao=e=>e===Oa||e===":",Oa=" ",Co={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:En.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},ab=new Set,pm=()=>{for(let e of ab)e()},$t=e=>{let n=e(Co),o=um(n.value),r=n.cursorPosition===n.value.length;Co={...n,commandMeta:lm(o,r)},pm()},Pr=({message:e,status:t})=>{let n=structuredClone(Co);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,Co=n,pm(),l(e,null)},Ua=e=>{$t(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},$a=e=>{$t(t=>{let{value:n,cursorPosition:o}=t,r=o;if(e==="left"){for(;r>0&&Ao(n[r-1]);)r--;for(;r>0&&!Ao(n[r-1]);)r--}else{for(;r<n.length&&!Ao(n[r]);)r++;for(;r<n.length&&Ao(n[r]);)r++}return{...t,cursorPosition:r}})},gm=()=>{$t(e=>{let t=e.value.slice(e.cursorPosition),n=Math.max(0,e.cursorPosition-1);return{...e,value:e.value.slice(0,n)+t,cursorPosition:n,commandIsPending:!1}})},fm=()=>{$t(e=>{let{value:t,cursorPosition:n}=e,o=n;for(;o>0&&Ao(t[o-1]);)o--;for(;o>0&&!Ao(t[o-1]);)o--;let r=t.slice(n);return{...e,value:t.slice(0,o)+r,cursorPosition:o,commandIsPending:!1}})},Qs=e=>{$t(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),o=t.value.slice(0,n),r=t.value.slice(n),s=e(o,t.commandMeta.autoCompletion),d=s+r,c=Math.max(0,Math.min(s.length,d.length));return{...t,value:d,cursorPosition:c,commandIsPending:!1}})},hm=()=>{$t(e=>({...e,commandIsPending:!0}))},ee=e=>{$t(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},vm=({addToHistory:e=!0})=>{$t(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},ym=()=>{$t(e=>{let t=Math.min(e.commandHistoryIndex+1,e.commandHistory.length-1),n=e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},bm=()=>{$t(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},ie=()=>Co,Zs=()=>{let[e,...t]=Co.value.split(Oa);return t.join(Oa).trim()}});var F,kn=h(()=>{"use strict";me();Sc();M();de();Be();F={NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MoveToPreviousContainer:"moveToPreviousContainer",MoveToNextContainer:"moveToNextContainer",Confirm:"confirm",Exit:"exit",ViewHelp:"viewHelp",HideHelp:"hideHelp",InitMove:"initMove",ConfirmMove:"confirmMove",Delete:"Delete",InitCommandPalette:"initCommandPalette",InitCommandLine:"initCommandLine",ExitCommandLine:"exitCommandLine",CaptureInput:"captureInput",EraseInput:"eraseInput",AddItem:"addItem",GetLastCommandFromHistory:"getLastCommandFromHistory",GetNextCommandFromHistory:"getNextCommandFromHistory",AutoCompleteCommand:"autoCompleteCommand",MoveCursorLeft:"MoveCursorLeft",MoveCursorRight:"MoveCursorRight",MoveCursorLeftOfWord:"MoveCursorLeftOfWord",MoveCursorRightOfWord:"MoveCursorRightOfWord",EraseInputWord:"EraseInputWord",None:"None",Edit:"edit",EditTitle:"editTitle",EditDescription:"editDescription",Yank:"yank",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"}});var Im,O,ja=h(()=>{"use strict";M();Yn();Im=e=>{let{context:t}=g().contextNode;if(!t)return O.None;switch(e){case b.EXIT:return O.Exit;case b.EXPORT:return O.Export;case b.INIT:return O.Init;case b.OPEN:return O.OpenProject;case b.DELETE:return O.Delete;case b.EDIT:return O.Edit;case b.COMMENT:return O.Comment;case b.HELP:return O.ViewHelp;case b.RE_OPEN_ISSUE:return O.ReopenIssue;case b.CLOSE_ISSUE:return O.CloseIssue;case b.TAG:return O.TagTicket;case b.UNTAG:return O.UntagTicket;case b.ASSIGN:return O.AssignUserToTicket;case b.UNASSIGN:return O.UnassignUserFromTicket;case b.NEW:return O.NewItem;case b.FILTER:return O.Filter;case b.MOVE:return O.Move;case b.PEEK:return O.Peek;case b.REPLAY:return O.Replay;case b.CONFIG:return O.Config;case b.YANK:return O.Yank;case b.SYNC:return O.Sync;default:return O.None}},O={Exit:"exit",Init:"init",OpenProject:"open-project",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",Replay:"replay",Yank:"yank",Config:"config",NewItem:"add-new-item",TagTicket:"ticket-tag",UntagTicket:"ticket-untag",AssignUserToTicket:"ticket-assign-user",UnassignUserFromTicket:"ticket-unassign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Comment:"comment-issue",Sync:"sync",Export:"export"}});import{Text as xm}from"ink";import Em,{useEffect as Rm,useState as db}from"react";var Sm,Xe,wo=h(()=>{"use strict";M();je();Sm={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},Xe=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=Je(),o=Sm[n]??Sm.default,[r,s]=db(0);if(Rm(()=>{s(0)},[o]),Rm(()=>{if(!e)return;let c=setInterval(()=>{s(u=>(u+1)%o.length)},500);return()=>clearInterval(c)},[e,o]),!e)return Em.createElement(xm,null,t);let d=o[r]??o[0]??t;return Em.createElement(xm,{color:C.accent,dimColor:r===1},d)}});import{Box as Ha,Text as cb}from"ink";import ei from"react";var lb,Rn,Lr=h(()=>{"use strict";je();lb=(e,t,n,o)=>{let r=u=>Math.max(1,e[u]??1),s=n,d=n+1,c=r(n);for(;d<t&&c+r(d)<=o;)c+=r(d),d++;for(;s>0&&c+r(s-1)<=o;)s--,c+=r(s);return{start:s,end:d}},Rn=({children:e=[],height:t,selectedIndex:n,itemHeight:o=1,itemHeights:r,scrollByOne:s=!1})=>{if(e.length===0)return null;let d=Math.max(1,Math.floor(t)),c=Math.max(1,Math.ceil(o)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(1,Math.floor(d/c)),p=Math.max(0,e.length-m),{start:f,end:x}=r?lb(r,e.length,u,d):s?{start:Math.min(p,Math.max(0,u-m+1)),end:Math.min(p,Math.max(0,u-m+1))+m}:{start:Math.min(p,Math.floor(u/m)*m),end:Math.min(p,Math.floor(u/m)*m)+m},S=Math.max(1,x-f),A=e.slice(f,x),P=e.length>S,T=d,w=P?Math.max(1,Math.floor(S/e.length*T)):T,_=Math.max(0,T-w),B=Math.max(1,e.length-S),$=P?Math.floor(f/B*_):0;return ei.createElement(Ha,{flexDirection:"row",height:d,width:"100%"},ei.createElement(Ha,{flexDirection:"column",flexGrow:1,height:d},A),ei.createElement(Ha,{flexDirection:"column",width:1,height:T},Array.from({length:T}).map((se,mn)=>ei.createElement(cb,{key:mn,color:P&&mn>=$&&mn<$+w?C.accent:C.secondary},P?"\u2502":" "))))}});var Nm,Wa,ub,ti,qa=h(()=>{"use strict";M();ub=()=>{let{eventLog:e=[]}=g();if(Wa&&Nm===e)return Wa;let t=new Set;for(let n of e)n?.userId&&t.add(n.userId);return Nm=e,Wa=t,t},ti=e=>ub().has(e)});import{Text as mb}from"ink";import pb from"react";var gb,fb,To,ni=h(()=>{"use strict";Us();dt();te();qa();ot();gb=e=>e.toLowerCase().trim(),fb=(e,t=yo)=>{let n=gb(e);return t[n]?t[n]:kr(n)},To=({id:e,isSelected:t,maxWidth:n})=>{let o=I.getContributor(e);if(!o)return;let r=o.name,s=n===void 0?r:Pn(r,n);return pb.createElement(mb,{underline:t,color:fb(r)},"@"+s,ti(e)?"":"\u2197")}});import{Text as hb}from"ink";import vb from"react";var oi,Ga=h(()=>{"use strict";te();je();dt();ot();oi=({id:e,isSelected:t,maxWidth:n})=>{let o=I.getTag(e);if(!o)return;let r=n===void 0?o.name:Pn(o.name,n);return vb.createElement(hb,{underline:t,backgroundColor:Ce(o.name),color:C.secondary}," "+r+" ")}});import{useEffect as yb,useState as bb}from"react";var Ib,Am,ri,Dr,xb,Eb,Mo,si=h(()=>{"use strict";dt();Ib=80,Am=1400,ri=new Set,Dr=null,xb=e=>(ri.add(e),Dr||(Dr=setInterval(()=>{for(let t of ri)t()},Ib)),()=>{ri.delete(e),ri.size===0&&Dr&&(clearInterval(Dr),Dr=null)}),Eb=()=>{let e=Date.now()%Am/Am;return e<.5?e*2:(1-e)*2},Mo=e=>{let[,t]=bb(0);return yb(()=>{if(e)return xb(()=>t(n=>n+1))},[e]),Xu(Eb())}});import{Box as ko,Text as Po}from"ink";import Qe from"react";var Rb,Cm,Sb,Nb,Tm,Mm=h(()=>{"use strict";te();je();ot();qa();st();Nr();ni();Ga();si();Rb=(e,t,n)=>{if(e.length<=t)return[e,null];let o=e.lastIndexOf(" ",t),r=o>0?o:t;return[e.slice(0,r),Pn(e.slice(r).trim(),n)]},Cm=3,Sb=2,Nb=(e,t)=>{let n=[],o=0;for(let[r,s]of e.entries()){let d=e.length-r-1,c=d>0?String(d).length+1:0;if(o+s.width+c>t)break;o+=s.width,n.push(s)}return{shown:n,hidden:e.length-n.length}},Tm=({width:e,ticket:t,isSelected:n,isFlashing:o=!1})=>{let r=Mo(o),s=e-4,d=s-7-1,[c,u]=Rb(pe(t.title),d,s),m=u?null:Pn(pe(t.props.description),s)||null,p=In(t),f=xn(t).map(w=>({...w,name:w.name})),x=Math.max(1,s-Cm),S=I.getCommentsByIssue(t.id),A=S.length?String(S.length).length+2+1:0,{shown:P,hidden:T}=Nb([...p.map(w=>({id:w.id,isTag:!0,width:Math.min(w.name.length,x)+Cm})),...f.map(w=>({id:w.id,isTag:!1,width:Math.min(w.name.length,x)+Sb+(ti(w.id)?0:1)}))],s-A);return Qe.createElement(ko,{borderStyle:"round",height:5,flexDirection:"column",overflow:"hidden",borderDimColor:!n,borderColor:o?r:n?C.accent:C.secondary,justifyContent:"space-between"},Qe.createElement(ko,{paddingLeft:1,paddingRight:1,flexDirection:"column"},Qe.createElement(ko,{justifyContent:"space-between"},Qe.createElement(Po,{color:C.primary},c),Qe.createElement(Po,{color:C.secondary2,dimColor:!0},j(t.id))),u&&Qe.createElement(Po,{color:C.primary},u),m&&Qe.createElement(Po,{color:C.secondary2,dimColor:!0},m)),Qe.createElement(ko,{flexDirection:"row",paddingLeft:1,paddingRight:1,justifyContent:"space-between"},Qe.createElement(ko,{flexDirection:"row"},P.map(w=>Qe.createElement(ko,{paddingRight:1,key:w.id},w.isTag?Qe.createElement(oi,{id:w.id,maxWidth:x}):Qe.createElement(To,{id:w.id,maxWidth:x}))),T>0&&Qe.createElement(Po,{color:C.secondary2,dimColor:!0},"+",T)),S.length>0&&Qe.createElement(Po,{color:C.accent},"[",S.length,"]")))}});import{Box as Qn,Text as Fr}from"ink";import ct from"react";var Ab,km,Pm=h(()=>{"use strict";me();te();je();dt();wo();si();Ab=(e,t)=>e.length>t?e.slice(0,Math.max(0,t-1))+"\u2026":e,km=({index:e,labelWidth:t,width:n,ticket:o,isSelected:r,isFlashing:s=!1,mode:d})=>{let c=Mo(s),u=(o.props.tags??[]).map(se=>I.getTag(se)).filter(se=>!!se),m=(o.props.assignees??[]).map(se=>I.getContributor(se)).map(se=>se&&{...se,name:se.name}).filter(se=>!!se),p=1,f=u.length*(1+p),x=m.length*(2+p),S=u.map(se=>ct.createElement(Qn,{key:se.id,paddingRight:p},ct.createElement(Fr,{color:Ce(se.name)},"\u25A0"))),A=m.map(se=>ct.createElement(Qn,{key:se.id,paddingRight:p},ct.createElement(Fr,{color:kr(se.name)},"@"+se.name.at(0)))),P=s?c:r?C.accent:d===y.MOVE?C.secondary:C.primary,T=I.getCommentsByIssue(o.id),w=T.length?String(T.length).length+2+p:0,_=T.length?ct.createElement(Qn,{paddingRight:p},ct.createElement(Fr,{color:C.accent},"[",T.length,"]")):null,B=f+x+w,$=Math.max(1,n-t-B-(B>0?1:0));return ct.createElement(Qn,{justifyContent:"space-between"},ct.createElement(Qn,null,ct.createElement(Qn,{width:t},r?ct.createElement(Xe,{isSelected:!0}):ct.createElement(Fr,{color:"gray",dimColor:!0},String(e+1).padStart(t-1)+" ")),ct.createElement(Fr,{wrap:"truncate",color:P},Ab(o.title,$))),ct.createElement(Qn,null,S,A,_))}});import Cb from"chalk";import{Box as za,Text as wb}from"ink";import jt from"react";var Tb,Lm,Dm=h(()=>{"use strict";V();M();je();wo();Lr();Mm();Pm();si();Tb=({swimlane:e,isSelected:t,width:n,height:o,isDense:r,isFocused:s,listSelectedIndex:d,mode:c})=>{let{renderedChildrenIndex:u,replay:m}=Je(),p=u[e.id]??[],f=m?new Set(m.flashNodeIds):null,x=f?.has(e.id)??!1,S=Mo(x),A=`${e.title} ${Cb.hex(C.secondary2).dim("("+p.length+")")}`,P=3,T=r?1:5,w=s&&d===-1,_=n-3-(r?1:0)-(w?2:0),B=Math.max(2,String(p.length).length+1),$=o-P-1,se=jt.createElement(za,{borderStyle:"round",borderColor:C.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1,marginRight:r?1:0},jt.createElement(Xe,{isSelected:t}),jt.createElement(wb,{bold:!0,color:x?S:t?C.accent:C.primary},A," ",e.readonly?"\u{1F512}":"")),mn=(zt,so)=>{let qo=s&&d===so;if(!k(zt))return null;let Go=f?.has(zt.id)??!1;return r?jt.createElement(km,{key:zt.id,index:so,labelWidth:B,width:_,ticket:zt,isSelected:qo,isFlashing:Go,mode:c}):jt.createElement(Tm,{key:zt.id,width:_,ticket:zt,isSelected:qo,isFlashing:Go})};return jt.createElement(za,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?C.accent:C.secondary,paddingRight:0,paddingLeft:r?1:0,height:o},se,jt.createElement(za,null,p.length>0&&jt.createElement(Rn,{selectedIndex:d,height:$,itemHeight:T},p.map(mn)),w&&jt.createElement(Xe,{isSelected:!0})))},Lm=jt.memo(Tb)});var Fm,_m,Va=h(()=>{"use strict";On();Fm=e=>{let t=new Set((e.log??[]).filter(n=>n.action==="delete.issue.comment").map(n=>n.payload.id));return(e.log??[]).filter(n=>n.action==="add.issue.comment"&&n.payload.issue===e.id&&!t.has(n.payload.id)).length},_m=(e,t,n)=>Te.comment({id:e.id,parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.id,props:{value:e.md},readonly:!1,isVirtual:!0})});var Lo,ii=h(()=>{"use strict";Lo=e=>{let t=Date.now()-e,n=[{label:"y",ms:1e3*60*60*24*365},{label:"mo",ms:1e3*60*60*24*30},{label:"w",ms:1e3*60*60*24*7},{label:"d",ms:1e3*60*60*24},{label:"h",ms:1e3*60*60},{label:"m",ms:1e3*60},{label:"s",ms:1e3}];for(let{label:o,ms:r}of n){let s=Math.floor(t/r);if(s>=1)return`${s}${o} ago`}return"just now"}});import{Box as Do,Text as an}from"ink";import _e,{useEffect as Mb,useMemo as kb,useRef as Pb}from"react";import{decodeTime as Bm}from"ulid";function Um({ticket:e,width:t,height:n}){let o=kb(()=>Db(e),[e]),r=Pb([]);Mb(()=>(Om(r.current),r.current=_b(e,o),()=>{Om(r.current),r.current=[]}),[e,o]);let{selectedIndex:s}=Je(),c=Math.max(1,n-4),u=Math.max(12,t-32);return o.length===0?_e.createElement(Do,{flexDirection:"column",width:t,height:n,padding:1},_e.createElement(an,{color:C.primary},"No attachments yet."),_e.createElement(Do,{paddingTop:1},_e.createElement(an,{color:C.primary},"Attach images from the browser GUI"),_e.createElement(an,{color:C.accent}," epiq gui "),_e.createElement(an,{color:C.primary},"by dropping or pasting them."))):_e.createElement(Do,{flexDirection:"column",width:t,height:n},_e.createElement(Do,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:C.secondary,borderStyle:"single",paddingBottom:1},_e.createElement(an,{color:C.secondary2},"Attachments (",o.length,") \u2014 enter to open"," ")),_e.createElement(Rn,{height:c,itemHeight:2,selectedIndex:s},o.map((m,p)=>{let f=p===s,x=m.name.length>u?m.name.slice(0,u-1)+"\u2026":m.name;return _e.createElement(Do,{key:m.id,flexDirection:"row",paddingX:1,paddingBottom:1},_e.createElement(an,{color:C.accent},f?"\u276F ":" "),_e.createElement(Do,{paddingLeft:1},_e.createElement(an,{color:C.secondary2},`#${p+1} `),_e.createElement(an,{color:f?C.accent:C.primary},x),_e.createElement(an,{color:C.secondary2}," "+Bb(m.bytes)+" "+Lo(Ze(m.id)))))})))}var Lb,Db,Om,Fb,_b,Bb,$m=h(()=>{"use strict";it();et();ii();V();R();te();On();M();je();Ro();Lr();Lb=e=>Me(e,"attachments"),Db=e=>I.getAttachmentsByIssue(e.id).sort((t,n)=>Bm(t.id)-Bm(n.id)),Om=e=>{for(let t of e)I.deleteNode(t.id)},Fb=(e,t,n)=>Te.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),_b=(e,t)=>{let n=I.getNode(Lb(e.id));if(!n||!nt(n))return[];let o=t.map((r,s)=>Fb(r,s,n.id)).map(r=>I.createNode(r)).filter(wt).map(({value:r})=>r).filter(nt);return t.length>0&&g().selectedIndex<0&&U.navigate({contextNode:n,selectedIndex:0}),o},Bb=e=>`${Math.max(1,Math.round(e/1024))} KB`});var Hm,Ka,jm,Ya,Wm,qm,Ob,Gm,Ub,Xa,zm=h(()=>{"use strict";Hm=/<!--\s*epiq-diff-comment:(.+?)-->\n?/,Ka=e=>e.replace(Hm,""),jm=e=>e==="additions"||e==="deletions",Ya=e=>{let t=Hm.exec(e);if(!t?.[1])return null;let n;try{n=JSON.parse(t[1])}catch{return null}let o=n;return typeof o?.filePath!="string"||typeof o.start!="number"||typeof o.end!="number"||typeof o.note!="string"||!jm(o.side)||!jm(o.endSide)||o.sha!==void 0&&typeof o.sha!="string"||o.issueRef!==void 0&&typeof o.issueRef!="string"?null:o},Wm=/```\n([\s\S]*?)\n?```\s*$/,qm=e=>Wm.exec(e)?.[1]??null,Ob=/`[^`\n]+`[^\n]*\n?$/,Gm=e=>Ka(e).replace(Wm,"").replace(Ob,"").trim(),Ub=e=>{let n=(e.endSide??e.side)==="deletions"?"removed":"added";return e.start===e.end?`line ${e.start} (${n})`:`lines ${e.start}-${e.end} (${n})`},Xa=e=>`${e.issueRef?`${e.issueRef} \xB7 `:""}${e.filePath} ${Ub(e)}`});var $b,_r,jb,Hb,Wb,qb,Km,Ja,Ym,Vm,Xm,Qa=h(()=>{"use strict";zm();$b=(e,t)=>{let n=Math.max(1,Math.floor(t)),o=e.split(/\s+/).filter(Boolean);if(o.length===0)return[""];let r=[],s="";for(let d of o){let c=d;for(;c.length>n;)s&&(r.push(s),s=""),r.push(c.slice(0,n)),c=c.slice(n);s?s.length+1+c.length<=n?s=`${s} ${c}`:(r.push(s),s=c):s=c}return s&&r.push(s),r},_r=e=>{let t=e.split("`");return t.length%2===0?[{text:e}]:t.map((n,o)=>o%2===1?{text:n,code:!0}:{text:n}).filter(n=>n.text.length>0)},jb=/!\[([^\]]*)\]\([^)]*\)/g,Hb=e=>e.replace(jb,(t,n)=>n.trim()?`[image: ${n.trim()}]`:"[image]"),Wb=e=>e.map(t=>t.code?`\`${t.text}\``:t.text).join(""),qb=4,Km=e=>e.replace(/\r$/,"").replaceAll(" "," ".repeat(qb)),Ja=e=>{let t=!1;return e.map(Km).map(n=>{if(/^\s*```/.test(n))return t=!t,{kind:"fence"};if(t)return{kind:"code",text:n};let o=Ya(n);if(o)return{kind:"caption",text:Xa(o)};let r=Hb(n);if(r.trim()==="")return{kind:"blank"};let s=/^#{1,6}\s+(.*)$/.exec(r);return s?{kind:"heading",spans:_r(s[1]??"")}:{kind:"text",spans:_r(r)}})},Ym=(e,t)=>e.length<=t?[e]:e.match(new RegExp(`.{1,${t}}`,"g"))??[""],Vm=(e,t)=>{let n=[];for(let o of Ja(e))if(o.kind!=="fence"){if(o.kind==="blank"){n.length>0&&n[n.length-1]?.kind!=="blank"&&n.push(o);continue}if(o.kind==="code"){for(let r of Ym(o.text,t))n.push({kind:"code",text:r});continue}if(o.kind==="caption"){n.push(o);continue}for(let r of $b(Wb(o.spans),t))n.push({kind:o.kind,spans:_r(r)})}for(;n.length>0&&n[n.length-1]?.kind==="blank";)n.pop();return n},Xm=(e,t)=>{let n=Ya(e),o=n?qm(e):null;if(!n||o===null)return Vm(Ka(e).split(`
|
|
59
|
-
`),t);let r=
|
|
60
|
-
`).map(
|
|
61
|
-
`),t),{kind:"blank"}]:[],{kind:"caption",text:Xa(n)},...s.flatMap((u,m)=>Ym(u,Math.max(1,t-c)).map((p,f)=>({kind:"code",text:p,number:d===void 0||f>0?void 0:d+m})))]}});import{Box as Jm,Text as Zn}from"ink";import It from"react";var Qm,Za,Zm,ed=h(()=>{"use strict";je();Qm=({spans:e,bold:t,wrap:n})=>It.createElement(Zn,{color:C.primary,bold:t,wrap:n},e.map((o,r)=>o.code?It.createElement(Zn,{key:r,color:C.yellow},o.text):It.createElement(Zn,{key:r},o.text))),Za=({line:e,width:t,gutter:n=0,wrap:o})=>{switch(e.kind){case"blank":return It.createElement(Zn,null," ");case"fence":return It.createElement(Zn,{color:C.secondary2},"```");case"caption":return It.createElement(Zn,{color:C.accent,wrap:o},e.text);case"heading":return It.createElement(Qm,{spans:e.spans,bold:!0,wrap:o});case"text":return It.createElement(Qm,{spans:e.spans,wrap:o});case"code":{let r=n>0?`${e.number===void 0?"":String(e.number)}`.padStart(n-3)+" \u2502 ":"";return It.createElement(Zn,{backgroundColor:C.secondary,color:C.primary,wrap:o},r,e.text.padEnd(Math.max(0,t-r.length)))}}},Zm=({lines:e,width:t})=>{let n=e.flatMap(r=>r.kind==="code"&&r.number!==void 0?[r.number]:[]),o=n.length>0?String(Math.max(...n)).length+3:0;return It.createElement(Jm,{flexDirection:"column"},e.map((r,s)=>It.createElement(Jm,{key:s},It.createElement(Za,{line:r,width:t,gutter:o}))))}});import{Box as Sn,Text as Nn}from"ink";import we,{useEffect as Gb,useMemo as ep,useRef as zb}from"react";import{decodeTime as tp}from"ulid";function op({ticket:e,width:t,height:n}){let o=ep(()=>Yb(e),[e]),r=zb([]);Gb(()=>(np(r.current),r.current=Xb(e,o),()=>{np(r.current),r.current=[]}),[e,o]);let{selectedIndex:s}=Je(),c=Math.max(1,n-4),u=Math.max(20,t-8),m=ep(()=>o.map(f=>{let x=Xm(f.md,u);return x.length>0?x:[{kind:"blank"}]}),[o,u]),p=m.map(f=>f.length+Vb);return o.length===0?we.createElement(Sn,{flexDirection:"column",width:t,height:n,padding:1},we.createElement(Nn,{color:C.primary},"No comments yet."),we.createElement(Sn,{paddingTop:1},we.createElement(Nn,{color:C.primary},"Use"),we.createElement(Nn,{color:C.accent}," :comment "),we.createElement(Nn,{color:C.primary},"to add the first one."))):we.createElement(Sn,{flexDirection:"column",width:t,height:n},we.createElement(Sn,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:C.secondary,borderStyle:"single",paddingBottom:1},we.createElement(Nn,{color:C.secondary2},"Comments (",o.length,") ")),we.createElement(Rn,{height:c,itemHeights:p,selectedIndex:s},o.map((f,x)=>{let S=x===s;return we.createElement(Sn,{key:f.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:C.secondary,borderStyle:"single"},we.createElement(Sn,{flexDirection:"row",paddingBottom:1},we.createElement(Nn,{color:C.accent},S?"\u276F ":" "),we.createElement(Sn,{paddingLeft:1},we.createElement(Nn,{color:C.secondary2},`#${x+1} `),we.createElement(To,{id:f.authorId}),we.createElement(Nn,{color:C.secondary2}," "+Lo(Ze(f.id))))),we.createElement(Sn,{paddingLeft:3,paddingBottom:1},we.createElement(Zm,{lines:m[x]??[],width:u})))})))}var Vb,Kb,Yb,np,Xb,rp=h(()=>{"use strict";it();et();ii();V();R();te();M();je();Ro();ni();Lr();Va();Qa();ed();Vb=4,Kb=e=>Me(e,"comments"),Yb=e=>I.getCommentsByIssue(e.id).sort((t,n)=>tp(t.id)-tp(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),np=e=>{for(let t of e)I.deleteNode(t.id)},Xb=(e,t)=>{let n=I.getNode(Kb(e.id));if(!n||!nt(n))return[];let o=t.map((r,s)=>_m(r,s,n.id)).map(I.createNode).filter(wt).map(({value:r})=>r).filter(Qo);return t.length>0&&g().selectedIndex<0&&U.navigate({contextNode:n,selectedIndex:0}),o}});import{Box as ai,Text as Jb}from"ink";import dn from"react";var sp,ip=h(()=>{"use strict";V();te();uo();M();je();ni();wo();Ga();sp=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:o}=Je(),{title:r}=t,s=t.parentNodeId?I.getNode(t.parentNodeId):void 0,d=s&&k(s)?r===le.ASSIGNEES?s.props.assignees??[]:r===le.TAGS?(s.props.tags??[]).filter(c=>I.getTag(c)):[]:[];return dn.createElement(ai,{alignItems:"center",paddingTop:1},dn.createElement(ai,{minWidth:12},dn.createElement(Xe,{isSelected:n}),dn.createElement(Jb,{color:n?C.accent:C.secondary2},r,":")),dn.createElement(ai,{flexDirection:"row",marginLeft:1,paddingRight:1},d.map((c,u)=>{let m=o.id===t.id&&u===e;return dn.createElement(ai,{key:`${r}-${c}`,paddingRight:2,minHeight:1},dn.createElement(Xe,{isSelected:m}),r===le.ASSIGNEES?dn.createElement(To,{isSelected:m,id:c}):r===le.TAGS?dn.createElement(oi,{isSelected:m,id:c}):null)})))}});var td,ap,nd,od=h(()=>{"use strict";td=e=>Math.max(5,String(Math.max(e,1)).length+3),ap=(e,t)=>Math.max(0,e-6-td(t)),nd=(e,t=0)=>Math.max(1,e-5-2*t)});import{Box as Fo,Text as rd}from"ink";import xt,{useEffect as Qb,useMemo as sd}from"react";var Zb,dp,id,cp,eI,ad,lp=h(()=>{"use strict";te();R();On();M();je();ot();od();wo();Lr();ed();Qa();ao();Zb="\u2029",dp=(e,t)=>`${e}::inline-line::${t}`,id=new Map,cp=e=>{let t=id.get(e)??[];id.delete(e);for(let n of t)I.deleteNode(n)},eI=(e,t)=>{cp(e);let n=[];t.forEach((o,r)=>{let s=mt(BigInt(r+1));if(!wt(s))return;let d=I.createNode(Te.text({id:dp(e,r),name:`Line ${r+1}`,parentNodeId:e,rank:s.value,props:{value:o},readonly:!0,isVirtual:!0}));wt(d)&&n.push(d.value.id)}),id.set(e,n)},ad=({id:e,label:t,text:n,rows:o,selected:r,maxWidth:s})=>{let{selectedIndex:d,contextNode:c}=Je(),u=sd(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=sd(()=>u.join("\0"),[u]);Qb(()=>(eI(e,u),()=>{cp(e)}),[e,m]);let p=td(u.length),f=ap(s,u.length),S=sd(()=>Ja(u).map(A=>{if(A.kind==="code"||A.kind==="caption")return{...A,text:Li(A.text,f)};if(A.kind==="text"||A.kind==="heading"){let P=A.spans.map(T=>T.code?`\`${T.text}\``:T.text).join("");return{...A,spans:_r(Li(P,f))}}return A}),[u,f]).map((A,P)=>{let T=c.id===e&&d===P;return xt.createElement(Fo,{key:dp(e,P)},xt.createElement(Fo,{flexShrink:0},xt.createElement(rd,{color:T?C.primary:C.secondary2,dimColor:!T},`${P+1} `.padStart(p,"\xA0"))),A.kind==="blank"?xt.createElement(rd,{backgroundColor:T?"gray":void 0},Zb):xt.createElement(Fo,null,xt.createElement(Za,{line:A,width:A.kind==="code"?f:0,wrap:"truncate-end"})))});return xt.createElement(Fo,{flexDirection:"column",paddingTop:1},xt.createElement(Fo,null,xt.createElement(Xe,{isSelected:r}),xt.createElement(rd,{color:r?C.accent:C.secondary2},t)),xt.createElement(Fo,{flexDirection:"row",borderStyle:"round",borderColor:C.secondary,paddingLeft:1,marginLeft:1,overflowY:"hidden"},xt.createElement(Rn,{scrollByOne:!0,height:o,selectedIndex:d,itemHeight:1},S)))}});import{Box as eo,Text as dd}from"ink";import Pe,{useMemo as Br}from"react";var tI,nI,oI,rI,up,mp=h(()=>{"use strict";V();te();M();je();Va();Ro();$m();rp();wo();ip();lp();od();tI=e=>Me(e,"description"),nI=e=>Me(e,"comments"),oI=e=>Me(e,"history"),rI=e=>Me(e,"attachments"),up=({ticket:e,height:t})=>{let n=Br(()=>Fm(e),[e]),{selectedIndex:o,contextNode:r}=Je(),s=process.stdout.columns||120,d=Br(()=>tI(e.id),[e.id]),c=Br(()=>nI(e.id),[e.id]),u=Br(()=>oI(e.id),[e.id]),m=Br(()=>rI(e.id),[e.id]),p=I.getAttachmentsByIssue(e.id).length,f=r.id===e.id,x=r.id===c||r.parentNodeId===c,S=r.id===u||r.parentNodeId===u,A=r.id===m||r.parentNodeId===m,P=oe(e.id);if(x){let $=t-3;return Pe.createElement(eo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Pe.createElement(op,{ticket:e,width:s,height:$}))}if(A){let $=t-3;return Pe.createElement(eo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Pe.createElement(Um,{ticket:e,width:s,height:$}))}if(S){let B=I.getNode(u),$=B&&nt(B)?B.props.value??"":"",se=nd(t);return Pe.createElement(eo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},B?Pe.createElement(ad,{id:B.id,label:"Event log",text:$,selected:!1,maxWidth:s,rows:se}):null)}let T=P.reduce((B,$)=>Xo($)||$.id===c||$.id===m||$.id===u?B+1:B,0),w=nd(t,T),_=(B,$)=>B.id===d?Pe.createElement(ad,{key:B.id,id:d,label:"Description (press e to edit)",text:e.props.description??"",selected:$,maxWidth:s,rows:w}):Xo(B)?Pe.createElement(sp,{key:B.id,parent:B,selected:$,selectedIndex:o}):B.id===c?Pe.createElement(eo,{key:B.id,paddingTop:1},Pe.createElement(Xe,{isSelected:$}),Pe.createElement(dd,{backgroundColor:C.secondary,color:$?C.accent:C.primary},` Comments (${n}) \u203A\u203A `)):B.id===m?Pe.createElement(eo,{key:B.id,paddingTop:1},Pe.createElement(Xe,{isSelected:$}),Pe.createElement(dd,{backgroundColor:C.secondary,color:$?C.accent:C.primary},` Attachments (${p}) \u203A\u203A `)):B.id===u?Pe.createElement(eo,{key:B.id,paddingTop:1},Pe.createElement(Xe,{isSelected:$}),Pe.createElement(dd,{backgroundColor:C.secondary,color:$?C.accent:C.primary}," History \u203A\u203A ")):null;return Pe.createElement(eo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},P.map((B,$)=>_(B,f&&o===$)))}});import{Box as sI}from"ink";import di from"react";var iI,pp,gp=h(()=>{"use strict";V();Dm();mp();iI=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:o,mode:r,viewMode:s,height:d,width:c})=>{let u=t.context,m=u===z.TICKET||u===z.FIELD_LIST||u===z.FIELD,p=u===z.BOARD||u===z.SWIMLANE,f=u===z.TICKET?t:o.find(T=>T.context===z.TICKET),x=Math.floor(c/3),S=Math.floor(c/Math.max(e.length,1)),A=Math.min(S,x),P=s==="dense";return di.createElement(sI,{flexDirection:"row",height:d},p&&e.map((T,w)=>{let _=t.id===T.id,B=_?n:-1,$=t.context===z.BOARD&&n===w;return di.createElement(Lm,{key:T.id,height:d,width:A,swimlane:T,isSelected:$,isDense:P,isFocused:_,listSelectedIndex:B,mode:r})}),m&&f&&di.createElement(up,{height:d,ticket:f}))},pp=di.memo(iI)});import fp from"node:fs";import aI from"node:path";import dI from"react";import{render as cI}from"ink";import{Writable as lI}from"node:stream";var Or,uI,mI,pI,gI,hp,vp=h(()=>{"use strict";gp();V();R();M();ae();Be();Or=e=>String(e).padStart(2,"0"),uI=e=>{let t=e.getUTCFullYear(),n=Or(e.getUTCMonth()+1),o=Or(e.getUTCDate()),r=Or(e.getUTCHours()),s=Or(e.getUTCMinutes()),d=Or(e.getUTCSeconds());return`${t}-${n}-${o}_${r}-${s}-${d}`},mI=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",pI=async(e,{width:t,height:n})=>{let o="",r=new lI({write(d,c,u){let m=gI(d.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(o=m),u()}});r.columns=t,r.rows=n,r.isTTY=!0;let s=cI(e,{stdout:r,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(d=>setTimeout(d,0)),s.unmount(),o},gI=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),hp=async()=>{let{viewMode:e}=Ie(),{contextNode:t,selectedIndex:n,breadCrumb:o,mode:r,renderedChildrenIndex:s}=g(),d=o.find(w=>w.context==="BOARD");if(!d)return i("No board found to export");let c=120,u=40,m=await pI(dI.createElement(pp,{height:u,width:c,swimlanes:(s[d.id]??[]).filter(w=>w!==void 0&&pn(w)),contextNode:t,selectedIndex:n,breadCrumb:o,viewMode:e??"dense",mode:r}),{width:c,height:u});if(!m)return i("Failed to render board export");let p=gs(process.cwd());if(a(p))return i("Unable to export, epiq root not found");let f=new Date,x=uI(f),S=`board_${mI(d.title)}_${x}.md`,A=nl(p.value);fp.mkdirSync(A,{recursive:!0});let P=aI.join(A,S),T=`# Board - ${d.title}
|
|
49
|
+
`,"utf8"),o.push(`${r} (${m.length})`)}catch{continue}}return o},Ib=(e,t)=>{let n=new Set(Ro(t));return Ro(e).filter(o=>!n.has(o))},Eb=(e,t,n)=>[`Refusing to commit ${e}: it is missing ${t.length} of the ${n} event(s) already committed.`,"","The event log is append-only, so a line can never legitimately go","missing. The working copy on disk is damaged; committing it would","publish that damage to everyone who pulls, and the log carries no way","to undo it.","","Nothing has been committed. The committed history is intact \u2014 recover","the file from it before syncing again:",` git show HEAD:${e}`,"","First dropped event:",` ${t[0]?.slice(0,200)??"<none>"}`].join(`
|
|
50
|
+
`),im=async({stateBranchRoot:e,relativePath:t,workingContent:n})=>{let o=await Be({args:["show",`HEAD:${t}`],cwd:e});if(o.exitCode!==0)return l("No committed log to compare against",void 0);let r=Ib(o.stdout,n);return r.length>0?a(Eb(t,r,Ro(o.stdout).length)):l("Event log only grew",void 0)}});import mn from"node:fs";import Fr from"node:path";var Sb,dm,am,Rb,qa,Ga,Nb,Cb,oo,Ab,wb,Js,cm,lm,um,_r,mm,Or=h(()=>{"use strict";Yn();R();xt();Cs();bo();Wa();Xe();ct();Sb="[epiq:init-repo]",dm=async e=>{let t=await Be({args:["rev-parse","--verify","--quiet","HEAD"],cwd:e});if(t.exitCode===0)return l("Initial commit already exists",!1);if(!(t.exitCode===1&&t.stdout.trim()===""&&t.stderr.trim()===""))return a(["Could not determine whether the repository has any commits, so nothing was written.",`git rev-parse exited ${t.exitCode}`,t.stderr.trim()].filter(Boolean).join(`
|
|
51
|
+
`));J.info("Creating initial commit");let o=await W({args:["hash-object","-w","-t","tree","/dev/null"],cwd:e});if(d(o))return a(o.message);let r=await W({args:["commit-tree",o.value.stdout.trim(),"-m",Sb],cwd:e});if(d(r))return a(r.message);let s=await W({args:["update-ref","HEAD",r.value.stdout.trim()],cwd:e});return d(s)?a(s.message):l("Created initial commit",!0)},am=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",Rb=async e=>{let t=await Ts(e);if(d(t))return a(t.message);let n=await _l(e);return d(n)?a(n.message):l("Built sync commit message",`[sync|branch:${am(t.value)}:sha:${am(n.value)}]`)},qa=async({repoRoot:e,stateBranchName:t})=>{J.info(`Creating ${t}`);let n=await W({args:["commit-tree",Gl,"-m","[epiq:init-state-branch]"],cwd:e});if(d(n))return a(`Failed to create state branch commit
|
|
52
|
+
${n.message}`);let o=n.value.stdout.trim(),r=await W({args:["update-ref",`refs/heads/${t}`,o],cwd:e});return d(r)?a(`Failed to create ${t}
|
|
53
|
+
${r.message}`):l("Created state branch",!0)},Ga=async({repoRoot:e,stateBranchName:t})=>{let n=await ws({repoRoot:e,branch:t});if(d(n))return a(`Ensure local state branch failed
|
|
54
|
+
`+n.message);if(n.value)return l("Local state branch already exists",!1);let o=await qn({repoRoot:e});if(d(o))return a(`Ensure local state branch failed
|
|
55
|
+
`+o.message);let r=o.value,s=r?await ma({repoRoot:e,branch:t}):l("No remote, no remote state branch",!1);if(d(s))return a(`Ensure local state branch failed
|
|
56
|
+
`+s.message);let i=s.value;if(r&&i){let c=await ye.fetch({cwd:e,remote:bt,branch:t});if(d(c))return a(`Failed to fetch ${t} from remote
|
|
57
|
+
${c.message}`)}if(i){let c=await W({args:["branch","--track",t,`${bt}/${t}`],cwd:e});return d(c)?a(`Failed to create local ${t} from remote
|
|
58
|
+
${c.message}`):l("Created local state branch from remote",!0)}return qa({repoRoot:e,stateBranchName:t})},Nb=async({repoRoot:e,branch:t})=>{let n=await W({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return a(n.message);let o=n.value.stdout.split(`
|
|
59
|
+
`),r=null;for(let s of o){if(s.startsWith("worktree ")){r=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&r)return l("Found worktree for branch",r)}return l("No worktree found for branch",null)},Cb=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let o=Sr(Fr.dirname(t));if(d(o))return a(`Failed to create state branch worktree
|
|
60
|
+
`+o.message);if(mn.existsSync(t)&&!mn.existsSync(Fr.join(t,".git"))){let s=nm(t);if(d(s))return a(s.message);if(s.value.length>0)return a([`Refusing to delete ${t}.`,"","It is not a usable worktree \u2014 it has no .git \u2014 but it still holds",`${s.value.length} event log(s) with content:`,...s.value.map(i=>` ${i}`),"","Deleting it would destroy them, and with no .git here there is no","committed copy to recover from. Move the directory aside and","salvage the logs before letting epiq recreate the worktree."].join(`
|
|
61
|
+
`));J.info("Removing broken state branch worktree path"),Yl(t)}J.info("Creating state branch worktree");let r=await ye.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return d(r)?a(`Failed to create state branch worktree
|
|
62
|
+
${r.message}`):l("Created state branch worktree",!0)},oo=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let o=await Nb({repoRoot:e,branch:n});if(d(o))return a(o.message);let r=xr(t),s=o.value?xr(o.value):null;if(s&&s===r&&mn.existsSync(s))return l("State branch already checked out in expected worktree",!1);if(s&&s!==r){let u=await $l(s);if(d(u))return a(u.message);if(u.value||pu(s))return a([`Refusing to move the state branch worktree away from ${s}.`,"","It holds changes that are not committed yet, which for this","branch means events no sync has published. Removing it would","destroy them outright \u2014 there is no stash or reflog to recover","a deleted worktree from.","",`This worktree is expected at ${r}, so something else is`,"using a different EPIQ_GLOBAL_DIR against the same repository.","Sync from that location first, or point both at the same one."].join(`
|
|
63
|
+
`));J.info("Moving state branch worktree to expected location");let m=await ye.worktreeRemove({cwd:e,worktreeRoot:s});if(d(m))return a(`Failed to remove existing state branch worktree
|
|
64
|
+
${m.message}`)}if(s&&!mn.existsSync(s)){J.info("Pruning stale state branch worktree");let u=await ye.worktreePrune({cwd:e});if(d(u))return a(`Failed to prune stale worktrees
|
|
65
|
+
${u.message}`)}let i=await Fl({repoRoot:e,worktreeRoot:t});if(d(i))return a(i.message);let c=mn.existsSync(t);if(i.value&&c)return l("State branch worktree already exists",!1);if(i.value&&!c){J.info("Pruning missing registered state branch worktree");let u=await ye.worktreePrune({cwd:e});if(d(u))return a(`Failed to prune stale worktrees
|
|
66
|
+
${u.message}`)}return Cb({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},Ab=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await Ts(e);if(d(n))return a(n.message);if(n.value===t)return l("State branch already checked out",!1);(await Be({cwd:e,args:["rebase","--abort"]})).exitCode===0&&J.info("Aborted stale state branch rebase");let r=await ye.checkout({cwd:e,branch:t});return d(r)?a(`Failed to checkout ${t}
|
|
67
|
+
${r.message}`):l("Checked out state branch",!0)},wb=async({repoRoot:e,stateBranchRoot:t})=>{let n=await pa(t);if(d(n))return a(n.message);if(n.value)return l("State branch upstream already configured",!1);let o=await qn({repoRoot:t});if(d(o))return a(o.message);if(!o.value)return l("No remote available for state branch upstream",!1);let r=Bt(e);if(d(r))return r;let s=r.value,i=await ma({repoRoot:t,branch:s});if(d(i))return a(i.message);if(!i.value)return l("Remote state branch missing; upstream will be configured on first push",!1);J.info(`Configuring ${s} upstream`);let c=await ye.fetch({cwd:t,remote:bt,branch:s});if(d(c))return a(`Failed to fetch ${s}
|
|
68
|
+
${c.message}`);let u=await ye.setUpstream({cwd:t,branch:s,upstream:`${bt}/${s}`});return d(u)?a(`Failed to set state branch upstream
|
|
69
|
+
${u.message}`):l("Configured state branch upstream",!0)},Js=async({stateBranchRoot:e,eventFileName:t})=>{let n=zl(t),o=Fr.join(e,n);if(!mn.existsSync(o))return l("No event file to stage",null);let r=await im({stateBranchRoot:e,relativePath:n,workingContent:mn.readFileSync(o,"utf8")});if(d(r))return a(r.message);let s=await ye.stage({cwd:e,pathspec:[n]});return d(s)?a(`Failed to stage state branch event file
|
|
70
|
+
${s.message}`):l("Staged state branch event file",n)},cm=async({stateBranchRoot:e})=>{let t=Vl(),n=Fr.join(e,t);if(!mn.existsSync(n))return l("No media directory to stage",null);let o=await ye.stage({cwd:e,pathspec:[t],ignoreRemoval:!0});return d(o)?a(`Failed to stage state branch media files
|
|
71
|
+
${o.message}`):l("Staged state branch media files",t)},lm=async({stateBranchRoot:e})=>{let t=[fa(),ga()].filter(o=>mn.existsSync(Fr.join(e,o)));if(t.length===0)return l("No event log config to stage",[]);let n=await ye.stage({cwd:e,pathspec:t});return d(n)?a(`Failed to stage event log config
|
|
72
|
+
${n.message}`):l("Staged event log config",t)},um=async({repoRoot:e,stateBranchRoot:t,pathspec:n})=>{let o=await Rb(e);return d(o)?a(`Create state branch sync commit failed
|
|
73
|
+
`+o.message):xo({cwd:t,message:o.value,pathspec:n})},_r=async({repoRoot:e,stateBranchRoot:t})=>{let n=await pa(t);if(d(n))return a(n.message);let o=Bt(e);if(d(o))return o;let r=o.value,s=n.value?await ye.push({cwd:t}):await ye.push({cwd:t,remote:bt,branch:r,setUpstream:!0});if(d(s))return a(`Failed during state branch push
|
|
74
|
+
${s.message}`);let i=!`${s.value.stdout}${s.value.stderr}`.includes("Everything up-to-date");return l(i?"Pushed state branch":"Remote already up to date",i)},mm=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let o=!1,r=Bt(e);if(d(r))return r;let s=r.value,i=[Ms(),await Ga({repoRoot:e,stateBranchName:s}),await oo({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await Ab({stateBranchRoot:t,stateBranchName:s}),await Jl(t),n?await wb({stateBranchRoot:t,repoRoot:e}):l("Skipped state branch upstream bootstrap",!1)];for(let c of i){if(d(c))return a(c.message);o=o||!!c.value}return l(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",o)}});import Qs from"node:fs";import Va from"node:os";import Tb from"node:path";var kb,pm,Mb,Pb,Lb,gm,za,fm,Db,Zs,Ka=h(()=>{"use strict";R();ct();xt();kb="epiq-sync.lock",pm=600*1e3,Mb=e=>{try{let t=JSON.parse(e);return typeof t.pid!="number"||typeof t.hostname!="string"||typeof t.startedAt!="number"||typeof t.operation!="string"?null:t}catch{return null}},Pb=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Lb=e=>e&&(e.hostname!==Va.hostname()||Pb(e.pid))?Date.now()-e.startedAt>pm:!0,gm=e=>`${e.operation} (pid ${e.pid} on ${e.hostname}, started ${new Date(e.startedAt).toISOString()})`,za=e=>{try{return Mb(Qs.readFileSync(e,"utf8"))}catch{return null}},fm=(e,t)=>{let n={pid:process.pid,hostname:Va.hostname(),startedAt:Date.now(),operation:t};try{return Qs.writeFileSync(e,JSON.stringify(n),{flag:"wx"}),!0}catch{return!1}},Db=async({worktreeRoot:e,operation:t})=>{let n=await ua(e);if(d(n))return a(n.message);let o=Tb.join(n.value,kb),r=()=>{try{let c=za(o);c&&c.pid===process.pid&&Qs.rmSync(o)}catch{}};if(fm(o,t))return l("Acquired sync lock",{acquired:!0,release:r});let s=za(o);if(!Lb(s))return l("Sync lock is held",{acquired:!1,heldBy:s});J.info(`Breaking an abandoned sync lock: ${s?gm(s):"unreadable lock file"}`);try{Qs.rmSync(o,{force:!0})}catch{}if(fm(o,t))return l("Acquired sync lock after breaking a stale one",{acquired:!0,release:r});let i=za(o);return l("Sync lock taken by another process",{acquired:!1,heldBy:i??{pid:-1,hostname:Va.hostname(),startedAt:Date.now(),operation:"unknown"}})},Zs=async({worktreeRoot:e,operation:t,fn:n})=>{let o=await Db({worktreeRoot:e,operation:t});if(d(o))return a(o.message);if(!o.value.acquired)return J.info(`Skipping ${t}: the state worktree is held by ${gm(o.value.heldBy)}`),l("State worktree is held by another process",null);let{release:r}=o.value;try{return l("Ran under the sync lock",await n())}finally{r()}}});import Fb from"node:fs";var _b,Ob,Ya,hm,Xa,ei,ti=h(()=>{"use strict";R();Lr();Xs();bo();Xe();ct();Or();Wa();Yn();Ka();_b=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=re("getRepoRootDir",await lt(e));if(d(n))return a(n.message);let o=n.value;logger.debug("[sync] repo root",o);let r=re("getStateBranchRoot",be({repoRoot:o}));if(d(r))return a(r.message);let s=r.value;logger.debug("[sync] state branch root",s),logger.debug("[sync] bootstrapping state branch storage",{repoRoot:o,stateBranchRoot:s,ensureUpstream:t});let i=re("bootstrapStateBranchStorage",await mm({repoRoot:o,stateBranchRoot:s,ensureUpstream:t}));if(d(i))return a(i.message);logger.debug("[sync] bootstrap result",{bootstrapped:i.value,stateBranchRoot:s}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:s});let c=re("hasInProgressGitOperation(stateBranchRoot)",await As(s));if(d(c))return a(c.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:c.value}),c.value)return logger.info("[sync] state branch git operation in progress"),a("Cannot sync while a git operation is in progress in the state branch");logger.debug("[sync] ensuring state branch layout",{repoRoot:o,stateBranchRoot:s});let u=re("ensureStateBranchLayout",Xl(o,s));return d(u)?a(u.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:o,stateBranchRoot:s,bootstrapped:i.value}),l("Sync preconditions satisfied",{repoRoot:o,stateBranchRoot:s,bootstrapped:i.value}))},Ob=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{logger.debug("[sync] committing own event file from state branch",{ownEventFileName:n,stateBranchRoot:t}),logger.debug("[sync] staging own event file",{stateBranchRoot:t,ownEventFileName:n});let o=re("stageStateBranchOwnEventFile",await Js({stateBranchRoot:t,eventFileName:n}));if(d(o))return a(o.message);let r=re("stageStateBranchMediaFiles",await cm({stateBranchRoot:t}));if(d(r))return a(r.message);let s=re("stageStateBranchEventConfig",await lm({stateBranchRoot:t}));if(d(s))return a(s.message);let i=[o.value,r.value,...s.value].filter(m=>m!==null);if(i.length===0)return l("Nothing to stage",{createdCommit:!1});let c=re("hasStagedChanges(after stage)",await jl(t,i));if(d(c))return a(c.message);if(logger.debug("[sync] state branch change check after stage result",{changed:c.value}),!c.value)return logger.info("[sync] no own event file changes to commit"),l("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let u=re("createStateBranchSyncCommit",await um({repoRoot:e,stateBranchRoot:t,pathspec:i}));return d(u)?a(u.message):(logger.debug("[sync] created sync commit",u.value),l("Committed own event file",{createdCommit:!0,commitSha:u.value}))},Ya=(e,t="offline")=>{let n=e.createdCommit?`Committed locally, ${t}`:t==="offline"?"Offline":"No remote";return Ys(n),l(n,{...e,pulled:!1,pushed:!1,offline:!0})},hm=async({cwd:e=process.cwd(),ownEventFileName:t})=>{if(logger.debug("[sync] syncEpiqWithRemote:start",{cwd:e,ownEventFileName:t}),t.includes("/")||t.includes("\\"))return logger.error("[sync] invalid own event file name: contains path separator",{ownEventFileName:t}),a("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return logger.error("[sync] invalid own event file name: missing .jsonl suffix",{ownEventFileName:t}),a("Own event file must end with .jsonl");Eo();let n=re("ensureSyncReady",await _b({cwd:e,ensureUpstream:!0}));if(d(n))return Re(n.message);let{repoRoot:o,stateBranchRoot:r,bootstrapped:s}=n.value,i=re("isDetachedHead(stateBranchRoot)",await Hl(r));if(d(i))return Re(i.message);if(logger.debug("[sync] detached state branch check result",{detached:i.value}),i.value)return Re("Cannot run :sync while the state branch is in detached HEAD state");let c=!1,u,m=!1,p=!1,f=re("getStateBranch",Bt(o));if(d(f))return Re(f.message);let y=f.value;logger.debug("[sync] resolved state branch",{stateBranch:y,stateBranchRoot:r});let I=re("flushPendingLogs",$s(r,t));d(I)&&logger.error(`[sync] ${I.message}`);let S=re("commitOwnEventFileToStateBranch",await Ob({repoRoot:o,stateBranchRoot:r,ownEventFileName:t}));if(d(S))return Re(S.message);c=S.value.createdCommit,u=S.value.commitSha;let A=re("hasRemote",await qn({repoRoot:r}));if(d(A))return Re(A.message);if(!A.value)return Ya({repoRoot:o,stateBranchRoot:r,createdCommit:c,commitSha:u,bootstrapped:s},"no remote");let w=re("pullBranchRebaseIfPresent",await Er({cwd:r,branch:y}));if(d(w))return Ir(w.message)?Ya({repoRoot:o,stateBranchRoot:r,createdCommit:c,commitSha:u,bootstrapped:s}):Re(w.message);m=w.value;let k=re("isAheadOfUpstream",await Ul(r));if(d(k))return Re(k.message);if(c||s||k.value){logger.info("[sync] pushing state branch",{createdCommit:c,bootstrapped:s,stateBranchRoot:r});let D=re("pushStateBranch",await _r({stateBranchRoot:r,repoRoot:o}));if(d(D)&&Ol(D.message)){let _=re("pullBranchRebaseIfPresent(retry)",await Er({cwd:r,branch:y}));if(d(_))return Re(_.message);m=m||_.value,D=re("pushStateBranch(retry)",await _r({stateBranchRoot:r,repoRoot:o}))}if(d(D))return Ir(D.message)?Ya({repoRoot:o,stateBranchRoot:r,createdCommit:c,commitSha:u,bootstrapped:s}):Re(D.message);p=D.value}if(c){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:r});let D=re("git rev-parse HEAD",await W({args:["rev-parse","HEAD"],cwd:r}));if(d(D))return Re(D.message);u=D.value.stdout.trim(),logger.debug("[sync] final sync commit sha",u)}return no(p?"Synced and pushed":m||c?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),l("Synced event logs with state branch",{repoRoot:o,stateBranchRoot:r,createdCommit:c,commitSha:u,pulled:m,pushed:p,bootstrapped:s,offline:!1})},Xa=async(e,t)=>{let n=rm(e);try{return await t()}finally{let o=sm(e,n);o.length>0&&logger.error(`[sync] restored event log lines git dropped from the worktree: ${o.join(", ")}`)}},ei=async e=>{let t=e.cwd??process.cwd(),n=await lt(t);if(d(n))return Re(n.message);let o=be({repoRoot:n.value});if(d(o))return Re(o.message);let r=o.value;if(!Fb.existsSync(r))return hm(e);let s=await Zs({worktreeRoot:r,operation:"sync",fn:()=>Xa(r,()=>hm(e))});return d(s)?Re(s.message):s.value===null?l("Another process is syncing this board",{repoRoot:n.value,stateBranchRoot:r,createdCommit:!1,pulled:!1,pushed:!1,bootstrapped:!1,offline:!1,skipped:!0}):s.value}});var Gt,ni,Bb,Ja,vm,oi=h(()=>{"use strict";Ju();to();St();Ce();pe();R();M();Lr();Xs();ti();Gt=null,ni=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!Gt,currentStatus:g().syncStatus?.status,currentMessage:g().syncStatus?.msg}),Gt)return logger.debug("[sync] syncAndReloadState joining existing promise"),Gt;logger.debug("[sync] syncAndReloadState creating promise"),Gt=Bb();try{let e=await Gt;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!d(e),message:(d(e),e.message),statusAfterResolve:g().syncStatus?.status,statusMessageAfterResolve:g().syncStatus?.msg}),d(e)&&g().syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),N({syncStatus:{msg:e.message,status:"failed"}})),e}catch(e){let t=e instanceof Error?e.message:String(e);return logger.error("[sync] syncAndReloadState promise threw",{message:t,error:e}),Gt||a(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:g().syncStatus?.status,statusMessageBeforeClear:g().syncStatus?.msg}),Gt=null}},Bb=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:g().mode,syncStatus:g().syncStatus});let e=vm();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:g().mode,message:e.message,syncStatus:g().syncStatus}),e;if(Gt)return Gt;logger.debug("[sync] syncAndReloadState:start");let t=re("resolveActorId",oe());if(d(t)||!t.value)return logger.info("[sync] unable to resolve actor id",{message:d(t)?t.message:"Missing actor id"}),a("Unable to resolve event log path");N({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:g().syncStatus});let n=Zn(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let o=re("syncEpiqWithRemote",await ei({ownEventFileName:n}));if(logger.debug("[sync] syncEpiqWithRemote:result",{success:!d(o),message:(d(o),o.message)}),d(o))return logger.error("[sync] syncAndReloadState:sync failed",o.message),N({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:g().syncStatus}),Re(`Unable to sync state. ${o.message}`);let{stateBranchRoot:r,offline:s}=o.value,i=Ja(r);return d(i)?i:(N({hasProjectDefinition:!0,syncStatus:s?{msg:"Committed locally, offline",status:"offline"}:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:g().syncStatus}),l("Synced",!0))},Ja=e=>{logger.debug("[sync] loading merged events after sync",{stateBranchRoot:e});let t=re("loadMergedEvents",Et(e));if(logger.debug("[sync] loadMergedEvents:result",{success:!d(t),message:(d(t),t.message),count:d(t)?void 0:t.value.events.length}),d(t))return N({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:g().syncStatus}),a(`Unable to load events. ${t.message}`);logger.debug("[sync] loaded merged events after sync",{count:t.value.events.length});let n=vm();if(n)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:g().mode,message:n.message,syncStatus:g().syncStatus}),n;let o=Ku(),r=g().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:o,selectedNodeId:g().selectedNode?.id,contextNodeId:g().contextNode?.id,selectedNodeIsVirtual:g().selectedNode?.isVirtual,contextNodeIsVirtual:g().contextNode?.isVirtual}),!g().selectedNode?.isVirtual&&!g().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:t.value.events.length});let i=re("bootStateFromEventLog",Wt(t.value.events,t.value.unreadable));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!d(i),message:(d(i),i.message)}),d(i))return N({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:g().syncStatus}),a(`Unable to boot synced state. ${i.message}`)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:g().selectedNode?.isVirtual,contextNodeIsVirtual:g().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),N({filters:r}),logger.debug("[sync] restoreNavigationAnchor:start");let s=re("restoreNavigationAnchor",Xu(o));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!d(s),message:d(s)?s.message:"Navigation restored",selectedNodeId:g().selectedNode?.id,contextNodeId:g().contextNode?.id}),d(s)?(N({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:g().syncStatus}),s):l("Reloaded state from event log",null)},vm=()=>g().mode===b.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:g().mode,syncStatus:g().syncStatus}),N({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),a("Will not re-materialize if not in default mode, to not lose edit data"))});var No,ym,bm,Qa,Za,Br,ed,Ub,xm,$b,Im,ri=h(()=>{"use strict";R();We();M();oi();No=3e3,ym=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<No?null:t},bm=0,Za=!1,Br=!1,ed=()=>{if(Za)return!0;let e=ze();return d(e)?!1:e.value.syncStatus.status==="syncing"},Ub=()=>{let e=Ie().autoSyncIntervalMs??1e4,t=Date.now()-bm;return Math.max(0,e-t)},xm=()=>{Qa||(Qa=setTimeout(async()=>{if(Qa=void 0,!!It()){if(ed()){Br=!0;return}Br=!1,await $b()}},Ub()))},$b=async()=>{if(g().readOnly||g().timeMode==="peek"||g().timeMode==="replay")return a("Cannot auto-sync while peeking");if(!It())return a("Cannot auto-sync before state is initialized");if(ed())return Br=!0,a("Sync already in progress");Za=!0,bm=Date.now(),N({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await ni()}finally{Za=!1,Br&&xm()}},Im=()=>{It()&&(Br=!0,!ed()&&xm())}});import Ur from"node:fs";import $r from"node:path";import{z as Co}from"zod";var si,jb,Hb,Wb,Sm,Rm,Em,Nm,Cm,Am,qb,ii,jr,Ao=h(()=>{"use strict";R();nn();Ns();ae();si="recent-projects.json",jb=20,Hb=Co.object({projectId:Co.string().min(1),root:Co.string().min(1),lastOpenedAt:Co.number().finite()}),Wb=Co.object({projects:Co.array(Hb)}),Sm=()=>$r.join(on(),si),Rm=e=>$r.basename(e)||e,Em=e=>{let t=$r.resolve(e);try{return Ur.realpathSync(t)}catch{return t}},Nm=(e,t)=>t.lastOpenedAt-e.lastOpenedAt,Cm=e=>{if(!Nr(e.root))return!1;let t=br(e.root);return!d(t)&&t.value===e.projectId},Am=()=>{let e=Sm();if(!Ur.existsSync(e))return l("No recent projects recorded",[]);let t;try{t=JSON.parse(Ur.readFileSync(e,"utf8"))}catch(o){return a(`Invalid ${si}: ${o instanceof Error?o.message:String(o)}`)}let n=Wb.safeParse(t);return n.success?l("Read recent projects",n.data.projects):a(`Invalid ${si} shape: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},qb=e=>{let t=Sm();try{Ur.mkdirSync($r.dirname(t),{recursive:!0}),Ur.writeFileSync(t,JSON.stringify({projects:e},null,2)+`
|
|
75
|
+
`,"utf8")}catch(n){return a(`Unable to write ${si}: ${n instanceof Error?n.message:String(n)}`)}return l("Recorded recent project",e)},ii=({exclude:e}={})=>{let t=Am();if(d(t))return t;let n=e===void 0?null:Em(e);return l("Listed recent projects",t.value.filter(o=>n===null||Em(o.root)!==n).filter(Cm).sort(Nm))},jr=({root:e,now:t=Date.now()})=>{let n=$r.resolve(e),o=br(n);if(d(o))return a(o.message);let r=o.value,s=Am(),i=d(s)?[]:s.value,c=[{projectId:r,root:n,lastOpenedAt:t},...i.filter(u=>u.projectId!==r&&u.root!==n)].filter(Cm).sort(Nm).slice(0,jb);return qb(c)}});var ai,wm,Tm,km,Hr=h(()=>{"use strict";R();nn();We();ae();ai=()=>{let e=Ie(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),o=e.autoSync===!0||e.autoSync===!1;return{isSetupDone:n&&t&&o,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:o}},wm=()=>{let e=Me(process.cwd());if(d(e))return!1;let t=Ot(e.value);return Dt(t)},Tm=e=>e===!0?"on":e===!1?"off":null,km=e=>e==="on"?!0:e==="off"?!1:null});var $e,T,Ve=h(()=>{"use strict";$e={bg:"#1a1b26",fg:"#c8d3ff",grayDark:"#3a3e54",gray:"#46507a",grayLight:"#969bb5",cyan:"#88d5ee",cyanSoft:"#8fe6fb",blue:"#5b8cff",magenta:"#a78bfa",magentaSoft:"#c4b5fd",green:"#8fdc8c",yellow:"#f1c27d",red:"#ff7a90",white:"#ffffff"},T={accent:$e.cyan,accent2:$e.magenta,primary:$e.white,secondary:$e.grayDark,secondary2:$e.grayLight,gray:$e.gray,green:$e.green,yellow:$e.yellow,red:$e.red}});var C,wo,di=h(()=>{"use strict";Ve();C={red:$e.red,yellow:$e.yellow,green:$e.green,blue:$e.blue,magenta:$e.magenta,cyan:$e.cyan},wo={urgent:C.red,critical:C.red,important:C.red,blocker:C.red,asap:C.red,immediate:C.red,fail:C.red,failure:C.red,broken:C.red,bug:C.red,error:C.red,incident:C.red,outage:C.red,production:C.red,crash:C.red,security:C.red,warning:C.yellow,warn:C.yellow,risky:C.yellow,risk:C.yellow,attention:C.yellow,pending:C.yellow,review:C.yellow,"needs-review":C.yellow,qa:C.yellow,testing:C.yellow,test:C.yellow,validate:C.yellow,verification:C.yellow,staging:C.yellow,check:C.yellow,"follow-up":C.yellow,followup:C.yellow,waiting:C.yellow,blocked:C.yellow,hold:C.yellow,done:C.green,complete:C.green,completed:C.green,success:C.green,ok:C.green,stable:C.green,resolved:C.green,fixed:C.green,closed:C.green,merged:C.green,released:C.green,deployed:C.green,approved:C.green,verified:C.green,working:C.green,healthy:C.green,pass:C.green,passing:C.green,info:C.blue,information:C.blue,note:C.blue,docs:C.blue,documentation:C.blue,doc:C.blue,guide:C.blue,help:C.blue,explanation:C.blue,detail:C.blue,details:C.blue,context:C.blue,design:C.blue,discussion:C.blue,proposal:C.blue,idea:C.blue,feature:C.magenta,enhancement:C.magenta,improvement:C.magenta,refactor:C.magenta,refactoring:C.magenta,cleanup:C.magenta,optimize:C.magenta,optimization:C.magenta,perf:C.magenta,performance:C.magenta,upgrade:C.magenta,migration:C.magenta,modernize:C.magenta,debt:C.magenta,todo:C.cyan,next:C.cyan,planned:C.cyan,plan:C.cyan,future:C.cyan,backlog:C.cyan,investigate:C.cyan,explore:C.cyan,prototype:C.cyan}});var Gb,zb,Tn,kn,ci,li,Wr=h(()=>{"use strict";K();R();ne();M();Gb=e=>e.props.tags??[],zb=e=>e.props.assignees??[],Tn=e=>Gb(e).map(t=>E.getTag(t)).filter(t=>!!t),kn=e=>zb(e).map(t=>E.getContributor(t)).filter(t=>!!t),ci=()=>{let{breadCrumb:e,selectedNode:t}=g(),n=[...e,t].find(o=>o?.context==="TICKET");return!n||!P(n)?a("Invalid untag target"):l("Retrieved tags from ticket in breadcrumb",Tn(n))},li=()=>{let{breadCrumb:e,selectedNode:t}=g(),n=[...e,t].find(o=>o?.context==="TICKET");return!n||!P(n)?a("Invalid unassign target"):l("Retrieved assignees from ticket in breadcrumb",kn(n))}});var x,ro=h(()=>{"use strict";x={PALETTE:"?",EXIT:"exit",INIT:"init",OPEN:"open",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",REPLAY:"replay",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",COMMENT:"comment",CONFIG:"config",EDIT:"edit",YANK:"yank",SYNC:"sync",EXPORT:"export",NONE:""}});var Vb,Kb,Yb,Xb,Jb,so,Mm,ui,mi,Pm,Qb,td,qr=h(()=>{"use strict";Vb=/^(\d+)(h|d|w|mo|y)$/,Kb=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Yb=({year:e,month:t,day:n,hour:o=0,minute:r=0})=>{let s=new Date(e,t-1,n,o,r);return s.getFullYear()===e&&s.getMonth()===t-1&&s.getDate()===n&&s.getHours()===o&&s.getMinutes()===r},Xb=(e,t=new Date)=>{let n=e.match(Vb);if(!n)return null;let[,o,r]=n,s=Number(o);if(!Number.isInteger(s)||s<=0)return null;let i=new Date(t);switch(r){case"h":return i.setHours(i.getHours()-s),i;case"d":return i.setDate(i.getDate()-s),i;case"w":return i.setDate(i.getDate()-s*7),i;case"mo":return i.setMonth(i.getMonth()-s),i;case"y":return i.setFullYear(i.getFullYear()-s),i;default:return null}},Jb=e=>{let t=e.match(Kb);if(!t)return null;let[,n,o,r,s,i]=t,c=Number(n),u=Number(o),m=Number(r),p=s?Number(s):0,f=i?Number(i):0;return Yb({year:c,month:u,day:m,hour:p,minute:f})?new Date(c,u-1,m,p,f):null},so=e=>{let t=e.trim().toLowerCase();return Xb(t)??Jb(t)},Mm=/^(\d+)(s|m)?$/,ui=e=>{let t=e.trim().toLowerCase().match(Mm);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},mi=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),o=n.length>0&&Mm.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:o}},Pm=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Qb=[{unit:"h",from:1,to:24},{unit:"d",from:1,to:7},{unit:"w",from:1,to:52},{unit:"mo",from:1,to:12},{unit:"y",from:1,to:5}],td=(e=Qb)=>{let t=[];for(let{unit:n,from:o,to:r}of e)for(let s=o;s<=r;s++)t.push(`${s}${n}`);return t}});var Zb,ve,mt,Ae,ex,tx,od,rd,Fm,io,pi,nd,Lm,nx,ox,Gr,Dm,rx,sx,sd,ix,we,pn=h(()=>{"use strict";ri();Ao();R();Hr();dn();K();ne();M();di();Wr();ro();qr();Zb=["BOARD","TICKET","SWIMLANE","COMMENT"],ve={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",LOG_LEVEL:"logLevel"},mt={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},Ae={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},ex=[ve.EDITOR,ve.VIEW,ve.USERNAME,ve.AUTOSYNC,ve.SYNC_DEBOUNCE_MS,ve.ATTACHMENT_MAX_KB,ve.LOG_LEVEL],tx=(e=g().selectedNode?.context)=>{switch(e){case"TICKET":return[mt.TITLE,mt.DESCRIPTION];case"BOARD":case"SWIMLANE":return[mt.TITLE];case"COMMENT":return[mt.COMMENT];default:return[]}},od=[String(No),"5000","15000","30000","60000"],rd=["250","500","1000"],Fm=["10s","20s","30s","45s"],io=[x.EXIT,x.SYNC,x.HELP,x.EXPORT,x.CONFIG,x.YANK],pi=[x.NEW,x.EDIT,x.DELETE,x.MOVE],nd=[x.TAG,x.UNTAG,x.ASSIGN,x.UNASSIGN,x.CLOSE_ISSUE,x.RE_OPEN_ISSUE,x.EDIT,x.COMMENT],Lm=[x.FILTER,x.PEEK,x.REPLAY],nx={WORKSPACE:[...io,...pi],BOARD:[...Lm,...io,...pi],SWIMLANE:[...Lm,...io,...pi],TICKET:[...io,...pi,...nd],FIELD:[...io,...nd],FIELD_LIST:[...io,...nd],TEXT:[...io],COMMENT:[x.EDIT,x.DELETE,x.YANK]},ox=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Gr=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&P(n)),Dm=e=>e.parentNodeId===he,rx=({selectedNode:e,breadCrumb:t})=>{let n=tx(e?.context);return Gr({breadCrumb:t,selectedNode:e})?n.includes(mt.DESCRIPTION)?n:[...n,mt.DESCRIPTION]:n},sx=({selectedNode:e,breadCrumb:t})=>{let n=Gr({breadCrumb:t,selectedNode:e});return n?[Ae.REF,Ae.TITLE,...n.props?.description?.trim()?[Ae.DESCRIPTION]:[],...Tn(n).length>0?[Ae.TAGS]:[],...kn(n).length>0?[Ae.ASSIGNEES]:[]]:e?[Ae.REF,Ae.TITLE]:[]},sd=()=>{let e=ii({exclude:process.cwd()});return d(e)?[]:[...e.value.map((t,n)=>String(n+1)),...e.value.map(t=>t.root)]},ix=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:o}=ai();if(!o)return[x.HELP,x.CONFIG];if(!wm())return[x.HELP,x.INIT,x.OPEN];if(t)return[x.HELP,x.PEEK,x.REPLAY,x.EXPORT,x.CONFIG,x.YANK];let r=e?.context,s=r&&Zb.includes(r),i=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?nx[u]:[]))],c=Gr({breadCrumb:n,selectedNode:e});return i.filter(u=>u===x.MOVE?!1:u===x.YANK?!!(c??e):u===x.EDIT?s||!!c:u===x.DELETE?s:u===x.UNTAG?!!(c&&Tn(c).length>0):u===x.UNASSIGN?!!(c&&kn(c).length>0):u===x.RE_OPEN_ISSUE?!!(c&&Dm(c)):u===x.CLOSE_ISSUE?!!(c&&!Dm(c)):!0)},we=(e,{contextNode:t,selectedNode:n,readOnly:o,breadCrumb:r}=g())=>{let s=t.context??"WORKSPACE";return{[x.NONE]:ix({breadCrumb:r,readOnly:o,selectedNode:n}),[x.EXIT]:["confirm"],[x.EXPORT]:[],[x.SYNC]:[],[x.INIT]:[],[x.OPEN]:e===x.OPEN?sd():[],[x.HELP]:[],[x.PEEK]:[...td(),"now","prev","next"],[x.REPLAY]:[...td()],[x.EDIT]:rx({selectedNode:n,breadCrumb:r}),[x.YANK]:sx({selectedNode:n,breadCrumb:r}),[x.COMMENT]:[],[x.DELETE]:["confirm"],[x.RE_OPEN_ISSUE]:["confirm"],[x.CLOSE_ISSUE]:["confirm"],[x.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[x.FILTER]:["tag","assignee","actor","description","title","ref","clear"],[x.TAG]:[...new Set([...Object.keys(wo),...E.getExistingTags()])],[x.UNTAG]:[...ci()?.value?.map(({name:c})=>c)??[]],[x.UNASSIGN]:[...li()?.value?.map(({name:c})=>c)??[]],[x.ASSIGN]:E.getExistingAssignees(),[x.NEW]:ox(s),[x.CONFIG]:[...ex]}[e]??[]}});var _m,Om=h(()=>{"use strict";_m=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"]});import{accessSync as ax,copyFileSync as dx,existsSync as fi,mkdirSync as Bm,readdirSync as Um,readFileSync as cx,renameSync as lx,rmSync as ux,statSync as $m,unlinkSync as mx,writeFileSync as px}from"node:fs";import To from"node:path";var id,Ze,gi=h(()=>{"use strict";id=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",Ze={writeToFile:(e,t)=>{try{let n=To.dirname(e);fi(n)||Bm(n,{recursive:!0});let o=typeof t=="string"?t:JSON.stringify(t,null,2);px(e,o,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return cx(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=Ze.readFile(e);return t===null?null:JSON.parse(t)}catch(t){return logger.error(`Failed to read JSON at ${e}:`,t),null}},dirExists:e=>{try{return fi(e)&&$m(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await ax(e),!0}catch{return!1}},mkDir:e=>Bm(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=To.parse(t);for(;;){let o=To.join(t,e);try{if(fi(o)&&$m(o).isDirectory())return o}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=To.dirname(t)}return null},readFirstJSON(e){try{if(!Ze.dirExists(e))return null;let t=Um(e).filter(o=>o.endsWith(".json")).sort()[0];if(!t)return null;let n=To.join(e,t);return Ze.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return Ze.dirExists(e)?Um(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{mx(e)}catch(t){(!id(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{ux(e,{recursive:!0,force:!0})}catch(t){(!id(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(To.dirname(t)),!n?.overwrite&&fi(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{lx(e,t)}catch(o){if(id(o)&&o.code==="EXDEV"){dx(e,t),this.rmFile(e);return}throw o}}}});import fx from"node:path";import{z as fn}from"zod";var gx,jm,hx,Hm,ad,dd,vx,ko,Wm,et,zr,zt=h(()=>{"use strict";Un();ae();R();gi();gx={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},jm=fn.object({logLevel:fn.enum(["info","error","debug"]),preferredEditor:fn.string().optional(),userName:fn.string().optional(),userId:fn.string().optional(),autoSync:fn.boolean().nullable().optional(),autoSyncDebounceMs:fn.number().optional(),attachmentMaxKb:fn.number().optional(),viewMode:fn.enum(["dense","wide"]).optional()}).partial(),hx="config.json",Hm=on,ad=()=>fx.join(Hm(),hx),dd=()=>{try{return Ze.mkDir(Hm()),l(`Ensured ~/${Tt} exists`,null)}catch{return a(`Unable to create ~/${Tt}`)}},vx=e=>{let t;try{t=JSON.parse(e)}catch{return a(`Invalid ~/${Tt}/config.json JSON`)}let n=jm.safeParse(t??{});return n.success?l("Parsed config",n.data):a(`Invalid ~/${Tt}/config.json shape: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},ko=()=>{let e=dd();if(d(e))return a(e.message);let t=ad(),n=Ze.readFile(t);return n==null||n.trim()===""?l("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):vx(n)},Wm=e=>{let t=dd();if(d(t))return a(t.message);let n=jm.safeParse(e);if(!n.success)return a(`Invalid config: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`);let o=ad();try{return Ze.writeToFile(o,JSON.stringify(n.data,null,2)+`
|
|
76
|
+
`),l("Config written",null)}catch{return a(`Unable to write ~/${Tt}/config.json`)}},et=e=>{let t=ko();if(d(t))return a("Failed to read existing config");let n={...t.value,...e};return Wm(n)},zr=()=>{let e=ad(),t=dd();if(d(t))return a(`Unable to create ~/${Tt}`);if(!(Ze.readFile(e)!==null)){let S=Wm(gx);if(d(S))throw new Error(`Unable to create ~/${Tt}/config.json`)}let o=ko();if(d(o))throw new Error(o.message||"Unable to load settings");let{preferredEditor:r,userName:s,userId:i,autoSync:c,autoSyncDebounceMs:u,attachmentMaxKb:m,logLevel:p,viewMode:f}=o.value,y=ta({userId:i,userName:s});if(d(y))return a(y.message);let I=y.value??{userId:i,userName:s};return!I.userName||!I.userId?a(`User name or ID not configured in ~/${Tt}/config.json`):(process.env.EPIQ_LOG_LEVEL=p,l("successfully loaded settings",{logLevel:p??"debug",preferredEditor:r??"",userName:I.userName,userId:I.userId,autoSync:c??!1,autoSyncIntervalMs:u??1e4,attachmentMaxKb:m??null,viewMode:f??"dense"}))}});var qm,Gm,cd,zm=h(()=>{"use strict";qm="/media/",Gm=e=>`${qm}${e}`,cd=(e,t)=>`})`});import yx from"node:crypto";import ld from"node:fs";import bx from"node:path";var gn,Mo,xx,Ix,Ex,Vm,Po=h(()=>{"use strict";Ft();R();ae();zm();gn=500,Mo=(e,t)=>`${e}.${t}`,xx=e=>e.length>=8&&e.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))?l("Sniffed image type","png"):e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?l("Sniffed image type","jpg"):e.length>=6&&(e.subarray(0,6).equals(Buffer.from("GIF87a","ascii"))||e.subarray(0,6).equals(Buffer.from("GIF89a","ascii")))?l("Sniffed image type","gif"):e.length>=12&&e.subarray(0,4).equals(Buffer.from("RIFF","ascii"))&&e.subarray(8,12).equals(Buffer.from("WEBP","ascii"))?l("Sniffed image type","webp"):a(`Unsupported image format. Allowed: ${pl.join(", ")}`),Ix=e=>yx.createHash("sha256").update(e).digest("hex"),Ex=(e,t=gn)=>{if(e.length===0)return a("Attachment is empty");if(e.length>t*1024)return a(`Attachment exceeds the ${t} KB size cap (${Math.ceil(e.length/1024)} KB)`);let n=xx(e);return d(n)?n:l("Validated attachment data",{hash:Ix(e),ext:n.value,bytes:e.length})},Vm=(e,t,n=gn)=>{let o=Ex(t,n);if(d(o))return o;let r=Ps(e),s=bx.join(r,Mo(o.value.hash,o.value.ext));try{ld.existsSync(s)||(ld.mkdirSync(r,{recursive:!0}),ld.writeFileSync(s,t))}catch(i){return a(`Unable to write attachment blob: ${i instanceof Error?i.message:String(i)}`)}return l("Wrote attachment blob",o.value)}});import Sx from"zod";var Vr,Kr,Km,ud=h(()=>{"use strict";zt();Po();pe();R();ce();We();M();Vr=50,Kr=5e3,Km=()=>{let e=de().commandMeta.inputString,t=Sx.coerce.number().int().min(Vr).max(Kr).safeParse(e);if(!t.success)return a(`Attachment size cap must be ${Vr}-${Kr} KB (default ${gn})`);let n=et({attachmentMaxKb:t.data});return d(n)?n:(ht({attachmentMaxKb:t.data}),N({mode:b.DEFAULT}),l(`Attachment size cap set to ${t.data} KB`,null))}});import Ym from"chalk";var pd,Xm,md,Jm,Rx,Nx,Qm,Cx,Ax,Yr,Te,Zm,ep,hi,wx,Tx,vi,pt=h(()=>{"use strict";di();pd={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Xm=(e,t,n)=>Math.max(t,Math.min(n,e)),md=(e,t,n)=>e+(t-e)*n,Jm=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},Rx=e=>e.toLowerCase().trim(),Nx=(e,t,n)=>{let o=t/100,r=n/100,s=(1-Math.abs(2*r-1))*o,i=e/60,c=s*(1-Math.abs(i%2-1)),u=0,m=0,p=0;i>=0&&i<1?(u=s,m=c):i>=1&&i<2?(u=c,m=s):i>=2&&i<3?(m=s,p=c):i>=3&&i<4?(m=c,p=s):i>=4&&i<5?(u=c,p=s):(u=s,p=c);let f=r-s/2;return[Math.round((u+f)*255),Math.round((m+f)*255),Math.round((p+f)*255)]},Qm=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,Cx=(e,t,n)=>{let o=Xm(n,0,1);return[Math.round(md(e[0],t[0],o)),Math.round(md(e[1],t[1],o)),Math.round(md(e[2],t[2],o))]},Ax=(e,t,n)=>Cx(e,t,n),Yr=e=>{let t=Jm(e)%360,n=Nx(t,pd.stringColor.saturation,pd.stringColor.lightness);return Qm(n)},Te=(e,t=wo)=>{let n=Rx(e??"");return n&&t[n]?t[n]:Yr(n)},Zm=e=>{let t=pd.gradient.stops,n=Xm(e,0,1);if(t.length===0)return[0,0,0];if(t.length===1)return t[0];let o=t.length-1,r=n*o,s=Math.min(Math.floor(r),o-1),i=r-s;return Ax(t[s],t[s+1],i)},ep=e=>Qm(Zm(e)),hi=e=>Jm(e.toLowerCase().trim())/4294967295,wx=e=>{let t=hi(e);return Zm(t)},Tx=e=>{let[t,n,o]=wx(e);return{normal:r=>Ym.bgRgb(t,n,o).black(r),cursor:r=>Ym.bgRgb(t,n,o).white.bold(r)}},vi=e=>Tx(e).normal(` ${e} `)});var tt,hn=h(()=>{"use strict";tt=(e,t,n)=>t.length>n?`${e} cannot exceed ${n} characters (got ${t.length})`:null});import{createHash as kx}from"node:crypto";var Mx,Px,Le,Lo=h(()=>{"use strict";Mx="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Px=e=>{let t=kx("sha256").update(e).digest(),n=0n;for(let r=0;r<16;r++)n=n<<8n|BigInt(t[r]);let o="";for(let r=0;r<26;r++){let s=BigInt((25-r)*5);o+=Mx[Number(n>>s&31n)]}return o},Le=(e,t)=>Px(`${e}:virtual:${t}`)});import tp from"chalk";var le,De,Ue,np=h(()=>{"use strict";pt();Ve();le=e=>tp.dim(e),De=e=>tp.hex(T.primary)(e),Ue=({prefix:e="",wordList:t,postfix:n="",noOfHints:o=100,inputString:r,minLengthForHints:s=1})=>{let i=r.trim();if(i.length<s)return"";let p=[...t.filter(Boolean).filter(f=>f.startsWith(i))].sort((f,y)=>hi(f)-hi(y)).slice(0,o).map(f=>vi(f)).join(" ");return p?`${le(e)}${p}${le(n)}`:""}});var Mn,yi=h(()=>{"use strict";Mn={None:"none",Invalid:"invalid",Valid:"valid"}});import sp from"chalk";var Lx,op,me,ee,G,Fo,rp,bi,fd,Dx,Do,Fx,_x,Ox,Bx,Ux,ip,ap=h(()=>{"use strict";ri();Hr();Om();Ke();Ft();R();ne();We();ud();Po();M();pt();hn();Wr();Lo();np();ro();yi();pn();qr();Lx=["BOARD","TICKET","SWIMLANE"],op=()=>{let e=g().selectedNode;if(!e?.context)return G({message:le("Missing target context")});if(Lx.includes(e.context))return ee();if(e.parentNodeId){let t=g().nodes[e.parentNodeId];if(t?.id===Le(t?.parentNodeId??"","comments"))return ee()}return G({message:le("Command not available in this context")})},me="<ENTER> to confirm",ee=(e="",t=[])=>({message:le(e),validity:Mn.Valid,completionWordList:t}),G=({message:e,completionWordList:t=[]})=>({validity:Mn.Invalid,message:e,completionWordList:t}),Fo=e=>e.length===0,rp=(e,t)=>{let n=it(g().breadCrumb,"BOARD");if(d(n))return G({message:De("Command is not applicable in this context")});let o=ml(n.value.id);return d(o)?G({message:De(`Unable to ${t}: board id is not a valid ULID`)}):Pm({date:e,horizonDate:o.value})?null:G({message:De(`nothing to ${t} before ${o.value.toISOString().slice(0,16).replace("T"," ")}`)})},bi=e=>` ${sp.hex("#000").bgHex(Te(e))(` ${e} `)} `,fd=({modifier:e})=>{let t="confirm";return e===t?ee(me):G({message:Fo(e)?le("if you are certain, enter ")+vi(t):"",completionWordList:[t]})},Dx=({list:e,hint:t,onValue:n})=>({modifier:o,inputString:r})=>e.includes(o)?r.trim().length<1?G({message:le(n)}):ee():G({message:Fo(o)?t:"",completionWordList:[...e]}),Do=({hint:e,onOk:t})=>({modifier:n,inputString:o})=>Fo(n)&&Fo(o)?G({message:e,completionWordList:[]}):ee(t??me),Fx=({modifier:e,inputString:t})=>{let n=sd();return!Fo(e)||!Fo(t)?ee(me):G({message:n.length?le("number from the list, or a path"):le("path to an epiq project"),completionWordList:n})},_x=({modifier:e,inputString:t})=>{let n=we(x.CONFIG);if(!n.includes(e))return G({message:Ue({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case ve.EDITOR:{let o=[..._m];return t.trim()?o.includes(t.trim())?ee(me):G({message:Ue({prefix:"editors: ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o}):G({message:Ue({prefix:"editors: ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o})}case ve.VIEW:{let o=["dense","wide"];return o.includes(t.trim())?ee(me):G({message:Ue({prefix:"view... ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o})}case ve.USERNAME:return t.trim()?ee(me):G({message:De("Enter a user name. Saved in ")+sp.bgBlack("~/.epiq-global/config.json")});case ve.LOG_LEVEL:{let o=["debug","error","info"],r=t.trim();return o.includes(r)?ee(me):G({message:Ue({prefix:"one of: ",wordList:[...o],inputString:r,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...o]})}case ve.AUTOSYNC:{let o=["on","off"],r=Ie().autoSync;if(!o.includes(t.trim())){let s=Tm(r);return G({message:Ue({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:o,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:o})}return ee(me)}case ve.ATTACHMENT_MAX_KB:{let o=Ie().attachmentMaxKb,r=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(r)||r<Vr||r>Kr){let s=Ue({prefix:" examples: ",wordList:rd,minLengthForHints:0,inputString:t});return G({message:De(`provide a size cap in KB (${Vr}-${Kr}). current: ${o??gn} KB.`)+s,completionWordList:rd})}return ee(me)}case ve.SYNC_DEBOUNCE_MS:{let o=Ie().autoSyncIntervalMs,r=ym(t);if(!t.trim()||r===null||r<No){let s=Ue({prefix:" examples: ",wordList:od,minLengthForHints:0,inputString:t});return G({message:De(`provide duration above ${No}ms. current duration: ${o}ms.`)+s,completionWordList:od})}return ee(me)}default:return G({message:De("Unknown config option"),completionWordList:n})}},Ox=({modifier:e,inputString:t})=>{let n=we(x.EDIT);if(!n.length)return G({message:De("Command not available in this context")});if(!n.includes(e)){let o=Ue({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return G({message:o||De("Unknown edit option"),completionWordList:n})}switch(e){case mt.COMMENT:return t.trim()?ee(me):G({message:le("write a comment...")});case mt.TITLE:return ee(me);case mt.DESCRIPTION:{let{preferredEditor:o}=Ie();return o?ee(le("<ENTER> to edit in ")+o):G({message:"No editor selected"})}default:return G({message:De("Unknown edit option"),completionWordList:n})}},Bx=({modifier:e})=>{let t=we(x.YANK);return t.length?t.includes(e)?ee(me+le(" and copy to clipboard")):G({message:Ue({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):G({message:De("Nothing selected to copy from")})},Ux={[x.EXPORT]:()=>ee(me+le(", and create export markdown file")),[x.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return ee(me);let n={message:le("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},o=t||e.inputString.trim(),r=so(o);if(!o||!r)return G(n);let s=rp(r,"peek");return s||ee(me)},[x.REPLAY]:e=>{let{dateInput:t,durationInput:n}=mi(e.modifier,e.inputString),o={message:le("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},r=so(t);if(!t||!r)return G(o);let s=rp(r,"replay");return s||(n&&ui(n)===null?G({message:De("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):ee("<ENTER> to replay board history",n?Fm:[]))},[x.EXIT]:()=>ee(me+le(" and exit the application")),[x.INIT]:()=>ee(me),[x.OPEN]:Fx,[x.PALETTE]:()=>ee(me),[x.FILTER]:e=>{if(e.modifier==="clear")return ee(me);let t=s=>we(x.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return G({message:Ue({wordList:we(x.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:we(x.FILTER)});let n=Object.values(g().tags).map(s=>s.name),o=Object.values(g().contributors).map(s=>s.name),r=e.modifier==="tag"?n:e.modifier==="assignee"?o:[];return e.inputString?r.length&&!r.includes(e.inputString.trim())?G({message:Ue({prefix:`existing ${e.modifier}s... `,wordList:r,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:r}):ee():G({message:Ue({prefix:"one of... ",wordList:r,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:r})},[x.NONE]:e=>{let t=we(x.NONE);return G({message:Ue({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[x.NEW]:e=>Dx({list:we(x.NEW),hint:Ue({wordList:we(x.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[x.HELP]:()=>ee(me),[x.EDIT]:Ox,[x.COMMENT]:e=>{let t=Do({hint:le(`write a comment (max ${4e3} char)...`),onOk:le(`(${e.inputString.length}/${4e3})`)})(e);return t.validity===Mn.Invalid?t:e.inputString.length>4e3?ee(De("max input exceeded")):t},[x.CONFIG]:_x,[x.YANK]:Bx,[x.DELETE]:e=>{let t=op();return t.validity==="invalid"?t:fd(e)},[x.CLOSE_ISSUE]:e=>fd(e),[x.RE_OPEN_ISSUE]:e=>fd(e),[x.MOVE]:e=>{let t=op();return t.validity==="invalid"?t:Do({hint:Ue({prefix:"hey hacker! These commands are blocked for you... ",wordList:we(x.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[x.TAG]:e=>{let n=E.getExistingTags().slice(0,10).map(bi).join("");return Do({hint:n.length?le("create tag or reuse:")+n+le(""):le("create tag ...")})(e)},[x.UNTAG]:e=>{let t=ci();if(d(t))return G({message:De("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:o})=>o).map(bi).slice(0,10);return n.length?Do({hint:le(" ... ")+n.join("")})(e):G({message:De("Issue has no tags"),completionWordList:[]})},[x.ASSIGN]:e=>{let t=E.getExistingAssignees().map(bi).slice(0,10);return Do({hint:le("assignees... ")+t.join("")})(e)},[x.UNASSIGN]:e=>{let t=li();if(d(t))return G({message:De("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:o})=>o).map(bi).slice(0,10);return n.length?Do({hint:le("remove assignee... ")+n.join("")})(e):G({message:De("Issue has no assignees"),completionWordList:[]})},[x.SYNC]:()=>ee(me)},ip=Object.fromEntries(Object.entries(Ux).map(([e,t])=>[e,{validate:(n,o,r)=>t({modifier:o,command:n,inputString:r})}]))});var xi,dp=h(()=>{"use strict";xi=["add","fix","bug","log","run","api","cli","ui","ux","test","mock","stub","sync","hash","sign","fork","push","pull","lock","warn","leak","hang","node","seed","lint","edit","save","load","read","send","drop","swap","wrap","port","host","role","user","auth","flag","diff","perf","docs","todo","task","team","epic","spec","remove","update","change","improve","enhance","refactor","rewrite","redesign","implement","build","create","delete","rename","migrate","upgrade","downgrade","revert","rollback","restore","replace","deprecate","cleanup","simplify","optimize","stabilize","harden","document","clarify","investigate","debug","reproduce","triage","mitigate","remediate","resolve","escalate","verify","validate","benchmark","profile","audit","monitor","instrument","configure","provision","deploy","release","publish","integrate","automate","support","enable","disable","prevent","handle","ensure","prioritize","estimate","schedule","track","install","uninstall","enforce","expose","extract","inject","override","extend","customize","localize","translate","redirect","forward","dispatch","broadcast","subscribe","unsubscribe","register","allocate","reserve","persist","retrieve","archive","expire","refresh","reload","reset","recover","replay","retry","scaffold","bootstrap","finalize","terminate","suspend","resume","cancel","abort","notify","alert","trigger","debounce","frontend","backend","fullstack","infrastructure","architecture","integration","application","environment","framework","platform","service","component","module","gateway","pipeline","container","orchestrator","middleware","endpoint","interface","database","datastore","cache","queue","scheduler","worker","daemon","runtime","library","package","plugin","extension","webhook","microservice","monolith","repository","namespace","cluster","sandbox","tenant","dashboard","console","portal","client","server","browser","mobile","desktop","kernel","driver","protocol","schema","migration","fixture","template","snippet","config","manifest","bundle","exception","incident","defect","regression","degradation","malfunction","instability","intermittent","workaround","failure","outage","crash","freeze","corruption","inconsistency","severity","criticality","diagnostics","analysis","blocker","flaky","timeout","mismatch","misconfiguration","boundary","overflow","underflow","panic","stacktrace","breakage","breaking","oversight","ambiguity","discrepancy","anomaly","authorize","authenticate","confidentiality","availability","accessibility","reliability","compliance","governance","encrypt","decrypt","integrity","traceability","accountability","protection","privileges","permissions","sanitize","escape","vulnerability","exposure","secrets","credentials","certificate","session","cookie","identity","tokenization","rotation","scanning","hardening","threat","exploit","payload","injection","phishing","breach","dependency","orchestrate","synchronize","compatibility","incompatibility","interoperability","observability","telemetry","discovery","registration","coordination","distribution","isolation","virtualization","networking","routing","proxy","firewall","balancer","failover","topology","replica","shard","region","capacity","quota","metrics","logging","tracing","alerting","monitoring","heartbeat","liveness","rollover","serialize","deserialize","initialize","instantiate","propagate","aggregate","consolidate","normalize","standardize","transform","reconcile","correlate","index","partition","enrich","filter","stream","batch","parse","encode","decode","compress","decompress","deduplicate","paginate","query","ingest","export","import","backup","snapshot","mapping","record","dataset","metadata","checksum","rollup","lookup","cursor","truncate","concurrency","parallelism","contention","deadlock","throttle","backpressure","fragmentation","saturation","exhaustion","replicate","redundancy","obsolescence","starvation","overload","latency","throughput","scalability","bottleneck","memoize","prefetch","warmup","autoscale","horizontal","vertical","elasticity","recursion","allocation","leakage","garbage","collection","pooling","buffering","caching","eviction","staleness","modularize","encapsulate","abstraction","extensibility","configurability","maintainability","recoverability","readability","testability","debuggability","reusability","simplicity","consistency","linting","formatting","typecheck","coverage","tooling","scaffolding","boilerplate","technical","cleanliness","naming","comments","docstring","testing","unittest","mocking","stubbing","assertion","smoke","sanity","fuzzing","flakiness","harness","scenario","baseline","performance","functionality","requirement","recommendation","improvement","enhancement","description","acceptance","criteria","deliverable","milestone","iteration","backlog","roadmap","followup","hotfix","patch","changelog","rollout","feature","spike","proposal","specification","priority","sprint","story","subtask","assignee","reviewer","reproduction","context","expected","actual","impact","workflow","version","tracking","discussion","decision","tradeoff","feedback","approval","planning","breakdown","scoping"]});var $x,jx,Hx,Wx,qx,cp,lp,up,mp=h(()=>{"use strict";R();M();dp();$x=3,jx=new Set(["the","and","for","are","but","not","you","all","any","can","was","one","our","out","use","this","that","with","have","from","will","your","they","them","then","than","when","what","were","been","into","should","would","could","about"]),Hx=e=>{let t=[];for(let n of Object.values(e.nodes)){n.title&&t.push(n.title);let o=n.props;typeof o.description=="string"&&t.push(o.description),typeof o.value=="string"&&t.push(o.value)}for(let n of Object.values(e.tags))t.push(n.name);for(let n of Object.values(e.contributors))t.push(n.name);for(let n of Object.values(e.comments))t.push(n.md);return t},Wx=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=$x&&!jx.has(t)&&!/^\d+$/.test(t)),qx=e=>{let t=new Map;for(let s of Hx(e))for(let i of Wx(s))t.set(i,(t.get(i)??0)+1);let n=[...t.entries()].sort((s,i)=>i[1]-s[1]||s[0].localeCompare(i[0])).map(([s])=>s),o=new Set(n),r=xi.filter(s=>!o.has(s));return[...n,...r]},cp=xi,lp=-1,up=()=>{let e=ze();if(d(e))return xi;let t=e.value,n=t.eventLog.length;return n!==lp&&(cp=qx(t),lp=n),cp}});var pp,fp,gd=h(()=>{"use strict";Rl();pn();ro();ap();mp();M();pe();pp=e=>Object.values(x).includes(e),fp=(e,t)=>{let n=e.command??"",{modifier:o,target:r,inputString:s}=e,{message:i,validity:c,completionWordList:u}=ip[n].validate(n,o,s),m=n!==x.PEEK&&n!==x.REPLAY,p=r==="command"||r==="modifier"?we(n):m?up():[],{mode:f}=g(),y=f===b.COMMAND_LINE?i??"":"",I=[...u,...p];return{validity:c,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:y,autoCompletion:t?Sl(e,I):{hint:"",hints:[],remainder:"",overlap:0}}}});var gp,Gx,zx,Vx,hp=h(()=>{"use strict";gd();pn();gp=e=>{let t=e.trimStart(),n=zx(t),o=n[0]??"",r=n[1]??"",s=/\s$/.test(e),i=Vx(e),c=pp(o)?o:null,u=c!==null,m=o!=="",p=c?we(c)??[]:[],f=c&&p.includes(r)?r:"",y="word";n.length===0||n.length===1&&!s?y="command":(n.length===1&&s||n.length===2&&!s)&&(y="modifier");let I=s?"":i,S=Gx(t,c,f);return{raw:e,trimmedStart:t,words:n,firstWord:o,lastWord:i,hasCommand:m,command:c,isCommandKeyword:u,isLastWordCompleted:s,modifier:f,target:y,inputToMatch:I,inputString:S}},Gx=(e,t,n)=>{let o=e;return t&&o.startsWith(t)&&(o=o.slice(t.length)),o=o.replace(/^\s+/,""),n&&o.startsWith(n)&&(o=o.slice(n.length),o=o.replace(/^\s+/,"")),o},zx=e=>e.trim()?e.trim().split(/\s+/):[],Vx=e=>e.trimEnd().split(/\s+/).at(-1)??""});import{useSyncExternalStore as aP}from"react";var _o,hd,Oo,Kx,vp,Vt,Xr,vd,yd,yp,bp,Ii,xp,te,Ip,Ep,Sp,de,Ei,ce=h(()=>{"use strict";gd();hp();R();yi();_o=e=>e===hd||e===":",hd=" ",Oo={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:Mn.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},Kx=new Set,vp=()=>{for(let e of Kx)e()},Vt=e=>{let n=e(Oo),o=gp(n.value),r=n.cursorPosition===n.value.length;Oo={...n,commandMeta:fp(o,r)},vp()},Xr=({message:e,status:t})=>{let n=structuredClone(Oo);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,Oo=n,vp(),l(e,null)},vd=e=>{Vt(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},yd=e=>{Vt(t=>{let{value:n,cursorPosition:o}=t,r=o;if(e==="left"){for(;r>0&&_o(n[r-1]);)r--;for(;r>0&&!_o(n[r-1]);)r--}else{for(;r<n.length&&!_o(n[r]);)r++;for(;r<n.length&&_o(n[r]);)r++}return{...t,cursorPosition:r}})},yp=()=>{Vt(e=>{let t=e.value.slice(e.cursorPosition),n=Math.max(0,e.cursorPosition-1);return{...e,value:e.value.slice(0,n)+t,cursorPosition:n,commandIsPending:!1}})},bp=()=>{Vt(e=>{let{value:t,cursorPosition:n}=e,o=n;for(;o>0&&_o(t[o-1]);)o--;for(;o>0&&!_o(t[o-1]);)o--;let r=t.slice(n);return{...e,value:t.slice(0,o)+r,cursorPosition:o,commandIsPending:!1}})},Ii=e=>{Vt(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),o=t.value.slice(0,n),r=t.value.slice(n),s=e(o,t.commandMeta.autoCompletion),i=s+r,c=Math.max(0,Math.min(s.length,i.length));return{...t,value:i,cursorPosition:c,commandIsPending:!1}})},xp=()=>{Vt(e=>({...e,commandIsPending:!0}))},te=e=>{Vt(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},Ip=({addToHistory:e=!0})=>{Vt(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},Ep=()=>{Vt(e=>{let t=Math.min(e.commandHistoryIndex+1,e.commandHistory.length-1),n=e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},Sp=()=>{Vt(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},de=()=>Oo,Ei=()=>{let[e,...t]=Oo.value.split(hd);return t.join(hd).trim()}});var O,jn=h(()=>{"use strict";pe();gl();M();ce();We();O={NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MoveToPreviousContainer:"moveToPreviousContainer",MoveToNextContainer:"moveToNextContainer",Confirm:"confirm",Exit:"exit",ViewHelp:"viewHelp",HideHelp:"hideHelp",InitMove:"initMove",ConfirmMove:"confirmMove",Delete:"Delete",InitCommandPalette:"initCommandPalette",InitCommandLine:"initCommandLine",ExitCommandLine:"exitCommandLine",CaptureInput:"captureInput",EraseInput:"eraseInput",AddItem:"addItem",GetLastCommandFromHistory:"getLastCommandFromHistory",GetNextCommandFromHistory:"getNextCommandFromHistory",AutoCompleteCommand:"autoCompleteCommand",MoveCursorLeft:"MoveCursorLeft",MoveCursorRight:"MoveCursorRight",MoveCursorLeftOfWord:"MoveCursorLeftOfWord",MoveCursorRightOfWord:"MoveCursorRightOfWord",EraseInputWord:"EraseInputWord",None:"None",Edit:"edit",EditTitle:"editTitle",EditDescription:"editDescription",Yank:"yank",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"}});var Rp,B,bd=h(()=>{"use strict";M();ro();Rp=e=>{let{context:t}=g().contextNode;if(!t)return B.None;switch(e){case x.EXIT:return B.Exit;case x.EXPORT:return B.Export;case x.INIT:return B.Init;case x.OPEN:return B.OpenProject;case x.DELETE:return B.Delete;case x.EDIT:return B.Edit;case x.COMMENT:return B.Comment;case x.HELP:return B.ViewHelp;case x.RE_OPEN_ISSUE:return B.ReopenIssue;case x.CLOSE_ISSUE:return B.CloseIssue;case x.TAG:return B.TagTicket;case x.UNTAG:return B.UntagTicket;case x.ASSIGN:return B.AssignUserToTicket;case x.UNASSIGN:return B.UnassignUserFromTicket;case x.NEW:return B.NewItem;case x.FILTER:return B.Filter;case x.MOVE:return B.Move;case x.PEEK:return B.Peek;case x.REPLAY:return B.Replay;case x.CONFIG:return B.Config;case x.YANK:return B.Yank;case x.SYNC:return B.Sync;default:return B.None}},B={Exit:"exit",Init:"init",OpenProject:"open-project",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",Replay:"replay",Yank:"yank",Config:"config",NewItem:"add-new-item",TagTicket:"ticket-tag",UntagTicket:"ticket-untag",AssignUserToTicket:"ticket-assign-user",UnassignUserFromTicket:"ticket-unassign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Comment:"comment-issue",Sync:"sync",Export:"export"}});import{Text as Np}from"ink";import Cp,{useEffect as Ap,useState as Yx}from"react";var wp,ot,Bo=h(()=>{"use strict";M();Ve();wp={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},ot=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=rt(),o=wp[n]??wp.default,[r,s]=Yx(0);if(Ap(()=>{s(0)},[o]),Ap(()=>{if(!e)return;let c=setInterval(()=>{s(u=>(u+1)%o.length)},500);return()=>clearInterval(c)},[e,o]),!e)return Cp.createElement(Np,null,t);let i=o[r]??o[0]??t;return Cp.createElement(Np,{color:T.accent,dimColor:r===1},i)}});import{Box as xd,Text as Xx}from"ink";import Si from"react";var Jx,Pn,Jr=h(()=>{"use strict";Ve();Jx=(e,t,n,o)=>{let r=u=>Math.max(1,e[u]??1),s=n,i=n+1,c=r(n);for(;i<t&&c+r(i)<=o;)c+=r(i),i++;for(;s>0&&c+r(s-1)<=o;)s--,c+=r(s);return{start:s,end:i}},Pn=({children:e=[],height:t,selectedIndex:n,itemHeight:o=1,itemHeights:r,scrollByOne:s=!1})=>{if(e.length===0)return null;let i=Math.max(1,Math.floor(t)),c=Math.max(1,Math.ceil(o)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(1,Math.floor(i/c)),p=Math.max(0,e.length-m),{start:f,end:y}=r?Jx(r,e.length,u,i):s?{start:Math.min(p,Math.max(0,u-m+1)),end:Math.min(p,Math.max(0,u-m+1))+m}:{start:Math.min(p,Math.floor(u/m)*m),end:Math.min(p,Math.floor(u/m)*m)+m},I=Math.max(1,y-f),S=e.slice(f,y),A=e.length>I,w=i,k=A?Math.max(1,Math.floor(I/e.length*w)):w,D=Math.max(0,w-k),_=Math.max(1,e.length-I),H=A?Math.floor(f/_*D):0;return Si.createElement(xd,{flexDirection:"row",height:i,width:"100%"},Si.createElement(xd,{flexDirection:"column",flexGrow:1,height:i},S),Si.createElement(xd,{flexDirection:"column",width:1,height:w},Array.from({length:w}).map((ie,En)=>Si.createElement(Xx,{key:En,color:A&&En>=H&&En<H+k?T.accent:T.secondary},A?"\u2502":" "))))}});var Tp,Id,Qx,Ri,Ed=h(()=>{"use strict";M();Qx=()=>{let{eventLog:e=[]}=g();if(Id&&Tp===e)return Id;let t=new Set;for(let n of e)n?.userId&&t.add(n.userId);return Tp=e,Id=t,t},Ri=e=>Qx().has(e)});import{Text as Zx}from"ink";import eI from"react";var tI,nI,Uo,Ni=h(()=>{"use strict";di();pt();ne();Ed();dt();tI=e=>e.toLowerCase().trim(),nI=(e,t=wo)=>{let n=tI(e);return t[n]?t[n]:Yr(n)},Uo=({id:e,isSelected:t,maxWidth:n})=>{let o=E.getContributor(e);if(!o)return;let r=o.name,s=n===void 0?r:Hn(r,n);return eI.createElement(Zx,{underline:t,color:nI(r)},"@"+s,Ri(e)?"":"\u2197")}});import{Text as oI}from"ink";import rI from"react";var Ci,Sd=h(()=>{"use strict";ne();Ve();pt();dt();Ci=({id:e,isSelected:t,maxWidth:n})=>{let o=E.getTag(e);if(!o)return;let r=n===void 0?o.name:Hn(o.name,n);return rI.createElement(oI,{underline:t,backgroundColor:Te(o.name),color:T.secondary}," "+r+" ")}});import{useEffect as sI,useState as iI}from"react";var aI,kp,Ai,Qr,dI,cI,$o,wi=h(()=>{"use strict";pt();aI=80,kp=1400,Ai=new Set,Qr=null,dI=e=>(Ai.add(e),Qr||(Qr=setInterval(()=>{for(let t of Ai)t()},aI)),()=>{Ai.delete(e),Ai.size===0&&Qr&&(clearInterval(Qr),Qr=null)}),cI=()=>{let e=Date.now()%kp/kp;return e<.5?e*2:(1-e)*2},$o=e=>{let[,t]=iI(0);return sI(()=>{if(e)return dI(()=>t(n=>n+1))},[e]),ep(cI())}});import{Box as jo,Text as Ho}from"ink";import st from"react";var lI,Mp,uI,mI,Pp,Lp=h(()=>{"use strict";ne();Ve();dt();Ed();Je();Wr();Ni();Sd();wi();lI=(e,t,n)=>{if(e.length<=t)return[e,null];let o=e.lastIndexOf(" ",t),r=o>0?o:t;return[e.slice(0,r),Hn(e.slice(r).trim(),n)]},Mp=3,uI=2,mI=(e,t)=>{let n=[],o=0;for(let[r,s]of e.entries()){let i=e.length-r-1,c=i>0?String(i).length+1:0;if(o+s.width+c>t)break;o+=s.width,n.push(s)}return{shown:n,hidden:e.length-n.length}},Pp=({width:e,ticket:t,isSelected:n,isFlashing:o=!1})=>{let r=$o(o),s=e-4,i=s-7-1,[c,u]=lI(fe(t.title),i,s),m=u?null:Hn(fe(t.props.description),s)||null,p=Tn(t),f=kn(t).map(k=>({...k,name:k.name})),y=Math.max(1,s-Mp),I=E.getCommentsByIssue(t.id),S=I.length?String(I.length).length+2+1:0,{shown:A,hidden:w}=mI([...p.map(k=>({id:k.id,isTag:!0,width:Math.min(k.name.length,y)+Mp})),...f.map(k=>({id:k.id,isTag:!1,width:Math.min(k.name.length,y)+uI+(Ri(k.id)?0:1)}))],s-S);return st.createElement(jo,{borderStyle:"round",height:5,flexDirection:"column",overflow:"hidden",borderDimColor:!n,borderColor:o?r:n?T.accent:T.secondary,justifyContent:"space-between"},st.createElement(jo,{paddingLeft:1,paddingRight:1,flexDirection:"column"},st.createElement(jo,{justifyContent:"space-between"},st.createElement(Ho,{color:T.primary},c),st.createElement(Ho,{color:T.secondary2,dimColor:!0},j(t.id))),u&&st.createElement(Ho,{color:T.primary},u),m&&st.createElement(Ho,{color:T.secondary2,dimColor:!0},m)),st.createElement(jo,{flexDirection:"row",paddingLeft:1,paddingRight:1,justifyContent:"space-between"},st.createElement(jo,{flexDirection:"row"},A.map(k=>st.createElement(jo,{paddingRight:1,key:k.id},k.isTag?st.createElement(Ci,{id:k.id,maxWidth:y}):st.createElement(Uo,{id:k.id,maxWidth:y}))),w>0&&st.createElement(Ho,{color:T.secondary2,dimColor:!0},"+",w)),I.length>0&&st.createElement(Ho,{color:T.accent},"[",I.length,"]")))}});import{Box as ao,Text as Zr}from"ink";import ft from"react";var pI,Dp,Fp=h(()=>{"use strict";pe();ne();Ve();pt();Bo();wi();pI=(e,t)=>e.length>t?e.slice(0,Math.max(0,t-1))+"\u2026":e,Dp=({index:e,labelWidth:t,width:n,ticket:o,isSelected:r,isFlashing:s=!1,mode:i})=>{let c=$o(s),u=(o.props.tags??[]).map(ie=>E.getTag(ie)).filter(ie=>!!ie),m=(o.props.assignees??[]).map(ie=>E.getContributor(ie)).map(ie=>ie&&{...ie,name:ie.name}).filter(ie=>!!ie),p=1,f=u.length*(1+p),y=m.length*(2+p),I=u.map(ie=>ft.createElement(ao,{key:ie.id,paddingRight:p},ft.createElement(Zr,{color:Te(ie.name)},"\u25A0"))),S=m.map(ie=>ft.createElement(ao,{key:ie.id,paddingRight:p},ft.createElement(Zr,{color:Yr(ie.name)},"@"+ie.name.at(0)))),A=s?c:r?T.accent:i===b.MOVE?T.secondary:T.primary,w=E.getCommentsByIssue(o.id),k=w.length?String(w.length).length+2+p:0,D=w.length?ft.createElement(ao,{paddingRight:p},ft.createElement(Zr,{color:T.accent},"[",w.length,"]")):null,_=f+y+k,H=Math.max(1,n-t-_-(_>0?1:0));return ft.createElement(ao,{justifyContent:"space-between"},ft.createElement(ao,null,ft.createElement(ao,{width:t},r?ft.createElement(ot,{isSelected:!0}):ft.createElement(Zr,{color:"gray",dimColor:!0},String(e+1).padStart(t-1)+" ")),ft.createElement(Zr,{wrap:"truncate",color:A},pI(o.title,H))),ft.createElement(ao,null,I,S,D))}});import fI from"chalk";import{Box as Rd,Text as gI}from"ink";import Kt from"react";var hI,_p,Op=h(()=>{"use strict";K();M();Ve();Bo();Jr();Lp();Fp();wi();hI=({swimlane:e,isSelected:t,width:n,height:o,isDense:r,isFocused:s,listSelectedIndex:i,mode:c})=>{let{renderedChildrenIndex:u,replay:m}=rt(),p=u[e.id]??[],f=m?new Set(m.flashNodeIds):null,y=f?.has(e.id)??!1,I=$o(y),S=`${e.title} ${fI.hex(T.secondary2).dim("("+p.length+")")}`,A=3,w=r?1:5,k=s&&i===-1,D=n-3-(r?1:0)-(k?2:0),_=Math.max(2,String(p.length).length+1),H=o-A-1,ie=Kt.createElement(Rd,{borderStyle:"round",borderColor:T.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1,marginRight:r?1:0},Kt.createElement(ot,{isSelected:t}),Kt.createElement(gI,{bold:!0,color:y?I:t?T.accent:T.primary},S," ",e.readonly?"\u{1F512}":"")),En=(en,ar)=>{let dr=s&&i===ar;if(!P(en))return null;let ho=f?.has(en.id)??!1;return r?Kt.createElement(Dp,{key:en.id,index:ar,labelWidth:_,width:D,ticket:en,isSelected:dr,isFlashing:ho,mode:c}):Kt.createElement(Pp,{key:en.id,width:D,ticket:en,isSelected:dr,isFlashing:ho})};return Kt.createElement(Rd,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?T.accent:T.secondary,paddingRight:0,paddingLeft:r?1:0,height:o},ie,Kt.createElement(Rd,null,p.length>0&&Kt.createElement(Pn,{selectedIndex:i,height:H,itemHeight:w},p.map(En)),k&&Kt.createElement(ot,{isSelected:!0})))},_p=Kt.memo(hI)});var Bp,Up,Nd=h(()=>{"use strict";Gn();Bp=e=>{let t=new Set((e.log??[]).filter(n=>n.action==="delete.issue.comment").map(n=>n.payload.id));return(e.log??[]).filter(n=>n.action==="add.issue.comment"&&n.payload.issue===e.id&&!t.has(n.payload.id)).length},Up=(e,t,n)=>Pe.comment({id:e.id,parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.id,props:{value:e.md},readonly:!1,isVirtual:!0})});var qo,Ti=h(()=>{"use strict";qo=e=>{let t=Date.now()-e,n=[{label:"y",ms:1e3*60*60*24*365},{label:"mo",ms:1e3*60*60*24*30},{label:"w",ms:1e3*60*60*24*7},{label:"d",ms:1e3*60*60*24},{label:"h",ms:1e3*60*60},{label:"m",ms:1e3*60},{label:"s",ms:1e3}];for(let{label:o,ms:r}of n){let s=Math.floor(t/r);if(s>=1)return`${s}${o} ago`}return"just now"}});import{Box as Go,Text as vn}from"ink";import je,{useEffect as vI,useMemo as yI,useRef as bI}from"react";import{decodeTime as $p}from"ulid";function Hp({ticket:e,width:t,height:n}){let o=yI(()=>II(e),[e]),r=bI([]);vI(()=>(jp(r.current),r.current=SI(e,o),()=>{jp(r.current),r.current=[]}),[e,o]);let{selectedIndex:s}=rt(),c=Math.max(1,n-4),u=Math.max(12,t-32);return o.length===0?je.createElement(Go,{flexDirection:"column",width:t,height:n,padding:1},je.createElement(vn,{color:T.primary},"No attachments yet."),je.createElement(Go,{paddingTop:1},je.createElement(vn,{color:T.primary},"Attach images from the browser GUI"),je.createElement(vn,{color:T.accent}," epiq gui "),je.createElement(vn,{color:T.primary},"by dropping or pasting them."))):je.createElement(Go,{flexDirection:"column",width:t,height:n},je.createElement(Go,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:T.secondary,borderStyle:"single",paddingBottom:1},je.createElement(vn,{color:T.secondary2},"Attachments (",o.length,") \u2014 enter to open"," ")),je.createElement(Pn,{height:c,itemHeight:2,selectedIndex:s},o.map((m,p)=>{let f=p===s,y=m.name.length>u?m.name.slice(0,u-1)+"\u2026":m.name;return je.createElement(Go,{key:m.id,flexDirection:"row",paddingX:1,paddingBottom:1},je.createElement(vn,{color:T.accent},f?"\u276F ":" "),je.createElement(Go,{paddingLeft:1},je.createElement(vn,{color:T.secondary2},`#${p+1} `),je.createElement(vn,{color:f?T.accent:T.primary},y),je.createElement(vn,{color:T.secondary2}," "+RI(m.bytes)+" "+qo(He(m.id)))))})))}var xI,II,jp,EI,SI,RI,Wp=h(()=>{"use strict";ut();Ke();Ti();K();R();ne();Gn();M();Ve();Lo();Jr();xI=e=>Le(e,"attachments"),II=e=>E.getAttachmentsByIssue(e.id).sort((t,n)=>$p(t.id)-$p(n.id)),jp=e=>{for(let t of e)E.deleteNode(t.id)},EI=(e,t,n)=>Pe.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),SI=(e,t)=>{let n=E.getNode(xI(e.id));if(!n||!at(n))return[];let o=t.map((r,s)=>EI(r,s,n.id)).map(r=>E.createNode(r)).filter(Dt).map(({value:r})=>r).filter(at);return t.length>0&&g().selectedIndex<0&&U.navigate({contextNode:n,selectedIndex:0}),o},RI=e=>`${Math.max(1,Math.round(e/1024))} KB`});var Gp,Cd,qp,Ad,zp,Vp,NI,Kp,CI,wd,Yp=h(()=>{"use strict";Gp=/<!--\s*epiq-diff-comment:(.+?)-->\n?/,Cd=e=>e.replace(Gp,""),qp=e=>e==="additions"||e==="deletions",Ad=e=>{let t=Gp.exec(e);if(!t?.[1])return null;let n;try{n=JSON.parse(t[1])}catch{return null}let o=n;return typeof o?.filePath!="string"||typeof o.start!="number"||typeof o.end!="number"||typeof o.note!="string"||!qp(o.side)||!qp(o.endSide)||o.sha!==void 0&&typeof o.sha!="string"||o.issueRef!==void 0&&typeof o.issueRef!="string"?null:o},zp=/```\n([\s\S]*?)\n?```\s*$/,Vp=e=>zp.exec(e)?.[1]??null,NI=/`[^`\n]+`[^\n]*\n?$/,Kp=e=>Cd(e).replace(zp,"").replace(NI,"").trim(),CI=e=>{let n=(e.endSide??e.side)==="deletions"?"removed":"added";return e.start===e.end?`line ${e.start} (${n})`:`lines ${e.start}-${e.end} (${n})`},wd=e=>`${e.issueRef?`${e.issueRef} \xB7 `:""}${e.filePath} ${CI(e)}`});var AI,es,wI,TI,kI,MI,Jp,Td,Qp,Xp,Zp,kd=h(()=>{"use strict";Yp();AI=(e,t)=>{let n=Math.max(1,Math.floor(t)),o=e.split(/\s+/).filter(Boolean);if(o.length===0)return[""];let r=[],s="";for(let i of o){let c=i;for(;c.length>n;)s&&(r.push(s),s=""),r.push(c.slice(0,n)),c=c.slice(n);s?s.length+1+c.length<=n?s=`${s} ${c}`:(r.push(s),s=c):s=c}return s&&r.push(s),r},es=e=>{let t=e.split("`");return t.length%2===0?[{text:e}]:t.map((n,o)=>o%2===1?{text:n,code:!0}:{text:n}).filter(n=>n.text.length>0)},wI=/!\[([^\]]*)\]\([^)]*\)/g,TI=e=>e.replace(wI,(t,n)=>n.trim()?`[image: ${n.trim()}]`:"[image]"),kI=e=>e.map(t=>t.code?`\`${t.text}\``:t.text).join(""),MI=4,Jp=e=>e.replace(/\r$/,"").replaceAll(" "," ".repeat(MI)),Td=e=>{let t=!1;return e.map(Jp).map(n=>{if(/^\s*```/.test(n))return t=!t,{kind:"fence"};if(t)return{kind:"code",text:n};let o=Ad(n);if(o)return{kind:"caption",text:wd(o)};let r=TI(n);if(r.trim()==="")return{kind:"blank"};let s=/^#{1,6}\s+(.*)$/.exec(r);return s?{kind:"heading",spans:es(s[1]??"")}:{kind:"text",spans:es(r)}})},Qp=(e,t)=>e.length<=t?[e]:e.match(new RegExp(`.{1,${t}}`,"g"))??[""],Xp=(e,t)=>{let n=[];for(let o of Td(e))if(o.kind!=="fence"){if(o.kind==="blank"){n.length>0&&n[n.length-1]?.kind!=="blank"&&n.push(o);continue}if(o.kind==="code"){for(let r of Qp(o.text,t))n.push({kind:"code",text:r});continue}if(o.kind==="caption"){n.push(o);continue}for(let r of AI(kI(o.spans),t))n.push({kind:o.kind,spans:es(r)})}for(;n.length>0&&n[n.length-1]?.kind==="blank";)n.pop();return n},Zp=(e,t)=>{let n=Ad(e),o=n?Vp(e):null;if(!n||o===null)return Xp(Cd(e).split(`
|
|
77
|
+
`),t);let r=Kp(e),s=o.split(`
|
|
78
|
+
`).map(Jp),i=n.side===n.endSide?n.start:void 0,c=i===void 0?0:String(i+s.length-1).length+3;return[...r?[...Xp(r.split(`
|
|
79
|
+
`),t),{kind:"blank"}]:[],{kind:"caption",text:wd(n)},...s.flatMap((u,m)=>Qp(u,Math.max(1,t-c)).map((p,f)=>({kind:"code",text:p,number:i===void 0||f>0?void 0:i+m})))]}});import{Box as ef,Text as co}from"ink";import Rt from"react";var tf,Md,nf,Pd=h(()=>{"use strict";Ve();tf=({spans:e,bold:t,wrap:n})=>Rt.createElement(co,{color:T.primary,bold:t,wrap:n},e.map((o,r)=>o.code?Rt.createElement(co,{key:r,color:T.yellow},o.text):Rt.createElement(co,{key:r},o.text))),Md=({line:e,width:t,gutter:n=0,wrap:o})=>{switch(e.kind){case"blank":return Rt.createElement(co,null," ");case"fence":return Rt.createElement(co,{color:T.secondary2},"```");case"caption":return Rt.createElement(co,{color:T.accent,wrap:o},e.text);case"heading":return Rt.createElement(tf,{spans:e.spans,bold:!0,wrap:o});case"text":return Rt.createElement(tf,{spans:e.spans,wrap:o});case"code":{let r=n>0?`${e.number===void 0?"":String(e.number)}`.padStart(n-3)+" \u2502 ":"";return Rt.createElement(co,{backgroundColor:T.secondary,color:T.primary,wrap:o},r,e.text.padEnd(Math.max(0,t-r.length)))}}},nf=({lines:e,width:t})=>{let n=e.flatMap(r=>r.kind==="code"&&r.number!==void 0?[r.number]:[]),o=n.length>0?String(Math.max(...n)).length+3:0;return Rt.createElement(ef,{flexDirection:"column"},e.map((r,s)=>Rt.createElement(ef,{key:s},Rt.createElement(Md,{line:r,width:t,gutter:o}))))}});import{Box as Ln,Text as Dn}from"ink";import ke,{useEffect as PI,useMemo as of,useRef as LI}from"react";import{decodeTime as rf}from"ulid";function af({ticket:e,width:t,height:n}){let o=of(()=>_I(e),[e]),r=LI([]);PI(()=>(sf(r.current),r.current=OI(e,o),()=>{sf(r.current),r.current=[]}),[e,o]);let{selectedIndex:s}=rt(),c=Math.max(1,n-4),u=Math.max(20,t-8),m=of(()=>o.map(f=>{let y=Zp(f.md,u);return y.length>0?y:[{kind:"blank"}]}),[o,u]),p=m.map(f=>f.length+DI);return o.length===0?ke.createElement(Ln,{flexDirection:"column",width:t,height:n,padding:1},ke.createElement(Dn,{color:T.primary},"No comments yet."),ke.createElement(Ln,{paddingTop:1},ke.createElement(Dn,{color:T.primary},"Use"),ke.createElement(Dn,{color:T.accent}," :comment "),ke.createElement(Dn,{color:T.primary},"to add the first one."))):ke.createElement(Ln,{flexDirection:"column",width:t,height:n},ke.createElement(Ln,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:T.secondary,borderStyle:"single",paddingBottom:1},ke.createElement(Dn,{color:T.secondary2},"Comments (",o.length,") ")),ke.createElement(Pn,{height:c,itemHeights:p,selectedIndex:s},o.map((f,y)=>{let I=y===s;return ke.createElement(Ln,{key:f.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:T.secondary,borderStyle:"single"},ke.createElement(Ln,{flexDirection:"row",paddingBottom:1},ke.createElement(Dn,{color:T.accent},I?"\u276F ":" "),ke.createElement(Ln,{paddingLeft:1},ke.createElement(Dn,{color:T.secondary2},`#${y+1} `),ke.createElement(Uo,{id:f.authorId}),ke.createElement(Dn,{color:T.secondary2}," "+qo(He(f.id))))),ke.createElement(Ln,{paddingLeft:3,paddingBottom:1},ke.createElement(nf,{lines:m[y]??[],width:u})))})))}var DI,FI,_I,sf,OI,df=h(()=>{"use strict";ut();Ke();Ti();K();R();ne();M();Ve();Lo();Ni();Jr();Nd();kd();Pd();DI=4,FI=e=>Le(e,"comments"),_I=e=>E.getCommentsByIssue(e.id).sort((t,n)=>rf(t.id)-rf(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),sf=e=>{for(let t of e)E.deleteNode(t.id)},OI=(e,t)=>{let n=E.getNode(FI(e.id));if(!n||!at(n))return[];let o=t.map((r,s)=>Up(r,s,n.id)).map(E.createNode).filter(Dt).map(({value:r})=>r).filter(hr);return t.length>0&&g().selectedIndex<0&&U.navigate({contextNode:n,selectedIndex:0}),o}});import{Box as ki,Text as BI}from"ink";import yn from"react";var cf,lf=h(()=>{"use strict";K();ne();Io();M();Ve();Ni();Bo();Sd();cf=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:o}=rt(),{title:r}=t,s=t.parentNodeId?E.getNode(t.parentNodeId):void 0,i=s&&P(s)?r===ue.ASSIGNEES?s.props.assignees??[]:r===ue.TAGS?(s.props.tags??[]).filter(c=>E.getTag(c)):[]:[];return yn.createElement(ki,{alignItems:"center",paddingTop:1},yn.createElement(ki,{minWidth:12},yn.createElement(ot,{isSelected:n}),yn.createElement(BI,{color:n?T.accent:T.secondary2},r,":")),yn.createElement(ki,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((c,u)=>{let m=o.id===t.id&&u===e;return yn.createElement(ki,{key:`${r}-${c}`,paddingRight:2,minHeight:1},yn.createElement(ot,{isSelected:m}),r===ue.ASSIGNEES?yn.createElement(Uo,{isSelected:m,id:c}):r===ue.TAGS?yn.createElement(Ci,{isSelected:m,id:c}):null)})))}});var Ld,uf,Dd,Fd=h(()=>{"use strict";Ld=e=>Math.max(5,String(Math.max(e,1)).length+3),uf=(e,t)=>Math.max(0,e-6-Ld(t)),Dd=(e,t=0)=>Math.max(1,e-5-2*t)});import{Box as zo,Text as _d}from"ink";import Nt,{useEffect as UI,useMemo as Od}from"react";var $I,mf,Bd,pf,jI,Ud,ff=h(()=>{"use strict";ne();R();Gn();M();Ve();dt();Fd();Bo();Jr();Pd();kd();yo();$I="\u2029",mf=(e,t)=>`${e}::inline-line::${t}`,Bd=new Map,pf=e=>{let t=Bd.get(e)??[];Bd.delete(e);for(let n of t)E.deleteNode(n)},jI=(e,t)=>{pf(e);let n=[];t.forEach((o,r)=>{let s=vt(BigInt(r+1));if(!Dt(s))return;let i=E.createNode(Pe.text({id:mf(e,r),name:`Line ${r+1}`,parentNodeId:e,rank:s.value,props:{value:o},readonly:!0,isVirtual:!0}));Dt(i)&&n.push(i.value.id)}),Bd.set(e,n)},Ud=({id:e,label:t,text:n,rows:o,selected:r,maxWidth:s})=>{let{selectedIndex:i,contextNode:c}=rt(),u=Od(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=Od(()=>u.join("\0"),[u]);UI(()=>(jI(e,u),()=>{pf(e)}),[e,m]);let p=Ld(u.length),f=uf(s,u.length),I=Od(()=>Td(u).map(S=>{if(S.kind==="code"||S.kind==="caption")return{...S,text:ia(S.text,f)};if(S.kind==="text"||S.kind==="heading"){let A=S.spans.map(w=>w.code?`\`${w.text}\``:w.text).join("");return{...S,spans:es(ia(A,f))}}return S}),[u,f]).map((S,A)=>{let w=c.id===e&&i===A;return Nt.createElement(zo,{key:mf(e,A)},Nt.createElement(zo,{flexShrink:0},Nt.createElement(_d,{color:w?T.primary:T.secondary2,dimColor:!w},`${A+1} `.padStart(p,"\xA0"))),S.kind==="blank"?Nt.createElement(_d,{backgroundColor:w?"gray":void 0},$I):Nt.createElement(zo,null,Nt.createElement(Md,{line:S,width:S.kind==="code"?f:0,wrap:"truncate-end"})))});return Nt.createElement(zo,{flexDirection:"column",paddingTop:1},Nt.createElement(zo,null,Nt.createElement(ot,{isSelected:r}),Nt.createElement(_d,{color:r?T.accent:T.secondary2},t)),Nt.createElement(zo,{flexDirection:"row",borderStyle:"round",borderColor:T.secondary,paddingLeft:1,marginLeft:1,overflowY:"hidden"},Nt.createElement(Pn,{scrollByOne:!0,height:o,selectedIndex:i,itemHeight:1},I)))}});import{Box as lo,Text as $d}from"ink";import Fe,{useMemo as ts}from"react";var HI,WI,qI,GI,gf,hf=h(()=>{"use strict";K();ne();M();Ve();Nd();Lo();Wp();df();Bo();lf();ff();Fd();HI=e=>Le(e,"description"),WI=e=>Le(e,"comments"),qI=e=>Le(e,"history"),GI=e=>Le(e,"attachments"),gf=({ticket:e,height:t})=>{let n=ts(()=>Bp(e),[e]),{selectedIndex:o,contextNode:r}=rt(),s=process.stdout.columns||120,i=ts(()=>HI(e.id),[e.id]),c=ts(()=>WI(e.id),[e.id]),u=ts(()=>qI(e.id),[e.id]),m=ts(()=>GI(e.id),[e.id]),p=E.getAttachmentsByIssue(e.id).length,f=r.id===e.id,y=r.id===c||r.parentNodeId===c,I=r.id===u||r.parentNodeId===u,S=r.id===m||r.parentNodeId===m,A=se(e.id);if(y){let H=t-3;return Fe.createElement(lo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Fe.createElement(af,{ticket:e,width:s,height:H}))}if(S){let H=t-3;return Fe.createElement(lo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Fe.createElement(Hp,{ticket:e,width:s,height:H}))}if(I){let _=E.getNode(u),H=_&&at(_)?_.props.value??"":"",ie=Dd(t);return Fe.createElement(lo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},_?Fe.createElement(Ud,{id:_.id,label:"Event log",text:H,selected:!1,maxWidth:s,rows:ie}):null)}let w=A.reduce((_,H)=>fr(H)||H.id===c||H.id===m||H.id===u?_+1:_,0),k=Dd(t,w),D=(_,H)=>_.id===i?Fe.createElement(Ud,{key:_.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:H,maxWidth:s,rows:k}):fr(_)?Fe.createElement(cf,{key:_.id,parent:_,selected:H,selectedIndex:o}):_.id===c?Fe.createElement(lo,{key:_.id,paddingTop:1},Fe.createElement(ot,{isSelected:H}),Fe.createElement($d,{backgroundColor:T.secondary,color:H?T.accent:T.primary},` Comments (${n}) \u203A\u203A `)):_.id===m?Fe.createElement(lo,{key:_.id,paddingTop:1},Fe.createElement(ot,{isSelected:H}),Fe.createElement($d,{backgroundColor:T.secondary,color:H?T.accent:T.primary},` Attachments (${p}) \u203A\u203A `)):_.id===u?Fe.createElement(lo,{key:_.id,paddingTop:1},Fe.createElement(ot,{isSelected:H}),Fe.createElement($d,{backgroundColor:T.secondary,color:H?T.accent:T.primary}," History \u203A\u203A ")):null;return Fe.createElement(lo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},A.map((_,H)=>D(_,f&&o===H)))}});import{Box as zI}from"ink";import Mi from"react";var VI,vf,yf=h(()=>{"use strict";K();Op();hf();VI=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:o,mode:r,viewMode:s,height:i,width:c})=>{let u=t.context,m=u===V.TICKET||u===V.FIELD_LIST||u===V.FIELD,p=u===V.BOARD||u===V.SWIMLANE,f=u===V.TICKET?t:o.find(w=>w.context===V.TICKET),y=Math.floor(c/3),I=Math.floor(c/Math.max(e.length,1)),S=Math.min(I,y),A=s==="dense";return Mi.createElement(zI,{flexDirection:"row",height:i},p&&e.map((w,k)=>{let D=t.id===w.id,_=D?n:-1,H=t.context===V.BOARD&&n===k;return Mi.createElement(_p,{key:w.id,height:i,width:S,swimlane:w,isSelected:H,isDense:A,isFocused:D,listSelectedIndex:_,mode:r})}),m&&f&&Mi.createElement(gf,{height:i,ticket:f}))},vf=Mi.memo(VI)});import bf from"node:fs";import KI from"node:path";import YI from"react";import{render as XI}from"ink";import{Writable as JI}from"node:stream";var ns,QI,ZI,eE,tE,xf,If=h(()=>{"use strict";yf();K();R();M();ae();We();ns=e=>String(e).padStart(2,"0"),QI=e=>{let t=e.getUTCFullYear(),n=ns(e.getUTCMonth()+1),o=ns(e.getUTCDate()),r=ns(e.getUTCHours()),s=ns(e.getUTCMinutes()),i=ns(e.getUTCSeconds());return`${t}-${n}-${o}_${r}-${s}-${i}`},ZI=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",eE=async(e,{width:t,height:n})=>{let o="",r=new JI({write(i,c,u){let m=tE(i.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(o=m),u()}});r.columns=t,r.rows=n,r.isTTY=!0;let s=XI(e,{stdout:r,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(i=>setTimeout(i,0)),s.unmount(),o},tE=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),xf=async()=>{let{viewMode:e}=Ie(),{contextNode:t,selectedIndex:n,breadCrumb:o,mode:r,renderedChildrenIndex:s}=g(),i=o.find(k=>k.context==="BOARD");if(!i)return a("No board found to export");let c=120,u=40,m=await eE(YI.createElement(vf,{height:u,width:c,swimlanes:(s[i.id]??[]).filter(k=>k!==void 0&&Sn(k)),contextNode:t,selectedIndex:n,breadCrumb:o,viewMode:e??"dense",mode:r}),{width:c,height:u});if(!m)return a("Failed to render board export");let p=Ls(process.cwd());if(d(p))return a("Unable to export, epiq root not found");let f=new Date,y=QI(f),I=`board_${ZI(i.title)}_${y}.md`,S=Ql(p.value);bf.mkdirSync(S,{recursive:!0});let A=KI.join(S,I),w=`# Board - ${i.title}
|
|
62
80
|
Date: ${f.toISOString()}
|
|
63
81
|
|
|
64
82
|
\`\`\`text
|
|
65
83
|
${m}
|
|
66
84
|
\`\`\`
|
|
67
|
-
`;return
|
|
85
|
+
`;return bf.writeFileSync(A,w,"utf8"),l("Exported board layout",A)}});import{useSyncExternalStore as jD}from"react";var jd,nE,oE,Vo,rE,Fn,Pi=h(()=>{"use strict";R();nE=new Set,oE=()=>{for(let e of nE)e()},Vo=()=>{if(!jd)throw new Error("Ui state not initialized. Call initUiState() first.");return jd},rE=e=>{let t=Vo();return jd=e(t),oE(),l("UX state updated",null)},Fn=e=>rE(t=>({...t,...e}))});import{spawn as zD,spawnSync as sE}from"node:child_process";import iE from"node:os";import Ef from"node:path";import{ulid as aE}from"ulid";function Sf(e){let t=[],n="",o=!1,r=null;for(let s of e.trim()){if(r){s===r?r=null:n+=s;continue}if(s==='"'||s==="'"){r=s,o=!0;continue}if(/\s/.test(s)){o&&t.push(n),n="",o=!1;continue}n+=s,o=!0}return o&&t.push(n),t}function dE(e){let t=e.trim();return t==="$EDITOR"?process.env.EDITOR:t==="$VISUAL"?process.env.VISUAL:t}function Rf(){let{preferredEditor:e}=Ie(),t=[e?dE(e):void 0,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function Nf(e){let[t=""]=Sf(e);return/(^|\/)code(-insiders)?$/.test(t)}function cE(e,t){let[n="",...o]=Sf(e);return{command:n,args:[...o,...t]}}function lE(e,t){return cE(e,Nf(e)?["--wait",t]:[t])}function Cf(e){let t=Ef.join(iE.tmpdir(),"epiq");Ze.mkDir(t);let n=Ef.join(t,aE());Ze.writeToFile(n,e??"");let o=Rf();for(let r of o){let{command:s,args:i}=lE(r,n);if(!s)continue;let c=sE(s,i,{stdio:"inherit"});if(!c.error&&c.status===0){let u=Ze.readFile(n);if(u==null)return a("Unable to read edited file");let m=u.replace(/\r?\n$/,"");return l("Successfully edited",m)}}return a("Unable to open editor")}var Hd=h(()=>{"use strict";R();We();gi()});import{ulid as Wd}from"ulid";var Af,uE,mE,wf=h(()=>{"use strict";Hd();Se();Ce();Ft();K();R();Io();ne();M();ae();pn();Af=async e=>{let{contextNode:t,selectedIndex:n}=g(),o=se(t.id)[n];if(e.modifier===mt.DESCRIPTION)return mE();if(o&&hr(o))return uE(e);if(e.modifier===mt.TITLE){let r=oe();if(d(r))return a("Unable to resolve user ID");let s=o;if(!s)return a("Missing node");if(s.readonly)return a("Cannot rename readonly node");let i=e.inputString.trim();if(!i)return a("Provide a title");let c=await $t();return d(c)?c:L([{id:Wd(),action:"edit.title",payload:{id:s.id,name:i},...r.value}],c.value)}return a("Unknown edit command")},uE=async e=>{let t=oe();if(d(t))return a("Unable to resolve user ID");let{contextNode:n,selectedIndex:o}=g(),r=se(n.id)[o];if(!r||!hr(r))return a("Select a comment first");if(r.readonly)return a("Cannot edit readonly comment");let s=n.parentNodeId;if(!s)return a("Unable to resolve comment issue");let i=g().nodes[s];if(!i||!P(i))return a("Unable to resolve comment issue");if(i.readonly)return a("Cannot edit readonly issue");let c=r.id.split(":").at(0)??"",u=E.getComment(c);if(!u||u.deleted)return a("Unable to resolve comment");if(u.issue!==i.id)return a("Comment does not belong to selected issue");if(u.authorId!==t.value.userId)return a("You can only edit your own comments"+u.authorId+"<->"+t.value.userId);let m=e.inputString.trim();if(!m)return a("Provide a comment");let p=await $t();if(d(p))return p;let f=p.value;return L([{id:Wd(),action:"edit.issue.comment",payload:{id:u.id,issue:i.id,md:m},...t.value}],f)},mE=async()=>{let e=oe();if(d(e))return a("Unable to resolve user ID");let t=await $t();if(d(t))return t;let n=t.value,{breadCrumb:o,selectedNode:r}=g(),s=it([...o,r],"TICKET");if(d(s))return a("Edit target must be an issue");let i=s.value;if(!P(i))return a("Edit target must be an issue");if(i.readonly)return a("Cannot edit readonly issue");let c=se(i.id).find(f=>f.title===ue.DESCRIPTION);if(!c)return a("No target found");if(c.readonly)return a("Cannot edit readonly field");let u=i.props.description??"";if(typeof u!="string")return a("Selected field is not editable text");let m=Cf(u);if(d(m))return a("Failed to edit field");let p=m.value;return p===u?l("No changes made",null):L([{id:Wd(),action:"edit.description",payload:{id:i.id,md:p},...e.value}],n)}});import qd from"node:fs";import pE from"node:path";var Tf,kf=h(()=>{"use strict";R();xt();Tf=async e=>{let t=pE.join(e,".gitignore"),n=qd.existsSync(t)?qd.readFileSync(t,"utf8"):"",o=[".epiq/events/",".epiq/log/"],r=n.split(`
|
|
68
86
|
`).map(u=>u.trim()),s=o.filter(u=>!r.some(m=>m===u||m===u.replace(/\/$/,"")||m==="/"+u||m==="/"+u.replace(/\/$/,"")));if(s.length===0)return l("Local epiq paths already ignored",!1);let c=["# [epiq]: local hydrated state is never committed",...s].join(`
|
|
69
87
|
`);return n=n.trimEnd()+`
|
|
70
88
|
|
|
71
89
|
${c}
|
|
72
|
-
`,
|
|
73
|
-
`).filter(n=>n.trim().length>0).map(n=>n.slice(3)))},
|
|
74
|
-
`));let u=$e();if(a(u))return Ur(16,u.message);let{rootNodeId:m,nodes:p}=u.value,f=p[m];return f?(U.navigate({contextNode:f,selectedIndex:0}),E({hasProjectDefinition:!0,mode:y.DEFAULT}),l(s,null)):Ur(16,"Unable to resolve initialized root node")}});import{ulid as TI}from"ulid";function fd(e){let t=kp();if(a(t))return t;let{contextNode:n,nodes:o}=g();if(!n.parentNodeId)return i("Missing parent node id");let r=o[n.parentNodeId];if(!r)return i("Missing parent node");let s=ge(r.id),d=s.findIndex(({id:m})=>m===n.id);if(d<0)return i("Current node not found among siblings");let c=s[d+e];if(!c)return i("Missing sibling node");let u=Pp({id:t.value.id,parentId:c.id,position:{at:"end"}});return a(u)?u:Lp(u.value)}function hd(e){let t=kp();if(a(t))return t;let{contextNode:n,selectedIndex:o}=g(),s=ge(n.id)[o+e];if(!s)return i("Missing sibling node");let d=Pp({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return a(d)?d:Lp(d.value)}var Mp,Cn,$r,kp,gd,Pp,Lp,vd=h(()=>{"use strict";Zt();Se();R();pt();M();Mp=null,Cn=()=>structuredClone(Mp),$r=e=>{Mp=e},kp=()=>{let{contextNode:e,selectedIndex:t}=g(),o=ge(e.id)[t];return o?l("Resolved selected child",o):i("Target node not found")},gd=({id:e,parentId:t,position:n={at:"end"}})=>{let o=ge(t).filter(r=>r.id!==e);return Rs(o,n)},Pp=({id:e,parentId:t,position:n={at:"end"}})=>{let o=ne();if(a(o))return i("Unable to resolve user ID");let r=gd({parentId:t,id:e,position:n});return a(r)?r:l("Created pending move state",{id:TI(),...o.value,action:"move.node",payload:{id:e,parent:t,rank:r.value.rank}})},Lp=e=>{$r(e);let t=hn(e,!0);return a(t)?t:l("Node moved successfully",t.value)}});import{ulid as MI}from"ulid";var Dp,ui,Fp,_p=h(()=>{"use strict";it();vd();xe();Se();me();R();pt();de();M();ae();Dp=()=>{let e=Cn();if(!e)return i("No pending move state");let t=e.payload.id,n=e.payload.parent,o=g().nodes[n];if(!o)return i("Move parent not found");let r=ge(n).findIndex(s=>s.id===t);return r===-1?i("Moved node not found among rendered children"):(U.navigate({contextNode:o,selectedIndex:r}),l("Synchronized navigation to moved node",null))},ui=(e,t="Moved preview")=>{if(a(e))return e;let n=Dp();return a(n)?n:(E({mode:y.MOVE}),l(t,null))},Fp=async()=>{let e=ne();if(a(e))return i("Unable to resolve user ID");let{modifier:t}=ie().commandMeta,{contextNode:n,selectedIndex:o}=g(),r=ge(n.id)[o];if(!r)return E({mode:y.DEFAULT}),i("No move target");if(t==="start"){if(r.readonly)return i("Target node is read-only");if(o===-1)return i("No item selected");if(!r.parentNodeId)return i("Target has no parent");let s=ge(r.parentNodeId),d=s.findIndex(({id:f})=>f===r.id);if(d===-1)return i("Target not found among siblings");let c=s[d-1],u=s[d+1],m=u!=null?{at:"before",sibling:u.id}:c!=null?{at:"after",sibling:c.id}:{at:"start"},p=gd({parentId:r.parentNodeId,id:r.id,position:m});return a(p)?p:($r({id:MI(),action:"move.node",payload:{id:r.id,parent:r.parentNodeId,rank:p.value.rank},...e.value}),E({mode:y.MOVE}),l("Move initialized",null))}if(t==="next")return ui(hd(1));if(t==="previous")return ui(hd(-1));if(t==="to-next")return ui(fd(1));if(t==="to-previous")return ui(fd(-1));if(t==="confirm"){let s=Cn();if(!s)return i("No pending move to confirm");let d=await Lt();if(a(d))return d;let c=L([s],d.value);if(a(c))return c;let u=Dp();return a(u)?u:($r(null),E({mode:y.DEFAULT}),l("Moved item",null))}return t==="cancel"?($r(null),E({mode:y.DEFAULT}),l("Cancelling move",null)):i("Invalid move modifier")}});import{monotonicFactory as kI,ulid as PI}from"ulid";var LI,mi,yd=h(()=>{"use strict";R();LI=kI(),mi=({name:e,parent:t,rank:n,user:{userId:o,userName:r}})=>{let s=LI();return l("Created issue events",[{id:PI(),userId:o,userName:r,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])}});import{ulid as pi}from"ulid";var Bp,Op=h(()=>{"use strict";it();yd();xe();Se();Tt();R();te();pt();M();ae();Bp=async(e,t)=>{let n=ne();if(a(n))return i("Unable to resolve user ID");let o=await Lt();if(a(o))return o;let r=o.value;if(!t.inputString)return i(`provide a name for your ${t.modifier}`);let{breadCrumb:s,contextNode:d,selectedIndex:c}=g(),u=m=>{let p=L([m],r);if(a(p))return p;let f=I.getNode(p.value[0].result.id);if(!f)return i("Created node not found");if(!f.parentNodeId)return p;let x=I.getNode(f.parentNodeId);return x?(U.navigate({contextNode:x,selectedIndex:I.getSiblings(f.parentNodeId).findIndex(({id:S})=>S===f.id)}),p):i("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=g(),p=I.getNode(m);if(!p)return i("Workspace not found");let f=bn(p.id,n.value,r);return a(f)?f:u({id:pi(),action:"add.board",payload:{id:pi(),name:t.inputString,parent:p.id,rank:f.value},...n.value})}if(t.modifier==="swimlane"){let m=tt(s,"BOARD");if(a(m))return i("Unable to add swimlane in this context");let p=bn(m.value.id,n.value,r);return a(p)?p:u({id:pi(),action:"add.swimlane",payload:{id:pi(),name:t.inputString,parent:m.value.id,rank:p.value},...n.value})}if(t.modifier==="issue"){let m=oe(d.id)[c],p=d.context==="SWIMLANE"?d:d.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let _=tt(s,"SWIMLANE");return a(_)?null:_.value})();if(!p)return i("Unable to add issue in this context");let f=bn(p.id,n.value,r);if(a(f))return f;let x=mi({name:t.inputString,parent:p.id,rank:f.value,user:n.value});if(a(x))return x;let S=x.value,A=L([...S],r);if(a(A))return A;if(!A.value[0])return i("Issue creation failed");let w=S.find(_=>_.action==="add.issue")?.payload.id;return w?(U.navigate({contextNode:p,selectedIndex:I.getSiblings(p.id).findIndex(({id:_})=>_===w)}),l("Issue created",null)):i("Unable to determine ticket id")}return l("Success",null)}});var DI,Up,FI,$p,_I,jp,Hp=h(()=>{"use strict";co();We();Nt();br();Ds();ha();Ps();vo();zn();bt();R();Yt();M();fr();ae();Cs();DI=e=>e.some(t=>t.action==="init.workspace"),Up=async(e,t)=>{let n=kt(e);return a(n)?i(n.message):rr({cwd:t,branch:n.value})},FI=e=>{let t=Ue(process.cwd());if(a(t))return!1;let n=ve({repoRoot:t.value});return!a(n)&&n.value===e},$p=async e=>{let t=ve({repoRoot:e});if(a(t))return po(3,t.message);let n=t.value,o=await Kn({repoRoot:e,stateBranchRoot:n,stateBranchName:rs().stateBranch});if(a(o))return po(3,o.message);let r=yt(n);if(a(r))return po(3,r.message);if(!DI(r.value.events)){let m=await Up(e,n);if(a(m)&&logger.info(3,m.message),r=yt(n),a(r))return po(3,r.message)}let{events:s,unreadable:d}=r.value,c=_t(s,d);if(a(c))return po(4,c.message);E({hasProjectDefinition:!0,hasInitializingEvents:!!s.length});let u=Rr({root:e});return a(u)&&logger.info(u.message),l("Loaded project",void 0)},_I=async e=>{let t=ve({repoRoot:e});if(a(t))return i(t.message);let n=t.value,o=await _n({repoRoot:n});if(a(o))return i(o.message);if(!o.value)return l("No remote to pull",void 0);let r=await Ms({worktreeRoot:n,operation:"boot pull",fn:()=>ya(n,()=>(mo("Pulling"),Up(e,n)))});if(a(r))return Ee(r.message);if(r.value===null)return l("Another process holds the state worktree",void 0);let s=r.value;if(a(s))return or(s.message)?(As("Offline"),l("Offline",void 0)):Ee(s.message);if(!s.value)return Vn("Already synced"),l("Already synced",void 0);if(!FI(n))return l("Project changed during the pull",void 0);let d=ba(n);return a(d)?d:(Vn("Pulled"),l("Pulled and reloaded",void 0))},jp=e=>{_I(e).then(t=>{a(t)&&logger.info(3,t.message)}).catch(t=>{logger.error(`[boot] pull failed: ${Jl(t)}`)})}});import BI from"node:os";import Wp from"node:path";var OI,UI,qp,Gp=h(()=>{"use strict";Hp();vo();R();de();M();ae();OI=e=>e==="~"||e.startsWith("~/")?Wp.join(BI.homedir(),e.slice(1)):e,UI=(e,t)=>{let n=e.trim();if(!n)return i("Provide a number from the list or a path to a project");if(/^\d+$/.test(n)){let r=t[Number(n)-1];return r?l("Resolved recent project",r.root):i(`No recent project #${n}`)}let o=Ue(Wp.resolve(OI(n)));return a(o)?i(`No epiq project at ${n}`):l("Resolved project path",o.value)},qp=async()=>{let e=Zs();if(ee(""),g().hasProjectDefinition)return i("Already in a project; run epiq from another directory");let t=Bs({exclude:process.cwd()}),n=a(t)?[]:t.value,o=UI(e,n);if(a(o))return i(o.message);let r=o.value,s=process.cwd();try{process.chdir(r)}catch(c){return i(`Unable to enter ${r}: ${c instanceof Error?c.message:String(c)}`)}let d=await $p(r);return a(d)?(process.chdir(s),i(d.message)):(jp(r),l(`Opened ${Iu(r)}`,null))}});var gi,bd=h(()=>{"use strict";it();bt();Zt();R();M();gi=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:o})=>{let r=g(),s=sa(n,t);if(a(s))return i(s.message);let{appliedEvents:d,unappliedEvents:c}=s.value,u=cn();if(a(u))return u;let m=Qt(d),{fatal:p,skipped:f}=Un(m);if(p.length>0)return cn(),E(r),i(p.map(S=>S.message).join(", "));$n(f);let x=g().nodes[e];return x?(U.navigate({contextNode:x,selectedIndex:o}),l("",{unappliedEvents:c})):(cn(),E(r),i("Board did not exist at that date"))}});var zp,Vp=h(()=>{"use strict";zp=e=>{let t=[],n=0;for(let r=0;r<e.length;r++){let s=r===0?0:Math.max(0,e[r]-e[r-1]);n+=Math.sqrt(s),t[r]=n}let o=n;return t.map((r,s)=>o>0?r/o:(s+1)/e.length)}});var $I,jI,HI,fi,hi,to,Kp,Yp,Id=h(()=>{"use strict";et();jr();Zt();me();R();Vp();M();$I=20,jI=16,HI=150,fi=null,hi=null,to=()=>{fi!==null&&(clearInterval(fi),fi=null),hi!==null&&(clearTimeout(hi),hi=null)},Kp=()=>{to(),E({mode:y.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},Yp=({events:e,startTime:t,durationMs:n})=>{to();let o=e.length,r=Ko(e.map(f=>Yo(f))).map(f=>f??t),s=r[o-1]??Date.now(),d=zp(r),c=Math.max(1,Math.round(n*$I/1e3)),u=Math.max(Math.round(n/c),jI),m=0,p=0;E({mode:y.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:o,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),fi=setInterval(()=>{m++;let f=m/c,x=[],S,A;for(;p<o&&d[p]<=f;){let T=e[p],w=hn(T);if(a(w)){if(lr(w)){p++;continue}Kp();return}x.push(...Yi(T)),S=T,A=r[p],p++}if(p>=o||m>=c){for(;p<o;p++){let w=hn(e[p]);if(a(w)&&!lr(w))break}let T=g().replay;E({unappliedEvents:[],replay:T&&{...T,progress:1,appliedCount:o}}),to(),hi=setTimeout(Kp,HI);return}let P=g().replay;E({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,f),appliedCount:p,totalCount:o,startTime:t,endTime:s,currentTime:S?A??P?.currentTime??t:P?.currentTime??t,currentLabel:S?xd(S):P?.currentLabel??"",flashNodeIds:S?[...new Set(x)]:P?.flashNodeIds??[]}})},u)}});var Xp,Jp=h(()=>{"use strict";We();et();bt();Zt();me();Tt();R();de();M();Ar();bd();Id();Xp=async()=>{let e=tt(g().breadCrumb,"BOARD");if(a(e))return e;let t=await rt(process.cwd());if(a(t))return i("Unable to locate repo root");let n=ve({repoRoot:t.value});if(a(n))return n;let{modifier:o,inputString:r}=ie().commandMeta;if(to(),o==="now"){let c=Hn(n.value);if(a(c))return i(c.message);let u=cn();if(a(u))return u;let m=Qt(c.value),{fatal:p,skipped:f}=Un(m);return p.length>0?i(p.map(x=>x.message).join(", ")):($n(f),E({mode:y.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null}),l("Peeking now",!0))}let s;if(o==="prev"||o==="next"){let c=ia(n.value);if(a(c))return c;let u=o==="prev"?g().eventLog.at(-1):g().unappliedEvents.at(0),m=u===void 0?null:Yo(u),p=(u===void 0?null:c.value.get(u.id)??null)??(m===null?null:Mi(m));if(p===null)return i(o==="prev"?"No previous event to peek":"No next event to peek");s=o==="prev"?p:p+1}else{let c=Xn(o||r.trim());if(!c)return i("Invalid peek date");s=c.getTime()}let d=gi({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return a(d)?d:(E({mode:y.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:d.value.unappliedEvents,replay:null}),l("Peeking",!0))}});var Qp,Zp=h(()=>{"use strict";We();Tt();R();de();M();Ar();bd();Id();Qp=async()=>{let e=tt(g().breadCrumb,"BOARD");if(a(e))return e;let t=await rt(process.cwd());if(a(t))return i("Unable to locate repo root");let n=ve({repoRoot:t.value});if(a(n))return n;let{modifier:o,inputString:r}=ie().commandMeta,{dateInput:s,durationInput:d}=Ws(o,r);if(to(),g().syncStatus.status==="syncing")return i("Cannot replay while syncing, try again in a moment");let c=Xn(s);if(!c)return i("Invalid replay date");let u=d?Hs(d):15e3;if(u===null)return i("Invalid replay duration (try e.g. 30s or 2m)");let m=c.getTime(),p=g(),f=gi({boardId:e.value.id,targetTime:m,stateBranchRoot:n.value,selectedIndex:-1});if(a(f))return f;let{unappliedEvents:x}=f.value;return x.length===0?(cn(),E(p),l("Nothing to replay from that point",!0)):(Yp({events:x,startTime:m,durationMs:u}),l("Replaying board history",!0))}});import{spawn as qI}from"node:child_process";var GI,eg,tg=h(()=>{"use strict";R();GI=()=>{switch(process.platform){case"darwin":return{command:"pbcopy",args:[]};case"win32":return{command:"clip",args:[]};default:return process.env.WAYLAND_DISPLAY?{command:"wl-copy",args:[]}:{command:"xclip",args:["-selection","clipboard"]}}},eg=async e=>new Promise(t=>{let{command:n,args:o}=GI();try{let r=qI(n,o,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>t(i(`Clipboard tool not available (${n})`))),r.on("close",s=>t(s===0?l("Copied to clipboard",null):i(`Clipboard tool failed (${n})`))),r.stdin.on("error",()=>{}),r.stdin.write(e),r.stdin.end()}catch{t(i(`Clipboard tool not available (${n})`))}})});var Hr,ng,og=h(()=>{"use strict";R();M();tg();st();Nr();nn();Hr=async(e,t)=>{if(!e.trim())return i(`Nothing to copy: ${t} is empty`);let n=await eg(e);return a(n)?n:l(`Copied ${t} to clipboard`,null)},ng=async e=>{let{breadCrumb:t,selectedNode:n}=g(),o=Cr({breadCrumb:t,selectedNode:n}),r=o??n;if(!r)return i("Nothing selected to copy from");switch(e.modifier){case Ne.REF:return Hr(j(r.id),"ref");case Ne.TITLE:return Hr(r.title,"title");case Ne.DESCRIPTION:return o?Hr(o.props?.description??"","description"):i("No issue in scope");case Ne.TAGS:{if(!o)return i("No issue in scope");let s=In(o).map(({name:d})=>d);return Hr(s.join(", "),"tags")}case Ne.ASSIGNEES:{if(!o)return i("No issue in scope");let s=xn(o).map(({name:d})=>d);return Hr(s.join(", "),"assignees")}default:return i("Yank one of: ref, title, description, tags, assignees")}}});var rg,sg=h(()=>{"use strict";Ds();me();R();de();M();rg=async()=>{ee(""),E({mode:y.DEFAULT});let e=$e();if(a(e))return i(e.message);if(e.value.syncStatus.status==="syncing")return i("Sync already in progress");E({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await Ls();return a(t)?(E({syncStatus:{msg:t.message,status:"failed"}}),t):(E({mode:y.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)}});var Le,Ht=h(()=>{"use strict";R();ae();Le=async()=>{let e=await Lt();return a(e)?e:l("Resolved persist root",e.value)}});import{ulid as ig}from"ulid";var zI,ag,dg=h(()=>{"use strict";xe();Se();V();R();M();Ht();zI=e=>e.action==="add.issue.comment",ag=async()=>{let e=ne();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),o=oe(t.id)[n];if(!o)return i("Unable to resolve child to delete");let r=await Le();if(a(r))return r;if(o.context==="COMMENT"){let s=o.id,d=k(t)?t.id:t.parentNodeId;if(!d)return i("Unable to resolve comment issue");let c=g().nodes[d];if(!c||!k(c))return i("Unable to resolve comment issue");let u=c.log?.filter(zI).find(m=>m.payload.id===s);return u?u.payload.author!==e.value.userId?i("You can only delete your own comments"):L([{id:ig(),action:"delete.issue.comment",payload:{id:s,issue:d},...e.value}],r.value):i("Unable to resolve comment")}return L([{id:ig(),action:"delete.node",payload:{id:o.id},...e.value}],r.value)}});import{ulid as VI}from"ulid";var cg,lg=h(()=>{"use strict";xe();Se();Jt();V();R();pt();M();Ht();cg=async()=>{let e=ne();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),o=oe(t.id)[n];if(!o)return i("Unable to close issue, no target found");if(!k(o))return i("Cannot close in this context");let r=g().nodes[fe];if(!r)return i("Unable to locate closed swimlane");if(o.parentNodeId===r.id)return i("Issue is already closed");let s=await Le();if(a(s))return s;let d=s.value,c=Dt(r.id,o.id,{at:"end"},e.value,d);if(a(c))return c;let u=L([{id:VI(),action:"close.issue",payload:{id:o.id,parent:r.id,rank:c.value},...e.value}],d);return a(u)?u:l("Issue closed",null)}});var vi,Ed=h(()=>{"use strict";vi=e=>{let t=e.log??[];for(let n=t.length-1;n>=0;n--){let o=t[n];if(o&&o.action==="close.issue"&&o.payload.id===e.id){for(let r=n-1;r>=0;r--){let s=t[r];if(s&&"id"in s.payload&&s.payload.id===e.id&&"parent"in s.payload&&s.payload.parent)return s.payload.parent}return null}}return null}});import{ulid as KI}from"ulid";var ug,mg=h(()=>{"use strict";xe();Se();Ed();Jt();V();R();te();pt();M();Ht();ug=async()=>{let e=ne();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),o=oe(t.id)[n];if(!o)return i("Unable to reopen issue, no target found");let r=o.context==="TICKET"?l("Resolved ticket",o):Et(o.id,"TICKET");if(a(r))return i("Cannot reopen in this context");let s=r.value,d=g().nodes[fe];if(!d)return i("Unable to locate closed swimlane");if(s.parentNodeId!==d.id)return i("Issue is not closed");if(!k(s))return i("Target node is not issue");let c=vi(s);if(!c)return i("Unable to resolve previous parent from issue history");if(c===d.id)return i("Previous parent resolves to closed swimlane");let u=g().nodes[c];if(!u)return i("Previous parent no longer exists");let m=await Le();if(a(m))return m;let p=m.value,f=Dt(u.id,s.id,{at:"end"},e.value,p);if(a(f))return f;let x=L([{id:KI(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:f.value},...e.value}],p);return a(x)?x:l("Issue reopened",null)}});import{ulid as YI}from"ulid";var pg,gg=h(()=>{"use strict";xe();Se();R();de();M();Ht();pg=async()=>{let e=ne();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),o=oe(t.id)[n];if(!o)return i("Missing node");if(o.readonly)return i("Cannot rename readonly node");let r=Zs();if(!r)return i("Provide a title");let s=await Le();return a(s)?s:L([{id:YI(),action:"edit.title",payload:{id:o.id,name:r},...e.value}],s.value)}});import{ulid as XI}from"ulid";var fg,hg=h(()=>{"use strict";te();xe();Se();V();R();de();M();Ht();fg=async()=>{let e=ne();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=ie().commandMeta,o=(t||n).trim();if(!o)return i("Provide a tag");let r=I.findTagByName(o);if(!r)return i(`Tag "${o}" does not exist`);let{selectedNode:s}=g();if(!s)return i("Invalid untag target");let d=Et(s.id,"TICKET");if(a(d))return i("Unable to untag issue in this context");let c=d.value;if(!k(c))return i("Target node is not issue");if(!(c.props.tags??[]).includes(r.id))return i("Issue is not tagged with that tag");let m=await Le();return a(m)?m:L([{id:XI(),action:"remove.issue.tag",payload:{id:c.id,tag:r.id},...e.value}],m.value)}});import{ulid as Rd}from"ulid";var vg,yg=h(()=>{"use strict";te();xe();Se();V();R();de();M();Ht();vg=async()=>{let e=ne();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=ie().commandMeta,o=(t||n).trim();if(!o)return i("Provide a tag");let{selectedNode:r}=g();if(!r)return i("Invalid tag target");let s=Et(r.id,"TICKET");if(a(s))return i("Unable to tag issue in this context");let d=s.value;if(!k(d))return i("Target node is not issue");let c=await Le();if(a(c))return c;let u=I.findTagByName(o),m=u?.id??Rd();return(d.props.tags??[]).includes(m)?i("Already tagged with that tag"):L([...u?[]:[{id:Rd(),action:"create.tag",payload:{id:m,name:o},...e.value}],{id:Rd(),action:"add.issue.tag",payload:{id:d.id,tag:m},...e.value}],c.value)}});var yi,Sd=h(()=>{"use strict";M();yi=()=>{let{eventLog:e=[],contributors:t}=g(),n=new Map,o=new Set;for(let r of e)r.userId&&(n.set(r.userId,r.userName??""),o.add(r.userId));for(let r of Object.values(t))n.set(r.id,r.name);return[...n.entries()].map(([r,s])=>({id:r,name:s,isExternal:!o.has(r)}))}});import{ulid as Nd}from"ulid";var bg,Ig=h(()=>{"use strict";xe();Se();V();R();te();de();M();Sd();Ht();bg=async()=>{let e=ne();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=ie().commandMeta,o=(t||n).trim();if(!o)return i("Provide an assignee");let r=o.startsWith("!"),s=(r?o.slice(1):o).trim();if(!s)return i("Provide an assignee");let{selectedIndex:d,contextNode:c}=g(),u=oe(c.id)[d];if(!u)return i("Invalid assign target");let m=Et(u.id,"TICKET");if(a(m))return i("Unable to assign issue in this context");let p=m.value;if(!k(p))return i("Target node is not issue");let f=await Le();if(a(f))return f;let x=yi(),S=!r&&s.toLowerCase()==="me",A,P;if(S)A=e.value.userId,P=x.find(_=>_.id===A)?.name??e.value.userName;else{let _=x.filter($=>$.name===s);if(_.length>1)return i(`"${s}" matches ${_.length} contributors (${_.map($=>$.id).join(", ")}). Assign from the GUI to choose by id.`);let B=_[0];if(!B&&!r)return i(`No contributor named "${s}". Use "!${s}" to add them as an external assignee.`);A=B?.id??Nd(),P=B?.name??s}if((p.props.assignees??[]).includes(A))return i("Assignee already assigned");let w=!!g().contributors[A];return L([...w?[]:[{id:Nd(),action:"create.contributor",payload:{id:A,name:P},...e.value}],{id:Nd(),action:"add.issue.assignee",payload:{id:p.id,assignee:A},...e.value}],f.value)}});import{ulid as JI}from"ulid";var xg,Eg=h(()=>{"use strict";xe();Se();V();R();te();de();M();Sd();Ht();xg=async()=>{let e=ne();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=ie().commandMeta,o=(t||n).trim();if(!o)return i("Provide an assignee to remove");let{selectedNode:r}=g();if(!r)return i("Invalid unassign target");let s=Et(r.id,"TICKET");if(a(s))return i("Unable to unassign in this context");let d=s.value;if(!k(d))return i("Target node is not issue");let c=d.props.assignees??[],u=o.toLowerCase()==="me",m=u?c.filter(x=>x===e.value.userId):yi().filter(x=>x.name===o&&c.includes(x.id)).map(x=>x.id);if(m.length>1)return i(`"${o}" matches ${m.length} assignees (${m.join(", ")}). Unassign from the GUI to choose by id.`);let p=m[0];if(!p)return i(u?"Issue is not assigned to you":`Issue is not assigned to "${o}"`);let f=await Le();return a(f)?f:L([{id:JI(),action:"remove.issue.assignee",payload:{id:d.id,assignee:p},...e.value}],f.value)}});import{ulid as Rg}from"ulid";var Sg,Ng=h(()=>{"use strict";xe();Se();Tt();V();R();te();M();sn();Ht();Sg=async e=>{let t=e.inputString.trim();if(!t)return i("Provide a comment");if(t.length>4e3)return i(`Cannot exceed ${4e3} characters`);let n=ne();if(a(n))return i("Unable to resolve user ID");let{breadCrumb:o,selectedNode:r}=g(),s=tt([...o,r],"TICKET");if(a(s))return i("Edit target must be an issue");let d=s.value;if(!d)return i("Invalid comment target");let c=d.context==="TICKET"?l("Resolved ticket",d):Et(d.id,"TICKET");if(a(c))return i("Unable to comment on issue in this context");let u=c.value;if(!k(u))return i("Target node is not issue");let m=await Le();return a(m)?m:L([{id:Rg(),action:"add.issue.comment",payload:{id:Rg(),issue:u.id,author:n.value.userId,md:t},...n.value}],m.value)}});import QI from"zod";var Ag,Cg=h(()=>{"use strict";Ut();me();R();de();Be();M();Ag=()=>{let e=ie().commandMeta.inputString,t=QI.coerce.number().int().min(3e3).safeParse(e);if(!t.success)return i("Auto sync duration must be a number of at least 3000 ms");let n=Ve({autoSyncDebounceMs:t.data});return a(n)?n:(ut({autoSyncIntervalMs:t.data}),E({mode:y.DEFAULT}),l(`Auto sync interval set to ${t.data}ms`,null))}});var wg,Tg=h(()=>{"use strict";Sr();Ut();me();R();de();Be();M();wg=()=>{let e=ie().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return i("Invalid response");let t=Au(e),n=Ve({autoSync:t});return a(n)?n:(ut({autoSync:t}),E({mode:y.DEFAULT}),l(`Auto sync set to "${e}"`,null))}});var Mg,kg=h(()=>{"use strict";Ut();me();R();de();Be();M();Mg=()=>{let e=ie().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return i("Invalid response");let n=Ve({logLevel:e});return a(n)?n:(ut({logLevel:e}),E({mode:y.DEFAULT}),l(`Auto sync set to "${e}"`,null))}});import{ulid as ZI}from"ulid";var Pg,Lg=h(()=>{"use strict";Mn();Ut();me();R();Be();M();nn();Cg();La();Tg();kg();Pg=e=>{let t=e.inputString.trim();switch(e.modifier){case he.USERNAME:{if(process.env[lt])return i(`Cannot change the configured user while ${lt} names this process`);let n=Io();if(a(n))return n;let{userId:o,preferredEditor:r,userName:s}=n.value,d=t||s,c=o||ZI();if(!d||!c)return i("Unable to resolve user name or id");let u=Ve({userName:d,userId:c,preferredEditor:r??""});return a(u)?u:(ut({userName:d,userId:c}),E({mode:y.DEFAULT}),l(`Username set to "${d}"`,null))}case he.EDITOR:{if(!t)return i("No editor provided");let n=Ve({preferredEditor:t});return a(n)?n:(ut({preferredEditor:t}),E({mode:y.DEFAULT}),l(`Editor configuration set to "${t}"`,null))}case he.VIEW:{if(t!=="wide"&&t!=="dense")return i("Invalid view mode");let n=Ve({viewMode:t});return a(n)?n:(ut({viewMode:t}),E({mode:y.DEFAULT}),l(`View set to "${t}"`,null))}case he.AUTOSYNC:return wg();case he.LOG_LEVEL:return Mg();case he.SYNC_DEBOUNCE_MS:return Ag();case he.ATTACHMENT_MAX_KB:return qu();default:return i("Unknown config command")}}});var Dg,Fg=h(()=>{"use strict";vp();it();me();R();de();M();ci();Yn();ja();nn();Sp();Tp();_p();Op();Gp();Jp();Zp();og();sg();dg();lg();mg();gg();hg();yg();Ig();Eg();Ng();Lg();Dg=[{systemOnly:!0,intent:O.Move,description:"Internal move-state command",mode:y.COMMAND_LINE,action:Fp},{intent:O.Delete,description:"Delete the currently selected node",mode:y.COMMAND_LINE,action:ag,onSuccess:()=>E({mode:y.DEFAULT})},{intent:O.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:y.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=ie().commandMeta,n=/(!=|=)/,[o]=e.split(n);if(!o||!(d=>Ae(b.FILTER).map(c=>c.split(n)[0]).includes(d))(o))return i("Invalid filter modifier");let s={target:o,operator:"=",value:t.trim()};return Re(d=>({...d,filters:e==="clear"?[]:[...d.filters,s],mode:y.DEFAULT})),l("Filter updated",null)}},{intent:O.ViewHelp,description:"Open the help screen",mode:y.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:o}=g();return An({pendingNavTarget:{contextNode:e,breadCrumb:o,selectedIndex:t,selectedNode:n}}),E({mode:y.HELP}),l("Viewing help",null)}},{intent:O.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:y.COMMAND_LINE,action:cg,onSuccess:()=>E({mode:y.DEFAULT})},{intent:O.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:y.COMMAND_LINE,action:ug,onSuccess:()=>E({mode:y.DEFAULT})},{intent:O.Init,description:"Initialize Epiq in the current git repository",mode:y.COMMAND_LINE,action:wp},{intent:O.OpenProject,description:"Open a recently used epiq project, by number or path",mode:y.COMMAND_LINE,action:qp,onSuccess:()=>E({mode:y.DEFAULT})},{intent:O.NewItem,description:"Create a new board, swimlane, or issue",mode:y.COMMAND_LINE,action:Bp,onSuccess:()=>E({mode:y.DEFAULT})},{intent:O.Rename,description:"Rename the currently selected node",mode:y.COMMAND_LINE,action:pg,onSuccess:()=>E({mode:y.DEFAULT})},{intent:O.UntagTicket,description:"Remove a tag from the selected issue",mode:y.COMMAND_LINE,action:fg,onSuccess:()=>E({mode:y.DEFAULT})},{intent:O.TagTicket,description:"Add or create a tag on the selected issue",mode:y.COMMAND_LINE,action:vg,onSuccess:()=>E({mode:y.DEFAULT})},{intent:O.AssignUserToTicket,description:"Assign a user to the selected issue",mode:y.COMMAND_LINE,action:bg,onSuccess:()=>E({mode:y.DEFAULT})},{intent:O.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:y.COMMAND_LINE,action:xg,onSuccess:()=>E({mode:y.DEFAULT})},{intent:O.Comment,description:"Add a comment to the selected issue",mode:y.COMMAND_LINE,action:async(e,t)=>Sg(t),onSuccess:()=>E({mode:y.DEFAULT})},{intent:O.Sync,description:"Pull, commit, and push Epiq state",mode:y.COMMAND_LINE,action:rg},{intent:O.Peek,description:"View board state at another point in time",mode:y.COMMAND_LINE,action:Xp},{intent:O.Replay,description:"Replay board history forward from a point in time",mode:y.COMMAND_LINE,action:Qp},{intent:O.Export,description:"Export the current board layout to markdown",mode:y.COMMAND_LINE,action:async()=>{let e=await hp();return a(e)?e:(E({mode:y.DEFAULT}),l("Export successful",!0))}},{intent:O.Exit,description:"Exit the application",mode:y.COMMAND_LINE,action:async()=>(U.exit(),l("Exit successful",!0))},{intent:O.Edit,description:"Edit title or description",mode:y.COMMAND_LINE,action:async(e,t)=>Rp(t),onSuccess:()=>E({mode:y.DEFAULT})},{intent:O.Yank,description:"Yank (copy) ref, title, description, tags, or assignees to the clipboard",mode:y.COMMAND_LINE,action:async(e,t)=>ng(t),onSuccess:()=>E({mode:y.DEFAULT})},{intent:O.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:y.COMMAND_LINE,action:(e,t)=>Pg(t)}]});var ex,Wt,Ad=h(()=>{"use strict";Fs();Ys();ja();Fg();R();de();Be();M();ex=new Set(["peek","replay","filter","view-help","yank"]),Wt=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:o,inputString:r}}=ie();if(!t)return i("No command to confirm");if(!e&&n===En.Invalid)return i("Invalid command");let s=Im(t);hm();let{readOnly:d}=g();if(d&&!ex.has(s))return Pr({status:Vt.Fail,message:"Command not available in readonly state",value:null});let c=Dg.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!c)return Pr({status:Vt.Fail,message:"Command not found",value:null});let u;try{u=await c.action(c,{command:t,inputString:r,modifier:o})}catch(m){return Pr({status:Vt.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return a(u)?Pr(u):(vm({addToHistory:!e}),c.onSuccess?.(),Ie().autoSync&&vu(),u)}});var bi,Ii,_g,Bg=h(()=>{"use strict";R();me();M();kn();Ad();vd();de();bi=[{intent:F.Exit,mode:y.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(E({mode:y.COMMAND_LINE}),ee("move cancel"),Wt({isForceExecutedBySystem:!0}))},{intent:F.InitMove,mode:y.DEFAULT,description:"[m] move",action:()=>(E({mode:y.COMMAND_LINE}),ee("move start"),Wt({isForceExecutedBySystem:!0}))},{intent:F.ConfirmMove,mode:y.MOVE,description:"[m] confirm move",action:()=>(E({mode:y.COMMAND_LINE}),ee("move confirm"),Wt({isForceExecutedBySystem:!0}))}],Ii=[{intent:F.MovePreviousItem,mode:y.MOVE,action:()=>Cn()?(E({mode:y.COMMAND_LINE}),ee("move previous"),Wt({isForceExecutedBySystem:!0})):i("No pending move")},{intent:F.MoveNextItem,mode:y.MOVE,action:()=>Cn()?(E({mode:y.COMMAND_LINE}),ee("move next"),Wt({isForceExecutedBySystem:!0})):i("No pending move")}],_g=[{intent:F.MoveToNextContainer,mode:y.MOVE,action:()=>Cn()?(E({mode:y.COMMAND_LINE}),ee("move to-next"),Wt({isForceExecutedBySystem:!0})):i("No pending move")},{intent:F.MoveToPreviousContainer,mode:y.MOVE,action:()=>Cn()?(E({mode:y.COMMAND_LINE}),ee("move to-previous"),Wt({isForceExecutedBySystem:!0})):i("No pending move")}]});var Og,Ug=h(()=>{"use strict";V();Bg();Og={[z.WORKSPACE]:[...bi,...Ii],[z.BOARD]:[...bi,...Ii],[z.SWIMLANE]:[...bi,...Ii,..._g],[z.TICKET]:[],[z.FIELD]:[],[z.FIELD_LIST]:[],[z.TEXT]:[],[z.COMMENT]:[]}});import{spawn as tx}from"node:child_process";function $g(e){let t=process.platform,r=tx(t==="darwin"?"open":t==="win32"?"cmd":"xdg-open",t==="win32"?["/c","start","",e]:[e],{detached:!0,stdio:"ignore",shell:!1});return r.unref(),r.on("error",()=>{}),!0}var jg=h(()=>{"use strict"});import nx from"node:fs";import ox from"node:path";var Hg,Wg=h(()=>{"use strict";We();Eo();R();ae();jg();Hg=e=>{let t=Ue(process.cwd());if(a(t))return i("Unable to resolve project root");let n=ve({repoRoot:t.value});if(a(n))return i(n.message);let o=xo(e.hash,e.ext),r=ox.join(ps(n.value),o);return nx.existsSync(r)?($g(r),l(`Opened ${e.name}`,null)):i("Attachment file not found \u2014 run :sync to fetch it")}});var qg,Gg,zg=h(()=>{"use strict";me();R();de();M();ci();kn();it();qg=()=>{ee("");let{pendingNavTarget:e}=_o();E({mode:y.DEFAULT}),e&&U.navigate(e),An({pendingNavTarget:void 0})},Gg=[{intent:F.ExitCommandLine,mode:y.HELP,action:()=>(qg(),l("Exiting help",null))},{intent:F.Exit,mode:y.HELP,action:()=>(qg(),l("Closed help",null))},{intent:F.NavPreviousItem,mode:y.HELP,description:"[arrows/hjkl] navigate",action:()=>(U.navigateToPreviousItem(),l("Navigating to previous help item",null))},{intent:F.NavNextItem,mode:y.HELP,action:()=>(U.navigateToNextItem(),l("Navigating to next help item",null))},{intent:F.NavToPreviousContainer,mode:y.HELP,action:()=>(U.navigateToPreviousContainer(),l("Navigating to previous help container",null))},{intent:F.NavToNextContainer,mode:y.HELP,action:()=>(U.navigateToNextContainer(),l("Navigating to next help container",null))}]});var rx,Vg,Kg,Yg=h(()=>{"use strict";me();V();R();de();M();ci();kn();it();rx=e=>{E({mode:y.COMMAND_LINE});let{pendingNavTarget:t}=_o();t&&U.navigate(t),An({pendingNavTarget:void 0}),ee(`${e} `)},Vg=()=>{ee("");let{pendingNavTarget:e}=_o();e&&U.navigate(e),An({pendingNavTarget:void 0}),E({mode:y.DEFAULT})},Kg=[{intent:F.InitCommandPalette,mode:y.DEFAULT,description:"[?] command palette",action:()=>{ee("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:o}=g();return An({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:o}}),E({mode:y.PALETTE}),l("Opening command palette",null)}},{intent:F.Confirm,mode:y.PALETTE,action:()=>{let{selectedNode:e}=g();if(!e||!Rc(e))return i("Command only applicable on text nodes");if(e.props.disabled)return i("Command is not available in this context");let t=e.title;return t?(rx(t),l("Selected command",t)):l("No command selected",null)}},{intent:F.ExitCommandLine,mode:y.PALETTE,action:()=>(Vg(),l("Exiting palette",null))},{intent:F.Exit,mode:y.PALETTE,action:()=>(Vg(),l("Closed command palette",null))},{intent:F.NavPreviousItem,mode:y.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(U.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:F.NavNextItem,mode:y.PALETTE,action:()=>(U.navigateToNextItem(),l("Navigating to next item",null))},{intent:F.NavToPreviousContainer,mode:y.PALETTE,action:()=>(U.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:F.NavToNextContainer,mode:y.PALETTE,action:()=>(U.navigateToNextContainer(),l("Navigating to next container",null))}]});var Xg,Jg=h(()=>{"use strict";Yn();nn();me();R();uo();te();pt();de();M();Wg();kn();zg();Yg();it();Xg=[{intent:F.InitCommandLine,mode:y.DEFAULT,description:"[:] write command",action:()=>(E({mode:y.COMMAND_LINE}),ee(""),l("Entering command line mode",null))},...Gg,...Kg,{intent:F.AddItem,mode:y.DEFAULT,description:"[n] new...",action:()=>(E({mode:y.COMMAND_LINE}),ee(`${b.NEW} `),l("Adding new item",null))},{intent:F.Delete,mode:y.DEFAULT,description:"[d] delete",action:()=>(E({mode:y.COMMAND_LINE}),ee(`${b.DELETE} `),l("Deleting item",null))},{intent:F.Confirm,mode:y.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=g();if(!ge(e?.id??"")?.length){let o=e?I.getAttachment(e.id):void 0;if(o)return Hg(o);if(e?.title===le.DESCRIPTION)return E({mode:y.COMMAND_LINE}),ee(`${b.EDIT} description `),l("Propose command",!0);if(e?.title===le.ASSIGNEES)return E({mode:y.COMMAND_LINE}),ee(`${b.ASSIGN} `),l("Propose command",!0);if(e?.title===le.TAGS)return E({mode:y.COMMAND_LINE}),ee(`${b.TAG} `),l("Propose command",!0);if(t.title===le.DESCRIPTION&&e?.context==="TEXT")return E({mode:y.COMMAND_LINE}),ee(`${b.EDIT} description `),l("Propose command",!0)}return U.enterChildNode(),l("Entering context",null)}},{intent:F.Yank,mode:y.DEFAULT,description:"[y] yank",action:()=>{let{selectedNode:e}=g(),t=e?.title===le.DESCRIPTION?Ne.DESCRIPTION:e?.title===le.TAGS?Ne.TAGS:e?.title===le.ASSIGNEES?Ne.ASSIGNEES:Ne.REF,o=Ae(b.YANK).includes(t)?t:Ne.REF;return E({mode:y.COMMAND_LINE}),ee(`${b.YANK} ${o}`),l("Propose command",!0)}},{intent:F.EditTitle,mode:y.DEFAULT,description:"[r] rename title",action:()=>(E({mode:y.COMMAND_LINE}),ee(`${b.EDIT} title ${g().selectedNode?.title}`),l("Exiting context",null))},{intent:F.EditDescription,mode:y.DEFAULT,description:"[e] edit desc",action:()=>(E({mode:y.COMMAND_LINE}),ee(`${b.EDIT} description `),l("Exiting context",null))},{intent:F.Exit,mode:y.DEFAULT,description:"[q] exit context",action:()=>(U.enterParentNode(),l("Exiting context",null))},{intent:F.NavPreviousItem,mode:y.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(U.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:F.NavNextItem,mode:y.DEFAULT,action:()=>(U.navigateToNextItem(),l("Navigating to next item",null))},{intent:F.NavToPreviousContainer,mode:y.DEFAULT,action:()=>(U.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:F.NavToNextContainer,mode:y.DEFAULT,action:()=>(U.navigateToNextContainer(),l("Navigating to next container",null))}]});var sx,ix,Qg,Zg=h(()=>{"use strict";de();sx=500,ix=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Qg=e=>{let t=ix(e);t&&Qs(n=>(n+t).slice(0,sx))}});var ax,dx,ef,tf=h(()=>{"use strict";Zg();me();R();de();M();kn();Ad();ax=[y.COMMAND_LINE,y.PALETTE],dx=e=>[{intent:F.MoveCursorLeft,mode:e,action:()=>(Ua(-1),l("Moving cursor left",null))},{intent:F.MoveCursorRight,mode:e,action:()=>(Ua(1),l("Moving cursor right",null))},{intent:F.MoveCursorLeftOfWord,mode:e,action:()=>($a("left"),l("Moving cursor left of word",null))},{intent:F.MoveCursorRightOfWord,mode:e,action:()=>($a("right"),l("Moving cursor right of word",null))},{intent:F.AutoCompleteCommand,mode:e,action:()=>(Qs((t,{remainder:n})=>{let o=n?t+n:t,r="";return o==="edit title "&&(r=g().selectedNode?.title??""),o+r}),l("Auto-completing command",null))},{intent:F.CaptureInput,mode:e,action:(t,{sequence:n})=>(Qg(n??""),l("Capturing input",null))},{intent:F.EraseInput,mode:e,action:()=>(gm(),l("Erasing input",null))},{intent:F.EraseInputWord,mode:e,action:()=>(fm(),l("Erasing input word",null))}],ef=[{intent:F.Confirm,mode:y.COMMAND_LINE,action:()=>(Wt(),l("Executing command",null))},{intent:F.ViewHelp,mode:y.DEFAULT,action:()=>(E({mode:y.HELP}),l("Viewing help",null))},...ax.flatMap(dx),{intent:F.ExitCommandLine,mode:y.COMMAND_LINE,action:()=>(E({mode:y.DEFAULT}),l("Exiting command line",null))},{intent:F.GetLastCommandFromHistory,mode:y.COMMAND_LINE,action:()=>(ym(),l("Getting last command from history",null))},{intent:F.GetNextCommandFromHistory,mode:y.COMMAND_LINE,action:()=>(bm(),l("Getting next command from history",null))}]});var cx,nf,of,rf=h(()=>{"use strict";cx=e=>{let t=/^\[(.+?)\]\s*(.+)$/.exec(e);return t?{keys:t[1]??"",label:t[2]??""}:null},nf=({keys:e})=>e.length===1?0:1,of=(e,t)=>{let n=new Set;for(let o of e)o.mode!==t||!o.description||n.add(o.description);return[...n].map(cx).filter(o=>o!==null).sort((o,r)=>nf(o)-nf(r))}});function sf(e,t,n){let o=t[e];if(!o)return i("buildBreadCrumb(): current node not found");let r=[],s=new Set,d=o;for(;d&&!s.has(d.id)&&(r.push(d),s.add(d.id),!(d.id===n||!d.parentNodeId));)d=t[d.parentNodeId];let c=r[r.length-1];return!c||c.id!==n?i("buildBreadCrumb(): node is not connected to root"):(r.reverse(),l("Breadcrumb built",r))}var af=h(()=>{"use strict";R()});var df,cf=h(()=>{"use strict";df=e=>{let t={};for(let n of e)n.intent&&(t[n.mode]||(t[n.mode]={}),t[n.mode][n.intent]=n);return t}});import{useSyncExternalStore as lx}from"react";function Md(e){let{contextNodeId:t,mode:n,rootNodeId:o,nodes:r,filters:s}=e;if(!t)return i("derive(): contextNodeId is missing");if(!o)return i("derive(): rootNode is missing");if(!r[o])return i("derive(): unable to find root node");let c=r[t];if(!c)return i("Unable to derive state, contextNode not found");let u=sf(t,r,o);if(a(u))return logger.error(u.message),u;let m=u.value,{context:p}=c,f=[...Xg,...Og[p]??[],...ef],x=of(f,n),S=df(f),A=mx(r,s),P=A[t]?.[e.selectedIndex]??null;return l("Derived successfully",{...e,contextNode:c,breadCrumb:m,availableHints:x,availableActions:f,actionIndex:S,selectedNode:P,renderedChildrenIndex:A})}function ur(e){Cd=e;let t=Ue(process.cwd()),n=!1;if(!a(t)){let s=Kt(t.value);if(a(s))return i(s.message);n=!0}let o={readOnly:!1,filters:[],tags:{},contributors:{},mode:y.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,contextNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],replay:null,timeMode:"live",hasProjectDefinition:n,hasInitializingEvents:!1,comments:{},attachments:{}},r=Md(o);return a(r)?r:(qt=r.value,Td(),l("State initialized",null))}function Re(e){let t=g(),n=e(t);if(no)return Wr=n,qt={...t,...n},l("State updated",null);let o=Md(n);return a(o)?i(o.message??"Unable to update state"):(qt=o.value,Td(),l("State updated",null))}function dl(e){if(no)return l("Joined batch",e());no=!0,Wr=null;let t=()=>{let n=Wr;if(no=!1,Wr=null,n===null)return null;let o=Md(n);return a(o)?i(o.message??"Unable to update state"):(qt=o.value,Td(),l("State updated",null))};try{let n=e(),o=t();return o&&a(o)?i(o.message):l("State updated",n)}finally{no&&t()}}function oo(e,t,n){if(!no)return Re(d=>({...d,[e]:{...d[e]??{},[t]:n}}));let o=g(),r=o[e]??{};r[t]=n;let s={...o,[e]:r};return Wr=s,qt={...o,...s},l("State updated",null)}var qt,Cd,wd,Td,ux,g,$e,no,Wr,Ul,E,Je,mx,oe,cn,vt,M=h(()=>{"use strict";Ug();Jg();tf();rf();Yt();me();R();ae();ca();af();cf();wd=new Set,Td=()=>{for(let e of wd)e()},ux=e=>(wd.add(e),()=>wd.delete(e));g=()=>{if(!qt)throw new Error("State not initialized. Call initWorkspaceState() first.");return qt},$e=()=>qt?l("Retrieved state",qt):i("State not initialized. Call initWorkspaceState() first.");no=!1,Wr=null;Ul=()=>no,E=e=>Re(t=>({...t,...e}));Je=()=>lx(ux,g,g),mx=Fl,oe=e=>g()?.renderedChildrenIndex[e]??[],cn=()=>Cd?ur(Cd):i("Cannot reset state: no initial workspace found"),vt=()=>qt!==void 0});var Et,px,wn,I,te=h(()=>{"use strict";Tt();V();R();M();pt();Et=(e,t)=>{let{nodes:n}=g(),o=n[e];if(!o)return i("Node not found");if(o.context===t)return l("Resolved ancestor node",o);let r=new Set([o.id]),s=o.parentNodeId?n[o.parentNodeId]:void 0;for(;s&&!r.has(s.id);){if(s.context===t)return l("Resolved ancestor node",s);r.add(s.id),s=s.parentNodeId?n[s.parentNodeId]:void 0}return i(`No ancestor found for context: ${t}`)},px=(e,t)=>{let{nodes:n}=g(),o=new Set,r=n[e];for(;r?.parentNodeId&&!o.has(r.id);){if(r.parentNodeId===t)return!0;o.add(r.id),r=n[r.parentNodeId]}return!1},wn=(e,t)=>e?e.readonly?i({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node",delete:"Cannot delete readonly node"}[t]):null:i("Node not found"),I={linkUserId({contributorId:e,userId:t}){let n=this.getContributor(e);if(!n)return i("Contributor not found");if(n.userId&&n.userId!==t)return i("Contributor is already linked to another user");let o={...n,userId:t},r=Re(s=>({...s,contributors:{...s.contributors,[e]:o}}));return a(r)?i("Unable to link contributor to user"):l("Linked contributor to user",o)},deleteNode(e){Re(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},createComment(e){let t=this.getNode(e.issue);if(!t)return i("Unable to create comment, missing issue");if(!k(t))return i("Can only comment on issues");let n=oo("comments",e.id,{...e,deleted:!1});return a(n)?i("Unable to create comment"):l("Created comment",{...e,deleted:!1})},editComment(e,t){let n=this.getComment(e);if(!n)return i("Unable to edit comment, missing comment");let o=this.getNode(n.issue);if(!o)return i("Unable to edit comment, missing issue");if(!k(o))return i("Can only edit issue comments");let r={...n,md:t,deleted:!1},s=oo("comments",e,r);return a(s)?i("Unable to edit comment"):l("Edited comment",r)},deleteComment(e){let t=this.getComment(e);if(!t)return i("Unable to delete comment, missing comment");let n={...t,deleted:!0},o=oo("comments",e,n);return a(o)?i("Unable to delete comment"):l("Deleted comment",n)},getComment(e){return g().comments?.[e]},getCommentsByIssue(e){return Object.values(g().comments??{}).filter(t=>t.issue===e&&!t.deleted)},getCommentsGroupedByIssue(){let e=new Map;for(let t of Object.values(g().comments??{})){if(t.deleted)continue;let n=e.get(t.issue);n?n.push(t):e.set(t.issue,[t])}return e},createAttachment(e){let t=this.getNode(e.issue);if(!t)return i("Unable to create attachment, missing issue");if(!k(t))return i("Can only attach to issues");let n=Re(o=>({...o,attachments:{...o.attachments??{},[e.id]:{...e,deleted:!1}}}));return a(n)?i("Unable to create attachment"):l("Created attachment",{...e,deleted:!1})},deleteAttachment(e){let t=this.getAttachment(e);if(!t)return i("Unable to delete attachment, missing attachment");let n={...t,deleted:!0},o=Re(r=>({...r,attachments:{...r.attachments??{},[e]:n}}));return a(o)?i("Unable to delete attachment"):l("Deleted attachment",n)},getAttachment(e){return g().attachments?.[e]},getAttachmentsByIssue(e){return Object.values(g().attachments??{}).filter(t=>t.issue===e&&!t.deleted)},getAttachmentsGroupedByIssue(){let e=new Map;for(let t of Object.values(g().attachments??{})){if(t.deleted)continue;let n=e.get(t.issue);n?n.push(t):e.set(t.issue,[t])}return e},editValue(e,t){let{nodes:n}=g(),o=n[e];if(!o)return i("Edit target node not found");let r=wn(o,"edit");if(r)return r;let s={...o,props:{...o.props,description:t}};return this.updateNode(s),l("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return i("Rename target node not found");let o=wn(n,"rename");if(o)return o;let r={...n,title:t};return this.updateNode(r),l("Renamed node",r)},getExistingTags(){let{tags:e}=g();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=g();return["me",...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return ge(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:o}=g(),r=this.getNode(e),s=this.getNode(t);if(!r)return i("Node not found");if(!s)return i("Target parent not found");if(o===e)return i("Cannot move root node");if(e===t)return i("Cannot move node into itself");let d=wn(r,"move");if(d)return d;if(px(t,e))return i("Cannot move node into its own descendant");let c={...r,parentNodeId:t,rank:n};return this.updateNode(c),l("Moved node successfully",c)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:o}=g(),r=this.getNode(e);if(!r)return i("Node not found");if(o===e)return i("Cannot delete root node");let s=wn(r,"delete");if(s)return s;let d=new Set,c=m=>{let p=t[m];if(!(!p||d.has(m))){d.add(m);for(let f of ge(p.id))c(f.id)}};c(e);let u={...structuredClone(t)};for(let m of d){if(!u[m])return i("Unable to locate node to delete");u[m]={...u[m],isDeleted:!0}}return n?(E({nodes:u}),l("Successfully tomb stoned",r)):i("Unable to delete undefined")},tombstoneContributor(e){let t=this.getContributor(e);if(!t)return i("Contributor not found");let n={...t,name:es,tombstoned:!0},o=Re(r=>({...r,contributors:{...r.contributors,[e]:n}}));return a(o)?i("Unable to remove contributor"):l("Tombstoned contributor",n)},renameContributor(e,t){let n=this.getContributor(e);if(!n)return i("Contributor not found");if(n.tombstoned)return i("Cannot rename a removed contributor");let o={...n,name:t},r=Re(s=>({...s,contributors:{...s.contributors,[e]:o}}));return a(r)?i("Unable to rename contributor"):l("Renamed contributor",o)},restoreContributor(e,t){let n=this.getContributor(e);if(!n)return i("Contributor not found");let o={...n,name:t,tombstoned:!1},r=Re(s=>({...s,contributors:{...s.contributors,[e]:o}}));return a(r)?i("Unable to restore contributor"):l("Restored contributor",o)},createContributor(e){let t=Re(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return a(t)?i("Unable to create contributor"):l("Created contributor",e)},assign(e,t){let n=this.getContributor(t),o=this.getNode(e);if(!n)return i("Unable to assign contributor, missing contributor");if(!o)return i("Unable to assign contributor, missing target");let r=wn(o,"edit");if(r)return r;if(!k(o))return i("Target is not an issue");let s=o.props.assignees??[];if(s.includes(t))return i("Contributor already assigned");let d={...o,props:{...o.props,assignees:[...s,t]}};return this.updateNode(d),l("Assigned contributor",{assignee:t})},unassign(e,t){let n=this.getContributor(t),o=this.getNode(e);if(!n)return i("Unable to unassign, missing contributor");if(!o)return i("Unable to unassign, missing target");let r=wn(o,"edit");if(r)return r;if(!k(o))return i("Target is not an issue");let s=o.props.assignees??[];if(!s.includes(t))return l("Issue is not assigned to that contributor",{assignee:t});let d={...o,props:{...o.props,assignees:s.filter(c=>c!==t)}};return this.updateNode(d),l("Assignee removed",{assignee:t})},tag(e,t){let n=this.getTag(t),o=this.getNode(e);if(!n)return i("Unable to add tag, missing tag");if(!o)return i("Unable to add tag, missing target");let r=wn(o,"edit");if(r)return r;if(!k(o))return i("Target is not an issue");let s=o.props.tags??[];if(s.includes(t))return i("Tag already assigned");let d={...o,props:{...o.props,tags:[...s,t]}};return this.updateNode(d),l("Tag added",{tag:t})},untag(e,t){let n=this.getTagRecord(t),o=this.getNode(e);if(!n)return i("Unable to remove tag, missing tag");if(!o)return i("Unable to remove tag, missing target");let r=wn(o,"edit");if(r)return r;if(!k(o))return i("Target is not an issue");let s=o.props.tags??[];if(!s.includes(t))return l("Issue is not tagged with that tag",{tag:t});let d={...o,props:{...o.props,tags:s.filter(c=>c!==t)}};return this.updateNode(d),l("Tag removed",{tag:t})},tombstoneTag(e){let t=this.getTagRecord(e);if(!t)return i("Tag not found");let n={...t,tombstoned:!0},o=Re(r=>({...r,tags:{...r.tags,[e]:n}}));return a(o)?i("Unable to delete tag"):l("Tombstoned tag",n)},restoreTag(e,t){let n=this.getTagRecord(e);if(!n)return i("Tag not found");let o={...n,name:t,tombstoned:!1},r=Re(s=>({...s,tags:{...s.tags,[e]:o}}));return a(r)?i("Unable to restore tag"):l("Restored tag",o)},createTag(e){let t=Re(n=>({...n,tags:{...n.tags,[e.id]:e}}));return a(t)?i("Could not create tag"):l("Tag created",e)},createNode(e){let t=oo("nodes",e.id,e);return a(t)?i("Unable to create node"):l("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return i("Failed to locate node");let n={...t,readonly:!0},o=oo("nodes",e,n);return a(o)?i(o.message):l("Locked node",n)},updateNode(e){let t=oo("nodes",e.id,e);return a(t)?t:l("Updated node",e)},getContributor(e){return g().contributors[e]},getTag(e){let t=g().tags[e];return t?.tombstoned?void 0:t},getTagRecord(e){return g().tags[e]},getTags(){return Object.values(g().tags).filter(e=>!e.tombstoned)},findTagByName(e){return this.getTags().find(t=>t.name===e)},getNode(e){return g().nodes[e]},getSiblings(e){return ge(e)}}});import Tn from"chalk";import lf from"string-width";var gx,fx,kd,hx,vx,uf,mf,yx,bx,Ix,xx,Ex,xd,pf,jr=h(()=>{"use strict";et();te();M();dt();ii();gx=(e,t)=>e+" ".repeat(Math.max(0,t-lf(e))),fx=(e,t)=>" ".repeat(Math.max(0,t-lf(e)))+e,kd=e=>({"add.issue":"Created with title","add.issue.assignee":"Assigned to","remove.issue.assignee":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","add.issue.tag":"Tagged with","remove.issue.tag":"Removed tag","lock.node":"Locked node","move.node":"Moved issue","add.issue.comment":"Commented","delete.issue.comment":"Deleted comment","add.issue.attachment":"Attached","delete.issue.attachment":"Removed attachment","edit.issue.comment":"Edited comment","init.workspace":"Created workspace","add.workspace":"Created workspace","add.board":"Created board","add.swimlane":"Created swimlane","add.field":"Added field","create.tag":"Created tag","tombstone.tag":"Deleted tag","restore.tag":"Restored tag","create.contributor":"Added contributor","rename.contributor":"Renamed contributor","link.contributor.user":"Linked contributor","tombstone.contributor":"Removed contributor","restore.contributor":"Restored contributor","rebalance.children":"Rebalanced order"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),hx=(e,t)=>t?e<t?"up":e>t?"down":null:null,vx=(e,t)=>{let n=I.getNode(e.payload.parent),o=n?Tn.dim.bgBlack(` ${n.title} `):"unknown",r=t.at(-1);if(r&&"parent"in r&&"rank"in r&&r.parent===e.payload.parent){let s=hx(e.payload.rank,r.rank);if(s)return`Moved ${s} in ${o}`}return`Moved issue to ${o}`},uf=e=>`${Math.max(1,Math.round(e/1024))} KB`,mf=e=>I.getAttachment(e)?.name??"",yx=e=>{switch(e.action){case"add.issue.tag":{let t=g().tags[e.payload.tag];return t?Tn.bgHex(Ce(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=g().tags[e.payload.tag];return t?Tn.bgHex(Ce(t.name))(` ${t.name} `):"unknown tag"}case"tombstone.tag":{let t=g().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?Tn.hex(Ce(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?Tn.hex(Ce(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;case"add.issue.attachment":return`"${e.payload.name}" ${Tn.dim(`(${uf(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=mf(e.payload.id);return t?`"${t}"`:""}default:return""}},bx=e=>{let t=Lo(Ze(e));return Tn.gray(fx(t,8))},Ix=12,xx=e=>gx(`${e}`,Ix),Ex=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=g().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?t.name:""}case"tombstone.tag":{let t=g().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"edit.title":return"name"in e.payload?`"${e.payload.name}"`:"";case"move.node":{let t=I.getNode(e.payload.parent);return t?`to ${t.title}`:""}case"add.issue.attachment":return`"${e.payload.name}" (${uf(e.payload.bytes)})`;case"delete.issue.attachment":{let t=mf(e.payload.id);return t?`"${t}"`:""}default:return""}},xd=e=>[kd(e.action),Ex(e)].filter(Boolean).join(" "),pf=(e,t)=>{let n=bx(e.id),o=xx(e.userName),r=Tn.dim("\u203A"),s=e.action==="move.node"?vx(e,t):[kd(e.action),yx(e)].filter(Boolean).join(" ");return`${o} ${n} ${r} ${s}`}});var ff={};Jr(ff,{areVirtualNodesEnabled:()=>vs,createOrUpdateVirtualField:()=>qr,createOrUpdateVirtualFieldList:()=>Pd,materializeTicketVirtualNodes:()=>hs,materializeVirtualNodes:()=>kx,setVirtualNodesEnabled:()=>Mx});var Rx,Sx,Nx,Ax,Cx,wx,qr,Pd,hs,Tx,gf,Mx,vs,kx,Xi=h(()=>{"use strict";jr();V();R();uo();te();On();M();ao();Ro();Rx=e=>Me(e,"comments"),Sx=e=>Me(e,"description"),Nx=e=>Me(e,"assignees"),Ax=e=>Me(e,"tags"),Cx=e=>Me(e,"history"),wx=e=>Me(e,"attachments"),qr=({id:e,name:t,parentNodeId:n,rank:o,value:r,readonly:s=!1,childRenderAxis:d="horizontal"})=>{let c=I.getNode(e);if(!c){let p=I.createNode({...Te.field({id:e,name:t,parentNodeId:n,rank:o,props:{value:r},isVirtual:!0}),readonly:s,childRenderAxis:d});return a(p)?p:l("Virtual field created",void 0)}if(!nt(c))return i(`Existing virtual node ${e} is not a field`);if(!(c.title!==t||c.parentNodeId!==n||c.rank!==o||c.props.value!==r||c.readonly!==s||c.childRenderAxis!==d))return l("Virtual field unchanged",void 0);let m=I.updateNode({...c,title:t,parentNodeId:n,rank:o,props:{...c.props,value:r},readonly:s,childRenderAxis:d});return a(m)?m:l("Virtual field updated",void 0)},Pd=({id:e,name:t,parentNodeId:n,rank:o,readonly:r=!1,childRenderAxis:s="horizontal"})=>{let d=I.getNode(e);if(!d){let m=I.createNode({...Te.fieldList({id:e,name:t,parentNodeId:n,rank:o,isVirtual:!0}),readonly:r,childRenderAxis:s});return a(m)?m:l("Virtual field list created",void 0)}if(!Xo(d))return i(`Existing virtual node ${e} is not a field list`);if(!(d.title!==t||d.parentNodeId!==n||d.rank!==o||d.readonly!==r||d.childRenderAxis!==s))return l("Virtual field list unchanged",void 0);let u=I.updateNode({...d,title:t,parentNodeId:n,rank:o,readonly:r,childRenderAxis:s});return a(u)?u:l("Virtual field list updated",void 0)},hs=e=>{let t=mt(Mt/4n),n=mt(Mt/2n),o=mt(Mt*3n/4n),r=mt(Mt*7n/8n),s=mt(Mt*15n/16n),d=mt(Mt*13n/16n);if(a(t))return t;if(a(n))return n;if(a(o))return o;if(a(r))return r;if(a(s))return s;if(a(d))return d;let c=qr({id:Sx(e.id),name:le.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(a(c))return c;let u=Pd({id:Nx(e.id),name:le.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(a(u))return u;let m=Pd({id:Ax(e.id),name:le.TAGS,parentNodeId:e.id,rank:o.value,readonly:!0});if(a(m))return m;let p=qr({id:Rx(e.id),name:le.COMMENTS,parentNodeId:e.id,rank:r.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(a(p))return p;let f=qr({id:wx(e.id),name:le.ATTACHMENTS,parentNodeId:e.id,rank:s.value,value:"",readonly:!0,childRenderAxis:"vertical"});if(a(f))return f;let x=qr({id:Cx(e.id),name:le.HISTORY,parentNodeId:e.id,rank:d.value,value:Tx(e),readonly:!0,childRenderAxis:"vertical"});return a(x)?x:l("Ticket virtual nodes materialized",void 0)},Tx=e=>{let t=[...e.log].reverse(),n=new Map;for(let o of t){let r=n.get(o.action)??[];r.push(o.payload),n.set(o.action,r)}return t.map(o=>pf(o,n.get(o.action)??[])).join(`
|
|
75
|
-
`)},gf=!0,Mx=e=>{gf=e},vs=()=>gf,kx=()=>{let{nodes:e}=g();for(let t of Object.values(e)){if(!k(t))continue;let n=hs(t);if(a(n))return n}return l("Virtual nodes materialized",void 0)}});var Px,hf,Ld=h(()=>{"use strict";et();bt();mr();jr();R();dt();Px=e=>{let t=new Map,n=new Set,o=r=>{let s=new Set,d=r;for(;d&&!s.has(d);){if(n.has(d))return d;s.add(d),d=t.get(d)}return null};return e.map(r=>{let s=r.payload,d=s?.id;if(!d)return null;r.action==="add.board"&&n.add(d);let c=s.parent??s.issue;return c&&t.set(d,c),n.has(d)?d:o(d)})},hf=(e,t)=>{let n=Px(e);return e.filter((o,r)=>n[r]===t)}});var Lx,vf,yf,Gr,zr=h(()=>{"use strict";We();Nt();st();ld();bt();Zt();R();Yt();zs();ae();M();Ld();Lx=null,vf=Promise.resolve(),yf=e=>{let t=vf.then(e,e);return vf=t.then(()=>{},()=>{}),t},Gr=()=>{if(!vt())return{mode:"live",asOfTime:null};let{timeMode:e}=g();return e==="live"?{mode:"live",asOfTime:null}:{mode:"scrub",asOfTime:Lx}}});import Dx from"node:fs";var ro,xi,K,J,Y,ln=h(()=>{"use strict";We();Nt();co();br();Ut();zn();mr();ae();bt();R();M();ht();zr();ro=e=>{let t=Ue(e??process.cwd());return a(t)?i(t.message):l("Resolved Epiq repo root",t.value)},xi=null,K=async(e,t)=>{let n=ro(e);if(a(n))return n;let o=ve({repoRoot:n.value});if(a(o))return i(o.message);let r=kt(n.value);if(a(r))return i(r.message);if(!(xi!==null&&xi.repoRoot===n.value&&xi.stateBranchRoot===o.value&&Dx.existsSync(Ln(o.value)))){let p=await pa({repoRoot:n.value,stateBranchName:r.value});if(a(p))return i(p.message);let f=await Kn({repoRoot:n.value,stateBranchRoot:o.value,stateBranchName:r.value});if(a(f))return i(f.message);xi={repoRoot:n.value,stateBranchRoot:o.value}}if(t?.pull??!1){let p=await q({cwd:o.value,args:["pull","--ff-only"]});a(p)&&X.info(3,p.message)}let d={repoRoot:n.value,stateBranchRoot:o.value},c=jn(o.value);if(ul(o.value)===c&&vt()&&Gr().mode==="live")return l("Booted Epiq state, unchanged",d);let u=yt(o.value);if(a(u))return i(u.message);let m=_t(u.value.events,u.value.unreadable);return a(m)?i(m.message):(ml(o.value,c),l("Booted Epiq state",d))},J=()=>{let e=wr();return a(e)?i(e.message):e.value.userId?e.value.userName?l("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):i("Unable to retrieve user name"):i("Unable to retrieve user id")},Y=()=>{let e=$e();return a(e)?i(e.message):e}});var Bo,bf,Oo,Dd=h(()=>{"use strict";et();te();dt();Bo=e=>(e.props.tags??[]).map(t=>I.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:Ce(t.name)})),bf=e=>I.getCommentsByIssue(e).sort((t,n)=>t.id<n.id?-1:t.id>n.id?1:0).map(t=>({id:t.id,author:I.getContributor(t.authorId)?.name??t.authorName??"Unknown",createdAt:Ze(t.id),body:t.md})),Oo=e=>(e.props.assignees??[]).map(t=>I.getContributor(t)).filter(t=>t!=null).map(({id:t,name:n})=>({id:t,name:n,color:Ce(n)}))});import Fx from"node:fs";import _x from"node:path";import{ulid as If}from"ulid";var Bx,xf,Fd,_d=h(()=>{"use strict";Ut();xe();V();R();ot();Eo();ln();Bx=e=>{if(e.filePath)try{return l("Read attachment file",{data:Fx.readFileSync(e.filePath),name:e.name??_x.basename(e.filePath)})}catch(t){return i(`Unable to read ${e.filePath}: ${t instanceof Error?t.message:String(t)}`)}return e.dataBase64?l("Decoded attachment data",{data:Buffer.from(e.dataBase64,"base64"),name:e.name??"image"}):i("Provide either filePath or dataBase64")},xf=()=>{let e=wr();return a(e)?rn:e.value.attachmentMaxKb??rn},Fd=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!k(r))return i("Attachment target must be an issue");if(r.readonly)return i("Cannot attach to readonly issue");let s=Bx(e);if(a(s))return s;let d=Wu(t.value.stateBranchRoot,s.value.data,xf());if(a(d))return d;let c=pe(s.value.name).trim()||"image",u=If(),m={id:If(),...n.value,action:"add.issue.attachment",payload:{id:u,issue:e.issueId,author:n.value.userId,hash:d.value.hash,ext:d.value.ext,name:c,bytes:d.value.bytes}},p=L([m],t.value.stateBranchRoot);if(a(p))return i(p.message);let f=xo(d.value.hash,d.value.ext);return l("Added issue attachment",{id:u,issueId:e.issueId,fileName:f,bytes:d.value.bytes,markdown:ka(c,f)})}});var Bd,k1,Od,Ef=h(()=>{"use strict";Ut();et();Jt();V();R();te();vo();dt();st();ot();Eo();ht();zr();ln();Dd();_d();Ps();Se();fr();Bd=async(e={})=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Y();return a(n)?n:l("Retrieved Epiq state",{root:t.value.repoRoot,stateBranchRoot:t.value.stateBranchRoot,nodes:n.value.nodes,rootNodeId:n.value.rootNodeId,contextNode:n.value.contextNode,selectedIndex:n.value.selectedIndex,eventLog:n.value.eventLog})},k1=365*24*60*60*1e3,Od=async(e={})=>{mo();let t=ro(e.repoRoot);if(a(t))return i("Sync failed");let n=J();if(a(n))return n;let o=await ks({cwd:t.value,ownEventFileName:qn(n.value)});return a(o)?(la(o.message),o):(Vn(),l("Synced",o.value))}});var Vr,Uo,Ud,Kr,$d=h(()=>{"use strict";V();R();st();ln();Vr=e=>{let t=[...new Set([...e.issueIds??[],...e.issueId?[e.issueId]:[]])];return t.length?l("Resolved targets",t):i("Provide issueId or issueIds")},Uo=(e,t)=>{let n=t.done.length,o=`${e} ${n} issue${n===1?"":"s"}`+(t.failed.length?`, ${t.failed.length} failed`:"");return n?l(o,t):i(`${o}: ${t.failed.map(r=>`${r.ref} ${r.reason}`).join("; ")}`)},Ud=(e,t)=>{let n={done:[],failed:[]};for(let o of e){let r=t(o);a(r)?n.failed.push({id:o,ref:j(o),reason:r.message}):n.done.push({id:o,ref:j(o)})}return n},Kr=e=>{let t=Y();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?i("Issue not found"):k(n)?n.readonly?i("Issue is readonly"):l("Found issue",n):i("Target must be an issue")}});import{ulid as Rt}from"ulid";async function Hd(e){let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Y();if(a(n))return n;let o=n.value.nodes,r=e.query?.trim().toLowerCase(),s=Object.values(o).filter(k).filter(c=>!c.isDeleted).filter(c=>e.includeClosed||c.parentNodeId!==fe).filter(c=>e.boardId?(c.parentNodeId?o[c.parentNodeId]:void 0)?.parentNodeId===e.boardId:!0).filter(c=>!e.swimlaneId||c.parentNodeId===e.swimlaneId).filter(c=>!e.tag||Bo(c).some(u=>Rf(u.name,e.tag))).filter(c=>!e.assignee||Oo(c).some(u=>Rf(u.name,e.assignee))).filter(c=>!r||c.title.toLowerCase().includes(r)||(c.props.description??"").toLowerCase().includes(r)),d=c=>pe((c.parentNodeId?o[c.parentNodeId]?.title:void 0)??"");return e.brief?l("Listed issues",s.map(c=>({id:c.id,ref:j(c.id),title:pe(c.title),swimlane:d(c),tags:Bo(c).map(u=>u.name),assignees:Oo(c).map(u=>u.name)}))):l("Listed issues",s.map(c=>({id:c.id,ref:j(c.id),title:pe(c.title),description:c.props.description??"",createdAt:Ze(c.id),parentNodeId:c.parentNodeId,isClosed:c.parentNodeId===fe,readonly:!!c.readonly,tags:Bo(c),assignees:Oo(c)})))}async function qd(e){let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Vr(e);if(a(o))return o;let r=s=>Ox(s,n.value,t.value.stateBranchRoot);return e.issueIds?Uo("Closed",Ud(o.value,r)):r(o.value[0])}async function zd(e){let t=ro(e.repoRoot);if(a(t))return t;let n=J();if(a(n))return n;let o=ve({repoRoot:t.value});if(a(o))return o;let r=yt(o.value);if(a(r))return r;let s=_t(r.value.events,r.value.unreadable);if(a(s))return s;let d=Vr(e);if(a(d))return d;let c=u=>Ux(u,e,n.value,o.value);return e.issueIds?Uo("Moved",Ud(d.value,c)):c(d.value[0])}var jd,Rf,Wd,Ox,Gd,Ux,Vd,Kd,Sf=h(()=>{"use strict";We();yd();et();zn();bt();xe();Ed();Jt();V();R();te();pt();jr();dt();sn();st();ot();ln();Dd();$d();jd=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Y();if(a(n))return n;let o=e.idOrRef.trim();if(!o)return i("Provide an issue id or ref");let r=Object.values(n.value.nodes).filter(k).filter(u=>!u.isDeleted),s=r.find(u=>u.id===o),d=s?[s]:r.filter(u=>dr(u.id,o));if(d.length===0)return i(`No issue matches "${o}"`);if(d.length>1)return i(`"${o}" matches ${d.length} issues: ${d.map(u=>`${j(u.id)} (${pe(u.title)})`).join(", ")}. Use a full ref or id.`);let c=d[0];return l("Found issue",{id:c.id,ref:j(c.id),title:pe(c.title),description:c.props.description??"",createdAt:Ze(c.id),parentNodeId:c.parentNodeId,isClosed:c.parentNodeId===fe,readonly:!!c.readonly,tags:Bo(c),assignees:Oo(c),comments:bf(c.id)})},Rf=(e,t)=>e.trim().toLowerCase()===t.trim().toLowerCase();Wd=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();if(a(o))return o;let r=pe(e.title);if(!r)return i("Issue title cannot be empty");let s=e.description??"",d=Ke("Issue title",r,300)??Ke("Issue description",s,2e4);if(d)return i(d);if((e.tagNames?.length??0)>20)return i(`Cannot set more than ${20} tags at once`);if((e.assigneeNames?.length??0)>20)return i(`Cannot set more than ${20} assignees at once`);let c=bn(e.parentId,n.value,t.value.stateBranchRoot);if(a(c))return c;let u=mi({name:r,parent:e.parentId,user:n.value,rank:c.value});if(a(u))return u;let m=[...u.value],p=m.find(A=>A.action==="add.issue")?.payload.id;if(!p)return i("Unable to determine created issue id");s&&m.push({id:Rt(),...n.value,action:"edit.description",payload:{id:p,md:s}});let f=[];for(let A of e.tagNames??[]){let P=pe(A).trim();if(!P||f.some(B=>B.name===P))continue;let T=Ke("Tag name",P,60);if(T)return i(T);let w=I.findTagByName(P),_=w?.id??Rt();w||m.push({id:Rt(),...n.value,action:"create.tag",payload:{id:_,name:P}}),m.push({id:Rt(),...n.value,action:"add.issue.tag",payload:{id:p,tag:_}}),f.push({id:_,name:P})}let x=[];for(let A of e.assigneeNames??[]){let P=pe(A).trim();if(!P||x.some(B=>B.name===P))continue;let T=Ke("Assignee name",P,80);if(T)return i(T);let w=Object.values(o.value.contributors).find(B=>B.name===P),_=w?.id??Rt();w||m.push({id:Rt(),...n.value,action:"create.contributor",payload:{id:_,name:P}}),m.push({id:Rt(),...n.value,action:"add.issue.assignee",payload:{id:p,assignee:_}}),x.push({id:_,name:P})}let S=L(m,t.value.stateBranchRoot);return a(S)?i(S.message):l("Created issue",{id:p,ref:j(p),title:r,parentId:e.parentId,description:s,tags:f,assignees:x})},Ox=(e,t,n)=>{let o=Kr(e);if(a(o))return o;let r=Dt(fe,e,{at:"end"},t,n);if(a(r))return r;let s={id:Rt(),...t,action:"close.issue",payload:{id:e,parent:fe,rank:r.value}},d=L([s],n);return a(d)?i(d.message):l("Closed issue",{id:e,ref:j(e)})};Gd=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!k(r))return i("Target node is not issue");if(r.parentNodeId!==fe)return i("Issue is not closed");let s=vi(r);if(!s)return i("Unable to resolve previous parent from issue history");if(s===fe)return i("Previous parent resolves to closed swimlane");let d=o.value.nodes[s];if(!d)return i("Previous parent no longer exists");let c=Dt(d.id,r.id,{at:"end"},n.value,t.value.stateBranchRoot);if(a(c))return c;let u={id:Rt(),...n.value,action:"reopen.issue",payload:{id:r.id,parent:d.id,rank:c.value}},m=L([u],t.value.stateBranchRoot);return a(m)?i(m.message):l("Reopened issue",{id:r.id,ref:j(r.id),parentId:d.id})},Ux=(e,t,n,o)=>{let r=Kr(e);if(a(r))return r;let s=Dt(t.parentId,e,t.position??{at:"end"},n,o);if(a(s))return s;let d={id:Rt(),...n,action:"move.node",payload:{id:e,parent:t.parentId,rank:s.value}},c=L([d],o);return a(c)?i(c.message):l("Moved issue",{id:e,ref:j(e),parentId:t.parentId})};Vd=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!k(r))return i("Edit target must be an issue");if(r.readonly)return i("Cannot edit readonly issue");let s=Ke("Issue description",e.description,2e4);if(s)return i(s);let d=r.props.description??"";if(d===e.description)return l("No changes made",{id:e.issueId,ref:j(e.issueId),description:d});let c={id:Rt(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},u=L([c],t.value.stateBranchRoot);return a(u)?i(u.message):l("Edited issue description",{id:e.issueId,ref:j(e.issueId),description:e.description})},Kd=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!k(r))return i("Edit target must be an issue");if(r.readonly)return i("Cannot edit readonly issue");let s=pe(e.title);if(!s.trim())return i("Issue title cannot be empty");let d=Ke("Issue title",s,300);if(d)return i(d);if(r.title===s)return l("No changes made",{id:e.issueId,ref:j(e.issueId),title:s});let c={id:Rt(),...n.value,action:"edit.title",payload:{id:e.issueId,name:s}},u=L([c],t.value.stateBranchRoot);return a(u)?i(u.message):l("Edited issue title",{id:e.issueId,ref:j(e.issueId),title:s})}});import{ulid as Xr}from"ulid";var Yd,Xd,Jd,Qd,Zd,ec,Nf=h(()=>{"use strict";We();zn();bt();xe();Jt();V();R();pt();sn();st();ot();zr();ln();Yd=async(e={})=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Y();if(a(n))return n;let o=Object.values(n.value.nodes).filter(r=>r.context==="BOARD"&&!r.isDeleted).map(r=>({id:r.id,ref:j(r.id),title:r.title,parentId:r.parentNodeId,readonly:!!r.readonly}));return l("Listed boards",o)},Xd=async(e={})=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Y();if(a(n))return n;let o=Object.values(n.value.nodes).filter(r=>r.context==="SWIMLANE"&&!r.isDeleted).filter(r=>!e.boardId||r.parentNodeId===e.boardId).map(r=>({id:r.id,title:r.title,boardId:r.parentNodeId,isClosed:r.id===fe,readonly:!!r.readonly}));return l("Listed swimlanes",o)},Jd=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();if(a(o))return o;let r=o.value.nodes[e.boardId];if(!r)return i("Board not found");if(!Jo(r))return i("Target parent must be a board");if(r.readonly)return i("Cannot add a swimlane to a readonly board");if(Gr().mode!=="live")return i("Cannot add a swimlane while time travelling");let s=pe(e.title);if(!s.trim())return i("Swimlane title cannot be empty");let d=Ke("Swimlane title",s,300);if(d)return i(d);let c=bn(e.boardId,n.value,t.value.stateBranchRoot);if(a(c))return c;let u=Xr(),m={id:Xr(),...n.value,action:"add.swimlane",payload:{id:u,name:s,parent:e.boardId,rank:c.value}},p=L([m],t.value.stateBranchRoot);return a(p)?i(p.message):l("Created swimlane",{id:u,ref:j(u),title:s,boardId:e.boardId})},Qd=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();if(a(o))return o;let r=o.value.nodes[e.swimlaneId];if(!r)return i("Swimlane not found");if(!pn(r))return i("Edit target must be a swimlane");if(r.readonly)return i("Cannot edit readonly swimlane");let s=pe(e.title);if(!s.trim())return i("Swimlane title cannot be empty");let d=Ke("Swimlane title",s,300);if(d)return i(d);if(r.title===s)return l("No changes made",{id:e.swimlaneId,ref:j(e.swimlaneId),title:s});let c={id:Xr(),...n.value,action:"edit.title",payload:{id:e.swimlaneId,name:s}},u=L([c],t.value.stateBranchRoot);return a(u)?i(u.message):l("Edited swimlane title",{id:e.swimlaneId,ref:j(e.swimlaneId),title:s})},Zd=async e=>{let t=ro(e.repoRoot);if(a(t))return t;let n=J();if(a(n))return n;let o=ve({repoRoot:t.value});if(a(o))return o;let r=yt(o.value);if(a(r))return r;let s=_t(r.value.events,r.value.unreadable);if(a(s))return s;let d=Dt(e.boardId,e.swimlaneId,e.position??{at:"end"},n.value,o.value);if(a(d))return d;let c={id:Xr(),...n.value,action:"move.node",payload:{id:e.swimlaneId,parent:e.boardId,rank:d.value}},u=L([c],o.value);return a(u)?i(u.message):l("Moved swimlane",{id:e.swimlaneId,ref:j(e.swimlaneId),boardId:e.boardId})},ec=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();if(a(o))return o;let r=o.value.nodes[e.swimlaneId];if(!r)return i("Swimlane not found");if(!pn(r))return i("Delete target must be a swimlane");let s={id:Xr(),...n.value,action:"delete.node",payload:{id:e.swimlaneId}},d=L([s],t.value.stateBranchRoot);return a(d)?i(d.message):l("Deleted swimlane",{id:e.swimlaneId,ref:j(e.swimlaneId)})}});import{ulid as Ho}from"ulid";async function tc(e){let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Vr(e);if(a(o))return o;let r=pe(e.tagName).trim();if(!r)return i("Tag name cannot be empty");let s=Ke("Tag name",r,60);if(s)return i(s);let d={done:[],failed:[]};for(let S of o.value){let A=Kr(S);a(A)?d.failed.push({id:S,ref:j(S),reason:A.message}):d.done.push({id:S,ref:j(S)})}if(!e.issueIds&&d.failed[0])return i(d.failed[0].reason);if(d.done.length===0)return i(Uo("Tagged",d).message);let c=I.findTagByName(r),u=c?.id??Ho(),m=[...c?[]:[{id:Ho(),...n.value,action:"create.tag",payload:{id:u,name:r}}],...d.done.map(({id:S})=>({id:Ho(),...n.value,action:"add.issue.tag",payload:{id:S,tag:u}}))],p=L(m,t.value.stateBranchRoot);if(a(p))return i(p.message);let f={id:u,name:r};if(!e.issueIds)return l("Added issue tag",{...d.done[0],tag:f});let x=Uo("Tagged",d);return a(x)?x:l(x.message,{...x.value,tag:f})}var nc,oc,rc,Af=h(()=>{"use strict";xe();V();R();te();sn();st();ot();ln();$d();nc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();if(a(o))return o;let r=o.value.tags[e.tagId];if(!r)return i("Tag not found");if(r.tombstoned)return i("Tag is already deleted");let s=[{id:Ho(),...n.value,action:"tombstone.tag",payload:{id:e.tagId}}],d=L(s,t.value.stateBranchRoot);return a(d)?i(d.message):l("Deleted tag",{id:r.id,name:r.name})},oc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();if(a(o))return o;let r=o.value.tags[e.tagId];if(!r)return i("Tag not found");if(!r.tombstoned)return i("Tag is not deleted");if(I.findTagByName(r.name))return i(`Cannot restore: another tag is already named "${r.name}"`);let s=[{id:Ho(),...n.value,action:"restore.tag",payload:{id:e.tagId,name:r.name}}],d=L(s,t.value.stateBranchRoot);return a(d)?i(d.message):l("Restored tag",{id:r.id,name:r.name})},rc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!k(r))return i("Untag target must be an issue");if(r.readonly)return i("Cannot untag readonly issue");if(!o.value.tags[e.tagId])return i("Tag not found");let s={id:Ho(),...n.value,action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},d=L([s],t.value.stateBranchRoot);return a(d)?i(d.message):l("Removed issue tag",{id:e.issueId,ref:j(e.issueId),tagId:e.tagId})}});import{ulid as un}from"ulid";var $x,Cf,sc,wf,ic,ac,jx,dc,cc,lc,Tf=h(()=>{"use strict";R();M();Tt();Mn();bt();xe();Ld();V();dt();sn();st();ot();ln();$x=()=>{let e=$e(),t=a(e)?[]:e.value.eventLog??[],n=new Map;for(let o of t)o.userId&&o.userName&&n.set(o.userId,o.userName);return n},Cf=(e,t)=>{let n=new Map(e);for(let o of Object.values(t))n.set(o.id,o.name);return n},sc=async e=>{let t=Ti(e.name,"name");if(a(t))return i(t.message);let n=await K(e.repoRoot,{pull:!1});if(a(n))return n;let o=J();if(a(o))return o;let r=Y();if(a(r))return r;let s=o.value,d=!!r.value.contributors[s.userId];if(!d){let c=L([{id:un(),...s,action:"create.contributor",payload:{id:s.userId,name:s.userName}}],n.value.stateBranchRoot);if(a(c))return i(c.message)}return l(`Assumed ${s.userName}`,{...s,registered:!d})},wf=async(e,t)=>{let n=ra(e);if(a(n))return;let o;for(let r of n.value)r.userId===t&&(o=r.userName??o);return o===void 0?void 0:{id:t,name:o}},ic=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!k(r))return i("Assign target must be an issue");if(r.readonly)return i("Cannot assign readonly issue");let s=e.self?n.value.userId:e.assigneeId;if(s){let T=o.value.contributors[s],w=T?void 0:await wf(t.value.stateBranchRoot,s);if(!T&&!w)return i("Unknown assignee id");let _=T??w,B=[...T?[]:[{id:un(),...n.value,action:"create.contributor",payload:{id:_.id,name:_.name}}],{id:un(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:_.id}}],$=L(B,t.value.stateBranchRoot);return a($)?i($.message):l("Added issue assignee",{id:e.issueId,ref:j(e.issueId),assignee:{id:_.id,name:_.name}})}let d=pe(e.assigneeName??"").trim();if(!d)return i("Provide assigneeId, self or assigneeName");let c=Ke("Assignee name",d,80);if(c)return i(c);let m=[...Cf($x(),o.value.contributors).entries()].filter(([,T])=>T===d);if(m.length>1)return i(`"${d}" matches ${m.length} contributors (${m.map(([T])=>T).join(", ")}). Assign by assigneeId to choose.`);let p=m[0];if(!p&&!e.createUnlinked)return i(`No contributor named "${d}". Assign by id, or pass createUnlinked to add them as an external assignee.`);let[f=un(),x=d]=p??[],A=[...!!o.value.contributors[f]?[]:[{id:un(),...n.value,action:"create.contributor",payload:{id:f,name:x}}],{id:un(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:f}}],P=L(A,t.value.stateBranchRoot);return a(P)?i(P.message):l("Added issue assignee",{id:e.issueId,ref:j(e.issueId),assignee:{id:f,name:x}})},ac=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();if(a(o))return o;if(!o.value.contributors[e.contributorId])return i("Contributor not found");if(await wf(t.value.stateBranchRoot,e.contributorId))return i("Cannot remove a contributor who has authored events \u2014 their name appears throughout the log");let d=[{id:un(),...n.value,action:"tombstone.contributor",payload:{id:e.contributorId}}],c=L(d,t.value.stateBranchRoot);return a(c)?i(c.message):l("Tombstoned contributor",{id:e.contributorId,name:es})},jx=async(e,t)=>{let n=Hn(e);if(a(n))return;let o;for(let r of n.value){if(r.action!=="create.contributor")continue;let s=r.payload;s.id===t&&s.name&&(o=s.name)}return o},dc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();if(a(o))return o;let r=o.value.contributors[e.contributorId];if(!r)return i("Contributor not found");if(!r.tombstoned)return i("Contributor is not tombstoned");let s=await jx(t.value.stateBranchRoot,e.contributorId);if(!s)return i("Cannot restore this contributor \u2014 no original name found in the event log");let d=[{id:un(),...n.value,action:"restore.contributor",payload:{id:e.contributorId,name:s}}],c=L(d,t.value.stateBranchRoot);return a(c)?i(c.message):l("Restored contributor",{id:e.contributorId,name:s})},cc=async(e={})=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();if(a(o))return o;let r=Hn(t.value.stateBranchRoot);if(a(r))return i(r.message);let s=e.boardId?hf(r.value,e.boardId):r.value,d=new Map,c=new Set,u=new Set,m=ra(t.value.stateBranchRoot);if(a(m))return i(m.message);for(let S of m.value)S.userId&&u.add(S.userId);for(let S of s)S.userId&&(d.set(S.userId,S.userName??""),c.add(S.userId));let p=o.value.contributors,x=[...Cf(d,p).entries()].map(([S,A])=>({id:S,name:A,color:Ce(A),isSelf:S===n.value.userId,isExternal:!c.has(S),isRemoved:p[S]?.tombstoned===!0,hasAuthoredAnywhere:u.has(S)}));return l("Listed board contributors",x)},lc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!k(r))return i("Unassign target must be an issue");if(r.readonly)return i("Cannot unassign readonly issue");if(!o.value.contributors[e.assigneeId])return i("Assignee not found");let s={id:un(),...n.value,action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},d=L([s],t.value.stateBranchRoot);return a(d)?i(d.message):l("Removed issue assignee",{id:e.issueId,ref:j(e.issueId),assigneeId:e.assigneeId})}});import{ulid as Si}from"ulid";var uc,mc,pc,Mf=h(()=>{"use strict";xe();V();R();sn();ln();uc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!k(r))return i("Comment target must be an issue");if(r.readonly)return i("Cannot comment on readonly issue");let s=e.body.trim();if(!s)return i("Comment cannot be empty");if(s.length>4e3)return i(`Comment cannot exceed ${4e3} characters (got ${s.length})`);let d=Si(),c={id:Si(),...n.value,action:"add.issue.comment",payload:{id:d,issue:e.issueId,md:s,author:n.value.userId}},u=L([c],t.value.stateBranchRoot);return a(u)?i(u.message):l("Added issue comment",{id:d,issueId:e.issueId,body:s})},mc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();if(a(o))return o;let r=o.value.eventLog.find(m=>m.action==="add.issue.comment"&&m.payload.id===e.commentId);if(!r)return i("Unable to resolve comment");if(r.payload.author!==n.value.userId)return i("You can only delete your own comments");let s=o.value.nodes[r.payload.issue];if(!s)return i("Issue not found");if(!k(s))return i("Comment target must be an issue");if(s.readonly)return i("Cannot delete comment on readonly issue");if(o.value.eventLog.some(m=>m.action==="delete.issue.comment"&&m.payload.id===e.commentId))return l("Comment already deleted",{id:e.commentId,issueId:r.payload.issue});let c={id:Si(),...n.value,action:"delete.issue.comment",payload:{id:e.commentId,issue:r.payload.issue}},u=L([c],t.value.stateBranchRoot);return a(u)?i(u.message):l("Deleted issue comment",{id:e.commentId,issueId:r.payload.issue})},pc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();if(a(o))return o;let r=o.value.eventLog.find(p=>p.action==="add.issue.comment"&&p.payload.id===e.commentId);if(!r)return i("Unable to resolve comment");if(r.payload.author!==n.value.userId)return i("You can only edit your own comments");let s=o.value.nodes[r.payload.issue];if(!s)return i("Issue not found");if(!k(s))return i("Comment target must be an issue");if(s.readonly)return i("Cannot edit comment on readonly issue");if(o.value.eventLog.some(p=>p.action==="delete.issue.comment"&&p.payload.id===e.commentId))return i("Comment was deleted");let c=e.body.trim();if(!c)return i("Comment cannot be empty");if(c.length>4e3)return i(`Comment cannot exceed ${4e3} characters (got ${c.length})`);let u={id:Si(),...n.value,action:"edit.issue.comment",payload:{id:e.commentId,issue:r.payload.issue,md:c}},m=L([u],t.value.stateBranchRoot);return a(m)?i(m.message):l("Edited issue comment",{id:e.commentId,issueId:r.payload.issue,body:c})}});var kf=h(()=>{"use strict";Ef();Sf();Nf();Af();Tf();Mf();_d()});import{ulid as Hx}from"ulid";var Pf,Lf,Df,Ff=h(()=>{"use strict";Mn();vo();Ut();R();pd();ht();Pf=[{name:"userName",question:"the name they want to appear under on the board"},{name:"preferredEditor",question:'the command that opens a file for editing, e.g. "vim", "nano" or "code --wait"'},{name:"autoSync",question:"whether the TUI and GUI should sync with the git remote on their own (true or false)"}],Lf=e=>e.trim().toLowerCase(),Df=async(e={})=>{let t=Io();if(a(t))return i(t.message);let n=t.value,o=e.userName?.trim(),r=(process.env[lt]??"").trim();if(o&&r&&Lf(o)===Lf(r))return i(`userName "${o}" is this agent's own identity. Pass the user's name, the one they want the TUI and GUI to write as.`);let s={userName:o||void 0,preferredEditor:e.preferredEditor?.trim()||void 0,autoSync:e.autoSync},d={userName:n.userName?.trim()||void 0,preferredEditor:n.preferredEditor?.trim()||void 0,autoSync:typeof n.autoSync=="boolean"?n.autoSync:void 0};for(let T of Pf){let w=s[T.name],_=d[T.name];if(!(w===void 0||_===void 0||w===_))return i(`This machine is already set up with ${T.name} ${JSON.stringify(_)}; epiq_project_init does not change it. Call again without ${T.name}, or let the user change it in the TUI with :config.`)}let c={};if(s.userName&&!d.userName&&(c.userName=s.userName),s.preferredEditor&&!d.preferredEditor&&(c.preferredEditor=s.preferredEditor),s.autoSync!==void 0&&d.autoSync===void 0&&(c.autoSync=s.autoSync),(c.userName||d.userName)&&!n.userId&&(c.userId=Hx()),Object.keys(c).length>0){let T=Ve(c);if(a(T))return i(T.message)}let u={...n,...c},m=Pf.filter(T=>{let w=u[T.name];return typeof w=="boolean"?!1:!w?.trim()});if(m.length>0){let T=m.map(w=>`${w.name} (${w.question})`).join("; ");return i(`Setup incomplete. Ask the user for: ${T}. Then call epiq_project_init again with the answers; what was given so far is saved.`)}let p={userId:u.userId??"",userName:u.userName??""};if(!p.userId||!p.userName)return i("Missing Epiq user id");let f=await li({cwd:e.repoRoot??process.cwd(),user:p});if(a(f))return f;let{defaultEvents:x,...S}=f.value,A=Rr({root:S.repoRoot});a(A)&&X.info(A.message);let P=S.warnings.length===0?"Project initialized":`Project initialized, with warnings: ${S.warnings.join(" ")}`;return l(P,{...S,user:p})}});var Wo,gc,_f=h(()=>{"use strict";Wo=".claude/skills/epiq/SKILL.md",gc="---\nname: epiq\ndescription: Workflow rules for working the epiq issue board \u2014 use the epiq MCP, sync on demand, scope tickets small, keep status/tags accurate, and communicate via comments.\n---\n\n# Epiq board workflow\n\n- **Never test against the real board.** Point any dev server, manual test or test run at a throwaway project, never at this repo's own. Deleting test tickets afterwards does not undo the events. Stop the dev server when you're done rather than leaving it autosyncing.\n- **Use the epiq MCP tools** (`epiq_*`) for all board operations \u2014 never the `epiq` CLI or hand-edited state files.\n- **Never edit the state branch directly.** Don't check it out, don't write to its worktree, don't touch the event log or any file under it by hand or by script \u2014 go through the MCP for every read and write. The event log is the system of record: an edit made outside it bypasses validation and ordering, and can corrupt history in ways no later fix can undo.\n- **Sync is on-demand only.** MCP reads/writes operate on local state and never pull/push automatically. Call `epiq_sync` explicitly when you need the latest remote state or want to publish local changes.\n- **Break work into small, scoped tickets.** One ticket per independent unit of work, not one giant ticket for a whole feature/epic. Small tickets move through the board cleanly and are easier to review.\n- **A small request tightly coupled to a ticket goes into that ticket, not a new one.** When the user asks for a tweak that only makes sense as part of work a ticket already covers \u2014 halving a limit it just introduced, moving a control it just added \u2014 do not file a fresh ticket for it. Record the new requirement as a comment on the original ticket and fold it into the description, move the ticket back to Ongoing if it had already reached Done, prefix the follow-up's commits with that ticket's ref, and add a further `Solution:` comment when it lands, so the ticket's own commit list tells the whole story. `QPPR7PE` is what this avoids: a one-line follow-up to `MBB6WY5` (halve the log cap it had just introduced) that now lives on a ticket of its own. The original does not have to be the ticket you took this session: any ticket open on the board and assigned to you counts. A new ticket is for work that stands on its own \u2014 that someone else could pick up cold, or that needs more than a line or two to describe.\n- **Keep the status column current as work progresses**\n- **Assign the ticket to yourself when you pick it up**, alongside moving it to Ongoing \u2014 so the board shows who is on what, not just what is in flight.\n- **A ticket you file for work you will do this session is assigned to you as you file it.** Filing it unassigned and picking it up a minute later leaves a window where the board shows nobody on it. Picking up a ticket assigned to somebody else is fine \u2014 but ask the user first: it may be mid-flight in another session, and the assignee is what says so.\n- **Take a name as soon as this skill loads, and say it.** Your board identity is `provider/human-name` \u2014 the model provider, a slash, then a short human first name: `claude/peter`, `codex/fred`. Announce it as your first line, exactly `Assuming claude/peter`, and work under it for the whole session so the log reads \"claude/peter did X\" rather than signing the user's name to your work. Before inventing one, call `epiq_contributor_list` and reuse an existing identity for your provider if there is one \u2014 a name is permanent once it has authored anything (`tombstoneContributor` refuses authors), and each new one adds a contributor and an event log file forever. Keep the name stable across sessions; never rename yourself mid-session.\n- **Make the name true with `epiq_actor_assume`, before your first board write.** Announcing alone changes nothing: the writes would still be signed with the user's name. The tool takes the identity for the rest of the session and registers it, so the board carries `claude/peter` rather than the sanitized `claude-peter` the log file name would give. It is idempotent, so re-announcing is free; if it refuses because the server was launched under a name, that name wins \u2014 work under the one it reports and say so. Never claim an attribution the tool did not confirm.\n- **Boot your own MCP instance, and never share one.** `epiq_actor_assume` binds the name to the server process it is called on, so two sessions on one server \u2014 or a session on the user's own instance \u2014 would sign every write with whichever name was assumed last, and the log would fold them into one contributor. Every session therefore needs a server process of its own before its first board call: the one Claude Code spawns for the session counts, and if that never connected (a `CONNECT_TIMEOUT` at boot), start one yourself \u2014 `npx -y -p epiq@latest epiq-mcp` speaks MCP JSON-RPC over stdio, so a small script holding that process and forwarding `tools/call` requests is enough \u2014 rather than waiting on the user or borrowing another session's. Assume the name on *that* process; a restart forgets it, so assume it again before the next write. Kill what you started when the session ends, including the `epiq-mcp` child, which outlives its parent.\n- **When other agents may be running, ask which name to take rather than picking one.** Nothing stops two live agents answering to one name \u2014 the log is a CRDT and takes concurrent writers happily, so they would converge into one indistinguishable identity rather than fail. Another session is likely whenever there is more than one `epiq-mcp` process, another worktree with recent changes, or the user says so; in that case list the existing names for your provider from `epiq_contributor_list` and ask the user which one is free, before `epiq_actor_assume` \u2014 a name once assumed binds the server process, and a second name is refused until it restarts. Ask with the names in the question, not \"which name?\": the user is choosing between identities they can see on the board.\n- **Name the terminal window after the identity.** Several sessions look alike; the name in the tab is how the user tells which window is `claude/peter`. The session cannot reach the terminal itself \u2014 the shell it runs has no tty \u2014 so put the request in the announcement line: `Assuming claude/peter \u2014 please /rename claude/peter so this window carries the name.`\n- **Prefix commits with the ticket ref. **Retrieve the ref programmatically, NEVER DERIVE IT.\\*\\* Read the `ref` field off the MCP response (`epiq_issue_list` and `epiq_board_list` include it on every entry). This is what link-by-reference feature matches on.\n- **Work in a worktree, and leave the root checkout alone.** Take one before the first edit (`EnterWorktree`, or `git worktree add .claude/worktrees/<ref>-<slug>` for a branch that already exists), and never check a feature branch out at the root: the root is where `main` belongs and where the user checks it out themselves, and a branch checked out anywhere is unavailable everywhere else. For the same reason `main` never goes *into* a worktree. Several sessions share this repository at once, so a shared checkout also means one session's `checkout` or `reset` quietly discarding another's work. A fresh worktree needs its own `npm install` before the hooks and suites will run there.\n- **Never work on main, and never merge into it locally. Every change reaches main through a pull request.** Branch before the first edit, push the branch, open the PR, let the gate run, then integrate it. A local merge into `main` looks like it worked and is invisible to everyone else: the work is on nobody's remote, no PR ran the gate over it, and it is one `git fetch origin +main:main` away from vanishing from the branch you are sitting on. That has already happened here \u2014 a tag-filter feature and a scrubber-URL feature lived only in one machine's local `main` for a day, and disappeared the moment somebody synced main with the remote. If you find yourself with commits on local `main`, move them onto a branch and open a PR before doing anything else.\n- **Always rebase onto the target, never merge into it.** Rebase the branch onto the target first, then integrate with a rebase merge \u2014 `gh pr merge --rebase`, never `--merge`. Main stays a flat sequence of ref-prefixed commits, which is what the commit\u2194ticket linking reads. A merge commit adds a subject carrying no ref and buries the branch's commits behind it.\n- **Squashing the branch down first is fine \u2014 one commit per ticket ref.** A branch's worth of fixups is history nobody needs on main, so collapsing it into a single commit (`git rebase -i`, or `gh pr merge --squash` with a ref-prefixed subject) is welcome, provided every commit that lands still opens with its ticket's ref. What the linking cannot survive is a squash *across* refs: fold two tickets' commits into one subject and one of them loses its commits for good. So a branch carrying two refs squashes to two commits, not one \u2014 and check the resulting subject before integrating, because `--squash` defaults to the PR title, which is only right if the title carries the ref.\n- **The git user is the sole author of every commit you write.** Commit under the repo's configured `user.name` / `user.email` and nothing else: no `Co-Authored-By:` line, no `Claude-Session:` line, no `\u{1F916} Generated with` footer, and never an `--author` override naming Claude or a tool. The commit body ends with the last line of prose. This holds for amends and rebases too \u2014 check `git log --format='%an <%ae>%n%b'` over the branch before pushing, because a trailer added by a default template survives a rebase and reaches main unnoticed. It does **not** license rewriting anyone else's authorship: commits by other contributors keep their author, and reassigning them would both misattribute their work and mean force-pushing main.\n- **Tag tickets properly.** Reuse existing tags where they fit (check current issues/tags first) instead of inventing near-duplicates.\n- **Read the ticket's comments before starting, not just its description.** The description is what was known when the ticket was written; comments carry later context \u2014 narrowed scope, a decision already taken, a dead end someone hit, a correction to the original diagnosis. Working from the description alone risks redoing settled work or implementing something that was already ruled out.\n- **Use comments to communicate deviations.** If the work diverges from what the ticket describes \u2014 scope changes, findings, blockers, test results \u2014 record it as a comment on the ticket, not just in chat.\n- When a ticket is done, **Document the outcome in a comment starting with `Solution:`.** Use that exact prefix as the comment's opening line, so `^Solution:` finds every resolved ticket on the board. Say what actually resolved it \u2014 the commit, the approach taken, and anything a reader would otherwise have to reverse-engineer from the diff; a bare commit hash is not a solution. Use the same prefix when a ticket is closed _without_ a code change, and say why.\n- **Attach a screenshot only when a picture carries what words cannot** \u2014 a layout that has to be seen, a rendering bug, a chart whose shape is the point. It is the special case, not a routine part of a `Solution:` comment: most outcomes are better described than photographed, and a screenshot of something a sentence already covers costs everyone the bytes below. When one does earn its place, use `epiq_issue_attachment_add` (it takes a file path) and paste the `markdown` it returns into the comment.\n- **Crop and compress it first.** `epiq_issue_attachment_add` stores the file exactly as it finds it \u2014 only the GUI compresses on upload \u2014 so a raw full-screen capture goes in at full size, up to the 500 KB cap. The blob lands in `.epiq/media/` on the state branch, replicates to every clone, and is never removed: deleting an attachment writes a tombstone and the bytes stay, so time travel can still resolve them. Crop to the region that makes the point, scale it down, and land well under the cap rather than against it. An oversized image is permanent, for everybody \u2014 the same reason the text limits exist.\n- **Be concise.** Titles, descriptions, and comments should be scannable, not essays.\n- If a ticket is blocked, **record the blocker in a comment** and move it to Blocked (or tag it blocked if there is no Blocked column).\n- If a you decide to take a new approach, make sure to document the fork in a new comment, and tag the ticket with a \"fork\" tag, **update the description** to reflect the new plan. Don't leave it as-is and expect readers to infer the change from comments.\n- **Park decisions that are the user's to make.** A design fork, a change with blast radius beyond its ticket, anything you'd want a second opinion on \u2014 file a ticket tagged `human-input-needed` naming the options and the trade-off, then carry on with whatever doesn't depend on the answer. Settling it alone in chat, while nobody is reading, is a decision the user never made.\n- **Findings from a code review get their own tickets**, tagged `from-review`, with the description saying which branch or PR the review covered \u2014 so the provenance survives even if the tag doesn't.\n"});import Ni from"node:fs";import Bf from"node:path";var Of,Uf=h(()=>{"use strict";We();R();_f();Of=async(e={})=>{let t=await rt(e.repoRoot??process.cwd());if(a(t))return i(t.message);let n=Bf.join(t.value,Wo);if(Ni.existsSync(n)){if(Ni.readFileSync(n,"utf8")===gc)return l("Skill already installed and up to date",{path:n,written:!1});if(!e.force)return i(`${Wo} already exists and differs from the bundled skill. Pass force:true to overwrite it.`)}try{Ni.mkdirSync(Bf.dirname(n),{recursive:!0}),Ni.writeFileSync(n,gc,"utf8")}catch(o){return i(o instanceof Error?`Failed to write ${Wo}: ${o.message}`:`Failed to write ${Wo}`)}return l(`Installed skill at ${Wo}`,{path:n,written:!0})}});var Hf={};Jr(Hf,{createMcpServer:()=>jf,resultJson:()=>$f,startMcpServer:()=>zx});import{McpServer as qx}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Gx}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as v}from"zod";var $f,Q,jf,zx,Wf=h(()=>{"use strict";R();sn();kf();Ff();Uf();zr();$f=e=>({isError:a(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),Q=e=>t=>yf(async()=>$f(await e(t))),jf=()=>{let e=new qx({name:"epiq",version:"0.2.30"});return e.registerTool("epiq_state_get",{description:"Get the full current Epiq state, including nodes and event log",inputSchema:v.object({repoRoot:v.string().optional()})},Q(Bd)),e.registerTool("epiq_issue_list",{description:"List Epiq issues. Narrow with boardId, swimlaneId, tag, assignee or query (matched against title and description), and pass brief to get id, ref, title, swimlane, tag names and assignee names only \u2014 descriptions are the bulk of a board. Read one ticket with epiq_issue_get.",inputSchema:v.object({repoRoot:v.string().optional(),includeClosed:v.boolean().optional(),boardId:v.string().optional(),swimlaneId:v.string().optional(),tag:v.string().optional(),assignee:v.string().optional(),query:v.string().optional(),brief:v.boolean().optional()})},Q(Hd)),e.registerTool("epiq_issue_get",{description:"Get one Epiq issue by its full id or its 7-character ref, with its comments in log order. Use this rather than listing the whole board when you already know which issue you want, and rather than epiq_state_get to read a thread.",inputSchema:v.object({idOrRef:v.string().min(1),repoRoot:v.string().optional()})},Q(jd)),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:v.object({repoRoot:v.string().optional()})},Q(Yd)),e.registerTool("epiq_swimlane_list",{description:"List Epiq swimlanes",inputSchema:v.object({repoRoot:v.string().optional(),boardId:v.string().optional()})},Q(Xd)),e.registerTool("epiq_swimlane_create",{description:"Create an Epiq swimlane on a board",inputSchema:v.object({repoRoot:v.string().optional(),boardId:v.string().min(1),title:v.string().min(1).max(300)})},Q(Jd)),e.registerTool("epiq_swimlane_title_edit",{description:"Edit an Epiq swimlane title",inputSchema:v.object({repoRoot:v.string().optional(),swimlaneId:v.string().min(1),title:v.string().min(1).max(300)})},Q(Qd)),e.registerTool("epiq_swimlane_move",{description:"Move/reorder an Epiq swimlane, optionally to another board",inputSchema:v.object({repoRoot:v.string().optional(),swimlaneId:v.string().min(1),boardId:v.string().min(1),position:v.discriminatedUnion("at",[v.object({at:v.literal("start")}),v.object({at:v.literal("end")}),v.object({at:v.literal("before"),sibling:v.string().min(1)}),v.object({at:v.literal("after"),sibling:v.string().min(1)})]).optional()})},Q(Zd)),e.registerTool("epiq_swimlane_delete",{description:"Delete (archive) an Epiq swimlane. This also archives every issue contained in it.",inputSchema:v.object({repoRoot:v.string().optional(),swimlaneId:v.string().min(1)})},Q(ec)),e.registerTool("epiq_issue_create",{description:"Create an Epiq issue. Optionally set description, tags, and assignees atomically in the same call instead of separate follow-up edits.",inputSchema:v.object({title:v.string().min(1).max(300),parentId:v.string().min(1),repoRoot:v.string().optional(),description:v.string().max(2e4).optional(),tagNames:v.array(v.string().max(60)).max(20).optional(),assigneeNames:v.array(v.string().max(80)).max(20).optional()})},Q(Wd)),e.registerTool("epiq_issue_description_edit",{description:"Edit the markdown description of an Epiq issue",inputSchema:v.object({issueId:v.string().min(1),description:v.string().max(2e4),repoRoot:v.string().optional()})},Q(Vd)),e.registerTool("epiq_issue_title_edit",{description:"Edit the title of an Epiq issue",inputSchema:v.object({issueId:v.string().min(1),title:v.string().min(1).max(300),repoRoot:v.string().optional()})},Q(Kd)),e.registerTool("epiq_issue_tag_add",{description:"Add a tag to an Epiq issue, or to many at once with issueIds, creating the tag if it does not exist",inputSchema:v.object({issueId:v.string().min(1).optional(),issueIds:v.array(v.string().min(1)).min(1).max(200).optional(),tagName:v.string().min(1).max(60),repoRoot:v.string().optional()})},Q(tc)),e.registerTool("epiq_issue_tag_remove",{description:"Remove a tag from an Epiq issue",inputSchema:v.object({issueId:v.string().min(1),tagId:v.string().min(1),repoRoot:v.string().optional()})},Q(rc)),e.registerTool("epiq_contributor_list",{description:"List people who can be assigned: everyone who has authored an event (optionally scoped to one board) unioned with the contributor registry. Use these ids with epiq_issue_assignee_add rather than assigning by name.",inputSchema:v.object({boardId:v.string().min(1).optional(),repoRoot:v.string().optional()})},Q(cc)),e.registerTool("epiq_contributor_remove",{description:"Remove an external contributor from the assignee suggestion lists. Their id and every reference to it survive, so existing assignments stay intact and the event log is untouched. Refused for anyone who has authored events, since their name is in the log regardless.",inputSchema:v.object({contributorId:v.string().min(1),repoRoot:v.string().optional()})},Q(ac)),e.registerTool("epiq_tag_remove",{description:"Delete a tag from the whole workspace. It disappears from every ticket, picker and filter, but its id and history stay in the event log, and the name is free for a new tag.",inputSchema:v.object({tagId:v.string().min(1),repoRoot:v.string().optional()})},Q(nc)),e.registerTool("epiq_tag_restore",{description:"Put back a tag deleted with epiq_tag_remove, on every ticket that still carried it.",inputSchema:v.object({tagId:v.string().min(1),repoRoot:v.string().optional()})},Q(oc)),e.registerTool("epiq_contributor_restore",{description:"Put a contributor removed with epiq_contributor_remove back into the suggestion lists, under the name they were created with.",inputSchema:v.object({contributorId:v.string().min(1),repoRoot:v.string().optional()})},Q(dc)),e.registerTool("epiq_issue_assignee_add",{description:"Assign a contributor to an Epiq issue. Pass self:true to assign yourself. Prefer assigneeId otherwise, which assigns a known contributor (from the registry or the event log) and fails if the id is unknown. assigneeName matches an existing contributor by name; to create somebody new from a name you must also pass createUnlinked, which adds them as an external (non-contributor) assignee.",inputSchema:v.object({issueId:v.string().min(1),assigneeId:v.string().min(1).optional(),self:v.boolean().optional(),assigneeName:v.string().min(1).max(80).optional(),createUnlinked:v.boolean().optional(),repoRoot:v.string().optional()})},Q(ic)),e.registerTool("epiq_issue_assignee_remove",{description:"Remove an assignee from an Epiq issue",inputSchema:v.object({issueId:v.string().min(1),assigneeId:v.string().min(1),repoRoot:v.string().optional()})},Q(lc)),e.registerTool("epiq_issue_comment_add",{description:"Add a comment to an Epiq issue",inputSchema:v.object({issueId:v.string().min(1),body:v.string().min(1).max(4e3),repoRoot:v.string().optional()})},Q(uc)),e.registerTool("epiq_issue_attachment_add",{description:"Attach an image file to an Epiq issue. Returns `markdown` \u2014 paste it into a comment or description body to render the image inline.",inputSchema:v.object({issueId:v.string().min(1),filePath:v.string().min(1),name:v.string().min(1).max(200).optional(),repoRoot:v.string().optional()})},Q(Fd)),e.registerTool("epiq_issue_comment_delete",{description:"Delete a comment from an Epiq issue",inputSchema:v.object({commentId:v.string().min(1),repoRoot:v.string().optional()})},Q(mc)),e.registerTool("epiq_issue_comment_edit",{description:"Replace the body of one of your own comments on an Epiq issue",inputSchema:v.object({commentId:v.string().min(1),body:v.string().min(1).max(4e3),repoRoot:v.string().optional()})},Q(pc)),e.registerTool("epiq_issue_reopen",{description:"Reopen a closed Epiq issue, restoring it to its previous swimlane",inputSchema:v.object({issueId:v.string().min(1),repoRoot:v.string().optional()})},Q(Gd)),e.registerTool("epiq_issue_close",{description:"Close an Epiq issue, or many at once with issueIds \u2014 one call, an outcome per ticket",inputSchema:v.object({issueId:v.string().min(1).optional(),issueIds:v.array(v.string().min(1)).min(1).max(200).optional(),repoRoot:v.string().optional()})},Q(qd)),e.registerTool("epiq_issue_move",{description:"Move an Epiq issue to another swimlane, or many at once with issueIds \u2014 one call, an outcome per ticket",inputSchema:v.object({issueId:v.string().min(1).optional(),issueIds:v.array(v.string().min(1)).min(1).max(200).optional(),parentId:v.string().min(1),position:v.discriminatedUnion("at",[v.object({at:v.literal("start")}),v.object({at:v.literal("end")}),v.object({at:v.literal("before"),sibling:v.string().min(1)}),v.object({at:v.literal("after"),sibling:v.string().min(1)})]).optional(),repoRoot:v.string().optional()})},Q(zd)),e.registerTool("epiq_actor_assume",{description:'Take a board identity for the rest of this session, so your writes are attributed to you rather than to the user. Pass the name you announced \u2014 the model provider, a slash, then a short human first name, e.g. "claude/peter". Takes effect on the very next write; no relaunch. A name the server was launched with wins, and re-assuming the same name is harmless. Reuse an existing agent identity (epiq_contributor_list) before inventing one: a name is permanent once it has authored anything.',inputSchema:v.object({name:v.string().min(1).max(80),repoRoot:v.string().optional()})},Q(sc)),e.registerTool("epiq_project_init",{description:`Set up a new Epiq board in a git repository without the TUI. Runs in the repository at repoRoot (default: the current directory), which must have no uncommitted changes. The first time on a machine it also records the user's setup: ask the user for userName (how they want to appear on the board), preferredEditor (e.g. "vim" or "code --wait") and autoSync (whether the TUI and GUI sync with the remote on their own) and pass them here; called without them it fails naming what is still missing, keeping whatever was given. It fills in answers the machine lacks and refuses to change ones it has. Pass the user's name, never your own agent identity. Commits the state branch and .epiq/project.json and tries to push both; a push that fails is a warning, not an error. Afterwards the other tools work in that repository.`,inputSchema:v.object({repoRoot:v.string().optional(),userName:v.string().min(1).max(80).optional(),preferredEditor:v.string().min(1).max(200).optional(),autoSync:v.boolean().optional()})},Q(Df)),e.registerTool("epiq_skill_install",{description:"Write the official Epiq workflow skill into the repository at .claude/skills/epiq/SKILL.md, so agents working there follow the same board rules. Run it after epiq_project_init, not before: the new file is an uncommitted change that init refuses. In a project that already has a board, run it any time. Refuses to overwrite a differing file unless force is true; an identical file is left alone.",inputSchema:v.object({repoRoot:v.string().optional(),force:v.boolean().optional()})},Q(Of)),e.registerTool("epiq_sync",{description:"Sync Epiq state with the configured Git remote (pull remote changes and push local ones). Other Epiq MCP tools only read and write local state and never sync automatically \u2014 call this on demand when you need to see or publish the latest remote changes.",inputSchema:v.object({repoRoot:v.string().optional()})},Q(Od)),e},zx=async()=>{let e=jf(),t=new Gx;await e.connect(t)}});process.env.EPIQ_MCP="true";console.log=console.error;console.info=console.error;console.debug=console.error;console.warn=console.error;var{applyActorNameArgument:Vx}=await Promise.resolve().then(()=>(Mn(),bc)),{isFail:Kx}=await Promise.resolve().then(()=>(R(),hc)),Ai=process.argv.slice(2);Ai.length>1&&(console.error(`Expected at most one name argument, got ${Ai.length}`),process.exit(1));if(Ai[0]!==void 0){let e=Vx(Ai[0],"The name argument");Kx(e)&&(console.error(e.message),process.exit(1))}var{setVirtualNodesEnabled:Yx}=await Promise.resolve().then(()=>(Xi(),ff));Yx(!1);var{startMcpServer:Xx}=await Promise.resolve().then(()=>(Wf(),Hf));await Xx();
|
|
90
|
+
`,qd.writeFileSync(t,n,"utf8"),J.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),l("Local epiq paths ignored",!0)}});import fE from"node:fs";import Mf from"node:path";var gE,xe,Li,Gd=h(()=>{"use strict";kf();Cs();Xe();ct();Or();to();Ce();Yn();R();ae();nn();gE=async e=>{let t=await W({cwd:e,args:["status","--porcelain"]});return d(t)?t:l("Checked git diff",t.value.stdout.split(`
|
|
91
|
+
`).filter(n=>n.trim().length>0).map(n=>n.slice(3)))},xe=(e,t)=>a(`[${e}] ${t}`),Li=async({cwd:e,user:t})=>{let n=Ss(),o=await lt(e);if(d(o))return xe(1,o.message);let r=o.value,s=await As(r);if(d(s))return xe(2,s.message);if(s.value)return xe(2,`Cannot initialize Epiq while a git operation is in progress: ${s.value}`);let i=await gE(r);if(d(i))return xe(2.5,i.message);if(i.value.length>0)return xe(3,`Cannot initialize Epiq with uncommitted changes (${i.value.join(", ")}). Commit or stash your changes first.`);if(Nr(r))return xe(4,"Epiq project already initialized");let{userId:c,userName:u}=t;if(!c||!u)return xe(5,"Missing Epiq user id");let m=await dm(r);if(d(m))return xe(6,m.message);let p=n.stateBranch,f=await ws({repoRoot:r,branch:p});if(d(f))return xe(6,f.message);if(f.value)return xe(6,`State branch already exists: ${p}`);let y=await qa({repoRoot:r,stateBranchName:p});if(d(y))return xe(6,y.message);let I=Ms();if(d(I))return xe(7,I.message);let S=Mf.join(ks(),n.projectId),A=await oo({repoRoot:r,stateBranchRoot:S,stateBranchName:p});if(d(A))return xe(8,A.message);let w=Mf.join(S,".epiq");fE.mkdirSync(w,{recursive:!0});let k=Qu({userId:c,userName:u});if(d(k))return xe(9,k.message);for(let Sv of k.value){let ol=Gs({event:Sv,rootDir:S});if(d(ol))return xe(9,ol.message)}let D=Zn({userId:c,userName:u}),_=$s(S,D);if(d(_))return xe(9,_.message);let H=await Js({stateBranchRoot:S,eventFileName:D});if(d(H))return xe(10,H.message);let ie=await xo({cwd:S,message:"[epiq:init]"});if(d(ie))return xe(10,ie.message);let En=await Tf(r);if(d(En))return xe(11,En.message);let en=wl({repoRoot:r,fileContents:n});if(d(en))return xe(12,en.message);let ar=await ye.stage({cwd:r,pathspec:[".epiq/project.json",".gitignore"]});if(d(ar))return xe(13,ar.message);let dr=await ye.commit({cwd:r,message:"[epiq:init-project]",pathspec:[".epiq/project.json",".gitignore"]});if(d(dr))return xe(13,dr.message);let ho=[],tl=await W({cwd:r,args:["push","-u","origin","HEAD"]});d(tl)&&ho.push(`[init:14] ${tl.message}`);let nl=await _r({repoRoot:r,stateBranchRoot:S});return d(nl)&&ho.push(`[init:15] ${nl.message}`),l("Project initialized",{repoRoot:r,projectId:n.projectId,stateBranch:p,stateBranchRoot:S,defaultEvents:k.value,warnings:ho})}});var os,Pf,Lf=h(()=>{"use strict";ut();Hr();ln();pe();R();Gd();ce();We();M();os=(e,t)=>a(`[${e}] ${t}`),Pf=async()=>{te("");let e=ai();if(!e.isSetupDone||!e.userName)return os(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let t=Ie(),n=t.userName,o=t.userId;if(!o||!n)return os(5,"Missing Epiq user id");let r=await Li({cwd:process.cwd(),user:{userId:o,userName:n}});if(d(r))return r;let s="Project initialized!";for(let y of r.value.warnings)s+=` Warn: ${y}`;let c=cn(r.value.defaultEvents).filter(d);if(c.length>0)return os(16,c.map(y=>y.message).join(`
|
|
92
|
+
`));let u=ze();if(d(u))return os(16,u.message);let{rootNodeId:m,nodes:p}=u.value,f=p[m];return f?(U.navigate({contextNode:f,selectedIndex:0}),N({hasProjectDefinition:!0,mode:b.DEFAULT}),l(s,null)):os(16,"Unable to resolve initialized root node")}});import{ulid as hE}from"ulid";function Vd(e){let t=Ff();if(d(t))return t;let{contextNode:n,nodes:o}=g();if(!n.parentNodeId)return a("Missing parent node id");let r=o[n.parentNodeId];if(!r)return a("Missing parent node");let s=ge(r.id),i=s.findIndex(({id:m})=>m===n.id);if(i<0)return a("Current node not found among siblings");let c=s[i+e];if(!c)return a("Missing sibling node");let u=_f({id:t.value.id,parentId:c.id,position:{at:"end"}});return d(u)?u:Of(u.value)}function Kd(e){let t=Ff();if(d(t))return t;let{contextNode:n,selectedIndex:o}=g(),s=ge(n.id)[o+e];if(!s)return a("Missing sibling node");let i=_f({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return d(i)?i:Of(i.value)}var Df,_n,rs,Ff,zd,_f,Of,Yd=h(()=>{"use strict";ln();Ce();R();yt();M();Df=null,_n=()=>structuredClone(Df),rs=e=>{Df=e},Ff=()=>{let{contextNode:e,selectedIndex:t}=g(),o=ge(e.id)[t];return o?l("Resolved selected child",o):a("Target node not found")},zd=({id:e,parentId:t,position:n={at:"end"}})=>{let o=ge(t).filter(r=>r.id!==e);return zs(o,n)},_f=({id:e,parentId:t,position:n={at:"end"}})=>{let o=oe();if(d(o))return a("Unable to resolve user ID");let r=zd({parentId:t,id:e,position:n});return d(r)?r:l("Created pending move state",{id:hE(),...o.value,action:"move.node",payload:{id:e,parent:t,rank:r.value.rank}})},Of=e=>{rs(e);let t=Nn(e,!0);return d(t)?t:l("Node moved successfully",t.value)}});import{ulid as vE}from"ulid";var Bf,Di,Uf,$f=h(()=>{"use strict";ut();Yd();Se();Ce();pe();R();yt();ce();M();ae();Bf=()=>{let e=_n();if(!e)return a("No pending move state");let t=e.payload.id,n=e.payload.parent,o=g().nodes[n];if(!o)return a("Move parent not found");let r=ge(n).findIndex(s=>s.id===t);return r===-1?a("Moved node not found among rendered children"):(U.navigate({contextNode:o,selectedIndex:r}),l("Synchronized navigation to moved node",null))},Di=(e,t="Moved preview")=>{if(d(e))return e;let n=Bf();return d(n)?n:(N({mode:b.MOVE}),l(t,null))},Uf=async()=>{let e=oe();if(d(e))return a("Unable to resolve user ID");let{modifier:t}=de().commandMeta,{contextNode:n,selectedIndex:o}=g(),r=ge(n.id)[o];if(!r)return N({mode:b.DEFAULT}),a("No move target");if(t==="start"){if(r.readonly)return a("Target node is read-only");if(o===-1)return a("No item selected");if(!r.parentNodeId)return a("Target has no parent");let s=ge(r.parentNodeId),i=s.findIndex(({id:f})=>f===r.id);if(i===-1)return a("Target not found among siblings");let c=s[i-1],u=s[i+1],m=u!=null?{at:"before",sibling:u.id}:c!=null?{at:"after",sibling:c.id}:{at:"start"},p=zd({parentId:r.parentNodeId,id:r.id,position:m});return d(p)?p:(rs({id:vE(),action:"move.node",payload:{id:r.id,parent:r.parentNodeId,rank:p.value.rank},...e.value}),N({mode:b.MOVE}),l("Move initialized",null))}if(t==="next")return Di(Kd(1));if(t==="previous")return Di(Kd(-1));if(t==="to-next")return Di(Vd(1));if(t==="to-previous")return Di(Vd(-1));if(t==="confirm"){let s=_n();if(!s)return a("No pending move to confirm");let i=await $t();if(d(i))return i;let c=L([s],i.value);if(d(c))return c;let u=Bf();return d(u)?u:(rs(null),N({mode:b.DEFAULT}),l("Moved item",null))}return t==="cancel"?(rs(null),N({mode:b.DEFAULT}),l("Cancelling move",null)):a("Invalid move modifier")}});import{monotonicFactory as yE,ulid as bE}from"ulid";var xE,Fi,Xd=h(()=>{"use strict";R();xE=yE(),Fi=({name:e,parent:t,rank:n,user:{userId:o,userName:r}})=>{let s=xE();return l("Created issue events",[{id:bE(),userId:o,userName:r,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])}});import{ulid as _i}from"ulid";var jf,Hf=h(()=>{"use strict";ut();Xd();Se();Ce();Ft();R();ne();yt();M();ae();jf=async(e,t)=>{let n=oe();if(d(n))return a("Unable to resolve user ID");let o=await $t();if(d(o))return o;let r=o.value;if(!t.inputString)return a(`provide a name for your ${t.modifier}`);let{breadCrumb:s,contextNode:i,selectedIndex:c}=g(),u=m=>{let p=L([m],r);if(d(p))return p;let f=E.getNode(p.value[0].result.id);if(!f)return a("Created node not found");if(!f.parentNodeId)return p;let y=E.getNode(f.parentNodeId);return y?(U.navigate({contextNode:y,selectedIndex:E.getSiblings(f.parentNodeId).findIndex(({id:I})=>I===f.id)}),p):a("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=g(),p=E.getNode(m);if(!p)return a("Workspace not found");let f=wn(p.id,n.value,r);return d(f)?f:u({id:_i(),action:"add.board",payload:{id:_i(),name:t.inputString,parent:p.id,rank:f.value},...n.value})}if(t.modifier==="swimlane"){let m=it(s,"BOARD");if(d(m))return a("Unable to add swimlane in this context");let p=wn(m.value.id,n.value,r);return d(p)?p:u({id:_i(),action:"add.swimlane",payload:{id:_i(),name:t.inputString,parent:m.value.id,rank:p.value},...n.value})}if(t.modifier==="issue"){let m=se(i.id)[c],p=i.context==="SWIMLANE"?i:i.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let D=it(s,"SWIMLANE");return d(D)?null:D.value})();if(!p)return a("Unable to add issue in this context");let f=wn(p.id,n.value,r);if(d(f))return f;let y=Fi({name:t.inputString,parent:p.id,rank:f.value,user:n.value});if(d(y))return y;let I=y.value,S=L([...I],r);if(d(S))return S;if(!S.value[0])return a("Issue creation failed");let k=I.find(D=>D.action==="add.issue")?.payload.id;return k?(U.navigate({contextNode:p,selectedIndex:E.getSiblings(p.id).findIndex(({id:D})=>D===k)}),l("Issue created",null)):a("Unable to determine ticket id")}return l("Success",null)}});var IE,Wf,EE,qf,SE,Gf,zf=h(()=>{"use strict";bo();Xe();ct();Or();oi();Ka();ti();Ao();to();St();R();nn();M();Lr();ae();Xs();IE=e=>e.some(t=>t.action==="init.workspace"),Wf=async(e,t)=>{let n=Bt(e);return d(n)?a(n.message):Er({cwd:t,branch:n.value})},EE=e=>{let t=Me(process.cwd());if(d(t))return!1;let n=be({repoRoot:t.value});return!d(n)&&n.value===e},qf=async e=>{let t=be({repoRoot:e});if(d(t))return So(3,t.message);let n=t.value,o=await oo({repoRoot:e,stateBranchRoot:n,stateBranchName:Ss().stateBranch});if(d(o))return So(3,o.message);let r=Et(n);if(d(r))return So(3,r.message);if(!IE(r.value.events)){let m=await Wf(e,n);if(d(m)&&logger.info(3,m.message),r=Et(n),d(r))return So(3,r.message)}let{events:s,unreadable:i}=r.value,c=Wt(s,i);if(d(c))return So(4,c.message);N({hasProjectDefinition:!0,hasInitializingEvents:!!s.length});let u=jr({root:e});return d(u)&&logger.info(u.message),l("Loaded project",void 0)},SE=async e=>{let t=be({repoRoot:e});if(d(t))return a(t.message);let n=t.value,o=await qn({repoRoot:n});if(d(o))return a(o.message);if(!o.value)return l("No remote to pull",void 0);let r=await Zs({worktreeRoot:n,operation:"boot pull",fn:()=>Xa(n,()=>(Eo("Pulling"),Wf(e,n)))});if(d(r))return Re(r.message);if(r.value===null)return l("Another process holds the state worktree",void 0);let s=r.value;if(d(s))return Ir(s.message)?(Ys("Offline"),l("Offline",void 0)):Re(s.message);if(!s.value)return no("Already synced"),l("Already synced",void 0);if(!EE(n))return l("Project changed during the pull",void 0);let i=Ja(n);return d(i)?i:(no("Pulled"),l("Pulled and reloaded",void 0))},Gf=e=>{SE(e).then(t=>{d(t)&&logger.info(3,t.message)}).catch(t=>{logger.error(`[boot] pull failed: ${tm(t)}`)})}});import RE from"node:os";import Vf from"node:path";var NE,CE,Kf,Yf=h(()=>{"use strict";zf();Ao();R();ce();M();ae();NE=e=>e==="~"||e.startsWith("~/")?Vf.join(RE.homedir(),e.slice(1)):e,CE=(e,t)=>{let n=e.trim();if(!n)return a("Provide a number from the list or a path to a project");if(/^\d+$/.test(n)){let r=t[Number(n)-1];return r?l("Resolved recent project",r.root):a(`No recent project #${n}`)}let o=Me(Vf.resolve(NE(n)));return d(o)?a(`No epiq project at ${n}`):l("Resolved project path",o.value)},Kf=async()=>{let e=Ei();if(te(""),g().hasProjectDefinition)return a("Already in a project; run epiq from another directory");let t=ii({exclude:process.cwd()}),n=d(t)?[]:t.value,o=CE(e,n);if(d(o))return a(o.message);let r=o.value,s=process.cwd();try{process.chdir(r)}catch(c){return a(`Unable to enter ${r}: ${c instanceof Error?c.message:String(c)}`)}let i=await qf(r);return d(i)?(process.chdir(s),a(i.message)):(Gf(r),l(`Opened ${Rm(r)}`,null))}});var Oi,Jd=h(()=>{"use strict";ut();St();ln();R();M();Oi=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:o})=>{let r=g(),s=_a(n,t);if(d(s))return a(s.message);let{appliedEvents:i,unappliedEvents:c}=s.value,u=bn();if(d(u))return u;let m=cn(i),{fatal:p,skipped:f}=zn(m);if(p.length>0)return bn(),N(r),a(p.map(I=>I.message).join(", "));Vn(f);let y=g().nodes[e];return y?(U.navigate({contextNode:y,selectedIndex:o}),l("",{unappliedEvents:c})):(bn(),N(r),a("Board did not exist at that date"))}});var Xf,Jf=h(()=>{"use strict";Xf=e=>{let t=[],n=0;for(let r=0;r<e.length;r++){let s=r===0?0:Math.max(0,e[r]-e[r-1]);n+=Math.sqrt(s),t[r]=n}let o=n;return t.map((r,s)=>o>0?r/o:(s+1)/e.length)}});var AE,wE,TE,Bi,Ui,uo,Qf,Zf,Qd=h(()=>{"use strict";Ke();ss();ln();pe();R();Jf();M();AE=20,wE=16,TE=150,Bi=null,Ui=null,uo=()=>{Bi!==null&&(clearInterval(Bi),Bi=null),Ui!==null&&(clearTimeout(Ui),Ui=null)},Qf=()=>{uo(),N({mode:b.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},Zf=({events:e,startTime:t,durationMs:n})=>{uo();let o=e.length,r=pr(e.map(f=>$n(f))).map(f=>f??t),s=r[o-1]??Date.now(),i=Xf(r),c=Math.max(1,Math.round(n*AE/1e3)),u=Math.max(Math.round(n/c),wE),m=0,p=0;N({mode:b.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:o,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),Bi=setInterval(()=>{m++;let f=m/c,y=[],I,S;for(;p<o&&i[p]<=f;){let w=e[p],k=Nn(w);if(d(k)){if(wr(k)){p++;continue}Qf();return}y.push(...Ra(w)),I=w,S=r[p],p++}if(p>=o||m>=c){for(;p<o;p++){let k=Nn(e[p]);if(d(k)&&!wr(k))break}let w=g().replay;N({unappliedEvents:[],replay:w&&{...w,progress:1,appliedCount:o}}),uo(),Ui=setTimeout(Qf,TE);return}let A=g().replay;N({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,f),appliedCount:p,totalCount:o,startTime:t,endTime:s,currentTime:I?S??A?.currentTime??t:A?.currentTime??t,currentLabel:I?Zd(I):A?.currentLabel??"",flashNodeIds:I?[...new Set(y)]:A?.flashNodeIds??[]}})},u)}});var eg,tg=h(()=>{"use strict";Xe();Ke();St();ln();pe();Ft();R();ce();M();qr();Jd();Qd();eg=async()=>{let e=it(g().breadCrumb,"BOARD");if(d(e))return e;let t=await lt(process.cwd());if(d(t))return a("Unable to locate repo root");let n=be({repoRoot:t.value});if(d(n))return n;let{modifier:o,inputString:r}=de().commandMeta;if(uo(),o==="now"){let c=Jn(n.value);if(d(c))return a(c.message);let u=bn();if(d(u))return u;let m=cn(c.value),{fatal:p,skipped:f}=zn(m);return p.length>0?a(p.map(y=>y.message).join(", ")):(Vn(f),N({mode:b.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null}),l("Peeking now",!0))}let s;if(o==="prev"||o==="next"){let c=Oa(n.value);if(d(c))return c;let u=o==="prev"?g().eventLog.at(-1):g().unappliedEvents.at(0),m=u===void 0?null:$n(u),p=(u===void 0?null:c.value.get(u.id)??null)??(m===null?null:mr(m));if(p===null)return a(o==="prev"?"No previous event to peek":"No next event to peek");s=o==="prev"?p:p+1}else{let c=so(o||r.trim());if(!c)return a("Invalid peek date");s=c.getTime()}let i=Oi({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return d(i)?i:(N({mode:b.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:i.value.unappliedEvents,replay:null}),l("Peeking",!0))}});var ng,og=h(()=>{"use strict";Xe();Ft();R();ce();M();qr();Jd();Qd();ng=async()=>{let e=it(g().breadCrumb,"BOARD");if(d(e))return e;let t=await lt(process.cwd());if(d(t))return a("Unable to locate repo root");let n=be({repoRoot:t.value});if(d(n))return n;let{modifier:o,inputString:r}=de().commandMeta,{dateInput:s,durationInput:i}=mi(o,r);if(uo(),g().syncStatus.status==="syncing")return a("Cannot replay while syncing, try again in a moment");let c=so(s);if(!c)return a("Invalid replay date");let u=i?ui(i):15e3;if(u===null)return a("Invalid replay duration (try e.g. 30s or 2m)");let m=c.getTime(),p=g(),f=Oi({boardId:e.value.id,targetTime:m,stateBranchRoot:n.value,selectedIndex:-1});if(d(f))return f;let{unappliedEvents:y}=f.value;return y.length===0?(bn(),N(p),l("Nothing to replay from that point",!0)):(Zf({events:y,startTime:m,durationMs:u}),l("Replaying board history",!0))}});import{spawn as ME}from"node:child_process";var PE,rg,sg=h(()=>{"use strict";R();PE=()=>{switch(process.platform){case"darwin":return{command:"pbcopy",args:[]};case"win32":return{command:"clip",args:[]};default:return process.env.WAYLAND_DISPLAY?{command:"wl-copy",args:[]}:{command:"xclip",args:["-selection","clipboard"]}}},rg=async e=>new Promise(t=>{let{command:n,args:o}=PE();try{let r=ME(n,o,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>t(a(`Clipboard tool not available (${n})`))),r.on("close",s=>t(s===0?l("Copied to clipboard",null):a(`Clipboard tool failed (${n})`))),r.stdin.on("error",()=>{}),r.stdin.write(e),r.stdin.end()}catch{t(a(`Clipboard tool not available (${n})`))}})});var is,ig,ag=h(()=>{"use strict";R();M();sg();Je();Wr();pn();is=async(e,t)=>{if(!e.trim())return a(`Nothing to copy: ${t} is empty`);let n=await rg(e);return d(n)?n:l(`Copied ${t} to clipboard`,null)},ig=async e=>{let{breadCrumb:t,selectedNode:n}=g(),o=Gr({breadCrumb:t,selectedNode:n}),r=o??n;if(!r)return a("Nothing selected to copy from");switch(e.modifier){case Ae.REF:return is(j(r.id),"ref");case Ae.TITLE:return is(r.title,"title");case Ae.DESCRIPTION:return o?is(o.props?.description??"","description"):a("No issue in scope");case Ae.TAGS:{if(!o)return a("No issue in scope");let s=Tn(o).map(({name:i})=>i);return is(s.join(", "),"tags")}case Ae.ASSIGNEES:{if(!o)return a("No issue in scope");let s=kn(o).map(({name:i})=>i);return is(s.join(", "),"assignees")}default:return a("Yank one of: ref, title, description, tags, assignees")}}});var dg,cg=h(()=>{"use strict";oi();pe();R();ce();M();dg=async()=>{te(""),N({mode:b.DEFAULT});let e=ze();if(d(e))return a(e.message);if(e.value.syncStatus.status==="syncing")return a("Sync already in progress");N({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await ni();return d(t)?(N({syncStatus:{msg:t.message,status:"failed"}}),t):(N({mode:b.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)}});var _e,Yt=h(()=>{"use strict";R();ae();_e=async()=>{let e=await $t();return d(e)?e:l("Resolved persist root",e.value)}});import{ulid as lg}from"ulid";var LE,ug,mg=h(()=>{"use strict";Se();Ce();K();R();M();Yt();LE=e=>e.action==="add.issue.comment",ug=async()=>{let e=oe();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),o=se(t.id)[n];if(!o)return a("Unable to resolve child to delete");let r=await _e();if(d(r))return r;if(o.context==="COMMENT"){let s=o.id,i=P(t)?t.id:t.parentNodeId;if(!i)return a("Unable to resolve comment issue");let c=g().nodes[i];if(!c||!P(c))return a("Unable to resolve comment issue");let u=c.log?.filter(LE).find(m=>m.payload.id===s);return u?u.payload.author!==e.value.userId?a("You can only delete your own comments"):L([{id:lg(),action:"delete.issue.comment",payload:{id:s,issue:i},...e.value}],r.value):a("Unable to resolve comment")}return L([{id:lg(),action:"delete.node",payload:{id:o.id},...e.value}],r.value)}});import{ulid as DE}from"ulid";var pg,fg=h(()=>{"use strict";Se();Ce();dn();K();R();yt();M();Yt();pg=async()=>{let e=oe();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),o=se(t.id)[n];if(!o)return a("Unable to close issue, no target found");if(!P(o))return a("Cannot close in this context");let r=g().nodes[he];if(!r)return a("Unable to locate closed swimlane");if(o.parentNodeId===r.id)return a("Issue is already closed");let s=await _e();if(d(s))return s;let i=s.value,c=jt(r.id,o.id,{at:"end"},e.value,i);if(d(c))return c;let u=L([{id:DE(),action:"close.issue",payload:{id:o.id,parent:r.id,rank:c.value},...e.value}],i);return d(u)?u:l("Issue closed",null)}});var $i,ec=h(()=>{"use strict";$i=e=>{let t=e.log??[];for(let n=t.length-1;n>=0;n--){let o=t[n];if(o&&o.action==="close.issue"&&o.payload.id===e.id){for(let r=n-1;r>=0;r--){let s=t[r];if(s&&"id"in s.payload&&s.payload.id===e.id&&"parent"in s.payload&&s.payload.parent)return s.payload.parent}return null}}return null}});import{ulid as FE}from"ulid";var gg,hg=h(()=>{"use strict";Se();Ce();ec();dn();K();R();ne();yt();M();Yt();gg=async()=>{let e=oe();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),o=se(t.id)[n];if(!o)return a("Unable to reopen issue, no target found");let r=o.context==="TICKET"?l("Resolved ticket",o):Ct(o.id,"TICKET");if(d(r))return a("Cannot reopen in this context");let s=r.value,i=g().nodes[he];if(!i)return a("Unable to locate closed swimlane");if(s.parentNodeId!==i.id)return a("Issue is not closed");if(!P(s))return a("Target node is not issue");let c=$i(s);if(!c)return a("Unable to resolve previous parent from issue history");if(c===i.id)return a("Previous parent resolves to closed swimlane");let u=g().nodes[c];if(!u)return a("Previous parent no longer exists");let m=await _e();if(d(m))return m;let p=m.value,f=jt(u.id,s.id,{at:"end"},e.value,p);if(d(f))return f;let y=L([{id:FE(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:f.value},...e.value}],p);return d(y)?y:l("Issue reopened",null)}});import{ulid as _E}from"ulid";var vg,yg=h(()=>{"use strict";Se();Ce();R();ce();M();Yt();vg=async()=>{let e=oe();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),o=se(t.id)[n];if(!o)return a("Missing node");if(o.readonly)return a("Cannot rename readonly node");let r=Ei();if(!r)return a("Provide a title");let s=await _e();return d(s)?s:L([{id:_E(),action:"edit.title",payload:{id:o.id,name:r},...e.value}],s.value)}});import{ulid as OE}from"ulid";var bg,xg=h(()=>{"use strict";ne();Se();Ce();K();R();ce();M();Yt();bg=async()=>{let e=oe();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=de().commandMeta,o=(t||n).trim();if(!o)return a("Provide a tag");let r=E.findTagByName(o);if(!r)return a(`Tag "${o}" does not exist`);let{selectedNode:s}=g();if(!s)return a("Invalid untag target");let i=Ct(s.id,"TICKET");if(d(i))return a("Unable to untag issue in this context");let c=i.value;if(!P(c))return a("Target node is not issue");if(!(c.props.tags??[]).includes(r.id))return a("Issue is not tagged with that tag");let m=await _e();return d(m)?m:L([{id:OE(),action:"remove.issue.tag",payload:{id:c.id,tag:r.id},...e.value}],m.value)}});import{ulid as tc}from"ulid";var Ig,Eg=h(()=>{"use strict";ne();Se();Ce();K();R();ce();M();Yt();Ig=async()=>{let e=oe();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=de().commandMeta,o=(t||n).trim();if(!o)return a("Provide a tag");let{selectedNode:r}=g();if(!r)return a("Invalid tag target");let s=Ct(r.id,"TICKET");if(d(s))return a("Unable to tag issue in this context");let i=s.value;if(!P(i))return a("Target node is not issue");let c=await _e();if(d(c))return c;let u=E.findTagByName(o),m=u?.id??tc();return(i.props.tags??[]).includes(m)?a("Already tagged with that tag"):L([...u?[]:[{id:tc(),action:"create.tag",payload:{id:m,name:o},...e.value}],{id:tc(),action:"add.issue.tag",payload:{id:i.id,tag:m},...e.value}],c.value)}});var ji,nc=h(()=>{"use strict";M();ji=()=>{let{eventLog:e=[],contributors:t}=g(),n=new Map,o=new Set;for(let r of e)r.userId&&(n.set(r.userId,r.userName??""),o.add(r.userId));for(let r of Object.values(t))n.set(r.id,r.name);return[...n.entries()].map(([r,s])=>({id:r,name:s,isExternal:!o.has(r)}))}});import{ulid as oc}from"ulid";var Sg,Rg=h(()=>{"use strict";Se();Ce();K();R();ne();ce();M();nc();Yt();Sg=async()=>{let e=oe();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=de().commandMeta,o=(t||n).trim();if(!o)return a("Provide an assignee");let r=o.startsWith("!"),s=(r?o.slice(1):o).trim();if(!s)return a("Provide an assignee");let{selectedIndex:i,contextNode:c}=g(),u=se(c.id)[i];if(!u)return a("Invalid assign target");let m=Ct(u.id,"TICKET");if(d(m))return a("Unable to assign issue in this context");let p=m.value;if(!P(p))return a("Target node is not issue");let f=await _e();if(d(f))return f;let y=ji(),I=!r&&s.toLowerCase()==="me",S,A;if(I)S=e.value.userId,A=y.find(D=>D.id===S)?.name??e.value.userName;else{let D=y.filter(H=>H.name===s);if(D.length>1)return a(`"${s}" matches ${D.length} contributors (${D.map(H=>H.id).join(", ")}). Assign from the GUI to choose by id.`);let _=D[0];if(!_&&!r)return a(`No contributor named "${s}". Use "!${s}" to add them as an external assignee.`);S=_?.id??oc(),A=_?.name??s}if((p.props.assignees??[]).includes(S))return a("Assignee already assigned");let k=!!g().contributors[S];return L([...k?[]:[{id:oc(),action:"create.contributor",payload:{id:S,name:A},...e.value}],{id:oc(),action:"add.issue.assignee",payload:{id:p.id,assignee:S},...e.value}],f.value)}});import{ulid as BE}from"ulid";var Ng,Cg=h(()=>{"use strict";Se();Ce();K();R();ne();ce();M();nc();Yt();Ng=async()=>{let e=oe();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=de().commandMeta,o=(t||n).trim();if(!o)return a("Provide an assignee to remove");let{selectedNode:r}=g();if(!r)return a("Invalid unassign target");let s=Ct(r.id,"TICKET");if(d(s))return a("Unable to unassign in this context");let i=s.value;if(!P(i))return a("Target node is not issue");let c=i.props.assignees??[],u=o.toLowerCase()==="me",m=u?c.filter(y=>y===e.value.userId):ji().filter(y=>y.name===o&&c.includes(y.id)).map(y=>y.id);if(m.length>1)return a(`"${o}" matches ${m.length} assignees (${m.join(", ")}). Unassign from the GUI to choose by id.`);let p=m[0];if(!p)return a(u?"Issue is not assigned to you":`Issue is not assigned to "${o}"`);let f=await _e();return d(f)?f:L([{id:BE(),action:"remove.issue.assignee",payload:{id:i.id,assignee:p},...e.value}],f.value)}});import{ulid as Ag}from"ulid";var wg,Tg=h(()=>{"use strict";Se();Ce();Ft();K();R();ne();M();hn();Yt();wg=async e=>{let t=e.inputString.trim();if(!t)return a("Provide a comment");if(t.length>4e3)return a(`Cannot exceed ${4e3} characters`);let n=oe();if(d(n))return a("Unable to resolve user ID");let{breadCrumb:o,selectedNode:r}=g(),s=it([...o,r],"TICKET");if(d(s))return a("Edit target must be an issue");let i=s.value;if(!i)return a("Invalid comment target");let c=i.context==="TICKET"?l("Resolved ticket",i):Ct(i.id,"TICKET");if(d(c))return a("Unable to comment on issue in this context");let u=c.value;if(!P(u))return a("Target node is not issue");let m=await _e();return d(m)?m:L([{id:Ag(),action:"add.issue.comment",payload:{id:Ag(),issue:u.id,author:n.value.userId,md:t},...n.value}],m.value)}});import UE from"zod";var kg,Mg=h(()=>{"use strict";zt();pe();R();ce();We();M();kg=()=>{let e=de().commandMeta.inputString,t=UE.coerce.number().int().min(3e3).safeParse(e);if(!t.success)return a("Auto sync duration must be a number of at least 3000 ms");let n=et({autoSyncDebounceMs:t.data});return d(n)?n:(ht({autoSyncIntervalMs:t.data}),N({mode:b.DEFAULT}),l(`Auto sync interval set to ${t.data}ms`,null))}});var Pg,Lg=h(()=>{"use strict";Hr();zt();pe();R();ce();We();M();Pg=()=>{let e=de().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return a("Invalid response");let t=km(e),n=et({autoSync:t});return d(n)?n:(ht({autoSync:t}),N({mode:b.DEFAULT}),l(`Auto sync set to "${e}"`,null))}});var Dg,Fg=h(()=>{"use strict";zt();pe();R();ce();We();M();Dg=()=>{let e=de().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return a("Invalid response");let n=et({logLevel:e});return d(n)?n:(ht({logLevel:e}),N({mode:b.DEFAULT}),l(`Auto sync set to "${e}"`,null))}});import{ulid as $E}from"ulid";var _g,Og=h(()=>{"use strict";Un();zt();pe();R();We();M();pn();Mg();ud();Lg();Fg();_g=e=>{let t=e.inputString.trim();switch(e.modifier){case ve.USERNAME:{if(process.env[gt])return a(`Cannot change the configured user while ${gt} names this process`);let n=ko();if(d(n))return n;let{userId:o,preferredEditor:r,userName:s}=n.value,i=t||s,c=o||$E();if(!i||!c)return a("Unable to resolve user name or id");let u=et({userName:i,userId:c,preferredEditor:r??""});return d(u)?u:(ht({userName:i,userId:c}),N({mode:b.DEFAULT}),l(`Username set to "${i}"`,null))}case ve.EDITOR:{if(!t)return a("No editor provided");let n=et({preferredEditor:t});return d(n)?n:(ht({preferredEditor:t}),N({mode:b.DEFAULT}),l(`Editor configuration set to "${t}"`,null))}case ve.VIEW:{if(t!=="wide"&&t!=="dense")return a("Invalid view mode");let n=et({viewMode:t});return d(n)?n:(ht({viewMode:t}),N({mode:b.DEFAULT}),l(`View set to "${t}"`,null))}case ve.AUTOSYNC:return Pg();case ve.LOG_LEVEL:return Dg();case ve.SYNC_DEBOUNCE_MS:return kg();case ve.ATTACHMENT_MAX_KB:return Km();default:return a("Unknown config command")}}});var Bg,Ug=h(()=>{"use strict";If();ut();pe();R();ce();M();Pi();ro();bd();pn();wf();Lf();$f();Hf();Yf();tg();og();ag();cg();mg();fg();hg();yg();xg();Eg();Rg();Cg();Tg();Og();Bg=[{systemOnly:!0,intent:B.Move,description:"Internal move-state command",mode:b.COMMAND_LINE,action:Uf},{intent:B.Delete,description:"Delete the currently selected node",mode:b.COMMAND_LINE,action:ug,onSuccess:()=>N({mode:b.DEFAULT})},{intent:B.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:b.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=de().commandMeta,n=/(!=|=)/,[o]=e.split(n);if(!o||!(i=>we(x.FILTER).map(c=>c.split(n)[0]).includes(i))(o))return a("Invalid filter modifier");let s={target:o,operator:"=",value:t.trim()};return Ne(i=>({...i,filters:e==="clear"?[]:[...i.filters,s],mode:b.DEFAULT})),l("Filter updated",null)}},{intent:B.ViewHelp,description:"Open the help screen",mode:b.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:o}=g();return Fn({pendingNavTarget:{contextNode:e,breadCrumb:o,selectedIndex:t,selectedNode:n}}),N({mode:b.HELP}),l("Viewing help",null)}},{intent:B.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:b.COMMAND_LINE,action:pg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:B.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:b.COMMAND_LINE,action:gg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:B.Init,description:"Initialize Epiq in the current git repository",mode:b.COMMAND_LINE,action:Pf},{intent:B.OpenProject,description:"Open a recently used epiq project, by number or path",mode:b.COMMAND_LINE,action:Kf,onSuccess:()=>N({mode:b.DEFAULT})},{intent:B.NewItem,description:"Create a new board, swimlane, or issue",mode:b.COMMAND_LINE,action:jf,onSuccess:()=>N({mode:b.DEFAULT})},{intent:B.Rename,description:"Rename the currently selected node",mode:b.COMMAND_LINE,action:vg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:B.UntagTicket,description:"Remove a tag from the selected issue",mode:b.COMMAND_LINE,action:bg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:B.TagTicket,description:"Add or create a tag on the selected issue",mode:b.COMMAND_LINE,action:Ig,onSuccess:()=>N({mode:b.DEFAULT})},{intent:B.AssignUserToTicket,description:"Assign a user to the selected issue",mode:b.COMMAND_LINE,action:Sg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:B.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:b.COMMAND_LINE,action:Ng,onSuccess:()=>N({mode:b.DEFAULT})},{intent:B.Comment,description:"Add a comment to the selected issue",mode:b.COMMAND_LINE,action:async(e,t)=>wg(t),onSuccess:()=>N({mode:b.DEFAULT})},{intent:B.Sync,description:"Pull, commit, and push Epiq state",mode:b.COMMAND_LINE,action:dg},{intent:B.Peek,description:"View board state at another point in time",mode:b.COMMAND_LINE,action:eg},{intent:B.Replay,description:"Replay board history forward from a point in time",mode:b.COMMAND_LINE,action:ng},{intent:B.Export,description:"Export the current board layout to markdown",mode:b.COMMAND_LINE,action:async()=>{let e=await xf();return d(e)?e:(N({mode:b.DEFAULT}),l("Export successful",!0))}},{intent:B.Exit,description:"Exit the application",mode:b.COMMAND_LINE,action:async()=>(U.exit(),l("Exit successful",!0))},{intent:B.Edit,description:"Edit title or description",mode:b.COMMAND_LINE,action:async(e,t)=>Af(t),onSuccess:()=>N({mode:b.DEFAULT})},{intent:B.Yank,description:"Yank (copy) ref, title, description, tags, or assignees to the clipboard",mode:b.COMMAND_LINE,action:async(e,t)=>ig(t),onSuccess:()=>N({mode:b.DEFAULT})},{intent:B.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:b.COMMAND_LINE,action:(e,t)=>_g(t)}]});var jE,Xt,rc=h(()=>{"use strict";ri();yi();bd();Ug();R();ce();We();M();jE=new Set(["peek","replay","filter","view-help","yank"]),Xt=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:o,inputString:r}}=de();if(!t)return a("No command to confirm");if(!e&&n===Mn.Invalid)return a("Invalid command");let s=Rp(t);xp();let{readOnly:i}=g();if(i&&!jE.has(s))return Xr({status:tn.Fail,message:"Command not available in readonly state",value:null});let c=Bg.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!c)return Xr({status:tn.Fail,message:"Command not found",value:null});let u;try{u=await c.action(c,{command:t,inputString:r,modifier:o})}catch(m){return Xr({status:tn.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return d(u)?Xr(u):(Ip({addToHistory:!e}),c.onSuccess?.(),Ie().autoSync&&Im(),u)}});var Hi,Wi,$g,jg=h(()=>{"use strict";R();pe();M();jn();rc();Yd();ce();Hi=[{intent:O.Exit,mode:b.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(N({mode:b.COMMAND_LINE}),te("move cancel"),Xt({isForceExecutedBySystem:!0}))},{intent:O.InitMove,mode:b.DEFAULT,description:"[m] move",action:()=>(N({mode:b.COMMAND_LINE}),te("move start"),Xt({isForceExecutedBySystem:!0}))},{intent:O.ConfirmMove,mode:b.MOVE,description:"[m] confirm move",action:()=>(N({mode:b.COMMAND_LINE}),te("move confirm"),Xt({isForceExecutedBySystem:!0}))}],Wi=[{intent:O.MovePreviousItem,mode:b.MOVE,action:()=>_n()?(N({mode:b.COMMAND_LINE}),te("move previous"),Xt({isForceExecutedBySystem:!0})):a("No pending move")},{intent:O.MoveNextItem,mode:b.MOVE,action:()=>_n()?(N({mode:b.COMMAND_LINE}),te("move next"),Xt({isForceExecutedBySystem:!0})):a("No pending move")}],$g=[{intent:O.MoveToNextContainer,mode:b.MOVE,action:()=>_n()?(N({mode:b.COMMAND_LINE}),te("move to-next"),Xt({isForceExecutedBySystem:!0})):a("No pending move")},{intent:O.MoveToPreviousContainer,mode:b.MOVE,action:()=>_n()?(N({mode:b.COMMAND_LINE}),te("move to-previous"),Xt({isForceExecutedBySystem:!0})):a("No pending move")}]});var Hg,Wg=h(()=>{"use strict";K();jg();Hg={[V.WORKSPACE]:[...Hi,...Wi],[V.BOARD]:[...Hi,...Wi],[V.SWIMLANE]:[...Hi,...Wi,...$g],[V.TICKET]:[],[V.FIELD]:[],[V.FIELD_LIST]:[],[V.TEXT]:[],[V.COMMENT]:[]}});import{spawn as HE}from"node:child_process";function qg(e){let t=process.platform,r=HE(t==="darwin"?"open":t==="win32"?"cmd":"xdg-open",t==="win32"?["/c","start","",e]:[e],{detached:!0,stdio:"ignore",shell:!1});return r.unref(),r.on("error",()=>{}),!0}var Gg=h(()=>{"use strict"});import WE from"node:fs";import qE from"node:path";var zg,Vg=h(()=>{"use strict";Xe();Po();R();ae();Gg();zg=e=>{let t=Me(process.cwd());if(d(t))return a("Unable to resolve project root");let n=be({repoRoot:t.value});if(d(n))return a(n.message);let o=Mo(e.hash,e.ext),r=qE.join(Ps(n.value),o);return WE.existsSync(r)?(qg(r),l(`Opened ${e.name}`,null)):a("Attachment file not found \u2014 run :sync to fetch it")}});var Kg,Yg,Xg=h(()=>{"use strict";pe();R();ce();M();Pi();jn();ut();Kg=()=>{te("");let{pendingNavTarget:e}=Vo();N({mode:b.DEFAULT}),e&&U.navigate(e),Fn({pendingNavTarget:void 0})},Yg=[{intent:O.ExitCommandLine,mode:b.HELP,action:()=>(Kg(),l("Exiting help",null))},{intent:O.Exit,mode:b.HELP,action:()=>(Kg(),l("Closed help",null))},{intent:O.NavPreviousItem,mode:b.HELP,description:"[arrows/hjkl] navigate",action:()=>(U.navigateToPreviousItem(),l("Navigating to previous help item",null))},{intent:O.NavNextItem,mode:b.HELP,action:()=>(U.navigateToNextItem(),l("Navigating to next help item",null))},{intent:O.NavToPreviousContainer,mode:b.HELP,action:()=>(U.navigateToPreviousContainer(),l("Navigating to previous help container",null))},{intent:O.NavToNextContainer,mode:b.HELP,action:()=>(U.navigateToNextContainer(),l("Navigating to next help container",null))}]});var GE,Jg,Qg,Zg=h(()=>{"use strict";pe();K();R();ce();M();Pi();jn();ut();GE=e=>{N({mode:b.COMMAND_LINE});let{pendingNavTarget:t}=Vo();t&&U.navigate(t),Fn({pendingNavTarget:void 0}),te(`${e} `)},Jg=()=>{te("");let{pendingNavTarget:e}=Vo();e&&U.navigate(e),Fn({pendingNavTarget:void 0}),N({mode:b.DEFAULT})},Qg=[{intent:O.InitCommandPalette,mode:b.DEFAULT,description:"[?] command palette",action:()=>{te("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:o}=g();return Fn({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:o}}),N({mode:b.PALETTE}),l("Opening command palette",null)}},{intent:O.Confirm,mode:b.PALETTE,action:()=>{let{selectedNode:e}=g();if(!e||!fl(e))return a("Command only applicable on text nodes");if(e.props.disabled)return a("Command is not available in this context");let t=e.title;return t?(GE(t),l("Selected command",t)):l("No command selected",null)}},{intent:O.ExitCommandLine,mode:b.PALETTE,action:()=>(Jg(),l("Exiting palette",null))},{intent:O.Exit,mode:b.PALETTE,action:()=>(Jg(),l("Closed command palette",null))},{intent:O.NavPreviousItem,mode:b.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(U.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:O.NavNextItem,mode:b.PALETTE,action:()=>(U.navigateToNextItem(),l("Navigating to next item",null))},{intent:O.NavToPreviousContainer,mode:b.PALETTE,action:()=>(U.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:O.NavToNextContainer,mode:b.PALETTE,action:()=>(U.navigateToNextContainer(),l("Navigating to next container",null))}]});var eh,th=h(()=>{"use strict";ro();pn();pe();R();Io();ne();yt();ce();M();Vg();jn();Xg();Zg();ut();eh=[{intent:O.InitCommandLine,mode:b.DEFAULT,description:"[:] write command",action:()=>(N({mode:b.COMMAND_LINE}),te(""),l("Entering command line mode",null))},...Yg,...Qg,{intent:O.AddItem,mode:b.DEFAULT,description:"[n] new...",action:()=>(N({mode:b.COMMAND_LINE}),te(`${x.NEW} `),l("Adding new item",null))},{intent:O.Delete,mode:b.DEFAULT,description:"[d] delete",action:()=>(N({mode:b.COMMAND_LINE}),te(`${x.DELETE} `),l("Deleting item",null))},{intent:O.Confirm,mode:b.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=g();if(!ge(e?.id??"")?.length){let o=e?E.getAttachment(e.id):void 0;if(o)return zg(o);if(e?.title===ue.DESCRIPTION)return N({mode:b.COMMAND_LINE}),te(`${x.EDIT} description `),l("Propose command",!0);if(e?.title===ue.ASSIGNEES)return N({mode:b.COMMAND_LINE}),te(`${x.ASSIGN} `),l("Propose command",!0);if(e?.title===ue.TAGS)return N({mode:b.COMMAND_LINE}),te(`${x.TAG} `),l("Propose command",!0);if(t.title===ue.DESCRIPTION&&e?.context==="TEXT")return N({mode:b.COMMAND_LINE}),te(`${x.EDIT} description `),l("Propose command",!0)}return U.enterChildNode(),l("Entering context",null)}},{intent:O.Yank,mode:b.DEFAULT,description:"[y] yank",action:()=>{let{selectedNode:e}=g(),t=e?.title===ue.DESCRIPTION?Ae.DESCRIPTION:e?.title===ue.TAGS?Ae.TAGS:e?.title===ue.ASSIGNEES?Ae.ASSIGNEES:Ae.REF,o=we(x.YANK).includes(t)?t:Ae.REF;return N({mode:b.COMMAND_LINE}),te(`${x.YANK} ${o}`),l("Propose command",!0)}},{intent:O.EditTitle,mode:b.DEFAULT,description:"[r] rename title",action:()=>(N({mode:b.COMMAND_LINE}),te(`${x.EDIT} title ${g().selectedNode?.title}`),l("Exiting context",null))},{intent:O.EditDescription,mode:b.DEFAULT,description:"[e] edit desc",action:()=>(N({mode:b.COMMAND_LINE}),te(`${x.EDIT} description `),l("Exiting context",null))},{intent:O.Exit,mode:b.DEFAULT,description:"[q] exit context",action:()=>(U.enterParentNode(),l("Exiting context",null))},{intent:O.NavPreviousItem,mode:b.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(U.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:O.NavNextItem,mode:b.DEFAULT,action:()=>(U.navigateToNextItem(),l("Navigating to next item",null))},{intent:O.NavToPreviousContainer,mode:b.DEFAULT,action:()=>(U.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:O.NavToNextContainer,mode:b.DEFAULT,action:()=>(U.navigateToNextContainer(),l("Navigating to next container",null))}]});var zE,VE,nh,oh=h(()=>{"use strict";ce();zE=500,VE=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),nh=e=>{let t=VE(e);t&&Ii(n=>(n+t).slice(0,zE))}});var KE,YE,rh,sh=h(()=>{"use strict";oh();pe();R();ce();M();jn();rc();KE=[b.COMMAND_LINE,b.PALETTE],YE=e=>[{intent:O.MoveCursorLeft,mode:e,action:()=>(vd(-1),l("Moving cursor left",null))},{intent:O.MoveCursorRight,mode:e,action:()=>(vd(1),l("Moving cursor right",null))},{intent:O.MoveCursorLeftOfWord,mode:e,action:()=>(yd("left"),l("Moving cursor left of word",null))},{intent:O.MoveCursorRightOfWord,mode:e,action:()=>(yd("right"),l("Moving cursor right of word",null))},{intent:O.AutoCompleteCommand,mode:e,action:()=>(Ii((t,{remainder:n})=>{let o=n?t+n:t,r="";return o==="edit title "&&(r=g().selectedNode?.title??""),o+r}),l("Auto-completing command",null))},{intent:O.CaptureInput,mode:e,action:(t,{sequence:n})=>(nh(n??""),l("Capturing input",null))},{intent:O.EraseInput,mode:e,action:()=>(yp(),l("Erasing input",null))},{intent:O.EraseInputWord,mode:e,action:()=>(bp(),l("Erasing input word",null))}],rh=[{intent:O.Confirm,mode:b.COMMAND_LINE,action:()=>(Xt(),l("Executing command",null))},{intent:O.ViewHelp,mode:b.DEFAULT,action:()=>(N({mode:b.HELP}),l("Viewing help",null))},...KE.flatMap(YE),{intent:O.ExitCommandLine,mode:b.COMMAND_LINE,action:()=>(N({mode:b.DEFAULT}),l("Exiting command line",null))},{intent:O.GetLastCommandFromHistory,mode:b.COMMAND_LINE,action:()=>(Ep(),l("Getting last command from history",null))},{intent:O.GetNextCommandFromHistory,mode:b.COMMAND_LINE,action:()=>(Sp(),l("Getting next command from history",null))}]});var XE,ih,ah,dh=h(()=>{"use strict";XE=e=>{let t=/^\[(.+?)\]\s*(.+)$/.exec(e);return t?{keys:t[1]??"",label:t[2]??""}:null},ih=({keys:e})=>e.length===1?0:1,ah=(e,t)=>{let n=new Set;for(let o of e)o.mode!==t||!o.description||n.add(o.description);return[...n].map(XE).filter(o=>o!==null).sort((o,r)=>ih(o)-ih(r))}});function ch(e,t,n){let o=t[e];if(!o)return a("buildBreadCrumb(): current node not found");let r=[],s=new Set,i=o;for(;i&&!s.has(i.id)&&(r.push(i),s.add(i.id),!(i.id===n||!i.parentNodeId));)i=t[i.parentNodeId];let c=r[r.length-1];return!c||c.id!==n?a("buildBreadCrumb(): node is not connected to root"):(r.reverse(),l("Breadcrumb built",r))}var lh=h(()=>{"use strict";R()});var uh,mh=h(()=>{"use strict";uh=e=>{let t={};for(let n of e)n.intent&&(t[n.mode]||(t[n.mode]={}),t[n.mode][n.intent]=n);return t}});import{useSyncExternalStore as JE}from"react";function dc(e){let{contextNodeId:t,mode:n,rootNodeId:o,nodes:r,filters:s}=e;if(!t)return a("derive(): contextNodeId is missing");if(!o)return a("derive(): rootNode is missing");if(!r[o])return a("derive(): unable to find root node");let c=r[t];if(!c)return a("Unable to derive state, contextNode not found");let u=ch(t,r,o);if(d(u))return logger.error(u.message),u;let m=u.value,{context:p}=c,f=[...eh,...Hg[p]??[],...rh],y=ah(f,n),I=uh(f),S=ZE(r,s),A=S[t]?.[e.selectedIndex]??null;return l("Derived successfully",{...e,contextNode:c,breadCrumb:m,availableHints:y,availableActions:f,actionIndex:I,selectedNode:A,renderedChildrenIndex:S})}function Tr(e){sc=e;let t=Me(process.cwd()),n=!1;if(!d(t)){let s=Ot(t.value);if(d(s))return a(s.message);n=!0}let o={readOnly:!1,filters:[],tags:{},contributors:{},mode:b.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,contextNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],replay:null,timeMode:"live",hasProjectDefinition:n,hasInitializingEvents:!1,comments:{},attachments:{}},r=dc(o);return d(r)?r:(Jt=r.value,ac(),l("State initialized",null))}function Ne(e){let t=g(),n=e(t);if(mo)return as=n,Jt={...t,...n},l("State updated",null);let o=dc(n);return d(o)?a(o.message??"Unable to update state"):(Jt=o.value,ac(),l("State updated",null))}function ru(e){if(mo)return l("Joined batch",e());mo=!0,as=null;let t=()=>{let n=as;if(mo=!1,as=null,n===null)return null;let o=dc(n);return d(o)?a(o.message??"Unable to update state"):(Jt=o.value,ac(),l("State updated",null))};try{let n=e(),o=t();return o&&d(o)?a(o.message):l("State updated",n)}finally{mo&&t()}}function po(e,t,n){if(!mo)return Ne(i=>({...i,[e]:{...i[e]??{},[t]:n}}));let o=g(),r=o[e]??{};r[t]=n;let s={...o,[e]:r};return as=s,Jt={...o,...s},l("State updated",null)}var Jt,sc,ic,ac,QE,g,ze,mo,as,Wu,N,rt,ZE,se,bn,It,M=h(()=>{"use strict";Wg();th();sh();dh();nn();pe();R();ae();ja();lh();mh();ic=new Set,ac=()=>{for(let e of ic)e()},QE=e=>(ic.add(e),()=>ic.delete(e));g=()=>{if(!Jt)throw new Error("State not initialized. Call initWorkspaceState() first.");return Jt},ze=()=>Jt?l("Retrieved state",Jt):a("State not initialized. Call initWorkspaceState() first.");mo=!1,as=null;Wu=()=>mo,N=e=>Ne(t=>({...t,...e}));rt=()=>JE(QE,g,g),ZE=Uu,se=e=>g()?.renderedChildrenIndex[e]??[],bn=()=>sc?Tr(sc):a("Cannot reset state: no initial workspace found"),It=()=>Jt!==void 0});var Ct,eS,On,E,ne=h(()=>{"use strict";Ft();K();R();M();yt();Ct=(e,t)=>{let{nodes:n}=g(),o=n[e];if(!o)return a("Node not found");if(o.context===t)return l("Resolved ancestor node",o);let r=new Set([o.id]),s=o.parentNodeId?n[o.parentNodeId]:void 0;for(;s&&!r.has(s.id);){if(s.context===t)return l("Resolved ancestor node",s);r.add(s.id),s=s.parentNodeId?n[s.parentNodeId]:void 0}return a(`No ancestor found for context: ${t}`)},eS=(e,t)=>{let{nodes:n}=g(),o=new Set,r=n[e];for(;r?.parentNodeId&&!o.has(r.id);){if(r.parentNodeId===t)return!0;o.add(r.id),r=n[r.parentNodeId]}return!1},On=(e,t)=>e?e.readonly?a({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node",delete:"Cannot delete readonly node"}[t]):null:a("Node not found"),E={linkUserId({contributorId:e,userId:t}){let n=this.getContributor(e);if(!n)return a("Contributor not found");if(n.userId&&n.userId!==t)return a("Contributor is already linked to another user");let o={...n,userId:t},r=Ne(s=>({...s,contributors:{...s.contributors,[e]:o}}));return d(r)?a("Unable to link contributor to user"):l("Linked contributor to user",o)},deleteNode(e){Ne(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},createComment(e){let t=this.getNode(e.issue);if(!t)return a("Unable to create comment, missing issue");if(!P(t))return a("Can only comment on issues");let n=po("comments",e.id,{...e,deleted:!1});return d(n)?a("Unable to create comment"):l("Created comment",{...e,deleted:!1})},editComment(e,t){let n=this.getComment(e);if(!n)return a("Unable to edit comment, missing comment");let o=this.getNode(n.issue);if(!o)return a("Unable to edit comment, missing issue");if(!P(o))return a("Can only edit issue comments");let r={...n,md:t,deleted:!1},s=po("comments",e,r);return d(s)?a("Unable to edit comment"):l("Edited comment",r)},deleteComment(e){let t=this.getComment(e);if(!t)return a("Unable to delete comment, missing comment");let n={...t,deleted:!0},o=po("comments",e,n);return d(o)?a("Unable to delete comment"):l("Deleted comment",n)},getComment(e){return g().comments?.[e]},getCommentsByIssue(e){return Object.values(g().comments??{}).filter(t=>t.issue===e&&!t.deleted)},getCommentsGroupedByIssue(){let e=new Map;for(let t of Object.values(g().comments??{})){if(t.deleted)continue;let n=e.get(t.issue);n?n.push(t):e.set(t.issue,[t])}return e},createAttachment(e){let t=this.getNode(e.issue);if(!t)return a("Unable to create attachment, missing issue");if(!P(t))return a("Can only attach to issues");let n=Ne(o=>({...o,attachments:{...o.attachments??{},[e.id]:{...e,deleted:!1}}}));return d(n)?a("Unable to create attachment"):l("Created attachment",{...e,deleted:!1})},deleteAttachment(e){let t=this.getAttachment(e);if(!t)return a("Unable to delete attachment, missing attachment");let n={...t,deleted:!0},o=Ne(r=>({...r,attachments:{...r.attachments??{},[e]:n}}));return d(o)?a("Unable to delete attachment"):l("Deleted attachment",n)},getAttachment(e){return g().attachments?.[e]},getAttachmentsByIssue(e){return Object.values(g().attachments??{}).filter(t=>t.issue===e&&!t.deleted)},getAttachmentsGroupedByIssue(){let e=new Map;for(let t of Object.values(g().attachments??{})){if(t.deleted)continue;let n=e.get(t.issue);n?n.push(t):e.set(t.issue,[t])}return e},editValue(e,t){let{nodes:n}=g(),o=n[e];if(!o)return a("Edit target node not found");let r=On(o,"edit");if(r)return r;let s={...o,props:{...o.props,description:t}};return this.updateNode(s),l("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return a("Rename target node not found");let o=On(n,"rename");if(o)return o;let r={...n,title:t};return this.updateNode(r),l("Renamed node",r)},getExistingTags(){let{tags:e}=g();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=g();return["me",...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return ge(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:o}=g(),r=this.getNode(e),s=this.getNode(t);if(!r)return a("Node not found");if(!s)return a("Target parent not found");if(o===e)return a("Cannot move root node");if(e===t)return a("Cannot move node into itself");let i=On(r,"move");if(i)return i;if(eS(t,e))return a("Cannot move node into its own descendant");let c={...r,parentNodeId:t,rank:n};return this.updateNode(c),l("Moved node successfully",c)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:o}=g(),r=this.getNode(e);if(!r)return a("Node not found");if(o===e)return a("Cannot delete root node");let s=On(r,"delete");if(s)return s;let i=new Set,c=m=>{let p=t[m];if(!(!p||i.has(m))){i.add(m);for(let f of ge(p.id))c(f.id)}};c(e);let u={...structuredClone(t)};for(let m of i){if(!u[m])return a("Unable to locate node to delete");u[m]={...u[m],isDeleted:!0}}return n?(N({nodes:u}),l("Successfully tomb stoned",r)):a("Unable to delete undefined")},tombstoneContributor(e){let t=this.getContributor(e);if(!t)return a("Contributor not found");let n={...t,name:bs,tombstoned:!0},o=Ne(r=>({...r,contributors:{...r.contributors,[e]:n}}));return d(o)?a("Unable to remove contributor"):l("Tombstoned contributor",n)},renameContributor(e,t){let n=this.getContributor(e);if(!n)return a("Contributor not found");if(n.tombstoned)return a("Cannot rename a removed contributor");let o={...n,name:t},r=Ne(s=>({...s,contributors:{...s.contributors,[e]:o}}));return d(r)?a("Unable to rename contributor"):l("Renamed contributor",o)},restoreContributor(e,t){let n=this.getContributor(e);if(!n)return a("Contributor not found");let o={...n,name:t,tombstoned:!1},r=Ne(s=>({...s,contributors:{...s.contributors,[e]:o}}));return d(r)?a("Unable to restore contributor"):l("Restored contributor",o)},createContributor(e){let t=Ne(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return d(t)?a("Unable to create contributor"):l("Created contributor",e)},assign(e,t){let n=this.getContributor(t),o=this.getNode(e);if(!n)return a("Unable to assign contributor, missing contributor");if(!o)return a("Unable to assign contributor, missing target");let r=On(o,"edit");if(r)return r;if(!P(o))return a("Target is not an issue");let s=o.props.assignees??[];if(s.includes(t))return a("Contributor already assigned");let i={...o,props:{...o.props,assignees:[...s,t]}};return this.updateNode(i),l("Assigned contributor",{assignee:t})},unassign(e,t){let n=this.getContributor(t),o=this.getNode(e);if(!n)return a("Unable to unassign, missing contributor");if(!o)return a("Unable to unassign, missing target");let r=On(o,"edit");if(r)return r;if(!P(o))return a("Target is not an issue");let s=o.props.assignees??[];if(!s.includes(t))return l("Issue is not assigned to that contributor",{assignee:t});let i={...o,props:{...o.props,assignees:s.filter(c=>c!==t)}};return this.updateNode(i),l("Assignee removed",{assignee:t})},tag(e,t){let n=this.getTag(t),o=this.getNode(e);if(!n)return a("Unable to add tag, missing tag");if(!o)return a("Unable to add tag, missing target");let r=On(o,"edit");if(r)return r;if(!P(o))return a("Target is not an issue");let s=o.props.tags??[];if(s.includes(t))return a("Tag already assigned");let i={...o,props:{...o.props,tags:[...s,t]}};return this.updateNode(i),l("Tag added",{tag:t})},untag(e,t){let n=this.getTagRecord(t),o=this.getNode(e);if(!n)return a("Unable to remove tag, missing tag");if(!o)return a("Unable to remove tag, missing target");let r=On(o,"edit");if(r)return r;if(!P(o))return a("Target is not an issue");let s=o.props.tags??[];if(!s.includes(t))return l("Issue is not tagged with that tag",{tag:t});let i={...o,props:{...o.props,tags:s.filter(c=>c!==t)}};return this.updateNode(i),l("Tag removed",{tag:t})},tombstoneTag(e){let t=this.getTagRecord(e);if(!t)return a("Tag not found");let n={...t,tombstoned:!0},o=Ne(r=>({...r,tags:{...r.tags,[e]:n}}));return d(o)?a("Unable to delete tag"):l("Tombstoned tag",n)},restoreTag(e,t){let n=this.getTagRecord(e);if(!n)return a("Tag not found");let o={...n,name:t,tombstoned:!1},r=Ne(s=>({...s,tags:{...s.tags,[e]:o}}));return d(r)?a("Unable to restore tag"):l("Restored tag",o)},createTag(e){let t=Ne(n=>({...n,tags:{...n.tags,[e.id]:e}}));return d(t)?a("Could not create tag"):l("Tag created",e)},createNode(e){let t=po("nodes",e.id,e);return d(t)?a("Unable to create node"):l("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return a("Failed to locate node");let n={...t,readonly:!0},o=po("nodes",e,n);return d(o)?a(o.message):l("Locked node",n)},updateNode(e){let t=po("nodes",e.id,e);return d(t)?t:l("Updated node",e)},getContributor(e){return g().contributors[e]},getTag(e){let t=g().tags[e];return t?.tombstoned?void 0:t},getTagRecord(e){return g().tags[e]},getTags(){return Object.values(g().tags).filter(e=>!e.tombstoned)},findTagByName(e){return this.getTags().find(t=>t.name===e)},getNode(e){return g().nodes[e]},getSiblings(e){return ge(e)}}});import Bn from"chalk";import ph from"string-width";var tS,nS,cc,oS,rS,fh,gh,sS,iS,aS,dS,cS,Zd,hh,ss=h(()=>{"use strict";Ke();ne();M();pt();Ti();tS=(e,t)=>e+" ".repeat(Math.max(0,t-ph(e))),nS=(e,t)=>" ".repeat(Math.max(0,t-ph(e)))+e,cc=e=>({"add.issue":"Created with title","add.issue.assignee":"Assigned to","remove.issue.assignee":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","add.issue.tag":"Tagged with","remove.issue.tag":"Removed tag","lock.node":"Locked node","move.node":"Moved issue","add.issue.comment":"Commented","delete.issue.comment":"Deleted comment","add.issue.attachment":"Attached","delete.issue.attachment":"Removed attachment","edit.issue.comment":"Edited comment","init.workspace":"Created workspace","add.workspace":"Created workspace","add.board":"Created board","add.swimlane":"Created swimlane","add.field":"Added field","create.tag":"Created tag","tombstone.tag":"Deleted tag","restore.tag":"Restored tag","create.contributor":"Added contributor","rename.contributor":"Renamed contributor","link.contributor.user":"Linked contributor","tombstone.contributor":"Removed contributor","restore.contributor":"Restored contributor","rebalance.children":"Rebalanced order"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),oS=(e,t)=>t?e<t?"up":e>t?"down":null:null,rS=(e,t)=>{let n=E.getNode(e.payload.parent),o=n?Bn.dim.bgBlack(` ${n.title} `):"unknown",r=t.at(-1);if(r&&"parent"in r&&"rank"in r&&r.parent===e.payload.parent){let s=oS(e.payload.rank,r.rank);if(s)return`Moved ${s} in ${o}`}return`Moved issue to ${o}`},fh=e=>`${Math.max(1,Math.round(e/1024))} KB`,gh=e=>E.getAttachment(e)?.name??"",sS=e=>{switch(e.action){case"add.issue.tag":{let t=g().tags[e.payload.tag];return t?Bn.bgHex(Te(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=g().tags[e.payload.tag];return t?Bn.bgHex(Te(t.name))(` ${t.name} `):"unknown tag"}case"tombstone.tag":{let t=g().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?Bn.hex(Te(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?Bn.hex(Te(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;case"add.issue.attachment":return`"${e.payload.name}" ${Bn.dim(`(${fh(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=gh(e.payload.id);return t?`"${t}"`:""}default:return""}},iS=e=>{let t=qo(He(e));return Bn.gray(nS(t,8))},aS=12,dS=e=>tS(`${e}`,aS),cS=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=g().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?t.name:""}case"tombstone.tag":{let t=g().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"edit.title":return"name"in e.payload?`"${e.payload.name}"`:"";case"move.node":{let t=E.getNode(e.payload.parent);return t?`to ${t.title}`:""}case"add.issue.attachment":return`"${e.payload.name}" (${fh(e.payload.bytes)})`;case"delete.issue.attachment":{let t=gh(e.payload.id);return t?`"${t}"`:""}default:return""}},Zd=e=>[cc(e.action),cS(e)].filter(Boolean).join(" "),hh=(e,t)=>{let n=iS(e.id),o=dS(e.userName),r=Bn.dim("\u203A"),s=e.action==="move.node"?rS(e,t):[cc(e.action),sS(e)].filter(Boolean).join(" ");return`${o} ${n} ${r} ${s}`}});var yh={};cr(yh,{areVirtualNodesEnabled:()=>_s,createOrUpdateVirtualField:()=>ds,createOrUpdateVirtualFieldList:()=>lc,materializeTicketVirtualNodes:()=>Fs,materializeVirtualNodes:()=>yS,setVirtualNodesEnabled:()=>vS});var lS,uS,mS,pS,fS,gS,ds,lc,Fs,hS,vh,vS,_s,yS,Na=h(()=>{"use strict";ss();K();R();Io();ne();Gn();M();yo();Lo();lS=e=>Le(e,"comments"),uS=e=>Le(e,"description"),mS=e=>Le(e,"assignees"),pS=e=>Le(e,"tags"),fS=e=>Le(e,"history"),gS=e=>Le(e,"attachments"),ds=({id:e,name:t,parentNodeId:n,rank:o,value:r,readonly:s=!1,childRenderAxis:i="horizontal"})=>{let c=E.getNode(e);if(!c){let p=E.createNode({...Pe.field({id:e,name:t,parentNodeId:n,rank:o,props:{value:r},isVirtual:!0}),readonly:s,childRenderAxis:i});return d(p)?p:l("Virtual field created",void 0)}if(!at(c))return a(`Existing virtual node ${e} is not a field`);if(!(c.title!==t||c.parentNodeId!==n||c.rank!==o||c.props.value!==r||c.readonly!==s||c.childRenderAxis!==i))return l("Virtual field unchanged",void 0);let m=E.updateNode({...c,title:t,parentNodeId:n,rank:o,props:{...c.props,value:r},readonly:s,childRenderAxis:i});return d(m)?m:l("Virtual field updated",void 0)},lc=({id:e,name:t,parentNodeId:n,rank:o,readonly:r=!1,childRenderAxis:s="horizontal"})=>{let i=E.getNode(e);if(!i){let m=E.createNode({...Pe.fieldList({id:e,name:t,parentNodeId:n,rank:o,isVirtual:!0}),readonly:r,childRenderAxis:s});return d(m)?m:l("Virtual field list created",void 0)}if(!fr(i))return a(`Existing virtual node ${e} is not a field list`);if(!(i.title!==t||i.parentNodeId!==n||i.rank!==o||i.readonly!==r||i.childRenderAxis!==s))return l("Virtual field list unchanged",void 0);let u=E.updateNode({...i,title:t,parentNodeId:n,rank:o,readonly:r,childRenderAxis:s});return d(u)?u:l("Virtual field list updated",void 0)},Fs=e=>{let t=vt(_t/4n),n=vt(_t/2n),o=vt(_t*3n/4n),r=vt(_t*7n/8n),s=vt(_t*15n/16n),i=vt(_t*13n/16n);if(d(t))return t;if(d(n))return n;if(d(o))return o;if(d(r))return r;if(d(s))return s;if(d(i))return i;let c=ds({id:uS(e.id),name:ue.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(d(c))return c;let u=lc({id:mS(e.id),name:ue.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(d(u))return u;let m=lc({id:pS(e.id),name:ue.TAGS,parentNodeId:e.id,rank:o.value,readonly:!0});if(d(m))return m;let p=ds({id:lS(e.id),name:ue.COMMENTS,parentNodeId:e.id,rank:r.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(d(p))return p;let f=ds({id:gS(e.id),name:ue.ATTACHMENTS,parentNodeId:e.id,rank:s.value,value:"",readonly:!0,childRenderAxis:"vertical"});if(d(f))return f;let y=ds({id:fS(e.id),name:ue.HISTORY,parentNodeId:e.id,rank:i.value,value:hS(e),readonly:!0,childRenderAxis:"vertical"});return d(y)?y:l("Ticket virtual nodes materialized",void 0)},hS=e=>{let t=[...e.log].reverse(),n=new Map;for(let o of t){let r=n.get(o.action)??[];r.push(o.payload),n.set(o.action,r)}return t.map(o=>hh(o,n.get(o.action)??[])).join(`
|
|
93
|
+
`)},vh=!0,vS=e=>{vh=e},_s=()=>vh,yS=()=>{let{nodes:e}=g();for(let t of Object.values(e)){if(!P(t))continue;let n=Fs(t);if(d(n))return n}return l("Virtual nodes materialized",void 0)}});var bS,xS,qi,uc=h(()=>{"use strict";Ke();bS=e=>{switch(e.action){case"add.issue":case"move.node":case"close.issue":case"reopen.issue":return e.payload.parent;default:return null}},xS=(e,t)=>{let n=[];for(let o of e){let r=bS(o);if(r===null||r===n.at(-1)?.laneId)continue;let s=$n(o);n.push({laneId:r,enteredAt:s===null?t:mr(s)})}return n},qi=(e,t)=>xS(e,t).at(-1)?.enteredAt??t});var bh=h(()=>{"use strict";R()});var IS,xh,mc=h(()=>{"use strict";Ke();St();kr();ss();R();pt();IS=e=>{let t=new Map,n=new Set,o=r=>{let s=new Set,i=r;for(;i&&!s.has(i);){if(n.has(i))return i;s.add(i),i=t.get(i)}return null};return e.map(r=>{let s=r.payload,i=s?.id;if(!i)return null;r.action==="add.board"&&n.add(i);let c=s.parent??s.issue;return c&&t.set(i,c),n.has(i)?i:o(i)})},xh=(e,t)=>{let n=IS(e);return e.filter((o,r)=>n[r]===t)}});var ES,Ih,Sh,SS,ls,cs,Eh,RS,Ko,NS,Rh,Yo=h(()=>{"use strict";Xe();ct();Je();Hd();St();ln();R();nn();gi();bh();ae();M();mc();ES=null,Ih=Promise.resolve(),Sh=e=>{let t=Ih.then(e,e);return Ih=t.then(()=>{},()=>{}),t},SS=e=>{let t=Me(e??process.cwd());return d(t)?a(t.message):l("Resolved Epiq repo root",t.value)},ls=()=>{if(!It())return{mode:"live",asOfTime:null};let{timeMode:e}=g();return e==="live"?{mode:"live",asOfTime:null}:{mode:"scrub",asOfTime:ES}},cs="",Eh="",RS=5e3,Ko=null,NS=async(e={})=>{let t=SS(e.repoRoot);if(d(t))return a(t.message);let n=Ot(t.value);if(d(n))return a(n.message);let o=e.start===void 0&&e.end===void 0;if(o&&Ko&&Ko.repoRoot===t.value&&Ko.stateBranch===n.value.stateBranch&&Date.now()-Ko.fetchedAt<RS)return l("Computed commit timeline",Ko.result);let r=await W({cwd:t.value,args:["log","--branches","--not",n.value.stateBranch,...e.start!==void 0?[`--since=@${Math.floor(e.start/1e3)}`]:[],...e.end!==void 0?[`--until=@${Math.floor(e.end/1e3)}`]:[],"--shortstat",`--format=${Eh}%H${cs}%at${cs}%an${cs}%s`]});if(d(r))return a(r.message);let s=r.value.stdout.split(Eh).filter(i=>i.trim().length>0).map(i=>{let[c,...u]=i.split(`
|
|
94
|
+
`),[m,p,f,...y]=(c??"").split(cs);if(!m||!p)return null;let I=u.join(" "),S=Number(/(\d+) insertion/.exec(I)?.[1]??0),A=Number(/(\d+) deletion/.exec(I)?.[1]??0);return{sha:m,time:Number(p)*1e3,author:f??"unknown",subject:y.join(cs),linesChanged:S+A,insertions:S,deletions:A}}).filter(i=>i!==null).filter(i=>(e.start===void 0||i.time>=e.start)&&(e.end===void 0||i.time<=e.end));return o&&(Ko={repoRoot:t.value,stateBranch:n.value.stateBranch,fetchedAt:Date.now(),result:s}),l("Computed commit timeline",s)},Rh=async e=>{let t=e.ref.trim();if(!t)return a("ref must not be empty");if(t.length!==7)return a(`"${t}" is ${t.length} characters; a ref is ${7}. Read it off the issue rather than slicing the id by hand.`);let n=await NS({repoRoot:e.repoRoot});if(d(n))return a(n.message);let o=`${t.toUpperCase()} `,r=c=>c.subject.toUpperCase().startsWith(o),s=n.value,i=[];for(let[c,u]of s.entries()){if(!r(u))continue;let m=s[c+1];i.push({...u,precedingSha:m&&r(m)?m.sha:null})}return l("Matched commits by ref",i)}});import CS from"node:fs";var fo,Gi,Y,Q,X,xn=h(()=>{"use strict";Xe();ct();bo();Or();zt();to();kr();ae();St();R();M();xt();Yo();fo=e=>{let t=Me(e??process.cwd());return d(t)?a(t.message):l("Resolved Epiq repo root",t.value)},Gi=null,Y=async(e,t)=>{let n=fo(e);if(d(n))return n;let o=be({repoRoot:n.value});if(d(o))return a(o.message);let r=Bt(n.value);if(d(r))return a(r.message);if(!(Gi!==null&&Gi.repoRoot===n.value&&Gi.stateBranchRoot===o.value&&CS.existsSync(Wn(o.value)))){let p=await Ga({repoRoot:n.value,stateBranchName:r.value});if(d(p))return a(p.message);let f=await oo({repoRoot:n.value,stateBranchRoot:o.value,stateBranchName:r.value});if(d(f))return a(f.message);Gi={repoRoot:n.value,stateBranchRoot:o.value}}if(t?.pull??!1){let p=await W({cwd:o.value,args:["pull","--ff-only"]});d(p)&&J.info(3,p.message)}let i={repoRoot:n.value,stateBranchRoot:o.value},c=Xn(o.value);if(hu(o.value)===c&&It()&&ls().mode==="live")return l("Booted Epiq state, unchanged",i);let u=Et(o.value);if(d(u))return a(u.message);let m=Wt(u.value.events,u.value.unreadable);return d(m)?a(m.message):(vu(o.value,c),l("Booted Epiq state",i))},Q=()=>{let e=zr();return d(e)?a(e.message):e.value.userId?e.value.userName?l("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):a("Unable to retrieve user name"):a("Unable to retrieve user id")},X=()=>{let e=ze();return d(e)?a(e.message):e}});var Xo,Nh,Jo,pc=h(()=>{"use strict";Ke();ne();pt();Xo=e=>(e.props.tags??[]).map(t=>E.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:Te(t.name)})),Nh=e=>E.getCommentsByIssue(e).sort((t,n)=>t.id<n.id?-1:t.id>n.id?1:0).map(t=>({id:t.id,author:E.getContributor(t.authorId)?.name??t.authorName??"Unknown",createdAt:He(t.id),body:t.md})),Jo=e=>(e.props.assignees??[]).map(t=>E.getContributor(t)).filter(t=>t!=null).map(({id:t,name:n})=>({id:t,name:n,color:Te(n)}))});import AS from"node:fs";import wS from"node:path";import{ulid as Ch}from"ulid";var TS,Ah,fc,gc=h(()=>{"use strict";zt();Se();K();R();dt();Po();xn();TS=e=>{if(e.filePath)try{return l("Read attachment file",{data:AS.readFileSync(e.filePath),name:e.name??wS.basename(e.filePath)})}catch(t){return a(`Unable to read ${e.filePath}: ${t instanceof Error?t.message:String(t)}`)}return e.dataBase64?l("Decoded attachment data",{data:Buffer.from(e.dataBase64,"base64"),name:e.name??"image"}):a("Provide either filePath or dataBase64")},Ah=()=>{let e=zr();return d(e)?gn:e.value.attachmentMaxKb??gn},fc=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;let r=o.value.nodes[e.issueId];if(!r)return a("Issue not found");if(!P(r))return a("Attachment target must be an issue");if(r.readonly)return a("Cannot attach to readonly issue");let s=TS(e);if(d(s))return s;let i=Vm(t.value.stateBranchRoot,s.value.data,Ah());if(d(i))return i;let c=fe(s.value.name).trim()||"image",u=Ch(),m={id:Ch(),...n.value,action:"add.issue.attachment",payload:{id:u,issue:e.issueId,author:n.value.userId,hash:i.value.hash,ext:i.value.ext,name:c,bytes:i.value.bytes}},p=L([m],t.value.stateBranchRoot);if(d(p))return a(p.message);let f=Mo(i.value.hash,i.value.ext);return l("Added issue attachment",{id:u,issueId:e.issueId,fileName:f,bytes:i.value.bytes,markdown:cd(c,f)})}});var hc,xq,vc,wh=h(()=>{"use strict";zt();Ke();dn();K();R();ne();Ao();pt();uc();Je();dt();Po();xt();Yo();xn();pc();gc();ti();Ce();Lr();hc=async(e={})=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=X();return d(n)?n:l("Retrieved Epiq state",{root:t.value.repoRoot,stateBranchRoot:t.value.stateBranchRoot,nodes:n.value.nodes,rootNodeId:n.value.rootNodeId,contextNode:n.value.contextNode,selectedIndex:n.value.selectedIndex,eventLog:n.value.eventLog})},xq=365*24*60*60*1e3,vc=async(e={})=>{Eo();let t=fo(e.repoRoot);if(d(t))return a("Sync failed");let n=Q();if(d(n))return n;let o=await ei({cwd:t.value,ownEventFileName:Zn(n.value)});return d(o)?(Ha(o.message),o):(no(),l("Synced",o.value))}});var us,Qo,yc,ms,bc=h(()=>{"use strict";K();R();Je();xn();us=e=>{let t=[...new Set([...e.issueIds??[],...e.issueId?[e.issueId]:[]])];return t.length?l("Resolved targets",t):a("Provide issueId or issueIds")},Qo=(e,t)=>{let n=t.done.length,o=`${e} ${n} issue${n===1?"":"s"}`+(t.failed.length?`, ${t.failed.length} failed`:"");return n?l(o,t):a(`${o}: ${t.failed.map(r=>`${r.ref} ${r.reason}`).join("; ")}`)},yc=(e,t)=>{let n={done:[],failed:[]};for(let o of e){let r=t(o);d(r)?n.failed.push({id:o,ref:j(o),reason:r.message}):n.done.push({id:o,ref:j(o)})}return n},ms=e=>{let t=X();if(d(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?a("Issue not found"):P(n)?n.readonly?a("Issue is readonly"):l("Found issue",n):a("Target must be an issue")}});import{ulid as At}from"ulid";async function Ic(e){let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=X();if(d(n))return n;let o=n.value.nodes,r=e.query?.trim().toLowerCase(),s=Object.values(o).filter(P).filter(c=>!c.isDeleted).filter(c=>e.includeClosed||c.parentNodeId!==he).filter(c=>e.boardId?(c.parentNodeId?o[c.parentNodeId]:void 0)?.parentNodeId===e.boardId:!0).filter(c=>!e.swimlaneId||c.parentNodeId===e.swimlaneId).filter(c=>!e.tag||Xo(c).some(u=>Th(u.name,e.tag))).filter(c=>!e.assignee||Jo(c).some(u=>Th(u.name,e.assignee))).filter(c=>!r||c.title.toLowerCase().includes(r)||(c.props.description??"").toLowerCase().includes(r)),i=c=>fe((c.parentNodeId?o[c.parentNodeId]?.title:void 0)??"");return e.brief?l("Listed issues",s.map(c=>({id:c.id,ref:j(c.id),title:fe(c.title),swimlane:i(c),tags:Xo(c).map(u=>u.name),assignees:Jo(c).map(u=>u.name)}))):l("Listed issues",s.map(c=>({id:c.id,ref:j(c.id),title:fe(c.title),description:c.props.description??"",createdAt:He(c.id),enteredLaneAt:qi(c.log??[],He(c.id)),parentNodeId:c.parentNodeId,isClosed:c.parentNodeId===he,readonly:!!c.readonly,tags:Xo(c),assignees:Jo(c)})))}async function Sc(e){let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=us(e);if(d(o))return o;let r=s=>kS(s,n.value,t.value.stateBranchRoot);return e.issueIds?Qo("Closed",yc(o.value,r)):r(o.value[0])}async function Nc(e){let t=fo(e.repoRoot);if(d(t))return t;let n=Q();if(d(n))return n;let o=be({repoRoot:t.value});if(d(o))return o;let r=Et(o.value);if(d(r))return r;let s=Wt(r.value.events,r.value.unreadable);if(d(s))return s;let i=us(e);if(d(i))return i;let c=u=>MS(u,e,n.value,o.value);return e.issueIds?Qo("Moved",yc(i.value,c)):c(i.value[0])}var xc,Th,Ec,kS,Rc,MS,Cc,Ac,kh=h(()=>{"use strict";Xe();Xd();Ke();to();St();Se();ec();dn();K();R();ne();yt();ss();pt();hn();uc();Je();dt();xn();pc();bc();xc=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=X();if(d(n))return n;let o=e.idOrRef.trim();if(!o)return a("Provide an issue id or ref");let r=Object.values(n.value.nodes).filter(P).filter(u=>!u.isDeleted),s=r.find(u=>u.id===o),i=s?[s]:r.filter(u=>Cr(u.id,o));if(i.length===0)return a(`No issue matches "${o}"`);if(i.length>1)return a(`"${o}" matches ${i.length} issues: ${i.map(u=>`${j(u.id)} (${fe(u.title)})`).join(", ")}. Use a full ref or id.`);let c=i[0];return l("Found issue",{id:c.id,ref:j(c.id),title:fe(c.title),description:c.props.description??"",createdAt:He(c.id),enteredLaneAt:qi(c.log??[],He(c.id)),parentNodeId:c.parentNodeId,isClosed:c.parentNodeId===he,readonly:!!c.readonly,tags:Xo(c),assignees:Jo(c),comments:Nh(c.id)})},Th=(e,t)=>e.trim().toLowerCase()===t.trim().toLowerCase();Ec=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;let r=fe(e.title);if(!r)return a("Issue title cannot be empty");let s=e.description??"",i=tt("Issue title",r,300)??tt("Issue description",s,2e4);if(i)return a(i);if((e.tagNames?.length??0)>20)return a(`Cannot set more than ${20} tags at once`);if((e.assigneeNames?.length??0)>20)return a(`Cannot set more than ${20} assignees at once`);let c=wn(e.parentId,n.value,t.value.stateBranchRoot);if(d(c))return c;let u=Fi({name:r,parent:e.parentId,user:n.value,rank:c.value});if(d(u))return u;let m=[...u.value],p=m.find(S=>S.action==="add.issue")?.payload.id;if(!p)return a("Unable to determine created issue id");s&&m.push({id:At(),...n.value,action:"edit.description",payload:{id:p,md:s}});let f=[];for(let S of e.tagNames??[]){let A=fe(S).trim();if(!A||f.some(_=>_.name===A))continue;let w=tt("Tag name",A,60);if(w)return a(w);let k=E.findTagByName(A),D=k?.id??At();k||m.push({id:At(),...n.value,action:"create.tag",payload:{id:D,name:A}}),m.push({id:At(),...n.value,action:"add.issue.tag",payload:{id:p,tag:D}}),f.push({id:D,name:A})}let y=[];for(let S of e.assigneeNames??[]){let A=fe(S).trim();if(!A||y.some(_=>_.name===A))continue;let w=tt("Assignee name",A,80);if(w)return a(w);let k=Object.values(o.value.contributors).find(_=>_.name===A),D=k?.id??At();k||m.push({id:At(),...n.value,action:"create.contributor",payload:{id:D,name:A}}),m.push({id:At(),...n.value,action:"add.issue.assignee",payload:{id:p,assignee:D}}),y.push({id:D,name:A})}let I=L(m,t.value.stateBranchRoot);return d(I)?a(I.message):l("Created issue",{id:p,ref:j(p),title:r,parentId:e.parentId,description:s,tags:f,assignees:y})},kS=(e,t,n)=>{let o=ms(e);if(d(o))return o;let r=jt(he,e,{at:"end"},t,n);if(d(r))return r;let s={id:At(),...t,action:"close.issue",payload:{id:e,parent:he,rank:r.value}},i=L([s],n);return d(i)?a(i.message):l("Closed issue",{id:e,ref:j(e)})};Rc=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;let r=o.value.nodes[e.issueId];if(!r)return a("Issue not found");if(!P(r))return a("Target node is not issue");if(r.parentNodeId!==he)return a("Issue is not closed");let s=$i(r);if(!s)return a("Unable to resolve previous parent from issue history");if(s===he)return a("Previous parent resolves to closed swimlane");let i=o.value.nodes[s];if(!i)return a("Previous parent no longer exists");let c=jt(i.id,r.id,{at:"end"},n.value,t.value.stateBranchRoot);if(d(c))return c;let u={id:At(),...n.value,action:"reopen.issue",payload:{id:r.id,parent:i.id,rank:c.value}},m=L([u],t.value.stateBranchRoot);return d(m)?a(m.message):l("Reopened issue",{id:r.id,ref:j(r.id),parentId:i.id})},MS=(e,t,n,o)=>{let r=ms(e);if(d(r))return r;let s=jt(t.parentId,e,t.position??{at:"end"},n,o);if(d(s))return s;let i={id:At(),...n,action:"move.node",payload:{id:e,parent:t.parentId,rank:s.value}},c=L([i],o);return d(c)?a(c.message):l("Moved issue",{id:e,ref:j(e),parentId:t.parentId})};Cc=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;let r=o.value.nodes[e.issueId];if(!r)return a("Issue not found");if(!P(r))return a("Edit target must be an issue");if(r.readonly)return a("Cannot edit readonly issue");let s=tt("Issue description",e.description,2e4);if(s)return a(s);let i=r.props.description??"";if(i===e.description)return l("No changes made",{id:e.issueId,ref:j(e.issueId),description:i});let c={id:At(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},u=L([c],t.value.stateBranchRoot);return d(u)?a(u.message):l("Edited issue description",{id:e.issueId,ref:j(e.issueId),description:e.description})},Ac=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;let r=o.value.nodes[e.issueId];if(!r)return a("Issue not found");if(!P(r))return a("Edit target must be an issue");if(r.readonly)return a("Cannot edit readonly issue");let s=fe(e.title);if(!s.trim())return a("Issue title cannot be empty");let i=tt("Issue title",s,300);if(i)return a(i);if(r.title===s)return l("No changes made",{id:e.issueId,ref:j(e.issueId),title:s});let c={id:At(),...n.value,action:"edit.title",payload:{id:e.issueId,name:s}},u=L([c],t.value.stateBranchRoot);return d(u)?a(u.message):l("Edited issue title",{id:e.issueId,ref:j(e.issueId),title:s})}});import{ulid as fs}from"ulid";var wc,Tc,kc,Mc,Pc,Lc,Mh=h(()=>{"use strict";Xe();to();St();Se();dn();K();R();yt();hn();Je();dt();Yo();xn();wc=async(e={})=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=X();if(d(n))return n;let o=Object.values(n.value.nodes).filter(r=>r.context==="BOARD"&&!r.isDeleted).map(r=>({id:r.id,ref:j(r.id),title:r.title,parentId:r.parentNodeId,readonly:!!r.readonly}));return l("Listed boards",o)},Tc=async(e={})=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=X();if(d(n))return n;let o=Object.values(n.value.nodes).filter(r=>r.context==="SWIMLANE"&&!r.isDeleted).filter(r=>!e.boardId||r.parentNodeId===e.boardId).map(r=>({id:r.id,title:r.title,boardId:r.parentNodeId,isClosed:r.id===he,readonly:!!r.readonly}));return l("Listed swimlanes",o)},kc=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;let r=o.value.nodes[e.boardId];if(!r)return a("Board not found");if(!gr(r))return a("Target parent must be a board");if(r.readonly)return a("Cannot add a swimlane to a readonly board");if(ls().mode!=="live")return a("Cannot add a swimlane while time travelling");let s=fe(e.title);if(!s.trim())return a("Swimlane title cannot be empty");let i=tt("Swimlane title",s,300);if(i)return a(i);let c=wn(e.boardId,n.value,t.value.stateBranchRoot);if(d(c))return c;let u=fs(),m={id:fs(),...n.value,action:"add.swimlane",payload:{id:u,name:s,parent:e.boardId,rank:c.value}},p=L([m],t.value.stateBranchRoot);return d(p)?a(p.message):l("Created swimlane",{id:u,ref:j(u),title:s,boardId:e.boardId})},Mc=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;let r=o.value.nodes[e.swimlaneId];if(!r)return a("Swimlane not found");if(!Sn(r))return a("Edit target must be a swimlane");if(r.readonly)return a("Cannot edit readonly swimlane");let s=fe(e.title);if(!s.trim())return a("Swimlane title cannot be empty");let i=tt("Swimlane title",s,300);if(i)return a(i);if(r.title===s)return l("No changes made",{id:e.swimlaneId,ref:j(e.swimlaneId),title:s});let c={id:fs(),...n.value,action:"edit.title",payload:{id:e.swimlaneId,name:s}},u=L([c],t.value.stateBranchRoot);return d(u)?a(u.message):l("Edited swimlane title",{id:e.swimlaneId,ref:j(e.swimlaneId),title:s})},Pc=async e=>{let t=fo(e.repoRoot);if(d(t))return t;let n=Q();if(d(n))return n;let o=be({repoRoot:t.value});if(d(o))return o;let r=Et(o.value);if(d(r))return r;let s=Wt(r.value.events,r.value.unreadable);if(d(s))return s;let i=jt(e.boardId,e.swimlaneId,e.position??{at:"end"},n.value,o.value);if(d(i))return i;let c={id:fs(),...n.value,action:"move.node",payload:{id:e.swimlaneId,parent:e.boardId,rank:i.value}},u=L([c],o.value);return d(u)?a(u.message):l("Moved swimlane",{id:e.swimlaneId,ref:j(e.swimlaneId),boardId:e.boardId})},Lc=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;let r=o.value.nodes[e.swimlaneId];if(!r)return a("Swimlane not found");if(!Sn(r))return a("Delete target must be a swimlane");let s={id:fs(),...n.value,action:"delete.node",payload:{id:e.swimlaneId}},i=L([s],t.value.stateBranchRoot);return d(i)?a(i.message):l("Deleted swimlane",{id:e.swimlaneId,ref:j(e.swimlaneId)})}});import{ulid as tr}from"ulid";async function Dc(e){let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=us(e);if(d(o))return o;let r=fe(e.tagName).trim();if(!r)return a("Tag name cannot be empty");let s=tt("Tag name",r,60);if(s)return a(s);let i={done:[],failed:[]};for(let I of o.value){let S=ms(I);d(S)?i.failed.push({id:I,ref:j(I),reason:S.message}):i.done.push({id:I,ref:j(I)})}if(!e.issueIds&&i.failed[0])return a(i.failed[0].reason);if(i.done.length===0)return a(Qo("Tagged",i).message);let c=E.findTagByName(r),u=c?.id??tr(),m=[...c?[]:[{id:tr(),...n.value,action:"create.tag",payload:{id:u,name:r}}],...i.done.map(({id:I})=>({id:tr(),...n.value,action:"add.issue.tag",payload:{id:I,tag:u}}))],p=L(m,t.value.stateBranchRoot);if(d(p))return a(p.message);let f={id:u,name:r};if(!e.issueIds)return l("Added issue tag",{...i.done[0],tag:f});let y=Qo("Tagged",i);return d(y)?y:l(y.message,{...y.value,tag:f})}var Fc,_c,Oc,Ph=h(()=>{"use strict";Se();K();R();ne();hn();Je();dt();xn();bc();Fc=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;let r=o.value.tags[e.tagId];if(!r)return a("Tag not found");if(r.tombstoned)return a("Tag is already deleted");let s=[{id:tr(),...n.value,action:"tombstone.tag",payload:{id:e.tagId}}],i=L(s,t.value.stateBranchRoot);return d(i)?a(i.message):l("Deleted tag",{id:r.id,name:r.name})},_c=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;let r=o.value.tags[e.tagId];if(!r)return a("Tag not found");if(!r.tombstoned)return a("Tag is not deleted");if(E.findTagByName(r.name))return a(`Cannot restore: another tag is already named "${r.name}"`);let s=[{id:tr(),...n.value,action:"restore.tag",payload:{id:e.tagId,name:r.name}}],i=L(s,t.value.stateBranchRoot);return d(i)?a(i.message):l("Restored tag",{id:r.id,name:r.name})},Oc=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;let r=o.value.nodes[e.issueId];if(!r)return a("Issue not found");if(!P(r))return a("Untag target must be an issue");if(r.readonly)return a("Cannot untag readonly issue");if(!o.value.tags[e.tagId])return a("Tag not found");let s={id:tr(),...n.value,action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},i=L([s],t.value.stateBranchRoot);return d(i)?a(i.message):l("Removed issue tag",{id:e.issueId,ref:j(e.issueId),tagId:e.tagId})}});import{ulid as In}from"ulid";var PS,Lh,Bc,Dh,Uc,$c,LS,jc,Hc,Wc,Fh=h(()=>{"use strict";R();M();Ft();Un();St();Se();mc();K();pt();hn();Je();dt();xn();PS=()=>{let e=ze(),t=d(e)?[]:e.value.eventLog??[],n=new Map;for(let o of t)o.userId&&o.userName&&n.set(o.userId,o.userName);return n},Lh=(e,t)=>{let n=new Map(e);for(let o of Object.values(t))n.set(o.id,o.name);return n},Bc=async e=>{let t=na(e.name,"name");if(d(t))return a(t.message);let n=await Y(e.repoRoot,{pull:!1});if(d(n))return n;let o=Q();if(d(o))return o;let r=X();if(d(r))return r;let s=o.value,i=!!r.value.contributors[s.userId];if(!i){let c=L([{id:In(),...s,action:"create.contributor",payload:{id:s.userId,name:s.userName}}],n.value.stateBranchRoot);if(d(c))return a(c.message)}return l(`Assumed ${s.userName}`,{...s,registered:!i})},Dh=async(e,t)=>{let n=Fa(e);if(d(n))return;let o;for(let r of n.value)r.userId===t&&(o=r.userName??o);return o===void 0?void 0:{id:t,name:o}},Uc=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;let r=o.value.nodes[e.issueId];if(!r)return a("Issue not found");if(!P(r))return a("Assign target must be an issue");if(r.readonly)return a("Cannot assign readonly issue");let s=e.self?n.value.userId:e.assigneeId;if(s){let w=o.value.contributors[s],k=w?void 0:await Dh(t.value.stateBranchRoot,s);if(!w&&!k)return a("Unknown assignee id");let D=w??k,_=[...w?[]:[{id:In(),...n.value,action:"create.contributor",payload:{id:D.id,name:D.name}}],{id:In(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:D.id}}],H=L(_,t.value.stateBranchRoot);return d(H)?a(H.message):l("Added issue assignee",{id:e.issueId,ref:j(e.issueId),assignee:{id:D.id,name:D.name}})}let i=fe(e.assigneeName??"").trim();if(!i)return a("Provide assigneeId, self or assigneeName");let c=tt("Assignee name",i,80);if(c)return a(c);let m=[...Lh(PS(),o.value.contributors).entries()].filter(([,w])=>w===i);if(m.length>1)return a(`"${i}" matches ${m.length} contributors (${m.map(([w])=>w).join(", ")}). Assign by assigneeId to choose.`);let p=m[0];if(!p&&!e.createUnlinked)return a(`No contributor named "${i}". Assign by id, or pass createUnlinked to add them as an external assignee.`);let[f=In(),y=i]=p??[],S=[...!!o.value.contributors[f]?[]:[{id:In(),...n.value,action:"create.contributor",payload:{id:f,name:y}}],{id:In(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:f}}],A=L(S,t.value.stateBranchRoot);return d(A)?a(A.message):l("Added issue assignee",{id:e.issueId,ref:j(e.issueId),assignee:{id:f,name:y}})},$c=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;if(!o.value.contributors[e.contributorId])return a("Contributor not found");if(await Dh(t.value.stateBranchRoot,e.contributorId))return a("Cannot remove a contributor who has authored events \u2014 their name appears throughout the log");let i=[{id:In(),...n.value,action:"tombstone.contributor",payload:{id:e.contributorId}}],c=L(i,t.value.stateBranchRoot);return d(c)?a(c.message):l("Tombstoned contributor",{id:e.contributorId,name:bs})},LS=async(e,t)=>{let n=Jn(e);if(d(n))return;let o;for(let r of n.value){if(r.action!=="create.contributor")continue;let s=r.payload;s.id===t&&s.name&&(o=s.name)}return o},jc=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;let r=o.value.contributors[e.contributorId];if(!r)return a("Contributor not found");if(!r.tombstoned)return a("Contributor is not tombstoned");let s=await LS(t.value.stateBranchRoot,e.contributorId);if(!s)return a("Cannot restore this contributor \u2014 no original name found in the event log");let i=[{id:In(),...n.value,action:"restore.contributor",payload:{id:e.contributorId,name:s}}],c=L(i,t.value.stateBranchRoot);return d(c)?a(c.message):l("Restored contributor",{id:e.contributorId,name:s})},Hc=async(e={})=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;let r=Jn(t.value.stateBranchRoot);if(d(r))return a(r.message);let s=e.boardId?xh(r.value,e.boardId):r.value,i=new Map,c=new Set,u=new Set,m=Fa(t.value.stateBranchRoot);if(d(m))return a(m.message);for(let I of m.value)I.userId&&u.add(I.userId);for(let I of s)I.userId&&(i.set(I.userId,I.userName??""),c.add(I.userId));let p=o.value.contributors,y=[...Lh(i,p).entries()].map(([I,S])=>({id:I,name:S,color:Te(S),isSelf:I===n.value.userId,isExternal:!c.has(I),isRemoved:p[I]?.tombstoned===!0,hasAuthoredAnywhere:u.has(I)}));return l("Listed board contributors",y)},Wc=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;let r=o.value.nodes[e.issueId];if(!r)return a("Issue not found");if(!P(r))return a("Unassign target must be an issue");if(r.readonly)return a("Cannot unassign readonly issue");if(!o.value.contributors[e.assigneeId])return a("Assignee not found");let s={id:In(),...n.value,action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},i=L([s],t.value.stateBranchRoot);return d(i)?a(i.message):l("Removed issue assignee",{id:e.issueId,ref:j(e.issueId),assigneeId:e.assigneeId})}});import{ulid as Ki}from"ulid";var qc,Gc,zc,_h=h(()=>{"use strict";Se();K();R();hn();xn();qc=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;let r=o.value.nodes[e.issueId];if(!r)return a("Issue not found");if(!P(r))return a("Comment target must be an issue");if(r.readonly)return a("Cannot comment on readonly issue");let s=e.body.trim();if(!s)return a("Comment cannot be empty");if(s.length>4e3)return a(`Comment cannot exceed ${4e3} characters (got ${s.length})`);let i=Ki(),c={id:Ki(),...n.value,action:"add.issue.comment",payload:{id:i,issue:e.issueId,md:s,author:n.value.userId}},u=L([c],t.value.stateBranchRoot);return d(u)?a(u.message):l("Added issue comment",{id:i,issueId:e.issueId,body:s})},Gc=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;let r=o.value.eventLog.find(m=>m.action==="add.issue.comment"&&m.payload.id===e.commentId);if(!r)return a("Unable to resolve comment");if(r.payload.author!==n.value.userId)return a("You can only delete your own comments");let s=o.value.nodes[r.payload.issue];if(!s)return a("Issue not found");if(!P(s))return a("Comment target must be an issue");if(s.readonly)return a("Cannot delete comment on readonly issue");if(o.value.eventLog.some(m=>m.action==="delete.issue.comment"&&m.payload.id===e.commentId))return l("Comment already deleted",{id:e.commentId,issueId:r.payload.issue});let c={id:Ki(),...n.value,action:"delete.issue.comment",payload:{id:e.commentId,issue:r.payload.issue}},u=L([c],t.value.stateBranchRoot);return d(u)?a(u.message):l("Deleted issue comment",{id:e.commentId,issueId:r.payload.issue})},zc=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;let r=o.value.eventLog.find(p=>p.action==="add.issue.comment"&&p.payload.id===e.commentId);if(!r)return a("Unable to resolve comment");if(r.payload.author!==n.value.userId)return a("You can only edit your own comments");let s=o.value.nodes[r.payload.issue];if(!s)return a("Issue not found");if(!P(s))return a("Comment target must be an issue");if(s.readonly)return a("Cannot edit comment on readonly issue");if(o.value.eventLog.some(p=>p.action==="delete.issue.comment"&&p.payload.id===e.commentId))return a("Comment was deleted");let c=e.body.trim();if(!c)return a("Comment cannot be empty");if(c.length>4e3)return a(`Comment cannot exceed ${4e3} characters (got ${c.length})`);let u={id:Ki(),...n.value,action:"edit.issue.comment",payload:{id:e.commentId,issue:r.payload.issue,md:c}},m=L([u],t.value.stateBranchRoot);return d(m)?a(m.message):l("Edited issue comment",{id:e.commentId,issueId:r.payload.issue,body:c})}});var Oh=h(()=>{"use strict";wh();kh();Mh();Ph();Fh();_h();gc()});import{ulid as DS}from"ulid";var Bh,Uh,$h,jh=h(()=>{"use strict";Un();Ao();zt();R();Gd();xt();Bh=[{name:"userName",question:"the name they want to appear under on the board"},{name:"preferredEditor",question:'the command that opens a file for editing, e.g. "vim", "nano" or "code --wait"'},{name:"autoSync",question:"whether the TUI and GUI should sync with the git remote on their own (true or false)"}],Uh=e=>e.trim().toLowerCase(),$h=async(e={})=>{let t=ko();if(d(t))return a(t.message);let n=t.value,o=e.userName?.trim(),r=(process.env[gt]??"").trim();if(o&&r&&Uh(o)===Uh(r))return a(`userName "${o}" is this agent's own identity. Pass the user's name, the one they want the TUI and GUI to write as.`);let s={userName:o||void 0,preferredEditor:e.preferredEditor?.trim()||void 0,autoSync:e.autoSync},i={userName:n.userName?.trim()||void 0,preferredEditor:n.preferredEditor?.trim()||void 0,autoSync:typeof n.autoSync=="boolean"?n.autoSync:void 0};for(let w of Bh){let k=s[w.name],D=i[w.name];if(!(k===void 0||D===void 0||k===D))return a(`This machine is already set up with ${w.name} ${JSON.stringify(D)}; epiq_project_init does not change it. Call again without ${w.name}, or let the user change it in the TUI with :config.`)}let c={};if(s.userName&&!i.userName&&(c.userName=s.userName),s.preferredEditor&&!i.preferredEditor&&(c.preferredEditor=s.preferredEditor),s.autoSync!==void 0&&i.autoSync===void 0&&(c.autoSync=s.autoSync),(c.userName||i.userName)&&!n.userId&&(c.userId=DS()),Object.keys(c).length>0){let w=et(c);if(d(w))return a(w.message)}let u={...n,...c},m=Bh.filter(w=>{let k=u[w.name];return typeof k=="boolean"?!1:!k?.trim()});if(m.length>0){let w=m.map(k=>`${k.name} (${k.question})`).join("; ");return a(`Setup incomplete. Ask the user for: ${w}. Then call epiq_project_init again with the answers; what was given so far is saved.`)}let p={userId:u.userId??"",userName:u.userName??""};if(!p.userId||!p.userName)return a("Missing Epiq user id");let f=await Li({cwd:e.repoRoot??process.cwd(),user:p});if(d(f))return f;let{defaultEvents:y,...I}=f.value,S=jr({root:I.repoRoot});d(S)&&J.info(S.message);let A=I.warnings.length===0?"Project initialized":`Project initialized, with warnings: ${I.warnings.join(" ")}`;return l(A,{...I,user:p})}});var Zt,Yi=h(()=>{"use strict";Zt=e=>({path:e.path,sha:e.shas[e.shas.length-1]??""})});var FS,Hh,Wh=h(()=>{"use strict";Yi();FS=e=>{let t=e.lastIndexOf("/");return t===-1?".":e.slice(0,t)},Hh=({commits:e,patch:t})=>{let n=e.map(i=>i.time),r=t.files.map(i=>({...Zt(i),changed:i.addedCount+i.removed})).reduce((i,c)=>i===null||c.changed>i.changed?c:i,null),s=t.insertions+t.deletions;return{commits:e.length,authors:[...new Set(e.map(i=>i.author))].sort(),firstCommitAt:n.length?Math.min(...n):null,lastCommitAt:n.length?Math.max(...n):null,files:t.files.length,filesAdded:t.files.filter(i=>i.status==="added").length,filesModified:t.files.filter(i=>i.status==="modified").length,filesDeleted:t.files.filter(i=>i.status==="deleted").length,binaryFiles:t.files.filter(i=>i.binary).length,directories:new Set(t.files.map(i=>FS(i.path))).size,insertions:t.insertions,deletions:t.deletions,net:t.insertions-t.deletions,largestFile:r,concentration:r&&s>0?r.changed/s:0,selfChurn:t.selfChurn,truncated:t.truncated}}});var Oe,wt,Vc,nr,_S,$,Xi,Ji,qh,OS,Gh,go,gs,BS,US,or,$S,jS,HS,Lt,zh,Vh,Kh,WS,qS,Yh,Xh,rr=h(()=>{"use strict";Oe={line:["//"],block:[["/*","*/"]]},wt={line:["#"],block:[]},Vc={line:["--"],block:[]},nr={line:[],block:[["<!--","-->"]]},_S={line:[],block:[]},$=(e,t)=>({name:e,comment:t}),Xi=$("TypeScript",Oe),Ji=$("JavaScript",Oe),qh={ts:Xi,tsx:Xi,mts:Xi,cts:Xi,js:Ji,jsx:Ji,mjs:Ji,cjs:Ji,py:$("Python",{line:["#"],block:[['"""','"""']]}),rb:$("Ruby",{line:["#"],block:[["=begin","=end"]]}),go:$("Go",Oe),rs:$("Rust",Oe),java:$("Java",Oe),kt:$("Kotlin",Oe),swift:$("Swift",Oe),c:$("C",Oe),h:$("C",Oe),cc:$("C++",Oe),cpp:$("C++",Oe),hpp:$("C++",Oe),cs:$("C#",Oe),php:$("PHP",Oe),scala:$("Scala",Oe),dart:$("Dart",Oe),lua:$("Lua",Vc),hs:$("Haskell",Vc),sql:$("SQL",Vc),ex:$("Elixir",wt),exs:$("Elixir",wt),pl:$("Perl",wt),r:$("R",wt),jl:$("Julia",wt),sh:$("Shell",wt),bash:$("Shell",wt),zsh:$("Shell",wt),vue:$("Vue",nr),svelte:$("Svelte",nr),html:$("HTML",nr),xml:$("XML",nr),md:$("Markdown",nr),mdx:$("Markdown",nr),css:$("CSS",{line:[],block:[["/*","*/"]]}),scss:$("CSS",Oe),less:$("CSS",Oe),yml:$("YAML",wt),yaml:$("YAML",wt),toml:$("TOML",wt),ini:$("INI",wt),json:$("JSON",_S)},OS="Other",Gh=e=>{let t=e.slice(e.lastIndexOf("/")+1),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()},go=e=>qh[Gh(e)]?.name??OS,gs=e=>qh[Gh(e)]?.comment??null,BS=[/\.(test|spec)\.[a-z0-9]+$/i,/(^|\/)test_[^/]+\.py$/,/_test\.[a-z0-9]+$/i,/(^|\/)conftest\.py$/,/Tests?\.(java|kt|cs|scala)$/],US=/(^|\/)(tests?|__tests__|spec|specs|e2e|src\/test|features)\//i,or=e=>US.test(e)||BS.some(t=>t.test(e)),$S=/(^|\/)(package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|Cargo\.lock|go\.sum|poetry\.lock|Gemfile\.lock|composer\.lock)$/,jS=/(^|\/)(node_modules|dist|build|out|target|vendor|coverage|\.next|__snapshots__)\//,HS=/(\.min\.(js|css)|\.map|\.snap|\.pb\.go|_pb2\.py)$/,Lt=e=>$S.test(e)||jS.test(e)||HS.test(e),zh=e=>/(^|\/)(package\.json|go\.mod|Cargo\.toml|requirements[^/]*\.txt|pyproject\.toml|Gemfile|composer\.json|pom\.xml|build\.gradle(\.kts)?)$/.test(e),Vh=e=>/(^|\/)\.github\/workflows\//.test(e)||/(^|\/)(Dockerfile|docker-compose[^/]*\.ya?ml|Makefile|Jenkinsfile|\.gitlab-ci\.yml)$/.test(e)||/\.tf$/.test(e),Kh=e=>/\.(md|mdx|rst|txt)$/i.test(e)||/(^|\/)docs?\//i.test(e),WS=/\b(it|test|describe|context|suite)\.skip\b|\bx(it|describe|test)\s*\(|@pytest\.mark\.skip|@unittest\.skip|\bt\.Skip\s*\(|@(Ignore|Disabled)\b/,qS=/\b(it|test|describe|context|suite)\.only\b|\bf(it|describe|test)\s*\(/,Yh=e=>WS.test(e),Xh=e=>qS.test(e)});var Jh,GS,Kc,zS,Qh,Yc=h(()=>{"use strict";rr();Jh=/\b(TODO|FIXME|HACK|XXX)\b/,GS=/[;{}]\s*$|^\s*(const|let|var|function|def|class|if|for|while|return|import|export|await|print)\b.*[=(]/,Kc=(e,t)=>{let n=e.trim();return n===""?"blank":t&&(t.line.some(o=>n.startsWith(o))||t.block.some(([o])=>n.startsWith(o))||t.block.some(([o])=>o==="/*")&&(n.startsWith("*")||n.startsWith("*/")))?"comment":"code"},zS=(e,t)=>{let n=e.trim();for(let o of[...t.line,...t.block.flat(),"*"])if(n.startsWith(o)){n=n.slice(o.length).trim();break}return n},Qh=({patch:e,repoShareByLanguage:t})=>{let n=new Map,o=0,r=0,s=0,i=0,c=0,u=0;for(let p of e.files){if(p.binary||Lt(p.path))continue;let f=gs(p.path);if(!f||f.line.length===0&&f.block.length===0)continue;let y=go(p.path),I=n.get(y)??{comment:0,code:0};for(let{text:S}of p.added){let A=Kc(S,f);if(Jh.test(S)&&i++,A==="blank"){s++;continue}if(A==="comment"){o++,I.comment++,f&&GS.test(zS(S,f))&&u++;continue}r++,I.code++}for(let{text:S}of p.removedLines)Jh.test(S)&&c++;n.set(y,I)}let m=o+r;return{byLanguage:[...n.entries()].map(([p,f])=>({name:p,commentLines:f.comment,codeLines:f.code,share:f.comment+f.code===0?0:f.comment/(f.comment+f.code),repoShare:t?.get(p)??null})).sort((p,f)=>f.commentLines+f.codeLines-(p.commentLines+p.codeLines)),commentLines:o,codeLines:r,blankLines:s,share:m===0?0:o/m,todoLinesAdded:i,todoLinesRemoved:c,commentedOutCodeLines:u}}});var VS,Qi,Xc,KS,YS,XS,Zh,ev=h(()=>{"use strict";rr();Yi();VS=/\bconsole\.(log|debug|dir)\s*\(|\bdebugger\b|^\s*print\s*\(|\bfmt\.Print(ln|f)?\s*\(|\bSystem\.out\.print|\bdbg!\s*\(/,Qi=6,Xc=10,KS=e=>{let t=0;for(let n of e){if(n.trim()===""||n.startsWith(" "))continue;let o=n.length-n.trimStart().length;o>0&&(t===0||o<t)&&(t=o)}return Math.min(Math.max(t,2),8)},YS=(e,t)=>{let n=e.length-e.trimStart().length;if(n===0)return 0;let o=e.slice(0,n).split(" ").length-1;return o>0?o:Math.floor(n/t)},XS=e=>{if(e.length<Qi*2)return 0;let t=new Map,n=new Array(e.length).fill(!1);for(let o=0;o+Qi<=e.length;o++){let r=e.slice(o,o+Qi);if(r.some(c=>c.text.length<3))continue;let s=r.map(c=>c.text).join(`
|
|
95
|
+
`),i=t.get(s);if(i===void 0){t.set(s,{...r[0],at:o});continue}if(i.file!==r[0]?.file)for(let c=0;c<Qi;c++)n[i.at+c]=!0,n[o+c]=!0}return n.filter(Boolean).length},Zh=({patch:e})=>{let t=[],n=[],o=[],r=!1,s=0,i=0,c=null,u=[];for(let[m,p]of e.files.entries()){if(Lt(p.path)&&t.push(Zt(p)),zh(p.path)&&n.push(Zt(p)),Vh(p.path)&&o.push(Zt(p)),Kh(p.path)&&(r=!0),p.binary||Lt(p.path))continue;let f=p.added.map(S=>S.text),y=KS(f),I=p.status!=="deleted";for(let S of f){VS.test(S)&&s++;let A=YS(S,y);A>i&&(i=A,c=Zt(p)),I&&u.push({text:S.trim(),file:m})}u.push({text:" ",file:m})}return{generatedPaths:t.slice(0,Xc),dependencyManifests:n.slice(0,Xc),buildOrCiPaths:o.slice(0,Xc),docsTouched:r,debugPrintLinesAdded:s,maxIndentLevels:i,deepestFile:c,duplicatedLines:XS(u)}}});var tv,nv=h(()=>{"use strict";rr();tv=({patch:e,languagesBefore:t})=>{let n=new Map,o=0;for(let i of e.files){if(i.binary)continue;let c=i.addedCount+i.removed;if(Lt(i.path)){o+=c;continue}let u=go(i.path),m=n.get(u)??{name:u,added:0,removed:0,addedInTests:0,share:0};m.added+=i.addedCount,m.removed+=i.removed,or(i.path)&&(m.addedInTests+=i.addedCount),n.set(u,m)}let r=[...n.values()].reduce((i,c)=>i+c.added+c.removed,0),s=[...n.values()].map(i=>({...i,share:r===0?0:(i.added+i.removed)/r})).sort((i,c)=>c.added+c.removed-(i.added+i.removed));return{languages:s,introduced:t===null?[]:s.filter(i=>!t.has(i.name)).map(i=>i.name),generatedLines:o}}});var JS,Jc,QS,ov,ZS,Qc,eR,tR,rv,sv,nR,oR,rR,iv,av=h(()=>{"use strict";ct();R();JS=200,Jc=2e5,QS=5e4,ov=25,ZS=64*1024*1024,Qc="",eR=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/,tR=/^diff --git a\/(.+) b\/\1$/,rv=(e,t)=>e==="/dev/null"?null:e.startsWith(t)?e.slice(2):e,sv=(e,t)=>e===null?"added":t===null?"deleted":"modified",nR=()=>({byPath:new Map,insertions:0,deletions:0,selfChurn:0,retainedLines:0}),oR=(e,t)=>{let n=e.byPath,o="",r=null,s=null,i=null,c=!1,u=0,m=(f,y)=>y==="modified"&&f==="added"?"added":y,p=(f,y)=>{let I=n.get(f);if(I)return I.entry.status=m(I.entry.status,y),I.entry.shas.includes(o)||I.entry.shas.push(o),I;let A={entry:{path:f,status:y,binary:!1,added:[],addedCount:0,removed:0,removedLines:[],shas:[o]},pendingByText:new Map};return n.set(f,A),A};for(let f of t.split(`
|
|
96
|
+
`)){if(f.startsWith(Qc)){o=f.slice(Qc.length).trim(),r=null,s=null,i=null,c=!1;continue}if(f.startsWith("diff --git ")){r=null,i=null,c=!0,s=tR.exec(f)?.[1]??null;continue}if(c&&f.startsWith("Binary files ")&&s){let[,I=""]=/^Binary files (.*) differ$/.exec(f)??[],[S="",A=""]=I.split(" and ");r=p(s,sv(S==="/dev/null"?null:S,A==="/dev/null"?null:A)),r.entry.binary=!0;continue}if(c&&f.startsWith("--- ")){i=rv(f.slice(4),"a/");continue}if(c&&f.startsWith("+++ ")){let I=rv(f.slice(4),"b/"),S=I??i??s;S&&(r=p(S,sv(i,I)));continue}let y=eR.exec(f);if(y){u=Number(y[1]),c=!1;continue}if(r){if(f.startsWith("+")){let I=f.slice(1);e.insertions++,r.entry.addedCount++,e.retainedLines<Jc&&(r.entry.added.push({sha:o,line:u,text:I}),e.retainedLines++),r.pendingByText.size<QS&&r.pendingByText.set(I,(r.pendingByText.get(I)??0)+1),u++;continue}if(f.startsWith("-")){let I=f.slice(1);e.deletions++,r.entry.removed++,e.retainedLines<Jc&&(r.entry.removedLines.push({sha:o,line:0,text:I}),e.retainedLines++);let S=r.pendingByText.get(I)??0;S>0&&I.trim().length>2&&(e.selfChurn++,r.pendingByText.set(I,S-1))}}}},rR=e=>({files:[...e.byPath.values()].map(t=>t.entry),insertions:e.insertions,deletions:e.deletions,selfChurn:e.selfChurn,retainedLines:e.retainedLines}),iv=async({repoRoot:e,shas:t})=>{if(t.length===0)return l("No commits to scan",{files:[],insertions:0,deletions:0,selfChurn:0,scannedCommits:0,truncated:!1});let n=t.slice(0,JS).reverse(),o=nR(),r=0,s=0,i=!1;for(let u=0;u<n.length;u+=ov){let m=n.slice(u,u+ov),p=await W({cwd:e,args:["-c","core.quotePath=false","show","--unified=0","--no-renames","--no-color",`--format=${Qc}%H`,...m]});if(d(p))return a(p.message);if(oR(o,p.value.stdout),r+=p.value.stdout.length,s+=m.length,r>ZS){i=!0;break}}let c=rR(o);return l("Scanned ticket patch",{files:c.files,insertions:c.insertions,deletions:c.deletions,selfChurn:c.selfChurn,scannedCommits:s,truncated:i||s<t.length||c.retainedLines>=Jc})}});var sR,iR,dv,cv=h(()=>{"use strict";ct();R();Yc();rr();sR=40,iR=/^\d{6} blob ([0-9a-f]{40})\t(.+)$/,dv=async({repoRoot:e,sha:t})=>{let n=await Be({cwd:e,args:["-c","core.quotePath=false","ls-tree","-r",`${t}~1`]});if(n.exitCode!==0)return null;let o=new Set,r=new Map;for(let p of n.stdout.split(`
|
|
97
|
+
`)){let f=iR.exec(p);if(!f)continue;let[,y="",I=""]=f;if(Lt(I))continue;let S=go(I);if(o.add(S),or(I)||!gs(I))continue;let A=r.get(S)??[];A.length<sR&&(A.push({blob:y,path:I}),r.set(S,A))}let s=[...r.values()].flat(),i=await la(s.map(p=>p.blob),e);if(d(i))return{languages:o,commentShareByLanguage:new Map};let c=i.value,u=new Map;for(let{blob:p,path:f}of s){let y=c.get(p);if(y===void 0)continue;let I=gs(f),S=go(f),A=u.get(S)??{comment:0,code:0};for(let w of y.split(`
|
|
98
|
+
`)){let k=Kc(w,I);k==="comment"&&A.comment++,k==="code"&&A.code++}u.set(S,A)}let m=new Map;for(let[p,f]of u){let y=f.comment+f.code;y>0&&m.set(p,f.comment/y)}return{languages:o,commentShareByLanguage:m}}});var lv,uv=h(()=>{"use strict";rr();Yi();lv=({patch:e})=>{let t=0,n=0,o=[],r=[],s=0,i=0;for(let c of e.files)if(!(c.binary||Lt(c.path))&&or(c.path)){t+=c.addedCount,n+=c.removed,c.status==="added"&&o.push(Zt(c)),c.status==="deleted"&&r.push(Zt(c));for(let{text:u}of c.added)Yh(u)&&s++,Xh(u)&&i++}return{testLinesAdded:t,testLinesRemoved:n,addedTestFiles:o,deletedTestFiles:r,skippedTestLinesAdded:s,focusedTestLinesAdded:i}}});var aR,mv,pv=h(()=>{"use strict";R();Wh();Yc();ev();nv();av();cv();uv();aR=e=>e.reduce((t,n)=>t===null||n.time<t.time?n:t,null)?.sha??null,mv=async({repoRoot:e,ref:t,commits:n})=>{let o=await iv({repoRoot:e,shas:n.map(c=>c.sha)});if(d(o))return a(o.message);let r=o.value,s=aR(n),i=s?await dv({repoRoot:e,sha:s}):null;return l("Derived issue stats",{ref:t,shape:Hh({commits:n,patch:r}),languages:tv({patch:r,languagesBefore:i?.languages??null}),tests:lv({patch:r}),comments:Qh({patch:r,repoShareByLanguage:i?.commentShareByLanguage??null}),flags:Zh({patch:r})})}});var dR,hs,cR,fv,gv=h(()=>{"use strict";R();pv();Je();ae();Yo();dR=32,hs=new Map,cR=(e,t)=>{if(hs.set(e,t),hs.size>dR){let n=hs.keys().next();n.done||hs.delete(n.value)}return t},fv=async(e={idOrRef:""})=>{let t=e.idOrRef.trim();if(!t)return a("idOrRef must not be empty");let n=t.length>7?j(t):t.toUpperCase(),o=Me(e.repoRoot??process.cwd());if(d(o))return a(o.message);let r=o.value,s=await Rh({repoRoot:r,ref:n});if(d(s))return a(s.message);let i=s.value.map(p=>({sha:p.sha,time:p.time,author:p.author,subject:p.subject})),c=[r,n,i.map(p=>p.sha).join(",")].join(" "),u=hs.get(c);if(u)return l("Derived issue stats",u);let m=await mv({repoRoot:r,ref:n,commits:i});return d(m)?a(m.message):l("Derived issue stats",cR(c,m.value))}});var sr,Zc,hv=h(()=>{"use strict";sr=".claude/skills/epiq/SKILL.md",Zc="---\nname: epiq\ndescription: Workflow rules for working the epiq issue board \u2014 use the epiq MCP, sync on demand, scope tickets small, keep status/tags accurate, and communicate via comments.\n---\n\n# Epiq board workflow\n\n- **Never test against the real board.** Point any dev server, manual test or test run at a throwaway project, never at this repo's own. Deleting test tickets afterwards does not undo the events. Stop the dev server when you're done rather than leaving it autosyncing.\n- **Use the epiq MCP tools** (`epiq_*`) for all board operations \u2014 never the `epiq` CLI or hand-edited state files.\n- **Never edit the state branch directly.** Don't check it out, don't write to its worktree, don't touch the event log or any file under it by hand or by script \u2014 go through the MCP for every read and write. The event log is the system of record: an edit made outside it bypasses validation and ordering, and can corrupt history in ways no later fix can undo.\n- **Sync is on-demand only.** MCP reads/writes operate on local state and never pull/push automatically. Call `epiq_sync` explicitly when you need the latest remote state or want to publish local changes.\n- **Break work into small, scoped tickets.** One ticket per independent unit of work, not one giant ticket for a whole feature/epic. Small tickets move through the board cleanly and are easier to review.\n- **A small request tightly coupled to a ticket goes into that ticket, not a new one.** When the user asks for a tweak that only makes sense as part of work a ticket already covers \u2014 halving a limit it just introduced, moving a control it just added \u2014 do not file a fresh ticket for it. Record the new requirement as a comment on the original ticket and fold it into the description, move the ticket back to Ongoing if it had already reached Done, prefix the follow-up's commits with that ticket's ref, and add a further `Solution:` comment when it lands, so the ticket's own commit list tells the whole story. `QPPR7PE` is what this avoids: a one-line follow-up to `MBB6WY5` (halve the log cap it had just introduced) that now lives on a ticket of its own. The original does not have to be the ticket you took this session: any ticket open on the board and assigned to you counts. A new ticket is for work that stands on its own \u2014 that someone else could pick up cold, or that needs more than a line or two to describe.\n- **Keep the status column current as work progresses**\n- **Assign the ticket to yourself when you pick it up**, alongside moving it to Ongoing \u2014 so the board shows who is on what, not just what is in flight.\n- **A ticket you file for work you will do this session is assigned to you as you file it.** Filing it unassigned and picking it up a minute later leaves a window where the board shows nobody on it. Picking up a ticket assigned to somebody else is fine \u2014 but ask the user first: it may be mid-flight in another session, and the assignee is what says so.\n- **Take a name as soon as this skill loads, and say it.** Your board identity is `provider/human-name` \u2014 the model provider, a slash, then a short human first name: `claude/peter`, `codex/fred`. Announce it as your first line, exactly `Assuming claude/peter`, and work under it for the whole session so the log reads \"claude/peter did X\" rather than signing the user's name to your work. Before inventing one, call `epiq_contributor_list` and reuse an existing identity for your provider if there is one \u2014 a name is permanent once it has authored anything (`tombstoneContributor` refuses authors), and each new one adds a contributor and an event log file forever. Keep the name stable across sessions; never rename yourself mid-session.\n- **Make the name true with `epiq_actor_assume`, before your first board write.** Announcing alone changes nothing: the writes would still be signed with the user's name. The tool takes the identity for the rest of the session and registers it, so the board carries `claude/peter` rather than the sanitized `claude-peter` the log file name would give. It is idempotent, so re-announcing is free; if it refuses because the server was launched under a name, that name wins \u2014 work under the one it reports and say so. Never claim an attribution the tool did not confirm.\n- **Boot your own MCP instance, and never share one.** `epiq_actor_assume` binds the name to the server process it is called on, so two sessions on one server \u2014 or a session on the user's own instance \u2014 would sign every write with whichever name was assumed last, and the log would fold them into one contributor. Every session therefore needs a server process of its own before its first board call: the one Claude Code spawns for the session counts, and if that never connected (a `CONNECT_TIMEOUT` at boot), start one yourself \u2014 `npx -y -p epiq@latest epiq-mcp` speaks MCP JSON-RPC over stdio, so a small script holding that process and forwarding `tools/call` requests is enough \u2014 rather than waiting on the user or borrowing another session's. Assume the name on *that* process; a restart forgets it, so assume it again before the next write. Kill what you started when the session ends, including the `epiq-mcp` child, which outlives its parent.\n- **When other agents may be running, ask which name to take rather than picking one.** Nothing stops two live agents answering to one name \u2014 the log is a CRDT and takes concurrent writers happily, so they would converge into one indistinguishable identity rather than fail. Another session is likely whenever there is more than one `epiq-mcp` process, another worktree with recent changes, or the user says so; in that case list the existing names for your provider from `epiq_contributor_list` and ask the user which one is free, before `epiq_actor_assume` \u2014 a name once assumed binds the server process, and a second name is refused until it restarts. Ask with the names in the question, not \"which name?\": the user is choosing between identities they can see on the board.\n- **Name the terminal window after the identity.** Several sessions look alike; the name in the tab is how the user tells which window is `claude/peter`. The session cannot reach the terminal itself \u2014 the shell it runs has no tty \u2014 so put the request in the announcement line: `Assuming claude/peter \u2014 please /rename claude/peter so this window carries the name.`\n- **Prefix commits with the ticket ref. **Retrieve the ref programmatically, NEVER DERIVE IT.\\*\\* Read the `ref` field off the MCP response (`epiq_issue_list` and `epiq_board_list` include it on every entry). This is what link-by-reference feature matches on.\n- **Work in a worktree, and leave the root checkout alone.** Take one before the first edit (`EnterWorktree`, or `git worktree add .claude/worktrees/<ref>-<slug>` for a branch that already exists), and never check a feature branch out at the root: the root is where `main` belongs and where the user checks it out themselves, and a branch checked out anywhere is unavailable everywhere else. For the same reason `main` never goes *into* a worktree. Several sessions share this repository at once, so a shared checkout also means one session's `checkout` or `reset` quietly discarding another's work. A fresh worktree needs its own `npm install` before the hooks and suites will run there.\n- **Never work on main, and never merge into it locally. Every change reaches main through a pull request.** Branch before the first edit, push the branch, open the PR, let the gate run, then integrate it. A local merge into `main` looks like it worked and is invisible to everyone else: the work is on nobody's remote, no PR ran the gate over it, and it is one `git fetch origin +main:main` away from vanishing from the branch you are sitting on. That has already happened here \u2014 a tag-filter feature and a scrubber-URL feature lived only in one machine's local `main` for a day, and disappeared the moment somebody synced main with the remote. If you find yourself with commits on local `main`, move them onto a branch and open a PR before doing anything else.\n- **Always rebase onto the target, never merge into it.** Rebase the branch onto the target first, then integrate with a rebase merge \u2014 `gh pr merge --rebase`, never `--merge`. Main stays a flat sequence of ref-prefixed commits, which is what the commit\u2194ticket linking reads. A merge commit adds a subject carrying no ref and buries the branch's commits behind it.\n- **Squashing the branch down first is fine \u2014 one commit per ticket ref.** A branch's worth of fixups is history nobody needs on main, so collapsing it into a single commit (`git rebase -i`, or `gh pr merge --squash` with a ref-prefixed subject) is welcome, provided every commit that lands still opens with its ticket's ref. What the linking cannot survive is a squash *across* refs: fold two tickets' commits into one subject and one of them loses its commits for good. So a branch carrying two refs squashes to two commits, not one \u2014 and check the resulting subject before integrating, because `--squash` defaults to the PR title, which is only right if the title carries the ref.\n- **The git user is the sole author of every commit you write.** Commit under the repo's configured `user.name` / `user.email` and nothing else: no `Co-Authored-By:` line, no `Claude-Session:` line, no `\u{1F916} Generated with` footer, and never an `--author` override naming Claude or a tool. The commit body ends with the last line of prose. This holds for amends and rebases too \u2014 check `git log --format='%an <%ae>%n%b'` over the branch before pushing, because a trailer added by a default template survives a rebase and reaches main unnoticed. It does **not** license rewriting anyone else's authorship: commits by other contributors keep their author, and reassigning them would both misattribute their work and mean force-pushing main.\n- **Tag tickets properly.** Reuse existing tags where they fit (check current issues/tags first) instead of inventing near-duplicates.\n- **Read the ticket's comments before starting, not just its description.** The description is what was known when the ticket was written; comments carry later context \u2014 narrowed scope, a decision already taken, a dead end someone hit, a correction to the original diagnosis. Working from the description alone risks redoing settled work or implementing something that was already ruled out.\n- **Use comments to communicate deviations.** If the work diverges from what the ticket describes \u2014 scope changes, findings, blockers, test results \u2014 record it as a comment on the ticket, not just in chat.\n- When a ticket is done, **Document the outcome in a comment starting with `Solution:`.** Use that exact prefix as the comment's opening line, so `^Solution:` finds every resolved ticket on the board. Say what actually resolved it \u2014 the commit, the approach taken, and anything a reader would otherwise have to reverse-engineer from the diff; a bare commit hash is not a solution. Use the same prefix when a ticket is closed _without_ a code change, and say why.\n- **Attach a screenshot only when a picture carries what words cannot** \u2014 a layout that has to be seen, a rendering bug, a chart whose shape is the point. It is the special case, not a routine part of a `Solution:` comment: most outcomes are better described than photographed, and a screenshot of something a sentence already covers costs everyone the bytes below. When one does earn its place, use `epiq_issue_attachment_add` (it takes a file path) and paste the `markdown` it returns into the comment.\n- **Crop and compress it first.** `epiq_issue_attachment_add` stores the file exactly as it finds it \u2014 only the GUI compresses on upload \u2014 so a raw full-screen capture goes in at full size, up to the 500 KB cap. The blob lands in `.epiq/media/` on the state branch, replicates to every clone, and is never removed: deleting an attachment writes a tombstone and the bytes stay, so time travel can still resolve them. Crop to the region that makes the point, scale it down, and land well under the cap rather than against it. An oversized image is permanent, for everybody \u2014 the same reason the text limits exist.\n- **Be concise.** Titles, descriptions, and comments should be scannable, not essays.\n- If a ticket is blocked, **record the blocker in a comment** and move it to Blocked (or tag it blocked if there is no Blocked column).\n- If a you decide to take a new approach, make sure to document the fork in a new comment, and tag the ticket with a \"fork\" tag, **update the description** to reflect the new plan. Don't leave it as-is and expect readers to infer the change from comments.\n- **Park decisions that are the user's to make.** A design fork, a change with blast radius beyond its ticket, anything you'd want a second opinion on \u2014 file a ticket tagged `human-input-needed` naming the options and the trade-off, then carry on with whatever doesn't depend on the answer. Settling it alone in chat, while nobody is reading, is a decision the user never made.\n- **Findings from a code review get their own tickets**, tagged `from-review`, with the description saying which branch or PR the review covered \u2014 so the provenance survives even if the tag doesn't.\n"});import Zi from"node:fs";import vv from"node:path";var yv,bv=h(()=>{"use strict";Xe();R();hv();yv=async(e={})=>{let t=await lt(e.repoRoot??process.cwd());if(d(t))return a(t.message);let n=vv.join(t.value,sr);if(Zi.existsSync(n)){if(Zi.readFileSync(n,"utf8")===Zc)return l("Skill already installed and up to date",{path:n,written:!1});if(!e.force)return a(`${sr} already exists and differs from the bundled skill. Pass force:true to overwrite it.`)}try{Zi.mkdirSync(vv.dirname(n),{recursive:!0}),Zi.writeFileSync(n,Zc,"utf8")}catch(o){return a(o instanceof Error?`Failed to write ${sr}: ${o.message}`:`Failed to write ${sr}`)}return l(`Installed skill at ${sr}`,{path:n,written:!0})}});var Iv={};cr(Iv,{createMcpServer:()=>xv,resultJson:()=>el,startMcpServer:()=>pR});import{McpServer as uR}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as mR}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as v}from"zod";var el,Z,xv,pR,Ev=h(()=>{"use strict";R();hn();Oh();jh();gv();bv();Yo();el=e=>({isError:d(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),Z=e=>t=>Sh(async()=>el(await e(t))),xv=()=>{let e=new uR({name:"epiq",version:"0.2.30"});return e.registerTool("epiq_state_get",{description:"Get the full current Epiq state, including nodes and event log",inputSchema:v.object({repoRoot:v.string().optional()})},Z(hc)),e.registerTool("epiq_issue_list",{description:"List Epiq issues. Narrow with boardId, swimlaneId, tag, assignee or query (matched against title and description), and pass brief to get id, ref, title, swimlane, tag names and assignee names only \u2014 descriptions are the bulk of a board. Read one ticket with epiq_issue_get.",inputSchema:v.object({repoRoot:v.string().optional(),includeClosed:v.boolean().optional(),boardId:v.string().optional(),swimlaneId:v.string().optional(),tag:v.string().optional(),assignee:v.string().optional(),query:v.string().optional(),brief:v.boolean().optional()})},Z(Ic)),e.registerTool("epiq_issue_get",{description:"Get one Epiq issue by its full id or its 7-character ref, with its comments in log order. Use this rather than listing the whole board when you already know which issue you want, and rather than epiq_state_get to read a thread.",inputSchema:v.object({idOrRef:v.string().min(1),repoRoot:v.string().optional()})},Z(xc)),e.registerTool("epiq_issue_stats",{description:"Code stats for one issue, derived from the commits whose subject carries its ref: how big the change is, how it is spread, and how much of it the ticket spent rewriting its own work. Reads git only \u2014 it never touches the board \u2014 so it is safe to call while other work is in flight. No commits carrying the ref reads as a change of zero size, which is not the same as no work: a commit only links if its subject opens with the ref.",inputSchema:v.object({idOrRef:v.string().min(1),repoRoot:v.string().optional()})},async t=>el(await fv(t))),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:v.object({repoRoot:v.string().optional()})},Z(wc)),e.registerTool("epiq_swimlane_list",{description:"List Epiq swimlanes",inputSchema:v.object({repoRoot:v.string().optional(),boardId:v.string().optional()})},Z(Tc)),e.registerTool("epiq_swimlane_create",{description:"Create an Epiq swimlane on a board",inputSchema:v.object({repoRoot:v.string().optional(),boardId:v.string().min(1),title:v.string().min(1).max(300)})},Z(kc)),e.registerTool("epiq_swimlane_title_edit",{description:"Edit an Epiq swimlane title",inputSchema:v.object({repoRoot:v.string().optional(),swimlaneId:v.string().min(1),title:v.string().min(1).max(300)})},Z(Mc)),e.registerTool("epiq_swimlane_move",{description:"Move/reorder an Epiq swimlane, optionally to another board",inputSchema:v.object({repoRoot:v.string().optional(),swimlaneId:v.string().min(1),boardId:v.string().min(1),position:v.discriminatedUnion("at",[v.object({at:v.literal("start")}),v.object({at:v.literal("end")}),v.object({at:v.literal("before"),sibling:v.string().min(1)}),v.object({at:v.literal("after"),sibling:v.string().min(1)})]).optional()})},Z(Pc)),e.registerTool("epiq_swimlane_delete",{description:"Delete (archive) an Epiq swimlane. This also archives every issue contained in it.",inputSchema:v.object({repoRoot:v.string().optional(),swimlaneId:v.string().min(1)})},Z(Lc)),e.registerTool("epiq_issue_create",{description:"Create an Epiq issue. Optionally set description, tags, and assignees atomically in the same call instead of separate follow-up edits.",inputSchema:v.object({title:v.string().min(1).max(300),parentId:v.string().min(1),repoRoot:v.string().optional(),description:v.string().max(2e4).optional(),tagNames:v.array(v.string().max(60)).max(20).optional(),assigneeNames:v.array(v.string().max(80)).max(20).optional()})},Z(Ec)),e.registerTool("epiq_issue_description_edit",{description:"Edit the markdown description of an Epiq issue",inputSchema:v.object({issueId:v.string().min(1),description:v.string().max(2e4),repoRoot:v.string().optional()})},Z(Cc)),e.registerTool("epiq_issue_title_edit",{description:"Edit the title of an Epiq issue",inputSchema:v.object({issueId:v.string().min(1),title:v.string().min(1).max(300),repoRoot:v.string().optional()})},Z(Ac)),e.registerTool("epiq_issue_tag_add",{description:"Add a tag to an Epiq issue, or to many at once with issueIds, creating the tag if it does not exist",inputSchema:v.object({issueId:v.string().min(1).optional(),issueIds:v.array(v.string().min(1)).min(1).max(200).optional(),tagName:v.string().min(1).max(60),repoRoot:v.string().optional()})},Z(Dc)),e.registerTool("epiq_issue_tag_remove",{description:"Remove a tag from an Epiq issue",inputSchema:v.object({issueId:v.string().min(1),tagId:v.string().min(1),repoRoot:v.string().optional()})},Z(Oc)),e.registerTool("epiq_contributor_list",{description:"List people who can be assigned: everyone who has authored an event (optionally scoped to one board) unioned with the contributor registry. Use these ids with epiq_issue_assignee_add rather than assigning by name.",inputSchema:v.object({boardId:v.string().min(1).optional(),repoRoot:v.string().optional()})},Z(Hc)),e.registerTool("epiq_contributor_remove",{description:"Remove an external contributor from the assignee suggestion lists. Their id and every reference to it survive, so existing assignments stay intact and the event log is untouched. Refused for anyone who has authored events, since their name is in the log regardless.",inputSchema:v.object({contributorId:v.string().min(1),repoRoot:v.string().optional()})},Z($c)),e.registerTool("epiq_tag_remove",{description:"Delete a tag from the whole workspace. It disappears from every ticket, picker and filter, but its id and history stay in the event log, and the name is free for a new tag.",inputSchema:v.object({tagId:v.string().min(1),repoRoot:v.string().optional()})},Z(Fc)),e.registerTool("epiq_tag_restore",{description:"Put back a tag deleted with epiq_tag_remove, on every ticket that still carried it.",inputSchema:v.object({tagId:v.string().min(1),repoRoot:v.string().optional()})},Z(_c)),e.registerTool("epiq_contributor_restore",{description:"Put a contributor removed with epiq_contributor_remove back into the suggestion lists, under the name they were created with.",inputSchema:v.object({contributorId:v.string().min(1),repoRoot:v.string().optional()})},Z(jc)),e.registerTool("epiq_issue_assignee_add",{description:"Assign a contributor to an Epiq issue. Pass self:true to assign yourself. Prefer assigneeId otherwise, which assigns a known contributor (from the registry or the event log) and fails if the id is unknown. assigneeName matches an existing contributor by name; to create somebody new from a name you must also pass createUnlinked, which adds them as an external (non-contributor) assignee.",inputSchema:v.object({issueId:v.string().min(1),assigneeId:v.string().min(1).optional(),self:v.boolean().optional(),assigneeName:v.string().min(1).max(80).optional(),createUnlinked:v.boolean().optional(),repoRoot:v.string().optional()})},Z(Uc)),e.registerTool("epiq_issue_assignee_remove",{description:"Remove an assignee from an Epiq issue",inputSchema:v.object({issueId:v.string().min(1),assigneeId:v.string().min(1),repoRoot:v.string().optional()})},Z(Wc)),e.registerTool("epiq_issue_comment_add",{description:"Add a comment to an Epiq issue",inputSchema:v.object({issueId:v.string().min(1),body:v.string().min(1).max(4e3),repoRoot:v.string().optional()})},Z(qc)),e.registerTool("epiq_issue_attachment_add",{description:"Attach an image file to an Epiq issue. Returns `markdown` \u2014 paste it into a comment or description body to render the image inline.",inputSchema:v.object({issueId:v.string().min(1),filePath:v.string().min(1),name:v.string().min(1).max(200).optional(),repoRoot:v.string().optional()})},Z(fc)),e.registerTool("epiq_issue_comment_delete",{description:"Delete a comment from an Epiq issue",inputSchema:v.object({commentId:v.string().min(1),repoRoot:v.string().optional()})},Z(Gc)),e.registerTool("epiq_issue_comment_edit",{description:"Replace the body of one of your own comments on an Epiq issue",inputSchema:v.object({commentId:v.string().min(1),body:v.string().min(1).max(4e3),repoRoot:v.string().optional()})},Z(zc)),e.registerTool("epiq_issue_reopen",{description:"Reopen a closed Epiq issue, restoring it to its previous swimlane",inputSchema:v.object({issueId:v.string().min(1),repoRoot:v.string().optional()})},Z(Rc)),e.registerTool("epiq_issue_close",{description:"Close an Epiq issue, or many at once with issueIds \u2014 one call, an outcome per ticket",inputSchema:v.object({issueId:v.string().min(1).optional(),issueIds:v.array(v.string().min(1)).min(1).max(200).optional(),repoRoot:v.string().optional()})},Z(Sc)),e.registerTool("epiq_issue_move",{description:"Move an Epiq issue to another swimlane, or many at once with issueIds \u2014 one call, an outcome per ticket",inputSchema:v.object({issueId:v.string().min(1).optional(),issueIds:v.array(v.string().min(1)).min(1).max(200).optional(),parentId:v.string().min(1),position:v.discriminatedUnion("at",[v.object({at:v.literal("start")}),v.object({at:v.literal("end")}),v.object({at:v.literal("before"),sibling:v.string().min(1)}),v.object({at:v.literal("after"),sibling:v.string().min(1)})]).optional(),repoRoot:v.string().optional()})},Z(Nc)),e.registerTool("epiq_actor_assume",{description:'Take a board identity for the rest of this session, so your writes are attributed to you rather than to the user. Pass the name you announced \u2014 the model provider, a slash, then a short human first name, e.g. "claude/peter". Takes effect on the very next write; no relaunch. A name the server was launched with wins, and re-assuming the same name is harmless. Reuse an existing agent identity (epiq_contributor_list) before inventing one: a name is permanent once it has authored anything.',inputSchema:v.object({name:v.string().min(1).max(80),repoRoot:v.string().optional()})},Z(Bc)),e.registerTool("epiq_project_init",{description:`Set up a new Epiq board in a git repository without the TUI. Runs in the repository at repoRoot (default: the current directory), which must have no uncommitted changes. The first time on a machine it also records the user's setup: ask the user for userName (how they want to appear on the board), preferredEditor (e.g. "vim" or "code --wait") and autoSync (whether the TUI and GUI sync with the remote on their own) and pass them here; called without them it fails naming what is still missing, keeping whatever was given. It fills in answers the machine lacks and refuses to change ones it has. Pass the user's name, never your own agent identity. Commits the state branch and .epiq/project.json and tries to push both; a push that fails is a warning, not an error. Afterwards the other tools work in that repository.`,inputSchema:v.object({repoRoot:v.string().optional(),userName:v.string().min(1).max(80).optional(),preferredEditor:v.string().min(1).max(200).optional(),autoSync:v.boolean().optional()})},Z($h)),e.registerTool("epiq_skill_install",{description:"Write the official Epiq workflow skill into the repository at .claude/skills/epiq/SKILL.md, so agents working there follow the same board rules. Run it after epiq_project_init, not before: the new file is an uncommitted change that init refuses. In a project that already has a board, run it any time. Refuses to overwrite a differing file unless force is true; an identical file is left alone.",inputSchema:v.object({repoRoot:v.string().optional(),force:v.boolean().optional()})},Z(yv)),e.registerTool("epiq_sync",{description:"Sync Epiq state with the configured Git remote (pull remote changes and push local ones). Other Epiq MCP tools only read and write local state and never sync automatically \u2014 call this on demand when you need to see or publish the latest remote changes.",inputSchema:v.object({repoRoot:v.string().optional()})},Z(vc)),e},pR=async()=>{let e=xv(),t=new mR;await e.connect(t)}});process.env.EPIQ_MCP="true";console.log=console.error;console.info=console.error;console.debug=console.error;console.warn=console.error;var{applyActorNameArgument:fR}=await Promise.resolve().then(()=>(Un(),al)),{isFail:gR}=await Promise.resolve().then(()=>(R(),rl)),{parseMcpArgs:hR}=await Promise.resolve().then(()=>(ll(),cl)),ir=hR(process.argv.slice(2));ir.kind==="error"&&(console.error(ir.message),process.exit(1));ir.kind==="print"&&(process.stdout.write(ir.text),process.exit(0));if(ir.kind==="name"){let e=fR(ir.name,"The name argument");gR(e)&&(console.error(e.message),process.exit(1))}var{setVirtualNodesEnabled:vR}=await Promise.resolve().then(()=>(Na(),yh));vR(!1);var{startMcpServer:yR}=await Promise.resolve().then(()=>(Ev(),Iv));await yR();
|