epiq 1.8.4 → 1.8.6
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 +4208 -2670
- package/dist/index.js +89 -85
- package/dist/mcp.js +80 -76
- package/package.json +1 -1
package/dist/mcp.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var Vv=Object.defineProperty;var h=(e,t)=>()=>(e&&(t=e(e=0)),t);var Eo=(e,t)=>{for(var n in t)Vv(e,n,{get:t[n],enumerable:!0})};var Sl={};Eo(Sl,{failed:()=>d,isFail:()=>a,isSuccess:()=>jt,resultStatuses:()=>sn,succeeded:()=>l});var sn,d,l,a,jt,S=h(()=>{"use strict";sn={Success:"success",Fail:"fail"},d=e=>({status:sn.Fail,message:e,value:null}),l=(e,t)=>({status:sn.Success,message:e,value:t}),a=e=>e.status==="fail",jt=e=>e.status==="success"});var wl={};Eo(wl,{ACTOR_ID_ENV:()=>Ro,ACTOR_NAME_ENV:()=>It,applyActorNameArgument:()=>ua,deriveActorId:()=>Cl,isValidUserId:()=>ws,isValidUserName:()=>So,resolveEnvActor:()=>la});import Kv from"node:crypto";var It,Ro,Nl,Yv,ca,ws,So,Cr,Cl,la,ua,zn=h(()=>{"use strict";S();It="EPIQ_USER_NAME",Ro="EPIQ_USER_ID",Nl="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Yv=26,ca=80,ws=e=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(e),So=e=>e.trim().length>0&&e.length<=ca,Cr=e=>e.trim().toLowerCase(),Cl=e=>{let t=Kv.createHash("sha256").update(`epiq:actor:${Cr(e)}`).digest(),n="";for(let r=0;r<Yv;r++)n+=Nl[(t[r]??0)%Nl.length];return n},la=(e,t=process.env)=>{let n=(t[It]??"").trim(),r=(t[Ro]??"").trim();return n?So(n)?!r&&e.userId&&e.userName&&Cr(e.userName)===Cr(n)?l("Actor override names the configured user",{userId:e.userId,userName:e.userName}):r&&!ws(r)?d(`${Ro} must be 26 characters of Crockford base32`):r&&e.userId&&r===e.userId?d(`${Ro} is the configured user's own id; using it under a different name would rename them on the board`):l("Resolved actor from environment",{userId:r||Cl(n),userName:r?n:Cr(n)}):d(`${It} must be 1-${ca} characters of text`):r?d(`${Ro} is set without ${It}`):l("No actor override",null)},ua=(e,t,n=process.env)=>{let r=e.trim();if(!So(r))return d(`${t} must be 1-${ca} characters of text`);let o=(n[It]??"").trim();return o&&Cr(o)!==Cr(r)?d(`${t} names ${r}, but ${It} names ${o}`):(o||(n[It]=r),l("Applied actor name argument",o||r))}});var ma,Al=h(()=>{"use strict";ma="1.8.6"});var Tl={};Eo(Tl,{parseMcpArgs:()=>Jv});var Xv,Jv,kl=h(()=>{"use strict";Al();Xv=`epiq-mcp ${ma}
|
|
3
3
|
|
|
4
4
|
Usage: epiq-mcp [name]
|
|
5
5
|
|
|
@@ -9,90 +9,94 @@ Usage: epiq-mcp [name]
|
|
|
9
9
|
Options:
|
|
10
10
|
-v, --version print the version
|
|
11
11
|
-h, --help print this help
|
|
12
|
-
`,
|
|
13
|
-
`}:t==="--help"||t==="-h"?{kind:"print",text:
|
|
14
|
-
`,"utf8"),l("Created project.json",null)}catch(
|
|
15
|
-
`);u(n?{stdout:i,stderr:f,exitCode:124}:
|
|
16
|
-
`)))}),
|
|
17
|
-
`)));return}u(l("Git command succeeded",{stdout:i,stderr:c,exitCode:y}))})}),W=({args:e,cwd:t})=>
|
|
18
|
-
${s}`:""}`));return}let p=Buffer.concat(
|
|
12
|
+
`,Jv=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:`${ma}
|
|
13
|
+
`}:t==="--help"||t==="-h"?{kind:"print",text:Xv}:t.startsWith("-")?{kind:"error",message:`Unknown option ${t}; expected a name, e.g. epiq-mcp claude/peter`}:{kind:"name",name:t}}});import{decodeTime as Ml}from"ulid";var As,No,Ge,Co,Pl,Vn,Je=h(()=>{"use strict";S();As=1440*60*1e3,No=(e,t=Date.now())=>e>t+As?t:e,Ge=e=>No(Ml(e)),Co=e=>{let t=Date.now()+As,n=e.find(o=>o!==null&&o<=t)??null;if(n===null)return[...e];let r=null;return e.map(o=>{if(o===null)return null;let s=o<=t?o:r??n;return r=s,s})},Pl=e=>{try{return l("Decoded date",new Date(Ge(e)))}catch(t){return d("Decoding failed + "+t.message)}},Vn=e=>{if(!e?.id)return null;try{return Ml(e.id)}catch{return null}}});var Ts,lt,Ll,$t=h(()=>{"use strict";S();Ts="removed",lt=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?l("Found node",n):d("Unable to find node in breadcrumb")},Ll=["png","jpg","gif","webp"]});function pa(e){return e.context===Y.WORKSPACE}function F(e){return e.context===Y.TICKET}function Dl(e){return e.context===Y.TEXT}function ut(e){return e.context===Y.FIELD}function wo(e){return e.context===Y.FIELD_LIST}var Y,Kn,Yn,Ao,ee=h(()=>{"use strict";Y={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};Kn=e=>e.context===Y.SWIMLANE,Yn=e=>e.context===Y.BOARD,Ao=e=>e.context===Y.COMMENT});var b,ve=h(()=>{"use strict";b={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"}});var _l=h(()=>{"use strict";Xn()});import Fl from"string-width";function ks(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var Jn,Qv,fa,Zv,ga,le,mt=h(()=>{"use strict";Jn=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Qv=/\u001B\[[0-9;]*m/,fa="\x1B[0m",Zv=e=>[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(e)].map(({segment:t})=>t),ga=(e,t)=>{if(t<=0)return"";if(Fl(e)<=t)return e;if(t<=3)return"...".slice(0,t);let r=t-3,o="",s=0,i=!1;for(let c of e.split(/(\u001B\[[0-9;]*m)/))if(c!==""){if(Qv.test(c)){o+=c,i=c!==fa&&c!=="\x1B[m";continue}for(let u of Zv(c)){let m=Fl(u);if(s+m>r)return`${o}...${i?fa:""}`;o+=u,s+=m}}return`${o}...${i?fa:""}`},le=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim()});var Bl,Ol,Ul=h(()=>{"use strict";Bl=e=>{let t=new Map;for(let n of e)for(let r=1;r<=n.length;r++){let o=n.slice(0,r),s=t.get(o);s?s.push(n):t.set(o,[n])}return t},Ol=(e,t)=>t?e.get(t)??[]:[]});var jl,ey,$l,Wl=h(()=>{"use strict";mt();Ul();jl=new WeakMap,ey=e=>{let t=jl.get(e);return t||(t=Bl(e),jl.set(e,t)),t},$l=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return Ol(ey(e),r).filter(s=>ks(r,s)>=n)}});var ty,Hl,ny,ql=h(()=>{"use strict";mt();Wl();ty={hint:"",hints:[],overlap:0,remainder:""},Hl=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return ty;let o=$l({wordList:r,inputToMatch:e,overlapThreshold:1});return ny(t,o)},ny=(e,t)=>{let n=t[0]??"",r=ks(e.toLowerCase(),n.toLowerCase()),[o,s]=n.split(":"),i=r<(o??"").length,c=!!s,p=(c&&i?o:n)+(c&&i?":":" "),f=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:f}}});import{useSyncExternalStore as bN}from"react";var Ms,ry,oy,xe,xt,ze=h(()=>{"use strict";Ms={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},ry=new Set,oy=()=>{for(let e of ry)e()},xe=()=>Ms,xt=e=>(Ms={...Ms,...e},oy(),Ms)});function Gl(e){return!e||!iy.test(e)?d(`Invalid hex rank: ${e}`):l("Converted rank to bigint",BigInt("0x"+e))}function Et(e,t=To){if(e<0n)return d("Negative rank not allowed");let n=e.toString(16);return l("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function Ve(e,t){if(!e&&!t)return Et(Wt/2n,To);let n=e?Gl(e):l("Resolved lower bound",0n);if(a(n))return n;let r=t?Gl(t):l("Resolved upper bound",Wt);if(a(r))return r;let o=n.value,s=r.value;if(s<=o)return d("Neighbouring ranks leave no space between them");let i=(o+s)/2n;return i===o||i===s?d("No rank space available between neighbors"):Et(i,To)}function zl(e){if(e<=0)return l("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=Wt*BigInt(r+1)/(t+1n),s=Et(o,To);if(a(s))return s;n.push(s.value)}return l("Resolved evenly spaced ranks",n)}var To,sy,Wt,iy,wr=h(()=>{"use strict";S();To=24n,sy=To*4n,Wt=(1n<<sy)-1n,iy=/^[0-9a-f]+$/});import{ulid as ay}from"ulid";var ha,Vl=h(()=>{"use strict";S();Rt();wr();ha=(e,t)=>{let n=ye(e),r=zl(n.length);if(a(r))return r;let o={};for(let s=0;s<n.length;s++){let i=n[s],c=r.value[s];if(!i||!c)return d("Unable to assign rebalance rank");o[i.id]=c}return l("Created rebalance event",{id:ay(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})}});import ko from"node:fs";import{ulid as dy}from"ulid";import{z as Ps}from"zod";var cy,ly,Ls,pt,Mo,va,Ht=h(()=>{"use strict";S();ie();cy="__epiq_state__",ly=Ps.object({projectId:Ps.string().min(1),stateBranch:Ps.string().min(1),createdAt:Ps.iso.datetime()}),Ls=()=>({projectId:dy(),stateBranch:cy,createdAt:new Date().toISOString()}),pt=e=>{let t=Ar(e);if(!ko.existsSync(t))return d("Missing .epiq/project.json");try{let n=ko.readFileSync(t,"utf8"),r=JSON.parse(n),o=ly.safeParse(r);return o.success?l("Read project.json",o.data):d(`Invalid .epiq/project.json: ${o.error.issues.map(s=>`${s.path.join(".")}: ${s.message}`).join(", ")}`)}catch(n){return d(n instanceof Error?`Failed to read .epiq/project.json: ${n.message}`:"Failed to read .epiq/project.json")}},Mo=e=>{let t=pt(e);return a(t)?d(t.message):l("Read projectId",t.value.projectId)},va=({repoRoot:e,fileContents:t})=>{let n=Qn(e),r=Ar(e);try{if(ko.mkdirSync(n,{recursive:!0}),ko.existsSync(r)){let o=pt(e);return a(o)?d(o.message):l("Project already initialized",null)}return ko.writeFileSync(r,JSON.stringify(t,null,2)+`
|
|
14
|
+
`,"utf8"),l("Created project.json",null)}catch(o){return d(o instanceof Error?`Failed to initialize project: ${o.message}`:"Failed to initialize project")}}});import uy from"node:os";import my from"node:path";var Dt,an,Ds=h(()=>{"use strict";Dt=".epiq-global",an=()=>process.env.EPIQ_GLOBAL_DIR??my.join(uy.homedir(),Dt)});var ya,Kl=h(()=>{"use strict";S();ya=(e,t)=>{let n=new Map,r=t??((...s)=>JSON.stringify(s)),o=((...s)=>{let i=r(...s);if(!n.has(i)){let c=e(...s).then(u=>(a(u)&&n.delete(i),u));n.set(i,c)}return n.get(i)});return o.clear=()=>n.clear(),o}});var ue,_s=h(()=>{"use strict";Qe();ue={stage:({cwd:e,pathspec:t,ignoreRemoval:n=!1})=>W({args:["add",...n?["--ignore-removal"]:[],...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1,pathspec:r})=>W({args:["commit","--no-verify",...n?["--allow-empty"]:[],"-m",t,...r?.length?["--",...r]:[]],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>W({args:["fetch",t,`+refs/heads/${n}:refs/remotes/${t}/${n}`],cwd:e}),rebaseOnto:({cwd:e,ref:t})=>W({args:["-c","rebase.autoStash=true","rebase",t],cwd:e}),checkout:({cwd:e,branch:t})=>W({args:["checkout",t],cwd:e}),push:({cwd:e,remote:t,branch:n,setUpstream:r=!1})=>{let o=t&&n?["push","--no-verify",...r?["-u"]:[],t,n]:["push","--no-verify"];return W({args:o,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>W({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>W({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>W({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>W({args:["worktree","prune"],cwd:e})}});var qt,ft,Zn=h(()=>{"use strict";Ht();S();ie();qt=e=>{let t=Me(e);if(a(t))return d("Unable to resolve epiq project root");let n=pt(t.value);return a(n)?d("Unable to read project.json"):l("Resolved state branch",n.value.stateBranch)},ft="origin"});import{spawn as Xl}from"node:child_process";import dn from"node:fs";import cn from"node:path";var ba,py,fy,gy,hy,Jl,Ql,Zl,W,Oe,Ia,kr,xa,vy,Fs,ln,Po,Bs,Tr,eu,Ea,Os,tu,nu,ru,yy,by,Iy,xy,Ey,Yl,Lo,Ry,Do,ou,su,iu,au,Qe=h(()=>{"use strict";S();_s();Zn();ba=1e4,py=12e4,fy=new Set(["fetch","push","pull","clone","ls-remote","rebase","checkout","worktree"]),gy=e=>{let t=e.find((n,r)=>!n.startsWith("-")&&e[r-1]!=="-c");return t&&fy.has(t)?py:ba},hy=()=>{let e=process.platform==="win32"?["git.exe","git"]:["git"];for(let t of(process.env.PATH??"").split(cn.delimiter))if(t)for(let n of e){let r=cn.join(t,n);try{if(!dn.statSync(r).isFile())continue;return dn.accessSync(r,dn.constants.X_OK),r}catch{continue}}return"git"},Jl=hy(),Ql={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo",GIT_SSH_COMMAND:process.env.GIT_SSH_COMMAND??"ssh -o BatchMode=yes -o ConnectTimeout=10"},Zl=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!dn.existsSync(t)){let f=`Git cwd does not exist: ${t}`;if(n){r({stdout:"",stderr:f,exitCode:1});return}r(d(f));return}let o=Xl(Jl,e,{cwd:t,stdio:["ignore","pipe","pipe"],env:Ql}),s=!1,i="",c="",u=f=>{s||(s=!0,clearTimeout(p),r(f))},m=gy(e),p=setTimeout(()=>{o.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}:d(f))},m);o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",f=>{i+=f}),o.stderr.on("data",f=>{c+=f}),o.on("error",f=>{if(n){u({stdout:i,stderr:f.message,exitCode:1});return}u(d([`git ${e.join(" ")}`,`cwd=${t}`,f.message].join(`
|
|
16
|
+
`)))}),o.on("close",f=>{let y=f??1;if(n){u({stdout:i,stderr:c,exitCode:y});return}if(y!==0){u(d([`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})=>Zl({args:e,cwd:t,allowFail:!1}),Oe=({args:e,cwd:t})=>Zl({args:e,cwd:t,allowFail:!0}),Ia=(e,t)=>new Promise(n=>{if(e.length===0){n(l("No blobs to read",new Map));return}let r=Xl(Jl,["cat-file","--batch"],{cwd:t,stdio:["pipe","pipe","pipe"],env:Ql}),o=[],s="",i=!1,c=m=>{i||(i=!0,clearTimeout(u),n(m))},u=setTimeout(()=>{r.kill("SIGTERM"),c(d(`git cat-file --batch timed out after ${ba}ms`))},ba);r.stdout.on("data",m=>o.push(m)),r.stderr.setEncoding("utf8"),r.stderr.on("data",m=>{s+=m}),r.on("error",m=>c(d(m.message))),r.on("close",m=>{if(m!==0){c(d(`git cat-file --batch exited ${m}${s?`
|
|
18
|
+
${s}`:""}`));return}let p=Buffer.concat(o),f=new Map,y=0;for(let x of e){let R=p.indexOf(10,y);if(R===-1){c(d(`git cat-file --batch output ended before a header for ${x}`));return}let A=p.toString("utf8",y,R);y=R+1;let w=/^[0-9a-f]{4,64} \S+ (\d+)$/.exec(A);if(!w||!w[1]){c(d(`Unexpected git cat-file --batch header: "${A}"`));return}let k=Number(w[1]);f.set(x,p.toString("utf8",y,y+k)),y+=k+1}c(l("Read blobs",f))}),r.stdin.write(e.join(`
|
|
19
19
|
`)+`
|
|
20
|
-
`),
|
|
21
|
-
${
|
|
22
|
-
${
|
|
23
|
-
`).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(
|
|
24
|
-
${t.stderr.trim()}`):l("Aborted stale rebase",!0)},
|
|
25
|
-
${
|
|
26
|
-
${s.message}`);let i=await
|
|
27
|
-
`+
|
|
28
|
-
`+
|
|
29
|
-
`,
|
|
30
|
-
`,
|
|
31
|
-
`+t.message);let
|
|
32
|
-
`).filter(Boolean).filter(i=>i!==
|
|
33
|
-
${
|
|
34
|
-
`);if(n[n.length-1]===""&&n.pop(),t<=
|
|
20
|
+
`),r.stdin.end()}),kr=async({cwd:e,message:t,pathspec:n})=>{let r=await ue.commit({cwd:e,message:t,pathspec:n});if(a(r))return d(`Failed to create commit
|
|
21
|
+
${r.message}`);let o=await W({args:["rev-parse","HEAD"],cwd:e});return a(o)?d(`Commit created, but failed to read HEAD SHA
|
|
22
|
+
${o.message}`):l("Created commit and resolved SHA",o.value.stdout.trim())},xa=async e=>{let t=await W({cwd:e,args:["rev-parse","--git-dir"]});if(a(t))return d(t.message);let n=t.value.stdout.trim();return l("Resolved git dir",cn.isAbsolute(n)?n:cn.resolve(e,n))},vy=async e=>{let t=await xa(e);if(a(t))return d(t.message);let n=t.value,r={MERGE_HEAD:"merge in progress"};for(let[s,i]of Object.entries(r))if(dn.existsSync(cn.join(n,s)))return l("Checked for in-progress Git operation",i);let o={"rebase-merge":"rebase in progress","rebase-apply":"rebase in progress"};for(let[s,i]of Object.entries(o))if(dn.existsSync(cn.join(n,s)))return l("Checked for in-progress Git operation",i);return l("Checked for in-progress Git operation",null)},Fs=async e=>{let t=await vy(e);return a(t)?d(t.message):l("Checked for in-progress Git operation",t.value!==null)},ln=async({repoRoot:e})=>{let n=(await Oe({args:["remote","get-url",ft],cwd:e})).exitCode===0;return l(`Checked remote ${n}`,n)},Po=async({repoRoot:e,branch:t})=>{let n=await Oe({args:["ls-remote","--heads",ft,t],cwd:e});return n.exitCode!==0?d(n.stderr.trim()||`Unable to inspect remote branch ${ft}/${t}`):l("Checked remote branch",n.stdout.trim().length>0)},Bs=async({repoRoot:e,branch:t})=>{let n=await Oe({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):d(n.stderr.trim()||`Unable to inspect branch ${t}`)},Tr=e=>{try{return dn.realpathSync.native(e)}catch{return cn.resolve(e)}},eu=async({repoRoot:e,worktreeRoot:t})=>{let n=await W({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return d(n.message);let r=Tr(t),o=n.value.stdout.split(`
|
|
23
|
+
`).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(Tr).includes(r);return l("Checked worktree registration",o)},Ea=async e=>{let t=await Oe({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return l("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},Os=async e=>{let t=await W({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return a(t)?d(t.message):l("Resolved current branch",t.value.stdout.trim())},tu=async e=>{let t=await W({args:["rev-parse","--short","HEAD"],cwd:e});return a(t)?d(t.message):l("Resolved short HEAD sha",t.value.stdout.trim())},nu=e=>e.includes("fetch first")||e.includes("non-fast-forward"),ru=async e=>{let t=await Oe({cwd:e,args:["rev-parse","--absolute-git-dir"]});if(t.exitCode!==0)return!1;let n=t.stdout.trim();return n?dn.existsSync(cn.join(n,"rebase-merge"))||dn.existsSync(cn.join(n,"rebase-apply")):!1},yy=3,by=120,Iy=e=>new Promise(t=>setTimeout(t,e)),xy=async(e,t)=>{let n=await ue.rebaseOnto({cwd:e,ref:t});for(let r=1;r<yy;r+=1){if(!a(n)||await ru(e))return n;await Iy(by),n=await ue.rebaseOnto({cwd:e,ref:t})}return n},Ey=async e=>{if(!await ru(e))return l("No rebase to abort",!1);let t=await Oe({cwd:e,args:["rebase","--abort"]});return t.exitCode!==0?d(`Failed to abort the rebase in progress at ${e}
|
|
24
|
+
${t.stderr.trim()}`):l("Aborted stale rebase",!0)},Yl=async e=>{let t=await Oe({args:["rev-parse","HEAD"],cwd:e});return t.exitCode===0?t.stdout.trim():null},Lo=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),Ry=e=>e.includes("couldn't find remote ref")||e.includes("Could not find remote branch"),Do=async({cwd:e,branch:t})=>{let n=await Ey(e);if(a(n))return d(n.message);let r=await Yl(e),o=await ue.fetch({cwd:e,remote:ft,branch:t});if(a(o))return Ry(o.message)?l("Remote branch missing, skipped pull",!1):d(`Failed to fetch ${t}
|
|
25
|
+
${o.message}`);let s=await xy(e,`${ft}/${t}`);if(a(s))return d(`Failed during rebase
|
|
26
|
+
${s.message}`);let i=await Yl(e),c=r!==null&&i!==null&&r!==i;return l(c?"Pulled with rebase":"Already up to date",c)},ou=async e=>{let t=await Oe({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)},su=async e=>{let t=await Oe({args:["status","--porcelain","--untracked-files=all"],cwd:e});return t.exitCode!==0?d(t.stderr.trim()||"Unable to inspect the worktree for changes"):l("Inspected worktree for changes",t.stdout.trim().length>0)},iu=async(e,t)=>{let n=await Oe({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):d(n.stderr.trim()||"Unable to inspect staged changes")},au=async e=>{let t=await Os(e);return a(t)?d(t.message):l("Checked detached HEAD state",t.value==="HEAD")}});import An from"node:fs";import Ze from"node:path";var lu,uu,mu,pu,er,Ie,Sy,du,_o,Fo,fu,Ny,Cy,Ra,Sa,cu,gu,hu,gt,fC,et=h(()=>{"use strict";Ht();S();Ds();ie();Kl();St();Qe();lu="4b825dc642cb6eb9a060e54bf8d69288fbee4904",uu=e=>Ze.join(Ke,un,e),mu=()=>Ze.join(Ke,Na),pu=an,er=()=>Ze.join(pu(),"worktrees"),Ie=({repoRoot:e})=>{let t=Mo(e);return a(t)?d(t.message):l("Resolved state branch root",Ze.join(er(),t.value))},Sy=e=>Ze.join(e,Ke),du=e=>Ze.join(Sy(e),un),_o=e=>{try{return An.mkdirSync(e,{recursive:!0}),l("Ensured directory",void 0)}catch(t){return d(t instanceof Error?t.message:String(t))}},Fo=()=>{let e=pu(),t=er(),n=!An.existsSync(e)||!An.existsSync(t),r=_o(e);if(a(r))return d(`Ensure epiq home failed.
|
|
27
|
+
`+r.message);let o=_o(t);return a(o)?d(`Ensure worktrees dir failed.
|
|
28
|
+
`+o.message):l("Ensured epiq storage",n)},fu=e=>{An.existsSync(e)&&(X.debug("[sync] remove path",e),An.rmSync(e,{recursive:!0,force:!0}))},Ny=`*.jsonl merge=union
|
|
29
|
+
`,Cy=`*~pending*.jsonl
|
|
30
|
+
`,Ra=()=>Ze.join(Ke,un,".gitattributes"),Sa=()=>Ze.join(Ke,un,".gitignore"),cu=(e,t)=>{try{An.readFileSync(e,"utf8")!==t&&An.writeFileSync(e,t)}catch{An.writeFileSync(e,t)}},gu=(e,t)=>{for(let n of[du(e),du(t)]){let r=_o(n);if(a(r))return d(r.message)}return cu(Ze.join(t,Ra()),Ny),cu(Ze.join(t,Sa()),Cy),l("Ensured state branch",void 0)},hu=async e=>{let t=await W({args:["ls-tree","--name-only","HEAD"],cwd:e});if(a(t))return d(`ensure state branch is storage only failed
|
|
31
|
+
`+t.message);let r=t.value.stdout.trim().split(`
|
|
32
|
+
`).filter(Boolean).filter(i=>i!==Ke);if(r.length===0)return l("State branch is storage-only",!1);let o=await W({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(a(o))return d(`Failed to clean storage branch
|
|
33
|
+
${o.message}`);let s=await kr({cwd:e,message:"[epiq:repair-storage-branch]",pathspec:r});return a(s)?d(s.message):l("Cleaned storage branch",!0)},gt=ya(async(e=process.cwd())=>{let t=await W({args:["rev-parse","--show-toplevel"],cwd:e});return a(t)?d("Not inside a Git repository"):l("Resolved repo root",t.value.stdout.trim())},e=>Ze.resolve(e)),fC=ya(async e=>{let t=await W({args:["rev-parse","--git-dir"],cwd:e});if(a(t))return d(t.message);let n=t.value.stdout.trim(),r=Ze.isAbsolute(n)?n:Ze.join(e,n);return l("Resolved git dir",r)},e=>Ze.resolve(e))});import Bo from"node:fs";import Gt from"node:path";var xC,Ke,un,Na,wy,Qn,Ar,_t,Us,vu,Ay,Oo,js,Ty,Me,yu,zt,ie=h(()=>{"use strict";S();et();Ds();xC=process.env.IS_LOCAL==="true",Ke=".epiq",un="events",Na="media",wy="project.json",Qn=e=>Gt.join(e,Ke),Ar=e=>Gt.join(Qn(e),wy),_t=e=>Gt.join(Qn(e),un),Us=e=>Gt.join(Qn(e),Na),vu=e=>Gt.join(e,Ke),Ay=e=>{let t=Gt.join(e,Ke);return Bo.existsSync(t)&&Bo.statSync(t).isDirectory()},Oo=e=>{let t=Ar(e);return Bo.existsSync(t)&&Bo.statSync(t).isFile()},js=e=>{let t=Gt.resolve(e);for(;;){if(Ay(t))return l("Resolved closest .epiq root",t);let n=Gt.dirname(t);if(n===t)return d("No .epiq directory found in any parent");t=n}},Ty="No .epiq/project.json found in any parent",Me=e=>{let t=Gt.resolve(e);for(;;){if(Oo(t))return l("Resolved closest epiq project root",t);let n=Gt.dirname(t);if(n===t)return d(Ty);t=n}},yu=e=>{let t=_t(e);try{return Bo.mkdirSync(t,{recursive:!0}),l("Resolved events dir",t)}catch(n){return d(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}},zt=async()=>{let e=await gt(process.cwd());if(a(e))return e;let t=Ie({repoRoot:e.value});return a(t)?t:l("Resolved persist root",t.value)}});import Ft from"fs";import ka from"path";import ky from"util";function Dy(e){if(!Ft.existsSync(e))return;let t=Ft.statSync(e).size,n=Ly(e,Ma).split(`
|
|
34
|
+
`);if(n[n.length-1]===""&&n.pop(),t<=Ma&&n.length<=bu)return;let r=n.slice(-bu).join(`
|
|
35
35
|
`)+`
|
|
36
|
-
`;
|
|
37
|
-
`;try{
|
|
38
|
-
`);return i===-1?"":s.slice(i+1)}finally{Mt.closeSync(o)}};hy=e=>{if(e.length<=va)return e;let t=e.length-va;return`${e.slice(0,va)} \u2026 [${t} more chars]`};xa=()=>ru()?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,Ar,Je=h(()=>{"use strict";j=e=>e.slice(-7).toUpperCase(),Ar=(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 vy,he,Fs,dn=h(()=>{"use strict";vy=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[he,Fs]=vy});function Nn(e,t=!1){let n=Ry[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=Sy(e,t);return r||o}var Sa,F,Tr,zn,Vn,su,iu,yy,by,Ra,xy,Iy,Qe,Ey,Sy,wr,Ry,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}),Tr=e=>d(e)&&e.convergence===!0,zn=e=>{let t=e.filter(d);return{fatal:t.filter(n=>!Tr(n)),skipped:t.filter(Tr)}},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("; ")}`)},su=e=>{let t=E.getNode(e);if(!t||!P(t)||t.isDeleted)return null;let n=_s(t);return d(n)?n:null},iu=e=>{if(!Os())return null;for(let t of e){let n=su(t);if(n)return n;let o=g().nodes[t]?.parentNodeId;if(!o)continue;let r=su(o);if(r)return r}return null},yy=(e,t)=>{let n=E.getNode(e);n&&E.updateNode({...n,log:[...n.log??[],t]})},by=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 by(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[]}},xy=e=>{Ne(t=>({...t,eventLog:[...t.eventLog,e]}))},Iy=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,Ey=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]})),iu([...e.virtualNodeIds])},Sy=(e,t)=>{let n=Iy(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(Os()){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=>yy(s,e)),xy(e));let r=iu(o);return r||null},wr=(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,Ry={"init.workspace":e=>{let{id:t,name:n,rank:o}=e.payload,r=Pe.workspace(t,n,o),s=kr(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=wr(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=wr(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):hr(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=wr(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=wr(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=wr(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=au(()=>{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=Ey(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,du=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 Ny}from"ulid";var Us,Aa,lu,uu,wa,mu,pu,$s,fu,Cy,Ay,gu,wy,hu,Ty,vu,ky,Bs,cu,js,Yn=h(()=>{"use strict";R();ae();Us="~pending",Aa=/~pending(-[0-9a-z]+)*$/i,lu=/-f(\d+)$/,uu=e=>{let t=e.indexOf(".");return t===-1?`${e}${Us}`:e.slice(0,t)+Us+e.slice(t)},wa=e=>{let t=e.indexOf(".");return t===-1?[e,""]:[e.slice(0,t),e.slice(t)]},mu=e=>{let[t,n]=wa(e);return Aa.test(t)?t.replace(Aa,"")+n:null},pu=e=>e.replace(Aa,""),$s=e=>e.endsWith(".jsonl")&&mu(e)!==null,fu=e=>{let[t]=wa(e),n=lu.exec(t);return n&&$s(e)?Number(n[1]):null},Cy=e=>uu(e).replace(Us,`${Us}-${Ny().toLowerCase()}`),Ay=(e,t)=>{let[n,o]=wa(e);return`${n.replace(lu,"")}-f${t}${o}`},gu=(e,t)=>Kn.join(kt(e),uu(t)),wy=(e,t)=>Math.max(0,Ee.statSync(e).size-(fu(t)??0)),hu=e=>{let t=kt(e);try{return Ee.existsSync(t)?Ee.readdirSync(t).filter($s).some(n=>wy(Kn.join(t,n),n)>0):!1}catch{return!0}},Ty=3,vu=(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>=Ty)return}},ky=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)}},Bs=10,cu=(e,t,n=!1)=>{let o=n?t.length:t.lastIndexOf(Bs)+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(ky(e)?"":`
|
|
39
|
-
`),
|
|
40
|
-
`)]));let s=0;for(let i of
|
|
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=
|
|
42
|
-
`),n&&(n.current=u);let f=ja.basename(i.value);return wu(t,f,u),Iu(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 Lu,Pu,Yy,Xy,Jy,Du,Qy,Zy,ku,eb,tb,Mu,nb,oe,Zn,ob,rb,Ce=h(()=>{"use strict";xt();Un();R();We();ae();du();Ke();Yn();St();Eo();La();Lu=1,Pu=Ky(),Yy=0xffffffffffff,Xy=bs,Jy=e=>{let t=Date.now(),n;try{n=Vy(e)}catch{return t}return n>=Yy?t:n>t+Xy?(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)},Du=Qn.tuple([Qn.string().min(1),Qn.string().min(1).nullable()]),Qy=Qn.looseObject({v:Qn.literal(Lu),id:Du}),Zy=Qn.looseObject({v:Qn.number().int().positive(),id:Du}),ku=e=>{let t=Zy.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(", ")}`)},eb=[1],tb=new Set(eb),Mu=e=>tb.has(e),nb=e=>{let t=Qy.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?ys(t)?mr(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`,ob=(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=ja.join(kt(e),o);return l("Successfully resolved event log path",s)},rb=(e,t)=>{let n={[e.action]:e.payload,v:Lu,id:t};return nb(n)}});import{ulid as sb}from"ulid";function Fu(e,t,n){let o=Ha(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=ib(e[0],t,n);if(d(o))return o;let r=e.map(i=>Fu(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 ib,Se=h(()=>{"use strict";R();ne();M();ln();Ce();ib=(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:sb(),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=Fu(r,t,n);return d(s)?a(s.message):l("Contributor name recorded",void 0)}});var eo,Wa,_u=h(()=>{"use strict";Je();eo=e=>e.trim().toLocaleLowerCase(),Wa=(e,t)=>eo(e).includes(eo(t))});var ab,db,Ou,Bu,cb,lb,Uu,$u=h(()=>{"use strict";M();Je();_u();ab=e=>{let{tags:t}=g();return(e.props.tags??[]).map(n=>t[n]).filter(n=>n!==void 0&&!n.tombstoned).map(n=>n.name)},db=e=>{let{contributors:t}=g();return(e.props.assignees??[]).map(n=>{let o=t[n];return o?o.name:void 0}).filter(n=>!!n)},Ou=null,Bu=new Map,cb=()=>{let e=g().eventLog??[];if(e===Ou)return Bu;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 Ou=e,Bu=t,t},lb=e=>{let{contributors:t}=g(),n=cb().get(e.id);return n?[...n].map(o=>t[o]?.name).filter(o=>!!o):[]},Uu=(e,t)=>{let n=eo(t.value);if(!n)return!0;switch(t.target){case"title":return Wa(e.title??"",n);case"description":return Wa(e.props.description??"",n);case"tag":return ab(e).map(eo).some(r=>r.includes(n));case"assignee":return db(e).map(eo).some(r=>r.includes(n));case"actor":return lb(e).map(eo).some(r=>r.includes(n));case"ref":return Ar(e.id,t.value);default:return!0}}});var ju,ub,Hu,Wu,qa=h(()=>{"use strict";K();$u();ju=(e,t)=>e.rank.localeCompare(t.rank),ub=(e,t)=>!!e&&!e.isDeleted&&e.parentNodeId===t,Hu=(e,t)=>Object.values(e).filter(n=>ub(n,t)).sort(ju),Wu=(e,t)=>{let n={};for(let o of Object.values(e)){if(P(o)&&t.length>0&&!t.every(s=>Uu(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(ju);return n}});var qu,zs,ge,Gu,zu,jt,wn,yt=h(()=>{"use strict";kl();Se();R();M();qa();yo();qu=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=Gu(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=Gu(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(!Vu()&&t.filters.length===0){let n=t.renderedChildrenIndex[e];if(n)return n}return Hu(t.nodes,e)},Gu=(e,t)=>e.findIndex(n=>n.id===t),zu=(e,t,n={at:"end"})=>zs(ge(t).filter(o=>o.id!==e),n),jt=(e,t,n,o,r)=>{let s=zu(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=zu(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=qu(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=qu(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,Ku,Yu,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:()=>Ku(1),navigateToPreviousItem:()=>Ku(-1),navigateToNextContainer:()=>Yu(1),navigateToPreviousContainer:()=>Yu(-1),navigate:({contextNode:e,selectedIndex:t})=>{N({contextNodeId:e.id,selectedIndex:t})}},Ku=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})},Yu=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 Ju,Qu,mb,Vs,Zu,Xu,pb,em,tm=h(()=>{"use strict";K();R();yt();M();ut();Ju=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),Qu=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=g();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},mb=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:Ju(t,r.length)}),!0},Zu=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):Zu(r.id)},Xu=e=>{let{nodes:t}=g(),n=e,o=new Set;for(;n&&!o.has(n);){if(o.add(n),Zu(n))return!0;n=t[n]?.parentNodeId}return!1},pb=e=>{if(!e)return!1;let t=g().nodes[e];return!!t&&!t.isDeleted},em=e=>{let{nodes:t,rootNodeId:n}=g();if(mb(e.contextNodeId)&&Vs(e.contextNodeId,e.selectedIndex))return l("Restored navigation inside text container",null);if(pb(e.selectedNodeId)&&e.selectedNodeId&&Xu(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(Xu(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:Ju(e.selectedIndex,r.length)}),l("Restored navigation to root",null)}});import{monotonicFactory as fb,ulid as Ht}from"ulid";function gb(){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 hb(){let e=gb();return d(e)?e:U.navigate(e.value)}function nm({userId:e,userName:t}){let n=Lr(),o=Lr(),r=Lr(),s=Lr(),i=Lr(),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:Fs,name:"Closed",parent:n,rank:m.value}},{id:Ht(),userId:e,userName:t,action:"add.swimlane",payload:{id:he,name:"Closed",parent:Fs,rank:I.value}},{id:Ht(),userId:e,userName:t,action:"lock.node",payload:{id:Fs}},{id:Ht(),userId:e,userName:t,action:"lock.node",payload:{id:he}}])}function Wt(e,t=[]){if(vb())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=kr(s);return d(i)?i:(N({hasProjectDefinition:!1,mode:b.DEFAULT}),l("Booted uninitialized workspace placeholder",null))}if(!e.some(s=>s.action==="init.workspace"))return a("Initialized Epiq project has no workspace init event");let n=cn(e),{fatal:o,skipped:r}=zn(n);return o.length>0?a(`Materializing failed:
|
|
43
|
-
${
|
|
44
|
-
`)}`):(
|
|
45
|
-
|
|
46
|
-
`);
|
|
36
|
+
`;Ft.writeFileSync(e,r,"utf8")}function Aa(e,t,n=!1){let r=Py();if(!r)return;let o=_y(ky.format(...t)),s=new Date,c=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${o}
|
|
37
|
+
`;try{Ft.mkdirSync(ka.dirname(r),{recursive:!0}),Ft.appendFileSync(r,c,"utf8"),wa++,(wa>=My||Ft.statSync(r).size>Ma)&&(wa=0,Dy(r))}catch{}}var bu,Ma,Ca,My,wa,Iu,Py,Ly,_y,Ta,X,St=h(()=>{"use strict";S();ie();bu=500,Ma=4*1024*1024,Ca=16*1024,My=50,wa=0,Iu=()=>process.env.EPIQ_MCP==="true",Py=()=>{let e=process.cwd(),t=js(e);return a(t)?Iu()?ka.join(an(),"epiq-mcp.log"):void 0:ka.join(t.value,Ke,"log","epiq.log")},Ly=(e,t)=>{let n=Ft.statSync(e).size;if(n<=t)return Ft.readFileSync(e,"utf8");let r=Ft.openSync(e,"r");try{let o=Buffer.alloc(t);Ft.readSync(r,o,0,t,n-t);let s=o.toString("utf8"),i=s.indexOf(`
|
|
38
|
+
`);return i===-1?"":s.slice(i+1)}finally{Ft.closeSync(r)}};_y=e=>{if(e.length<=Ca)return e;let t=e.length-Ca;return`${e.slice(0,Ca)} \u2026 [${t} more chars]`};Ta=()=>Iu()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",X={info(...e){let t=Ta();(t==="info"||t==="debug")&&Aa("[Info]",e,!1)},debug(...e){Ta()==="debug"&&Aa("[Debug]",e,!0)},error(...e){let t=Ta();if(t==="error"||t==="info"||t==="debug"){let r=e.some(o=>o instanceof Error)?void 0:new Error().stack;Aa("[Error]",[...e,r].filter(Boolean),!1)}}};globalThis.logger=X});var ge,Mr=h(()=>{"use strict";ge={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments",ATTACHMENTS:"Attachments"}});var j,Uo,tt=h(()=>{"use strict";j=e=>e.slice(-7).toUpperCase(),Uo=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?j(e).includes(n):!0}});var Pe,tr=h(()=>{"use strict";ee();tt();Pe={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:Y.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r,o=!1)=>({id:e,title:t,rank:r,isDeleted:!1,props:{ref:j(e)},context:Y.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:Y.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:r,props:o={},childRenderAxis:s="horizontal",isVirtual:i=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:Y.FIELD,childRenderAxis:s,parentNodeId:n,readonly:!1,log:[],isVirtual:i}),fieldList:({id:e,name:t,parentNodeId:n,rank:r,childRenderAxis:o="horizontal",isVirtual:s=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:Y.FIELD_LIST,childRenderAxis:o,parentNodeId:n,readonly:!1,log:[],isVirtual:s}),ticket:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{ref:j(e)},context:Y.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!0,isVirtual:s=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:Y.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:o,log:[],isVirtual:s}),comment:({id:e,name:t,parentNodeId:n,rank:r,props:o={},readonly:s=!0,isVirtual:i=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:Y.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:i})}});var Fy,me,$s,Bt=h(()=>{"use strict";Fy=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[me,$s]=Fy});function Tn(e,t=!1){let n=Hy[e.action];if(!n)return d(`Unknown event action "${e.action}", likely created by a newer epiq version. Evt id: ${e.id}`);if(!Nt()&&e.action!=="init.workspace")return _(`${e.action} arrived before the workspace was initialized`,e);if(e.action==="init.workspace"&&nt){if(nt.genesisApplied)return _("the workspace is already initialized",e);nt.genesisApplied=!0}let r;try{r=n(e)}catch(s){return _(`threw while materializing (${s instanceof Error?s.message:String(s)})`,e)}if(a(r))return r;let o=Wy(e,t);return o||r}var Pa,_,$o,nr,rr,xu,Eu,By,Oy,La,Uy,jy,nt,$y,Wy,jo,Hy,mn,pn=h(()=>{"use strict";St();ee();S();Mr();re();tr();M();Da();Bt();Pa=(e,t)=>d(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),_=(e,t)=>({...Pa(e,t),convergence:!0}),$o=e=>a(e)&&e.convergence===!0,nr=e=>{let t=e.filter(a);return{fatal:t.filter(n=>!$o(n)),skipped:t.filter($o)}},rr=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("; ")}`)},xu=e=>{let t=E.getNode(e);if(!t||!F(t)||t.isDeleted)return null;let n=Hs(t);return a(n)?n:null},Eu=e=>{if(!qs())return null;for(let t of e){let n=xu(t);if(n)return n;let r=g().nodes[t]?.parentNodeId;if(!r)continue;let o=xu(r);if(o)return o}return null},By=(e,t)=>{let n=E.getNode(e);n&&E.updateNode({...n,log:[...n.log??[],t]})},Oy=e=>{let t=[e],n=g().nodes[e]?.parentNodeId;return n&&t.push(n),t},La=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 Oy(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[]}},Uy=e=>{Ne(t=>({...t,eventLog:[...t.eventLog,e]}))},jy=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?Pa("Invalid user ID format",e):l("Valid user",null)},nt=null,$y=e=>{for(let[t,n]of e.nodeLog){let r=E.getNode(t);r&&E.updateNode({...r,log:[...r.log??[],...n]})}return e.appLog.length>0&&Ne(t=>({...t,eventLog:[...t.eventLog,...e.appLog]})),Eu([...e.virtualNodeIds])},Wy=(e,t)=>{let n=jy(e);if(a(n))return n;let r=[...new Set(La(e))];if(nt){for(let s of r){if(!t){let i=nt.nodeLog.get(s);i?i.push(e):nt.nodeLog.set(s,[e])}if(qs()){nt.virtualNodeIds.add(s);let i=g().nodes[s]?.parentNodeId;i&&nt.virtualNodeIds.add(i)}}return t||nt.appLog.push(e),null}t||(r.forEach(s=>By(s,e)),Uy(e));let o=Eu(r);return o||null},jo=(e,t,n)=>E.getNode(e)?_(`a node with id ${e} already exists`,n):t===e?_("a node cannot be its own parent",n):null,Hy={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=Pe.workspace(t,n,r),s=Wo(o);if(a(s))return Pa(s.message,e);let i=E.createNode(o);return a(i)?_(i.message??"Failed to initialize workspace",e):pa(i.value)?l("Workspace initialized",{action:e.action,result:i.value}):d("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=jo(t,void 0,e);if(o)return o;let s=E.createNode(Pe.workspace(t,n,r));return a(s)?_(s.message??"Failed to add workspace",e):pa(s.value)?l("Added workspace",{action:e.action,result:s.value}):d("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=jo(t,r,e);if(s)return s;let i=E.createNode(Pe.board(t,n,r,o));return a(i)?_(i.message??"Unable to create board",e):Yn(i.value)?l("Added board",{action:e.action,result:i.value}):d("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=jo(t,r,e);if(s)return s;let i=E.createNode(Pe.swimlane(t,n,r,o));return a(i)?_(i.message??"Unable to create swimlane",e):Kn(i.value)?l("Added swimlane",{action:e.action,result:i.value}):d("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=jo(t,r,e);if(s)return s;let i=E.createNode(Pe.ticket(t,n,r,o));return a(i)?_(i.message??"Unable to create issue",e):F(i.value)?l("Added issue",{action:e.action,result:i.value}):d("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:s}=e.payload,i=jo(t,r,e);if(i)return i;let c=E.createNode(Pe.field({id:t,name:n,parentNodeId:r,rank:s,props:{value:o},childRenderAxis:n.includes(ge.DESCRIPTION)?"vertical":"horizontal"}));return a(c)?_(c.message??`Unable to create field: ${n}`,e):ut(c.value)?l("Added field",{action:e.action,result:c.value}):d("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!E.getNode(t))return _(`Unable to locate node with id ${t}`,e);let o=E.renameNode(t,n);return a(o)?_(o.message??"Unable to edit title",e):l("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=E.tombstoneNode(t);return a(n)?_(n.message??"Unable to delete node",e):l("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=E.createTag({id:t,name:n});return a(r)?_(r.message??"Unable to create tag",e):l("Tag added",{action:e.action,result:r.value})},"tombstone.tag":e=>{let{id:t}=e.payload,n=E.tombstoneTag(t);return a(n)?_(n.message??"Unable to delete tag",e):l("Tag tombstoned",{action:e.action,result:n.value})},"restore.tag":e=>{let{id:t,name:n}=e.payload,r=E.restoreTag(t,n);return a(r)?_(r.message??"Unable to restore tag",e):l("Tag restored",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=E.createContributor({id:t,name:n});return a(r)?_(r.message??"Unable to create contributor",e):l("Contributor created",{action:e.action,result:r.value})},"rename.contributor":e=>{let{id:t,name:n}=e.payload,r=E.renameContributor(t,n);return a(r)?_(r.message??"Unable to rename contributor",e):l("Contributor renamed",{action:e.action,result:r.value})},"tombstone.contributor":e=>{let{id:t}=e.payload,n=E.tombstoneContributor(t);return a(n)?_(n.message??"Unable to remove contributor",e):l("Contributor tombstoned",{action:e.action,result:n.value})},"restore.contributor":e=>{let{id:t,name:n}=e.payload,r=E.restoreContributor(t,n);return a(r)?_(r.message??"Unable to restore contributor",e):l("Contributor restored",{action:e.action,result:r.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=E.tag(t,n);return a(r)?_(r.message??"Unable to tag issue",e):l("Issue tagged",{action:e.action,result:{tag:n}})},"remove.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=E.untag(t,n);return a(r)?_(r.message??"Unable to untag issue",e):l("Issue untagged",{action:e.action,result:{tag:n}})},"add.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=E.assign(t,n);return a(r)?_(r.message??"Unable to assign issue",e):l("Assigned successfully",{action:e.action,result:{assignee:n}})},"remove.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=E.unassign(t,n);return a(r)?_(r.message??"Unable to unassign issue",e):l("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=E.moveNodeToRank({id:t,parentId:n,rank:r});return a(o)?_(o.message??"Failed to move node",e):l("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=E.editValue(t,n);return a(r)?_(r.message??"Unable to edit description",e):l("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=E.getNode(t);if(!o)return _("Unable to locate issue",e);if(!F(o))return _("Can only close issues",e);let s=E.getNode(me);if(!s)return _("Unable to locate target swimlane",e);if(n!==s.id)return _("Close target must be closed swimlane",e);let i=E.moveNodeToRank({id:t,parentId:n,rank:r});return a(i)?_(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:r}=e.payload,o=E.getNode(t);if(!o)return _("Unable to locate issue",e);if(!F(o))return _("Can only reopen issues",e);let s=E.getNode(me);if(!s)return _("Unable to locate closed swimlane",e);if(n===s.id)return _("Cannot reopen issue into closed swimlane",e);if(!E.getNode(n))return _("Reopen parent no longer exists",e);let c=E.moveNodeToRank({id:t,parentId:n,rank:r});return a(c)?_(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 a(n)?_(n.message??"Unable to lock node",e):l("Node locked",{action:e.action,result:n.value})},"rebalance.children":e=>{let{parent:t,ranks:n}=e.payload;for(let[r,o]of Object.entries(n)){let s=E.getNode(r);if(!s)return _(`Unable to locate node ${r}`,e);if(s.parentNodeId!==t)return _(`Node ${r} is not child of ${t}`,e);let i=E.updateNode({...s,rank:o});if(a(i))return _(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:r,md:o}=e.payload,s=E.createComment({id:t,issue:n,authorId:r,authorName:E.getContributor(r)?.name??"Unknown",md:o,deleted:!1});return a(s)?_(s.message??"Unable to add comment",e):l("Comment added",{action:e.action,result:{id:t,issue:n,author:r,md:o}})},"edit.issue.comment":e=>{let{id:t,issue:n,md:r}=e.payload,o=E.getComment(t);if(!o)return _("Unable to locate comment",e);if(o.issue!==n)return _("Comment does not belong to issue",e);let s=E.editComment(t,r);return a(s)?_(s.message??"Unable to edit comment",e):l("Comment edited",{action:e.action,result:{id:t,issue:n,md:r}})},"delete.issue.comment":e=>{let{id:t,issue:n}=e.payload,r=E.getComment(t);if(!r)return _("Unable to locate comment",e);if(r.issue!==n)return _("Comment does not belong to issue",e);let o=E.deleteComment(t);return a(o)?_(o.message??"Unable to delete comment",e):l("Comment deleted",{action:e.action,result:{id:t,issue:n}})},"add.issue.attachment":e=>{let{id:t,issue:n,hash:r,ext:o,name:s,bytes:i}=e.payload,c=E.createAttachment({id:t,issue:n,hash:r,ext:o,name:s,bytes:i,deleted:!1});return a(c)?_(c.message??"Unable to add attachment",e):l("Attachment added",{action:e.action,result:{id:t,issue:n,hash:r}})},"delete.issue.attachment":e=>{let{id:t,issue:n}=e.payload,r=E.getAttachment(t);if(!r)return _("Unable to locate attachment",e);if(r.issue!==n)return _("Attachment does not belong to issue",e);let o=E.deleteAttachment(t);return a(o)?_(o.message??"Unable to delete attachment",e):l("Attachment deleted",{action:e.action,result:{id:t,issue:n}})},"link.contributor.user":e=>{let{contributor:t}=e.payload,n=E.linkUserId({contributorId:t,userId:e.userId});return a(n)?_(n.message??"Unable to link contributor",e):l("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};mn=e=>{let t=Ws(()=>{let n=nt===null;n&&(nt={appLog:[],nodeLog:new Map,virtualNodeIds:new Set,genesisApplied:!1});try{let r=e.map(o=>Tn(o));if(n&&nt){let o=$y(nt);if(o)return e.map(()=>o)}return r}finally{n&&(nt=null)}});return a(t)?e.map(()=>d(t.message)):t.value}});var _a,Ru=h(()=>{"use strict";_a=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/\.jsonl/g,"-jsonl").replace(/^-+|-+$/g,"")||"unknown"});import Ee from"node:fs";import or from"node:path";import{ulid as qy}from"ulid";var zs,Fa,Nu,Cu,Ba,wu,Au,Vs,Tu,Gy,zy,ku,Vy,Mu,Ky,Pu,Yy,Gs,Su,Ks,sr=h(()=>{"use strict";S();ie();zs="~pending",Fa=/~pending(-[0-9a-z]+)*$/i,Nu=/-f(\d+)$/,Cu=e=>{let t=e.indexOf(".");return t===-1?`${e}${zs}`:e.slice(0,t)+zs+e.slice(t)},Ba=e=>{let t=e.indexOf(".");return t===-1?[e,""]:[e.slice(0,t),e.slice(t)]},wu=e=>{let[t,n]=Ba(e);return Fa.test(t)?t.replace(Fa,"")+n:null},Au=e=>e.replace(Fa,""),Vs=e=>e.endsWith(".jsonl")&&wu(e)!==null,Tu=e=>{let[t]=Ba(e),n=Nu.exec(t);return n&&Vs(e)?Number(n[1]):null},Gy=e=>Cu(e).replace(zs,`${zs}-${qy().toLowerCase()}`),zy=(e,t)=>{let[n,r]=Ba(e);return`${n.replace(Nu,"")}-f${t}${r}`},ku=(e,t)=>or.join(_t(e),Cu(t)),Vy=(e,t)=>Math.max(0,Ee.statSync(e).size-(Tu(t)??0)),Mu=e=>{let t=_t(e);try{return Ee.existsSync(t)?Ee.readdirSync(t).filter(Vs).some(n=>Vy(or.join(t,n),n)>0):!1}catch{return!0}},Ky=3,Pu=(e,t)=>{for(let n=1;;n++){let r=Ee.openSync(e,"a"),o;try{Ee.writeSync(r,t),o=Ee.fstatSync(r).ino}finally{Ee.closeSync(r)}let s;try{s=Ee.statSync(e).ino}catch{s=null}if(s===o||n>=Ky)return}},Yy=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 r=Buffer.alloc(1);return Ee.readSync(t,r,0,1,n-1),r[0]===10}finally{Ee.closeSync(t)}},Gs=10,Su=(e,t,n=!1)=>{let r=n?t.length:t.lastIndexOf(Gs)+1;if(r===0)return{bytes:0,lines:0};let o=t.subarray(0,r);if(o.toString("utf8").trim().length===0)return{bytes:r,lines:0};Ee.appendFileSync(e,Buffer.concat([Buffer.from(Yy(e)?"":`
|
|
39
|
+
`),o,Buffer.from(o[o.length-1]===Gs?"":`
|
|
40
|
+
`)]));let s=0;for(let i of o)i===Gs&&s++;return o[o.length-1]!==Gs&&s++,{bytes:r,lines:s}},Ks=(e,t)=>{let n=_t(e);if(!Ee.existsSync(n))return l("No events directory",0);try{let r=Ee.readdirSync(n).filter(i=>wu(i)===t),o=or.join(n,t),s=0;for(let i of r){let c=Tu(i);if(c!==null){let f=or.join(n,i),y=Ee.readFileSync(f).subarray(c);s+=Su(o,y,!0).lines,Ee.rmSync(f,{force:!0});continue}let u=/~pending-/i.test(i)?i:Gy(t),m=or.join(n,u);u!==i&&Ee.renameSync(or.join(n,i),m);let p=Su(o,Ee.readFileSync(m));s+=p.lines,Ee.renameSync(m,or.join(n,zy(u,p.bytes)))}return l("Folded pending logs",s)}catch(r){return d(`Unable to fold pending event logs in ${n}: ${r instanceof Error?r.message:String(r)}`)}}});import Oa from"node:fs";import Xy from"node:path";var Ho,Ua,ja,ir,Lu,$a,kn,Du,_u,Fu,Pr=h(()=>{"use strict";ie();Ho=e=>e?.code==="ENOENT",Ua=3,ja=e=>Oa.readdirSync(e).filter(t=>t.endsWith(".jsonl")).sort(),ir=e=>{let t=_t(e);for(let n=1;;n++){if(!Oa.existsSync(t))return"none";let r=[],o=!1;for(let s of ja(t))try{let{size:i,mtimeMs:c}=Oa.statSync(Xy.join(t,s));r.push(`${s}:${i}:${c}`)}catch(i){if(!Ho(i))throw i;if(n<Ua){o=!0;break}}if(!o)return r.join("|")}},Lu=e=>new Map(e.split("|").filter(Boolean).map(t=>{let n=t.indexOf(":");return[t.slice(0,n),t.slice(n+1)]})),$a=(e,t,n)=>{let r=Lu(t),o=ir(e),s=Lu(o);for(let[i,c]of s)if(i!==n&&r.get(i)!==c)return null;for(let i of r.keys())if(i!==n&&!s.has(i))return null;return o},kn=null,Du=e=>kn&&kn.root===e?kn.signature:null,_u=(e,t)=>{kn={root:e,signature:t}},Fu=(e,t)=>{if(!kn||kn.root!==e)return;let n=$a(e,kn.signature,t);kn=n===null?null:{root:e,signature:n}}});var Jy,Qy,Bu,Ou,Wa=h(()=>{"use strict";Jy=["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"],Qy=new Set(Jy),Bu=e=>Qy.has(e),Ou=e=>({action:e.action,payload:e.payload})});import{z as V}from"zod";var q,Ot,Mn,Ys,Ha,Zy,Uu,ju=h(()=>{"use strict";S();q=V.string().min(1),Ot=V.string(),Mn=V.string(),Ys=V.looseObject({id:q}),Ha=V.looseObject({id:q,name:Ot,parent:q,rank:Mn}),Zy={"init.workspace":V.looseObject({id:q,name:Ot,rank:Mn}),"add.workspace":V.looseObject({id:q,name:Ot,rank:Mn}),"add.board":Ha,"add.swimlane":Ha,"add.issue":Ha,"add.field":V.looseObject({id:q,name:Ot,parent:q,rank:Mn}),"edit.title":V.looseObject({id:q,name:Ot}),"delete.node":Ys,"lock.node":Ys,"move.node":V.looseObject({id:q,parent:q,rank:Mn}),"edit.description":V.looseObject({id:q,md:V.string()}),"close.issue":V.looseObject({id:q,parent:q,rank:Mn}),"reopen.issue":V.looseObject({id:q,parent:q,rank:Mn}),"create.tag":V.looseObject({id:q,name:Ot}),"tombstone.tag":Ys,"restore.tag":V.looseObject({id:q,name:Ot}),"create.contributor":V.looseObject({id:q,name:Ot}),"rename.contributor":V.looseObject({id:q,name:Ot}),"tombstone.contributor":Ys,"restore.contributor":V.looseObject({id:q,name:Ot}),"link.contributor.user":V.looseObject({contributor:q}),"add.issue.assignee":V.looseObject({id:q,assignee:q}),"remove.issue.assignee":V.looseObject({id:q,assignee:q}),"add.issue.tag":V.looseObject({id:q,tag:q}),"remove.issue.tag":V.looseObject({id:q,tag:q}),"add.issue.comment":V.looseObject({id:q,issue:q,md:V.string()}),"edit.issue.comment":V.looseObject({id:q,issue:q,md:V.string()}),"delete.issue.comment":V.looseObject({id:q,issue:q}),"add.issue.attachment":V.looseObject({id:q,issue:q,hash:V.string().min(1),ext:V.string().min(1),name:Ot,bytes:V.number()}),"delete.issue.attachment":V.looseObject({id:q,issue:q}),"rebalance.children":V.looseObject({parent:q,ranks:V.record(V.string(),Mn)})},Uu=(e,t)=>{let r=Zy[e].safeParse(t);return r.success?l("Payload is readable",void 0):d(`${e}: ${r.error.issues.map(o=>`${o.path.join(".")||"payload"} ${o.message}`).join(", ")}`)}});import Wu from"node:fs";import Js from"node:path";import{decodeTime as eb}from"ulid";import{z as qa}from"zod";function qo(e,t){let n=_t(e),r=ir(e);if(!Wu.existsSync(n))return l("No events found",[]);let o=[],s=[];for(let c=1;;c++){o=[],s=[];let u=!1;for(let m of ja(n)){let p=cb(Js.join(n,m),s);if(a(p))return d(p.message);if(p.value===null){if(c<Ua){u=!0;break}continue}o.push(...p.value)}if(!u)break}t?.push(...s);let i=lb(o);return fn={root:e,signature:r,edge:i.at(-1)?.id?.[0]??null},l("All events loaded",i)}function Ct(e){let t=[],n=qo(e,t);if(a(n))return d(n.message);let r=za(n.value,t);return a(r)?d(r.message):l("Loaded merged events",{events:r.value,unreadable:t})}function Va(e){let t=qo(e);return a(t)?d(t.message):l("Loaded event actors",t.value.map(({userId:n,userName:r})=>({userId:n,userName:r})))}function ar(e){let t=Ct(e);return a(t)?d(t.message):l("Loaded merged events",t.value.events)}function Ka(e,t){let n=qo(e);if(a(n))return d(n.message);let{appliedEvents:r,unappliedEvents:o}=ub(n.value,t),s=za(r);if(a(s))return d(s.message);let i=za(o);return a(i)?d(i.message):l("Loaded merged events before time",{appliedEvents:s.value,unappliedEvents:i.value})}function Hu(e=process.cwd()){let t=ir(e);if(fn&&fn.root===e&&fn.signature===t)return l("Loaded edge reference, unchanged",fn.edge);let n=qo(e);return a(n)?d(n.message):l("Loaded edge reference",n.value.at(-1)?.id?.[0]??null)}function qu(e,t,n){if(!fn||fn.root!==e)return;let r=$a(e,fn.signature,t);fn=r===null?null:{root:e,signature:r,edge:n}}function Ya(e){let t=qo(e);if(a(t))return d(t.message);let n=Gu(t.value);return l("Loaded effective event times",new Map(t.value.map((r,o)=>[r.id[0],n[o]??null])))}var tb,Xs,nb,rb,ob,sb,ib,ab,db,za,cb,fn,$u,Ga,lb,Gu,ub,wt=h(()=>{"use strict";St();S();ie();Pr();Je();Wa();Ce();ju();sr();tb=qa.object({userId:qa.string().min(1).default("unknown"),userName:qa.string().min(1).default("unknown")}),Xs=e=>{let t=Object.entries(e).filter(([o])=>o!=="id"&&o!=="v"&&o!=="userId"&&o!=="userName");if(t.length!==1)return null;let n=t[0]?.[1];if(typeof n!="object"||n===null)return null;let r=n.id;return typeof r=="string"&&r.length>0?r:null},nb=/^[0-9a-hjkmnp-tv-z]{26}$/i,rb=e=>nb.test(e)?e.toUpperCase():e,ob=e=>{let t=Js.basename(e,".jsonl"),n=t.indexOf("."),r=Au(n===-1?t:t.slice(0,n)),o=n===-1?void 0:t.slice(n+1),s=tb.safeParse({userId:rb(r),userName:o});return s.success?l("Parsed event file actor",s.data):d(`Invalid event file name ${Js.basename(e)}: ${s.error.issues.map(i=>i.path.join(".")||i.message).join(", ")}`)},sb=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?d(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?d("Invalid persisted event: action key is missing or invalid"):l("Resolved persisted action",t[0])},ib=(e,t)=>t in e,ab=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),db=e=>{let{userId:t,userName:n,...r}=e,o=sb(r);if(a(o))return d(o.message);let s=o.value,i=e.id?.[0];return i?ib(r,s)?l("Decoded persisted event",ab({id:i,action:s,payload:r[s],userId:t,userName:n})):d(`Persisted event is missing payload for action: ${s}`):d("Persisted event is missing id")},za=(e,t)=>{let n=[],r=new Map,o=new Map;for(let s of e){if(!Vu(s.v)){o.set(s.v,(o.get(s.v)??0)+1),t?.push({eventId:s.id[0],reason:"unsupported-schema-version",detail:`v${s.v}`,targetNodeId:Xs(s)});continue}let i=db(s);if(a(i)){t?.push({eventId:s.id[0],reason:"invalid-payload",detail:i.message,targetNodeId:Xs(s)});continue}let c=i.value.action;if(!Bu(c)){r.set(c,(r.get(c)??0)+1),t?.push({eventId:s.id[0],reason:"unknown-action",detail:c,targetNodeId:Xs(s)});continue}let u=Uu(c,i.value.payload);if(a(u)){t?.push({eventId:s.id[0],reason:"invalid-payload",detail:u.message,targetNodeId:Xs(s)});continue}n.push(i.value)}if(r.size>0){let s=[...r.entries()].map(([i,c])=>`${i} (x${c})`).join(", ");X.info(`Skipped events with unknown actions, likely created by a newer epiq version: ${s}. Upgrade to apply them.`)}if(o.size>0){let s=[...o.entries()].map(([i,c])=>`v${i} (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)},cb=(e,t)=>{let n=ob(e);if(a(n))return d(n.message);let r;try{r=Wu.readFileSync(e,"utf8")}catch(c){if(Ho(c))return l("Event file missing",null);throw c}let o=[],s=Js.basename(e),i=(c,u)=>{t?.push({eventId:null,reason:"corrupt-line",detail:`${s}:${c} (${u})`,targetNodeId:null})};for(let[c,u]of r.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=zu(p);if(a(f)){i(c+1,f.message);continue}o.push({...f.value,userId:n.value.userId,userName:n.value.userName})}return l("Parsed persisted events file",o)};fn=null;$u=(e,t)=>e<t?-1:e>t?1:0,Ga=(e,t)=>{let n=$u(e.id[0],t.id[0]);return n!==0?n:$u(JSON.stringify(e),JSON.stringify(t))},lb=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(Ga);let r=[],o=new Set,s=m=>{let p=[m];for(;p.length>0;){let f=p.pop(),y=f.id[0];if(o.has(y))continue;r.push(f),o.add(y);let x=n.get(y)??[];for(let R=x.length-1;R>=0;R--)p.push(x[R])}},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 o.has(p)?!1:f===null||!t.has(f)}).sort(Ga);for(let m of c)s(m);let u=e.filter(m=>!o.has(m.id[0])).sort(Ga);for(let m of u)s(m);return r},Gu=e=>Co(e.map(t=>{try{return eb(t.id[0])}catch{return null}}));ub=(e,t)=>{let n=new Set,r=[],o=[],s=Gu(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),o.push(c)):r.push(c)}return{appliedEvents:r,unappliedEvents:o}}});import Xa from"node:path";import{decodeTime as mb,monotonicFactory as pb}from"ulid";import{z as dr}from"zod";function Ja(e,t){let n;if(t&&t.current!==void 0)n=t.current;else{let o=Hu(e);if(a(o))return d(o.message);n=o.value}let r=n?Ku(hb(n)):Ku();return l("Minted event id",[r,n])}function Qs({event:e,rootDir:t,edge:n,id:r}){try{let o=yu(t);if(a(o))return o;let s=Eb(t,{userId:e.userId,userName:e.userName});if(a(s))return s;let i=l("Resolved pending event log path",ku(t,Xa.basename(s.value))),c=r?l("Minted event id",r):Ja(t,n);if(a(c))return d(c.message);let[u,m]=c.value,p=Rb(Ou(e),[u,m]);if(a(p))return d(p.message);Pu(i.value,`${JSON.stringify(p.value)}
|
|
42
|
+
`),n&&(n.current=u);let f=Xa.basename(i.value);return qu(t,f,u),Fu(t,f),l("Event persisted",{path:i.value,entry:p.value})}catch(o){let s=o instanceof Error?o.message:"Unknown persist error";return d(`Failed to persist event: ${s}`)}}var Yu,Ku,fb,gb,hb,Xu,vb,yb,zu,bb,Ib,Vu,xb,oe,cr,Eb,Rb,Ce=h(()=>{"use strict";St();zn();S();ze();ie();Ru();Je();sr();wt();Pr();Wa();Yu=1,Ku=pb(),fb=0xffffffffffff,gb=As,hb=e=>{let t=Date.now(),n;try{n=mb(e)}catch{return t}return n>=fb?t:n>t+gb?(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)},Xu=dr.tuple([dr.string().min(1),dr.string().min(1).nullable()]),vb=dr.looseObject({v:dr.literal(Yu),id:Xu}),yb=dr.looseObject({v:dr.number().int().positive(),id:Xu}),zu=e=>{let t=yb.safeParse(e);return t.success?l("Parsed persisted event envelope",t.data):d(`Invalid persisted event envelope: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},bb=[1],Ib=new Set(bb),Vu=e=>Ib.has(e),xb=e=>{let t=vb.safeParse(e);return t.success?l("Parsed persisted event",t.data):d(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},oe=()=>{let{userName:e,userId:t}=xe();return e?t?ws(t)?So(e)?l("Successfully resolved actor ID",{userId:t,userName:e}):d("Invalid user name in config"):d("Invalid user ID in config"):d("User ID not configured"):d("User name not configured")},cr=({userId:e,userName:t})=>`${_a(e)}.${_a(t)}.jsonl`,Eb=(e,{userId:t,userName:n})=>{let r=cr({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return d(`Invalid event log file name: ${r}`);let s=Xa.join(_t(e),r);return l("Successfully resolved event log path",s)},Rb=(e,t)=>{let n={[e.action]:e.payload,v:Yu,id:t};return xb(n)}});import{ulid as Sb}from"ulid";function Ju(e,t,n){let r=Ja(t,n);if(a(r))return d(r.message);let o={...e,id:r.value[0]},s=Tn(o);if(s.status!==sn.Success)return s;let i=Qs({event:o,rootDir:t,edge:n,id:r.value});return a(i)?i:s}function P(e,t){if(e.length===0||!e[0])return d("No events provided");if(g().readOnly)return d(g().readOnlyReason??"Cannot change the board while time travelling");let n=Ws(()=>{let r={},o=Nb(e[0],t,r);if(a(o))return d(o.message);let s=e.map(c=>Ju(c,t,r)),i=s.filter(a);return i.length>0?d("Materialize and persist failed: "+i.map(c=>c.message).join(", ")):l("Materialization succeeded",s.map(c=>c.value))});return a(n)?d(n.message):n.value??d("Materialize and persist produced nothing")}var Nb,Re=h(()=>{"use strict";S();re();M();pn();Ce();Nb=(e,t,n)=>{if(e.action==="create.contributor"||e.action==="rename.contributor")return l("Contributor write already in flight",void 0);let r=E.getContributor(e.userId),o={id:Sb(),action:r?"rename.contributor":"create.contributor",payload:{id:e.userId,name:e.userName},userId:e.userId,userName:e.userName};if(r&&(r.tombstoned||r.name===e.userName))return l("Contributor name is current",void 0);let s=Ju(o,t,n);return a(s)?d(s.message):l("Contributor name recorded",void 0)}});var lr,Qa,Qu=h(()=>{"use strict";tt();lr=e=>e.trim().toLocaleLowerCase(),Qa=(e,t)=>lr(e).includes(lr(t))});var Cb,wb,Zu,em,Ab,Tb,tm,nm=h(()=>{"use strict";M();tt();Qu();Cb=e=>{let{tags:t}=g();return(e.props.tags??[]).map(n=>t[n]).filter(n=>n!==void 0&&!n.tombstoned).map(n=>n.name)},wb=e=>{let{contributors:t}=g();return(e.props.assignees??[]).map(n=>{let r=t[n];return r?r.name:void 0}).filter(n=>!!n)},Zu=null,em=new Map,Ab=()=>{let e=g().eventLog??[];if(e===Zu)return em;let t=new Map;for(let n of e){if(!n.userId)continue;let r=n.payload;for(let o of[r.id,r.issue]){if(typeof o!="string")continue;let s=t.get(o)??new Set;s.add(n.userId),t.set(o,s)}}return Zu=e,em=t,t},Tb=e=>{let{contributors:t}=g(),n=Ab().get(e.id);return n?[...n].map(r=>t[r]?.name).filter(r=>!!r):[]},tm=(e,t)=>{let n=lr(t.value);if(!n)return!0;switch(t.target){case"title":return Qa(e.title??"",n);case"description":return Qa(e.props.description??"",n);case"tag":return Cb(e).map(lr).some(o=>o.includes(n));case"assignee":return wb(e).map(lr).some(o=>o.includes(n));case"actor":return Tb(e).map(lr).some(o=>o.includes(n));case"ref":return Uo(e.id,t.value);default:return!0}}});var Za,kb,rm,om,sm,ed=h(()=>{"use strict";ee();nm();Za=(e,t)=>e.rank<t.rank?-1:e.rank>t.rank?1:0,kb=(e,t)=>!!e&&!e.isDeleted&&e.parentNodeId===t,rm=(e,t)=>Object.values(e).filter(n=>kb(n,t)).sort(Za),om=(e,t)=>{let n={};for(let r of Object.values(e)){if(F(r)&&t.length>0&&!t.every(s=>tm(r,s))||!r.parentNodeId||r.isDeleted)continue;let o=n[r.parentNodeId];o?o.push(r):n[r.parentNodeId]=[r]}for(let r of Object.keys(n))n[r].sort(Za);return n},sm=(e,t)=>{let n={};for(let r of Object.values(e)){if(!r.parentNodeId||r.isDeleted||!t.has(r.parentNodeId))continue;let o=n[r.parentNodeId];o?o.push(r):n[r.parentNodeId]=[r]}for(let r of Object.keys(n))n[r].sort(Za);return n}});var im,Zs,ye,am,dm,Vt,gn,Rt=h(()=>{"use strict";Vl();Re();S();M();ed();wr();im=e=>Zs(ye(e),{at:"end"}),Zs=(e,t={at:"end"})=>{let n=o=>a(o)?l("Rank space exhausted",{rank:"",needsRebalance:!0}):l("Resolved rank",{rank:o.value,needsRebalance:!1});if(e.length===0)return n(Ve(void 0,void 0));let r=()=>n(Ve(e[e.length-1]?.rank,void 0));switch(t.at){case"start":{let o=e[0];return o?n(Ve(void 0,o.rank)):d("Unable to resolve first sibling")}case"end":{let o=e[e.length-1];return o?n(Ve(o.rank,void 0)):d("Unable to resolve last sibling")}case"before":{let o=am(e,t.sibling),s=o<0?void 0:e[o];if(!s)return r();let i=o>0?e[o-1]:void 0;return n(Ve(i?.rank,s.rank))}case"after":{let o=am(e,t.sibling),s=o<0?void 0:e[o];if(!s)return r();let i=o<e.length-1?e[o+1]:void 0;return n(Ve(s.rank,i?.rank))}}},ye=e=>{let t=g();if(!cm()&&t.filters.length===0){let n=t.renderedChildrenIndex[e];if(n)return n}return rm(t.nodes,e)},am=(e,t)=>e.findIndex(n=>n.id===t),dm=(e,t,n={at:"end"})=>Zs(ye(t).filter(r=>r.id!==e),n),Vt=(e,t,n,r,o)=>{let s=dm(t,e,n);if(a(s))return s;if(!s.value.needsRebalance)return l("Resolved rank",s.value.rank);let i=ha(e,r);if(a(i))return i;let c=P([i.value],o);if(a(c))return c;let u=dm(t,e,n);return a(u)?u:u.value.needsRebalance?d("Rank rebalance failed to create space"):l("Resolved rank after rebalance",u.value.rank)},gn=(e,t,n)=>{let r=im(e);if(a(r))return r;if(!r.value.needsRebalance)return l("Resolved rank",r.value.rank);let o=ha(e,t);if(a(o))return o;let s=P([o.value],n);if(a(s))return s;let i=im(e);return a(i)?i:i.value.needsRebalance?d("Rank rebalance failed to create space"):l("Resolved rank after rebalance",i.value.rank)}});var $,lm,um,ht=h(()=>{"use strict";M();$={exit(){process.exit(0)},enterChildNode(){let e=g(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=ae(t.id),o=r[n];o&&(t.context==="FIELD"&&r.length===0||o.context==="COMMENT"||o.context==="TEXT"||$.navigate({contextNode:o,selectedIndex:ae(o.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 r=ae(n.id),o=r.findIndex(({id:i})=>i===e.id),s=r.length===0?-1:o>=0?o:0;$.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>lm(1),navigateToPreviousItem:()=>lm(-1),navigateToNextContainer:()=>um(1),navigateToPreviousContainer:()=>um(-1),navigate:({contextNode:e,selectedIndex:t})=>{N({contextNodeId:e.id,selectedIndex:t})}},lm=e=>{let{selectedIndex:t,contextNode:n}=g(),r=ae(n.id).length;if(r===0)return;let s=(Math.max(0,t)+e+r)%r;$.navigate({selectedIndex:s,contextNode:n})},um=e=>{let{contextNode:t,nodes:n,selectedIndex:r}=g();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!o)return;let s=ae(o.id),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=ae(c.id),m=Math.max(0,u.length-1),p=Math.min(Math.max(0,r),m),f=u.length?p:-1;$.navigate({contextNode:c,selectedIndex:f})}});var pm,fm,Mb,ei,gm,mm,Pb,hm,vm=h(()=>{"use strict";ee();S();Rt();M();ht();pm=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),fm=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=g();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},Mb=e=>{let t=g().nodes[e];return!!t&&!t.isDeleted&&ut(t)&&t.childRenderAxis==="vertical"},ei=(e,t)=>{let{nodes:n}=g(),r=n[e];if(!r||r.isDeleted)return!1;let o=ye(r.id);return $.navigate({contextNode:r,selectedIndex:pm(t,o.length)}),!0},gm=e=>{let{nodes:t}=g(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return ei(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let i=ye(o.id).findIndex(c=>c.id===n.id);return i>=0?($.navigate({contextNode:o,selectedIndex:i}),!0):gm(o.id)},mm=e=>{let{nodes:t}=g(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),gm(n))return!0;n=t[n]?.parentNodeId}return!1},Pb=e=>{if(!e)return!1;let t=g().nodes[e];return!!t&&!t.isDeleted},hm=e=>{let{nodes:t,rootNodeId:n}=g();if(Mb(e.contextNodeId)&&ei(e.contextNodeId,e.selectedIndex))return l("Restored navigation inside text container",null);if(Pb(e.selectedNodeId)&&e.selectedNodeId&&mm(e.selectedNodeId))return l("Restored navigation to selected node or ancestor",null);if(ei(e.contextNodeId,e.selectedIndex))return l("Restored navigation to previous container",null);if(e.parentNodeId&&ei(e.parentNodeId,e.selectedIndex))return l("Restored navigation to previous parent",null);if(mm(e.contextNodeId))return l("Restored navigation to previous container or ancestor",null);let r=t[n];if(!r||r.isDeleted)return d("Unable to restore navigation");let o=ye(r.id);return $.navigate({contextNode:r,selectedIndex:pm(e.selectedIndex,o.length)}),l("Restored navigation to root",null)}});import{monotonicFactory as Lb,ulid as Kt}from"ulid";function Db(){let e=Ye();if(a(e))return d("Unable to boot. State not initialized");let t=e.value,n=Object.values(t.nodes).find(s=>s.context==="WORKSPACE");if(!n)return d("No workspace found in event log");let[r]=ae(n.id),[o]=r?ae(r.id):[];if(o){let s=t.renderedChildrenIndex?.[o.id]??[];return l("Resolved boot nav target",{contextNode:o,selectedIndex:s.length>0?0:-1})}else return r?l("Resolved boot nav target",{contextNode:r,selectedIndex:0}):l("Resolved boot nav target",{contextNode:n,selectedIndex:0})}function _b(){let e=Db();return a(e)?e:$.navigate(e.value)}function ym({userId:e,userName:t}){let n=Go(),r=Go(),o=Go(),s=Go(),i=Go(),c=Ve(void 0,void 0);if(a(c))return c;let u=Ve(void 0,void 0);if(a(u))return u;let m=Ve(u.value,void 0);if(a(m))return m;let p=Ve(void 0,void 0);if(a(p))return p;let f=Ve(p.value,void 0);if(a(f))return f;let y=Ve(f.value,void 0);if(a(y))return y;let x=Ve(void 0,void 0);return a(x)?x:l("Created default events",[{id:Kt(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:c.value}},{id:Kt(),userId:e,userName:t,action:"create.contributor",payload:{id:e,name:t}},{id:Kt(),userId:e,userName:t,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:u.value}},{id:Kt(),userId:e,userName:t,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:p.value}},{id:Kt(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"In progress",parent:r,rank:f.value}},{id:Kt(),userId:e,userName:t,action:"add.swimlane",payload:{id:i,name:"Done",parent:r,rank:y.value}},{id:Kt(),userId:e,userName:t,action:"add.board",payload:{id:$s,name:"Closed",parent:n,rank:m.value}},{id:Kt(),userId:e,userName:t,action:"add.swimlane",payload:{id:me,name:"Closed",parent:$s,rank:x.value}},{id:Kt(),userId:e,userName:t,action:"lock.node",payload:{id:$s}},{id:Kt(),userId:e,userName:t,action:"lock.node",payload:{id:me}}])}function Yt(e,t=[]){if(Fb())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=Wo(s);return a(i)?i:(N({hasProjectDefinition:!1,mode:b.DEFAULT}),l("Booted uninitialized workspace placeholder",null))}if(!e.some(s=>s.action==="init.workspace"))return d("Initialized Epiq project has no workspace init event");let n=mn(e),{fatal:r,skipped:o}=nr(n);return r.length>0?d(`Materializing failed:
|
|
43
|
+
${r.map(s=>s.message).join(`
|
|
44
|
+
`)}`):(rr(o),_b(),N({hasProjectDefinition:!0}),Bb(t),l("State booted successfully",null))}var Go,Fb,Bb,ur=h(()=>{"use strict";St();ht();ve();S();tr();M();wr();pn();Bt();Go=Lb();Fb=()=>{let e=Ye();if(a(e))return!1;let{timeMode:t}=e.value;return t==="peek"||t==="replay"},Bb=e=>{if(e.length===0)return;let t=e.filter(r=>r.reason==="corrupt-line"||r.reason==="invalid-payload"),n=e.filter(r=>r.reason==="unsupported-schema-version"||r.reason==="unknown-action");if(n.length>0){let r=[...new Set(n.map(o=>o.detail))].join(", ");X.info(`This build cannot read ${n.length} event(s) in the log (${r}). They are skipped, so anything they changed may be out of date until you upgrade.`)}if(t.length>0){let r=[...new Set(t.map(o=>o.detail))].join(", ");X.info(`Skipped ${t.length} corrupt line(s) in the event log (${r}). The rest of the board loaded normally; those events are unrecoverable.`)}}});import{WebSocket as Ob}from"ws";var Ub,bm,Im=h(()=>{"use strict";Ub=new Set,bm=e=>{let t=JSON.stringify(e);for(let n of Ub)n.readyState===Ob.OPEN&&n.send(t)}});var ti,Lr,mr,td,ni,Se,zo=h(()=>{"use strict";Im();S();M();ti=e=>{Nt()&&(N({syncStatus:e}),bm({type:"sync-status",payload:e}))},Lr=(e="Syncing...")=>{ti({status:"syncing",msg:e})},mr=(e="Synced")=>{ti({status:"synced",msg:e})},td=e=>{ti({status:"failed",msg:e})},ni=e=>{ti({status:"offline",msg:e})},Se=e=>(td(e),d(e))});var Dr,xm,se,ri=h(()=>{"use strict";S();Dr=(e,t)=>(logger.error(`[boot:${e}] ${t}`),d(`[boot:${e}] ${t}`)),xm=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)}},se=(e,t)=>(a(t)&&logger.info(`[${e}]:failed`,t.message),t)});import oi from"node:fs";import Em from"node:path";var $e,Rm,jb,nd,$b,Sm,rd=h(()=>{"use strict";Zn();Qe();S();ie();Ht();$e=".epiq/project.json",Rm=e=>Em.join(e,$e),jb=e=>{if(!oi.existsSync(Rm(e)))return l("State branch carries no identity yet",null);let t=pt(e);return a(t)?d(`On the state branch: ${t.message}`):l("Read the state branch identity",t.value)},nd=(e,t)=>{try{let n=Rm(e);return oi.mkdirSync(Em.dirname(n),{recursive:!0}),oi.writeFileSync(n,JSON.stringify(t,null,2)+`
|
|
45
|
+
`,"utf8"),l("Wrote the state branch identity",void 0)}catch(n){return d(n instanceof Error?`Failed to write the state branch identity: ${n.message}`:"Failed to write the state branch identity")}},$b=({checkout:e,branch:t,stateBranch:n})=>[`This checkout's ${$e} names project ${e.projectId}`,`(created ${e.createdAt}), but the state branch ${n}`,`belongs to project ${t.projectId} (created ${t.createdAt}).`,"","The branch holds the board, so its id is the one that counts. Point the","checkout at it and commit the change:","",` git show ${n}:${$e} > ${$e}`,"","A second id is minted when init runs in a checkout that has no","project file while the state branch already exists; nothing on the","board is lost by it, but every checkout has to agree on one."].join(`
|
|
46
|
+
`),Sm=({repoRoot:e,stateBranchRoot:t,stateBranch:n})=>{if(!oi.existsSync(Ar(e)))return l("No project file to compare","no-checkout-file");let r=pt(e);if(a(r))return d(r.message);let o=jb(t);if(a(o))return d(o.message);if(o.value===null){let s=nd(t,r.value);return a(s)?d(s.message):l("Stamped the state branch with this project","stamped")}return o.value.projectId!==r.value.projectId?d($b({checkout:r.value,branch:o.value,stateBranch:n})):l("The checkout and the state branch agree","matched")}});import Xt from"node:fs";import Vo from"node:path";var _r,Nm,Cm,wm,Wb,Am,Hb,qb,Tm,od=h(()=>{"use strict";Qe();S();sr();Pr();ie();_r=e=>e.split(`
|
|
47
|
+
`).filter(t=>t.trim().length>0),Nm=e=>{let t=Vo.join(e,Ke,un);try{if(!Xt.existsSync(t))return l("No events directory",[]);let n=Xt.readdirSync(t).filter(r=>r.endsWith(".jsonl")).filter(r=>_r(Xt.readFileSync(Vo.join(t,r),"utf8")).length>0);return l("Looked for stranded event logs",n)}catch(n){return d(`Unable to check ${t} for event logs before deleting it: ${n instanceof Error?n.message:String(n)}`)}},Cm=e=>Vo.join(e,Ke,un),wm=e=>{let t=Cm(e),n=new Map;try{if(!Xt.existsSync(t))return n;for(let r of Xt.readdirSync(t))if(r.endsWith(".jsonl")&&!Vs(r))try{n.set(r,_r(Xt.readFileSync(Vo.join(t,r),"utf8")))}catch(o){if(!Ho(o))throw o}}catch{return n}return n},Wb=e=>{try{let t=JSON.parse(e);return typeof t=="object"&&t!==null}catch{return!1}},Am=(e,t)=>{if(t.size===0)return[];let n=Cm(e),r=[];for(let[o,s]of t){if(s.length===0)continue;let i=Vo.join(n,o);try{let c=Xt.existsSync(i)?Xt.readFileSync(i,"utf8"):null,u=new Set(c===null?[]:_r(c)),m=s.filter(f=>!u.has(f)).filter(Wb);if(m.length===0)continue;Xt.mkdirSync(n,{recursive:!0});let p=c!==null&&c.length>0&&!c.endsWith(`
|
|
48
|
+
`);Xt.appendFileSync(i,`${p?`
|
|
47
49
|
`:""}${m.join(`
|
|
48
50
|
`)}
|
|
49
|
-
`,"utf8"),
|
|
50
|
-
`),
|
|
51
|
-
`));
|
|
52
|
-
${n.message}`);let
|
|
53
|
-
${
|
|
54
|
-
`+n.message);if(n.value)return l("Local state branch already exists",!1);let
|
|
55
|
-
`+
|
|
56
|
-
`+s.message);let i=s.value;if(
|
|
57
|
-
${c.message}`)}if(i){let c=await W({args:["branch","--track",t,`${
|
|
58
|
-
${c.message}`):l("Created local state branch from remote",!0)}return
|
|
59
|
-
`),
|
|
60
|
-
`+
|
|
61
|
-
`));
|
|
62
|
-
${
|
|
63
|
-
`));
|
|
64
|
-
|
|
65
|
-
${
|
|
66
|
-
${u.message}`)}
|
|
67
|
-
${
|
|
68
|
-
${
|
|
69
|
-
${
|
|
70
|
-
${
|
|
71
|
-
${
|
|
72
|
-
${
|
|
73
|
-
|
|
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)},hm=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let o=!1,r=Bt(e);if(d(r))return r;let s=r.value,i=[Ps(),await Ka({repoRoot:e,stateBranchName:s}),await oo({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await wb({stateBranchRoot:t,stateBranchName:s}),await eu(t),n?await Tb({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 Xa from"node:os";import kb from"node:path";var Mb,vm,Pb,Lb,Db,bm,Ya,ym,Fb,Zs,Ja=h(()=>{"use strict";R();ct();xt();Mb="epiq-sync.lock",vm=600*1e3,Pb=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}},Lb=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Db=e=>e&&(e.hostname!==Xa.hostname()||Lb(e.pid))?Date.now()-e.startedAt>vm:!0,bm=e=>`${e.operation} (pid ${e.pid} on ${e.hostname}, started ${new Date(e.startedAt).toISOString()})`,Ya=e=>{try{return Pb(Qs.readFileSync(e,"utf8"))}catch{return null}},ym=(e,t)=>{let n={pid:process.pid,hostname:Xa.hostname(),startedAt:Date.now(),operation:t};try{return Qs.writeFileSync(e,JSON.stringify(n),{flag:"wx"}),!0}catch{return!1}},Fb=async({worktreeRoot:e,operation:t})=>{let n=await ua(e);if(d(n))return a(n.message);let o=kb.join(n.value,Mb),r=()=>{try{let c=Ya(o);c&&c.pid===process.pid&&Qs.rmSync(o)}catch{}};if(ym(o,t))return l("Acquired sync lock",{acquired:!0,release:r});let s=Ya(o);if(!Db(s))return l("Sync lock is held",{acquired:!1,heldBy:s});J.info(`Breaking an abandoned sync lock: ${s?bm(s):"unreadable lock file"}`);try{Qs.rmSync(o,{force:!0})}catch{}if(ym(o,t))return l("Acquired sync lock after breaking a stale one",{acquired:!0,release:r});let i=Ya(o);return l("Sync lock taken by another process",{acquired:!1,heldBy:i??{pid:-1,hostname:Xa.hostname(),startedAt:Date.now(),operation:"unknown"}})},Zs=async({worktreeRoot:e,operation:t,fn:n})=>{let o=await Fb({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 ${bm(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 _b from"node:fs";var Ob,Bb,Qa,xm,Za,ei,ti=h(()=>{"use strict";R();Dr();Xs();bo();Xe();ct();Br();za();Yn();Ja();Ob=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 hm({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 ws(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",Zl(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}))},Bb=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 pm({stateBranchRoot:t}));if(d(r))return a(r.message);let s=re("stageStateBranchEventConfig",await fm({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 ql(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 gm({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}))},Qa=(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})},xm=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");So();let n=re("ensureSyncReady",await Ob({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 Gl(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",js(r,t));d(I)&&logger.error(`[sync] ${I.message}`);let S=re("commitOwnEventFileToStateBranch",await Bb({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 Qa({repoRoot:o,stateBranchRoot:r,createdCommit:c,commitSha:u,bootstrapped:s},"no remote");let w=re("pullBranchRebaseIfPresent",await Sr({cwd:r,branch:y}));if(d(w))return Er(w.message)?Qa({repoRoot:o,stateBranchRoot:r,createdCommit:c,commitSha:u,bootstrapped:s}):Re(w.message);m=w.value;let k=re("isAheadOfUpstream",await Hl(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 Or({stateBranchRoot:r,repoRoot:o}));if(d(D)&&$l(D.message)){let _=re("pullBranchRebaseIfPresent(retry)",await Sr({cwd:r,branch:y}));if(d(_))return Re(_.message);m=m||_.value,D=re("pushStateBranch(retry)",await Or({stateBranchRoot:r,repoRoot:o}))}if(d(D))return Er(D.message)?Qa({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})},Za=async(e,t)=>{let n=dm(e);try{return await t()}finally{let o=cm(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(!_b.existsSync(r))return xm(e);let s=await Zs({worktreeRoot:r,operation:"sync",fn:()=>Za(r,()=>xm(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,Ub,ed,Im,oi=h(()=>{"use strict";tm();to();St();Ce();pe();R();M();Dr();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=Ub();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}},Ub=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:g().mode,syncStatus:g().syncStatus});let e=Im();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=ed(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))},ed=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=Im();if(n)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:g().mode,message:n.message,syncStatus:g().syncStatus}),n;let o=Qu(),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",em(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)},Im=()=>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 Co,Em,Sm,td,nd,Ur,od,$b,Rm,jb,Nm,ri=h(()=>{"use strict";R();We();M();oi();Co=3e3,Em=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<Co?null:t},Sm=0,nd=!1,Ur=!1,od=()=>{if(nd)return!0;let e=ze();return d(e)?!1:e.value.syncStatus.status==="syncing"},$b=()=>{let e=Ie().autoSyncIntervalMs??1e4,t=Date.now()-Sm;return Math.max(0,e-t)},Rm=()=>{td||(td=setTimeout(async()=>{if(td=void 0,!!It()){if(od()){Ur=!0;return}Ur=!1,await jb()}},$b()))},jb=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(od())return Ur=!0,a("Sync already in progress");nd=!0,Sm=Date.now(),N({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await ni()}finally{nd=!1,Ur&&Rm()}},Nm=()=>{It()&&(Ur=!0,!od()&&Rm())}});import $r from"node:fs";import jr from"node:path";import{z as Ao}from"zod";var si,Hb,Wb,qb,Am,wm,Cm,Tm,km,Mm,Gb,ii,Hr,wo=h(()=>{"use strict";R();nn();Cs();ae();si="recent-projects.json",Hb=20,Wb=Ao.object({projectId:Ao.string().min(1),root:Ao.string().min(1),lastOpenedAt:Ao.number().finite()}),qb=Ao.object({projects:Ao.array(Wb)}),Am=()=>jr.join(on(),si),wm=e=>jr.basename(e)||e,Cm=e=>{let t=jr.resolve(e);try{return $r.realpathSync(t)}catch{return t}},Tm=(e,t)=>t.lastOpenedAt-e.lastOpenedAt,km=e=>{if(!Cr(e.root))return!1;let t=xr(e.root);return!d(t)&&t.value===e.projectId},Mm=()=>{let e=Am();if(!$r.existsSync(e))return l("No recent projects recorded",[]);let t;try{t=JSON.parse($r.readFileSync(e,"utf8"))}catch(o){return a(`Invalid ${si}: ${o instanceof Error?o.message:String(o)}`)}let n=qb.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(", ")}`)},Gb=e=>{let t=Am();try{$r.mkdirSync(jr.dirname(t),{recursive:!0}),$r.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=Mm();if(d(t))return t;let n=e===void 0?null:Cm(e);return l("Listed recent projects",t.value.filter(o=>n===null||Cm(o.root)!==n).filter(km).sort(Tm))},Hr=({root:e,now:t=Date.now()})=>{let n=jr.resolve(e),o=xr(n);if(d(o))return a(o.message);let r=o.value,s=Mm(),i=d(s)?[]:s.value,c=[{projectId:r,root:n,lastOpenedAt:t},...i.filter(u=>u.projectId!==r&&u.root!==n)].filter(km).sort(Tm).slice(0,Hb);return Gb(c)}});var ai,Pm,Lm,Dm,Wr=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}},Pm=()=>{let e=Me(process.cwd());if(d(e))return!1;let t=Ot(e.value);return Dt(t)},Lm=e=>e===!0?"on":e===!1?"off":null,Dm=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,To,di=h(()=>{"use strict";Ve();C={red:$e.red,yellow:$e.yellow,green:$e.green,blue:$e.blue,magenta:$e.magenta,cyan:$e.cyan},To={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 zb,Vb,Tn,kn,ci,li,qr=h(()=>{"use strict";K();R();ne();M();zb=e=>e.props.tags??[],Vb=e=>e.props.assignees??[],Tn=e=>zb(e).map(t=>E.getTag(t)).filter(t=>!!t),kn=e=>Vb(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 Kb,Yb,Xb,Jb,Qb,so,Fm,ui,mi,_m,Zb,rd,Gr=h(()=>{"use strict";Kb=/^(\d+)(h|d|w|mo|y)$/,Yb=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Xb=({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},Jb=(e,t=new Date)=>{let n=e.match(Kb);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}},Qb=e=>{let t=e.match(Yb);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 Xb({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 Jb(t)??Qb(t)},Fm=/^(\d+)(s|m)?$/,ui=e=>{let t=e.trim().toLowerCase().match(Fm);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&&Fm.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:o}},_m=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Zb=[{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}],rd=(e=Zb)=>{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 ex,ve,mt,Ae,tx,nx,id,ad,Um,io,pi,sd,Om,ox,rx,zr,Bm,sx,ix,dd,ax,we,pn=h(()=>{"use strict";ri();wo();R();Wr();dn();K();ne();M();di();qr();ro();Gr();ex=["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"},tx=[ve.EDITOR,ve.VIEW,ve.USERNAME,ve.AUTOSYNC,ve.SYNC_DEBOUNCE_MS,ve.ATTACHMENT_MAX_KB,ve.LOG_LEVEL],nx=(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[]}},id=[String(Co),"5000","15000","30000","60000"],ad=["250","500","1000"],Um=["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],sd=[x.TAG,x.UNTAG,x.ASSIGN,x.UNASSIGN,x.CLOSE_ISSUE,x.RE_OPEN_ISSUE,x.EDIT,x.COMMENT],Om=[x.FILTER,x.PEEK,x.REPLAY],ox={WORKSPACE:[...io,...pi],BOARD:[...Om,...io,...pi],SWIMLANE:[...Om,...io,...pi],TICKET:[...io,...pi,...sd],FIELD:[...io,...sd],FIELD_LIST:[...io,...sd],TEXT:[...io],COMMENT:[x.EDIT,x.DELETE,x.YANK]},rx=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],zr=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&P(n)),Bm=e=>e.parentNodeId===he,sx=({selectedNode:e,breadCrumb:t})=>{let n=nx(e?.context);return zr({breadCrumb:t,selectedNode:e})?n.includes(mt.DESCRIPTION)?n:[...n,mt.DESCRIPTION]:n},ix=({selectedNode:e,breadCrumb:t})=>{let n=zr({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]:[]},dd=()=>{let e=ii({exclude:process.cwd()});return d(e)?[]:[...e.value.map((t,n)=>String(n+1)),...e.value.map(t=>t.root)]},ax=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:o}=ai();if(!o)return[x.HELP,x.CONFIG];if(!Pm())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&&ex.includes(r),i=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?ox[u]:[]))],c=zr({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&&Bm(c)):u===x.CLOSE_ISSUE?!!(c&&!Bm(c)):!0)},we=(e,{contextNode:t,selectedNode:n,readOnly:o,breadCrumb:r}=g())=>{let s=t.context??"WORKSPACE";return{[x.NONE]:ax({breadCrumb:r,readOnly:o,selectedNode:n}),[x.EXIT]:["confirm"],[x.EXPORT]:[],[x.SYNC]:[],[x.INIT]:[],[x.OPEN]:e===x.OPEN?dd():[],[x.HELP]:[],[x.PEEK]:[...rd(),"now","prev","next"],[x.REPLAY]:[...rd()],[x.EDIT]:sx({selectedNode:n,breadCrumb:r}),[x.YANK]:ix({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(To),...E.getExistingTags()])],[x.UNTAG]:[...ci()?.value?.map(({name:c})=>c)??[]],[x.UNASSIGN]:[...li()?.value?.map(({name:c})=>c)??[]],[x.ASSIGN]:E.getExistingAssignees(),[x.NEW]:rx(s),[x.CONFIG]:[...tx]}[e]??[]}});var $m,jm=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 dx,copyFileSync as cx,existsSync as fi,mkdirSync as Hm,readdirSync as Wm,readFileSync as lx,renameSync as ux,rmSync as mx,statSync as qm,unlinkSync as px,writeFileSync as fx}from"node:fs";import ko from"node:path";var cd,Ze,gi=h(()=>{"use strict";cd=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",Ze={writeToFile:(e,t)=>{try{let n=ko.dirname(e);fi(n)||Hm(n,{recursive:!0});let o=typeof t=="string"?t:JSON.stringify(t,null,2);fx(e,o,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return lx(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)&&qm(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await dx(e),!0}catch{return!1}},mkDir:e=>Hm(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=ko.parse(t);for(;;){let o=ko.join(t,e);try{if(fi(o)&&qm(o).isDirectory())return o}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=ko.dirname(t)}return null},readFirstJSON(e){try{if(!Ze.dirExists(e))return null;let t=Wm(e).filter(o=>o.endsWith(".json")).sort()[0];if(!t)return null;let n=ko.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)?Wm(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{px(e)}catch(t){(!cd(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{mx(e,{recursive:!0,force:!0})}catch(t){(!cd(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(ko.dirname(t)),!n?.overwrite&&fi(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{ux(e,t)}catch(o){if(cd(o)&&o.code==="EXDEV"){cx(e,t),this.rmFile(e);return}throw o}}}});import gx from"node:path";import{z as fn}from"zod";var hx,Gm,vx,zm,ld,ud,yx,Mo,Vm,et,Vr,zt=h(()=>{"use strict";Un();ae();R();gi();hx={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},Gm=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(),vx="config.json",zm=on,ld=()=>gx.join(zm(),vx),ud=()=>{try{return Ze.mkDir(zm()),l(`Ensured ~/${Tt} exists`,null)}catch{return a(`Unable to create ~/${Tt}`)}},yx=e=>{let t;try{t=JSON.parse(e)}catch{return a(`Invalid ~/${Tt}/config.json JSON`)}let n=Gm.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(", ")}`)},Mo=()=>{let e=ud();if(d(e))return a(e.message);let t=ld(),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}):yx(n)},Vm=e=>{let t=ud();if(d(t))return a(t.message);let n=Gm.safeParse(e);if(!n.success)return a(`Invalid config: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`);let o=ld();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=Mo();if(d(t))return a("Failed to read existing config");let n={...t.value,...e};return Vm(n)},Vr=()=>{let e=ld(),t=ud();if(d(t))return a(`Unable to create ~/${Tt}`);if(!(Ze.readFile(e)!==null)){let S=Vm(hx);if(d(S))throw new Error(`Unable to create ~/${Tt}/config.json`)}let o=Mo();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 Km,Ym,md,Xm=h(()=>{"use strict";Km="/media/",Ym=e=>`${Km}${e}`,md=(e,t)=>`})`});import bx from"node:crypto";import pd from"node:fs";import xx from"node:path";var gn,Po,Ix,Ex,Sx,Jm,Lo=h(()=>{"use strict";Ft();R();ae();Xm();gn=500,Po=(e,t)=>`${e}.${t}`,Ix=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: ${hl.join(", ")}`),Ex=e=>bx.createHash("sha256").update(e).digest("hex"),Sx=(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=Ix(e);return d(n)?n:l("Validated attachment data",{hash:Ex(e),ext:n.value,bytes:e.length})},Jm=(e,t,n=gn)=>{let o=Sx(t,n);if(d(o))return o;let r=Ls(e),s=xx.join(r,Po(o.value.hash,o.value.ext));try{pd.existsSync(s)||(pd.mkdirSync(r,{recursive:!0}),pd.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 Rx from"zod";var Kr,Yr,Qm,fd=h(()=>{"use strict";zt();Lo();pe();R();ce();We();M();Kr=50,Yr=5e3,Qm=()=>{let e=de().commandMeta.inputString,t=Rx.coerce.number().int().min(Kr).max(Yr).safeParse(e);if(!t.success)return a(`Attachment size cap must be ${Kr}-${Yr} 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 Zm from"chalk";var hd,ep,gd,tp,Nx,Cx,np,Ax,wx,Xr,Te,op,rp,hi,Tx,kx,vi,pt=h(()=>{"use strict";di();hd={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},ep=(e,t,n)=>Math.max(t,Math.min(n,e)),gd=(e,t,n)=>e+(t-e)*n,tp=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},Nx=e=>e.toLowerCase().trim(),Cx=(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)]},np=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,Ax=(e,t,n)=>{let o=ep(n,0,1);return[Math.round(gd(e[0],t[0],o)),Math.round(gd(e[1],t[1],o)),Math.round(gd(e[2],t[2],o))]},wx=(e,t,n)=>Ax(e,t,n),Xr=e=>{let t=tp(e)%360,n=Cx(t,hd.stringColor.saturation,hd.stringColor.lightness);return np(n)},Te=(e,t=To)=>{let n=Nx(e??"");return n&&t[n]?t[n]:Xr(n)},op=e=>{let t=hd.gradient.stops,n=ep(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 wx(t[s],t[s+1],i)},rp=e=>np(op(e)),hi=e=>tp(e.toLowerCase().trim())/4294967295,Tx=e=>{let t=hi(e);return op(t)},kx=e=>{let[t,n,o]=Tx(e);return{normal:r=>Zm.bgRgb(t,n,o).black(r),cursor:r=>Zm.bgRgb(t,n,o).white.bold(r)}},vi=e=>kx(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 Mx}from"node:crypto";var Px,Lx,Le,Do=h(()=>{"use strict";Px="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Lx=e=>{let t=Mx("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+=Px[Number(n>>s&31n)]}return o},Le=(e,t)=>Lx(`${e}:virtual:${t}`)});import sp from"chalk";var le,De,Ue,ip=h(()=>{"use strict";pt();Ve();le=e=>sp.dim(e),De=e=>sp.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 cp from"chalk";var Dx,ap,me,ee,G,_o,dp,bi,vd,Fx,Fo,_x,Ox,Bx,Ux,$x,lp,up=h(()=>{"use strict";ri();Wr();jm();Ke();Ft();R();ne();We();fd();Lo();M();pt();hn();qr();Do();ip();ro();yi();pn();Gr();Dx=["BOARD","TICKET","SWIMLANE"],ap=()=>{let e=g().selectedNode;if(!e?.context)return G({message:le("Missing target context")});if(Dx.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}),_o=e=>e.length===0,dp=(e,t)=>{let n=it(g().breadCrumb,"BOARD");if(d(n))return G({message:De("Command is not applicable in this context")});let o=gl(n.value.id);return d(o)?G({message:De(`Unable to ${t}: board id is not a valid ULID`)}):_m({date:e,horizonDate:o.value})?null:G({message:De(`nothing to ${t} before ${o.value.toISOString().slice(0,16).replace("T"," ")}`)})},bi=e=>` ${cp.hex("#000").bgHex(Te(e))(` ${e} `)} `,vd=({modifier:e})=>{let t="confirm";return e===t?ee(me):G({message:_o(e)?le("if you are certain, enter ")+vi(t):"",completionWordList:[t]})},Fx=({list:e,hint:t,onValue:n})=>({modifier:o,inputString:r})=>e.includes(o)?r.trim().length<1?G({message:le(n)}):ee():G({message:_o(o)?t:"",completionWordList:[...e]}),Fo=({hint:e,onOk:t})=>({modifier:n,inputString:o})=>_o(n)&&_o(o)?G({message:e,completionWordList:[]}):ee(t??me),_x=({modifier:e,inputString:t})=>{let n=dd();return!_o(e)||!_o(t)?ee(me):G({message:n.length?le("number from the list, or a path"):le("path to an epiq project"),completionWordList:n})},Ox=({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 ")+cp.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=Lm(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<Kr||r>Yr){let s=Ue({prefix:" examples: ",wordList:ad,minLengthForHints:0,inputString:t});return G({message:De(`provide a size cap in KB (${Kr}-${Yr}). current: ${o??gn} KB.`)+s,completionWordList:ad})}return ee(me)}case ve.SYNC_DEBOUNCE_MS:{let o=Ie().autoSyncIntervalMs,r=Em(t);if(!t.trim()||r===null||r<Co){let s=Ue({prefix:" examples: ",wordList:id,minLengthForHints:0,inputString:t});return G({message:De(`provide duration above ${Co}ms. current duration: ${o}ms.`)+s,completionWordList:id})}return ee(me)}default:return G({message:De("Unknown config option"),completionWordList:n})}},Bx=({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})}},Ux=({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")})},$x={[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=dp(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=dp(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?Um:[]))},[x.EXIT]:()=>ee(me+le(" and exit the application")),[x.INIT]:()=>ee(me),[x.OPEN]:_x,[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=>Fx({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]:Bx,[x.COMMENT]:e=>{let t=Fo({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]:Ox,[x.YANK]:Ux,[x.DELETE]:e=>{let t=ap();return t.validity==="invalid"?t:vd(e)},[x.CLOSE_ISSUE]:e=>vd(e),[x.RE_OPEN_ISSUE]:e=>vd(e),[x.MOVE]:e=>{let t=ap();return t.validity==="invalid"?t:Fo({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 Fo({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?Fo({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 Fo({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?Fo({hint:le("remove assignee... ")+n.join("")})(e):G({message:De("Issue has no assignees"),completionWordList:[]})},[x.SYNC]:()=>ee(me)},lp=Object.fromEntries(Object.entries($x).map(([e,t])=>[e,{validate:(n,o,r)=>t({modifier:o,command:n,inputString:r})}]))});var xi,mp=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 jx,Hx,Wx,qx,Gx,pp,fp,gp,hp=h(()=>{"use strict";R();M();mp();jx=3,Hx=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"]),Wx=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},qx=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=jx&&!Hx.has(t)&&!/^\d+$/.test(t)),Gx=e=>{let t=new Map;for(let s of Wx(e))for(let i of qx(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]},pp=xi,fp=-1,gp=()=>{let e=ze();if(d(e))return xi;let t=e.value,n=t.eventLog.length;return n!==fp&&(pp=Gx(t),fp=n),pp}});var vp,yp,yd=h(()=>{"use strict";Al();pn();ro();up();hp();M();pe();vp=e=>Object.values(x).includes(e),yp=(e,t)=>{let n=e.command??"",{modifier:o,target:r,inputString:s}=e,{message:i,validity:c,completionWordList:u}=lp[n].validate(n,o,s),m=n!==x.PEEK&&n!==x.REPLAY,p=r==="command"||r==="modifier"?we(n):m?gp():[],{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?Cl(e,I):{hint:"",hints:[],remainder:"",overlap:0}}}});var bp,zx,Vx,Kx,xp=h(()=>{"use strict";yd();pn();bp=e=>{let t=e.trimStart(),n=Vx(t),o=n[0]??"",r=n[1]??"",s=/\s$/.test(e),i=Kx(e),c=vp(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=zx(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}},zx=(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},Vx=e=>e.trim()?e.trim().split(/\s+/):[],Kx=e=>e.trimEnd().split(/\s+/).at(-1)??""});import{useSyncExternalStore as cP}from"react";var Oo,bd,Bo,Yx,Ip,Vt,Jr,xd,Id,Ep,Sp,Ii,Rp,te,Np,Cp,Ap,de,Ei,ce=h(()=>{"use strict";yd();xp();R();yi();Oo=e=>e===bd||e===":",bd=" ",Bo={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:Mn.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},Yx=new Set,Ip=()=>{for(let e of Yx)e()},Vt=e=>{let n=e(Bo),o=bp(n.value),r=n.cursorPosition===n.value.length;Bo={...n,commandMeta:yp(o,r)},Ip()},Jr=({message:e,status:t})=>{let n=structuredClone(Bo);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,Bo=n,Ip(),l(e,null)},xd=e=>{Vt(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Id=e=>{Vt(t=>{let{value:n,cursorPosition:o}=t,r=o;if(e==="left"){for(;r>0&&Oo(n[r-1]);)r--;for(;r>0&&!Oo(n[r-1]);)r--}else{for(;r<n.length&&!Oo(n[r]);)r++;for(;r<n.length&&Oo(n[r]);)r++}return{...t,cursorPosition:r}})},Ep=()=>{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}})},Sp=()=>{Vt(e=>{let{value:t,cursorPosition:n}=e,o=n;for(;o>0&&Oo(t[o-1]);)o--;for(;o>0&&!Oo(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}})},Rp=()=>{Vt(e=>({...e,commandIsPending:!0}))},te=e=>{Vt(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},Np=({addToHistory:e=!0})=>{Vt(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},Cp=()=>{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}})},Ap=()=>{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=()=>Bo,Ei=()=>{let[e,...t]=Bo.value.split(bd);return t.join(bd).trim()}});var O,jn=h(()=>{"use strict";pe();yl();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 wp,B,Ed=h(()=>{"use strict";M();ro();wp=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 Tp}from"ink";import kp,{useEffect as Mp,useState as Xx}from"react";var Pp,ot,Uo=h(()=>{"use strict";M();Ve();Pp={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},ot=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=rt(),o=Pp[n]??Pp.default,[r,s]=Xx(0);if(Mp(()=>{s(0)},[o]),Mp(()=>{if(!e)return;let c=setInterval(()=>{s(u=>(u+1)%o.length)},500);return()=>clearInterval(c)},[e,o]),!e)return kp.createElement(Tp,null,t);let i=o[r]??o[0]??t;return kp.createElement(Tp,{color:T.accent,dimColor:r===1},i)}});import{Box as Sd,Text as Jx}from"ink";import Si from"react";var Qx,Pn,Qr=h(()=>{"use strict";Ve();Qx=(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?Qx(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(Sd,{flexDirection:"row",height:i,width:"100%"},Si.createElement(Sd,{flexDirection:"column",flexGrow:1,height:i},S),Si.createElement(Sd,{flexDirection:"column",width:1,height:w},Array.from({length:w}).map((ie,En)=>Si.createElement(Jx,{key:En,color:A&&En>=H&&En<H+k?T.accent:T.secondary},A?"\u2502":" "))))}});var Lp,Rd,Zx,Ri,Nd=h(()=>{"use strict";M();Zx=()=>{let{eventLog:e=[]}=g();if(Rd&&Lp===e)return Rd;let t=new Set;for(let n of e)n?.userId&&t.add(n.userId);return Lp=e,Rd=t,t},Ri=e=>Zx().has(e)});import{Text as eI}from"ink";import tI from"react";var nI,oI,$o,Ni=h(()=>{"use strict";di();pt();ne();Nd();dt();nI=e=>e.toLowerCase().trim(),oI=(e,t=To)=>{let n=nI(e);return t[n]?t[n]:Xr(n)},$o=({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 tI.createElement(eI,{underline:t,color:oI(r)},"@"+s,Ri(e)?"":"\u2197")}});import{Text as rI}from"ink";import sI from"react";var Ci,Cd=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 sI.createElement(rI,{underline:t,backgroundColor:Te(o.name),color:T.secondary}," "+r+" ")}});import{useEffect as iI,useState as aI}from"react";var dI,Dp,Ai,Zr,cI,lI,jo,wi=h(()=>{"use strict";pt();dI=80,Dp=1400,Ai=new Set,Zr=null,cI=e=>(Ai.add(e),Zr||(Zr=setInterval(()=>{for(let t of Ai)t()},dI)),()=>{Ai.delete(e),Ai.size===0&&Zr&&(clearInterval(Zr),Zr=null)}),lI=()=>{let e=Date.now()%Dp/Dp;return e<.5?e*2:(1-e)*2},jo=e=>{let[,t]=aI(0);return iI(()=>{if(e)return cI(()=>t(n=>n+1))},[e]),rp(lI())}});import{Box as Ho,Text as Wo}from"ink";import st from"react";var uI,Fp,mI,pI,_p,Op=h(()=>{"use strict";ne();Ve();dt();Nd();Je();qr();Ni();Cd();wi();uI=(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)]},Fp=3,mI=2,pI=(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}},_p=({width:e,ticket:t,isSelected:n,isFlashing:o=!1})=>{let r=jo(o),s=e-4,i=s-7-1,[c,u]=uI(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-Fp),I=E.getCommentsByIssue(t.id),S=I.length?String(I.length).length+2+1:0,{shown:A,hidden:w}=pI([...p.map(k=>({id:k.id,isTag:!0,width:Math.min(k.name.length,y)+Fp})),...f.map(k=>({id:k.id,isTag:!1,width:Math.min(k.name.length,y)+mI+(Ri(k.id)?0:1)}))],s-S);return st.createElement(Ho,{borderStyle:"round",height:5,flexDirection:"column",overflow:"hidden",borderDimColor:!n,borderColor:o?r:n?T.accent:T.secondary,justifyContent:"space-between"},st.createElement(Ho,{paddingLeft:1,paddingRight:1,flexDirection:"column"},st.createElement(Ho,{justifyContent:"space-between"},st.createElement(Wo,{color:T.primary},c),st.createElement(Wo,{color:T.secondary2,dimColor:!0},j(t.id))),u&&st.createElement(Wo,{color:T.primary},u),m&&st.createElement(Wo,{color:T.secondary2,dimColor:!0},m)),st.createElement(Ho,{flexDirection:"row",paddingLeft:1,paddingRight:1,justifyContent:"space-between"},st.createElement(Ho,{flexDirection:"row"},A.map(k=>st.createElement(Ho,{paddingRight:1,key:k.id},k.isTag?st.createElement(Ci,{id:k.id,maxWidth:y}):st.createElement($o,{id:k.id,maxWidth:y}))),w>0&&st.createElement(Wo,{color:T.secondary2,dimColor:!0},"+",w)),I.length>0&&st.createElement(Wo,{color:T.accent},"[",I.length,"]")))}});import{Box as ao,Text as es}from"ink";import ft from"react";var fI,Bp,Up=h(()=>{"use strict";pe();ne();Ve();pt();Uo();wi();fI=(e,t)=>e.length>t?e.slice(0,Math.max(0,t-1))+"\u2026":e,Bp=({index:e,labelWidth:t,width:n,ticket:o,isSelected:r,isFlashing:s=!1,mode:i})=>{let c=jo(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(es,{color:Te(ie.name)},"\u25A0"))),S=m.map(ie=>ft.createElement(ao,{key:ie.id,paddingRight:p},ft.createElement(es,{color:Xr(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(es,{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(es,{color:"gray",dimColor:!0},String(e+1).padStart(t-1)+" ")),ft.createElement(es,{wrap:"truncate",color:A},fI(o.title,H))),ft.createElement(ao,null,I,S,D))}});import gI from"chalk";import{Box as Ad,Text as hI}from"ink";import Kt from"react";var vI,$p,jp=h(()=>{"use strict";K();M();Ve();Uo();Qr();Op();Up();wi();vI=({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=jo(y),S=`${e.title} ${gI.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(Ad,{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(hI,{bold:!0,color:y?I:t?T.accent:T.primary},S," ",e.readonly?"\u{1F512}":"")),En=(en,dr)=>{let cr=s&&i===dr;if(!P(en))return null;let ho=f?.has(en.id)??!1;return r?Kt.createElement(Bp,{key:en.id,index:dr,labelWidth:_,width:D,ticket:en,isSelected:cr,isFlashing:ho,mode:c}):Kt.createElement(_p,{key:en.id,width:D,ticket:en,isSelected:cr,isFlashing:ho})};return Kt.createElement(Ad,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?T.accent:T.secondary,paddingRight:0,paddingLeft:r?1:0,height:o},ie,Kt.createElement(Ad,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(vI)});var Hp,Wp,wd=h(()=>{"use strict";Gn();Hp=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},Wp=(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 Go,Ti=h(()=>{"use strict";Go=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 zo,Text as vn}from"ink";import je,{useEffect as yI,useMemo as bI,useRef as xI}from"react";import{decodeTime as qp}from"ulid";function zp({ticket:e,width:t,height:n}){let o=bI(()=>EI(e),[e]),r=xI([]);yI(()=>(Gp(r.current),r.current=RI(e,o),()=>{Gp(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(zo,{flexDirection:"column",width:t,height:n,padding:1},je.createElement(vn,{color:T.primary},"No attachments yet."),je.createElement(zo,{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(zo,{flexDirection:"column",width:t,height:n},je.createElement(zo,{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(zo,{key:m.id,flexDirection:"row",paddingX:1,paddingBottom:1},je.createElement(vn,{color:T.accent},f?"\u276F ":" "),je.createElement(zo,{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}," "+NI(m.bytes)+" "+Go(He(m.id)))))})))}var II,EI,Gp,SI,RI,NI,Vp=h(()=>{"use strict";ut();Ke();Ti();K();R();ne();Gn();M();Ve();Do();Qr();II=e=>Le(e,"attachments"),EI=e=>E.getAttachmentsByIssue(e.id).sort((t,n)=>qp(t.id)-qp(n.id)),Gp=e=>{for(let t of e)E.deleteNode(t.id)},SI=(e,t,n)=>Pe.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),RI=(e,t)=>{let n=E.getNode(II(e.id));if(!n||!at(n))return[];let o=t.map((r,s)=>SI(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},NI=e=>`${Math.max(1,Math.round(e/1024))} KB`});var Yp,Td,Kp,kd,Xp,Jp,CI,Qp,AI,Md,Zp=h(()=>{"use strict";Yp=/<!--\s*epiq-diff-comment:(.+?)-->\n?/,Td=e=>e.replace(Yp,""),Kp=e=>e==="additions"||e==="deletions",kd=e=>{let t=Yp.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"||!Kp(o.side)||!Kp(o.endSide)||o.sha!==void 0&&typeof o.sha!="string"||o.issueRef!==void 0&&typeof o.issueRef!="string"?null:o},Xp=/```\n([\s\S]*?)\n?```\s*$/,Jp=e=>Xp.exec(e)?.[1]??null,CI=/`[^`\n]+`[^\n]*\n?$/,Qp=e=>Td(e).replace(Xp,"").replace(CI,"").trim(),AI=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})`},Md=e=>`${e.issueRef?`${e.issueRef} \xB7 `:""}${e.filePath} ${AI(e)}`});var wI,ts,TI,kI,MI,PI,tf,Pd,nf,ef,of,Ld=h(()=>{"use strict";Zp();wI=(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},ts=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)},TI=/!\[([^\]]*)\]\([^)]*\)/g,kI=e=>e.replace(TI,(t,n)=>n.trim()?`[image: ${n.trim()}]`:"[image]"),MI=e=>e.map(t=>t.code?`\`${t.text}\``:t.text).join(""),PI=4,tf=e=>e.replace(/\r$/,"").replaceAll(" "," ".repeat(PI)),Pd=e=>{let t=!1;return e.map(tf).map(n=>{if(/^\s*```/.test(n))return t=!t,{kind:"fence"};if(t)return{kind:"code",text:n};let o=kd(n);if(o)return{kind:"caption",text:Md(o)};let r=kI(n);if(r.trim()==="")return{kind:"blank"};let s=/^#{1,6}\s+(.*)$/.exec(r);return s?{kind:"heading",spans:ts(s[1]??"")}:{kind:"text",spans:ts(r)}})},nf=(e,t)=>e.length<=t?[e]:e.match(new RegExp(`.{1,${t}}`,"g"))??[""],ef=(e,t)=>{let n=[];for(let o of Pd(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 nf(o.text,t))n.push({kind:"code",text:r});continue}if(o.kind==="caption"){n.push(o);continue}for(let r of wI(MI(o.spans),t))n.push({kind:o.kind,spans:ts(r)})}for(;n.length>0&&n[n.length-1]?.kind==="blank";)n.pop();return n},of=(e,t)=>{let n=kd(e),o=n?Jp(e):null;if(!n||o===null)return ef(Td(e).split(`
|
|
77
|
-
`),t);let r=Qp(e),s=o.split(`
|
|
78
|
-
`)
|
|
79
|
-
`),t),{kind:"blank"}]:[],{kind:"caption",text:Md(n)},...s.flatMap((u,m)=>nf(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 rf,Text as co}from"ink";import Rt from"react";var sf,Dd,af,Fd=h(()=>{"use strict";Ve();sf=({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))),Dd=({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(sf,{spans:e.spans,bold:!0,wrap:o});case"text":return Rt.createElement(sf,{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)))}}},af=({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(rf,{flexDirection:"column"},e.map((r,s)=>Rt.createElement(rf,{key:s},Rt.createElement(Dd,{line:r,width:t,gutter:o}))))}});import{Box as Ln,Text as Dn}from"ink";import ke,{useEffect as LI,useMemo as df,useRef as DI}from"react";import{decodeTime as cf}from"ulid";function uf({ticket:e,width:t,height:n}){let o=df(()=>OI(e),[e]),r=DI([]);LI(()=>(lf(r.current),r.current=BI(e,o),()=>{lf(r.current),r.current=[]}),[e,o]);let{selectedIndex:s}=rt(),c=Math.max(1,n-4),u=Math.max(20,t-8),m=df(()=>o.map(f=>{let y=of(f.md,u);return y.length>0?y:[{kind:"blank"}]}),[o,u]),p=m.map(f=>f.length+FI);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($o,{id:f.authorId}),ke.createElement(Dn,{color:T.secondary2}," "+Go(He(f.id))))),ke.createElement(Ln,{paddingLeft:3,paddingBottom:1},ke.createElement(af,{lines:m[y]??[],width:u})))})))}var FI,_I,OI,lf,BI,mf=h(()=>{"use strict";ut();Ke();Ti();K();R();ne();M();Ve();Do();Ni();Qr();wd();Ld();Fd();FI=4,_I=e=>Le(e,"comments"),OI=e=>E.getCommentsByIssue(e.id).sort((t,n)=>cf(t.id)-cf(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),lf=e=>{for(let t of e)E.deleteNode(t.id)},BI=(e,t)=>{let n=E.getNode(_I(e.id));if(!n||!at(n))return[];let o=t.map((r,s)=>Wp(r,s,n.id)).map(E.createNode).filter(Dt).map(({value:r})=>r).filter(vr);return t.length>0&&g().selectedIndex<0&&U.navigate({contextNode:n,selectedIndex:0}),o}});import{Box as ki,Text as UI}from"ink";import yn from"react";var pf,ff=h(()=>{"use strict";K();ne();Io();M();Ve();Ni();Uo();Cd();pf=({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(UI,{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($o,{isSelected:m,id:c}):r===ue.TAGS?yn.createElement(Ci,{isSelected:m,id:c}):null)})))}});var _d,gf,Od,Bd=h(()=>{"use strict";_d=e=>Math.max(5,String(Math.max(e,1)).length+3),gf=(e,t)=>Math.max(0,e-6-_d(t)),Od=(e,t=0)=>Math.max(1,e-5-2*t)});import{Box as Vo,Text as Ud}from"ink";import Nt,{useEffect as $I,useMemo as $d}from"react";var jI,hf,jd,vf,HI,Hd,yf=h(()=>{"use strict";ne();R();Gn();M();Ve();dt();Bd();Uo();Qr();Fd();Ld();yo();jI="\u2029",hf=(e,t)=>`${e}::inline-line::${t}`,jd=new Map,vf=e=>{let t=jd.get(e)??[];jd.delete(e);for(let n of t)E.deleteNode(n)},HI=(e,t)=>{vf(e);let n=[];t.forEach((o,r)=>{let s=vt(BigInt(r+1));if(!Dt(s))return;let i=E.createNode(Pe.text({id:hf(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)}),jd.set(e,n)},Hd=({id:e,label:t,text:n,rows:o,selected:r,maxWidth:s})=>{let{selectedIndex:i,contextNode:c}=rt(),u=$d(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=$d(()=>u.join("\0"),[u]);$I(()=>(HI(e,u),()=>{vf(e)}),[e,m]);let p=_d(u.length),f=gf(s,u.length),I=$d(()=>Pd(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:ts(ia(A,f))}}return S}),[u,f]).map((S,A)=>{let w=c.id===e&&i===A;return Nt.createElement(Vo,{key:hf(e,A)},Nt.createElement(Vo,{flexShrink:0},Nt.createElement(Ud,{color:w?T.primary:T.secondary2,dimColor:!w},`${A+1} `.padStart(p,"\xA0"))),S.kind==="blank"?Nt.createElement(Ud,{backgroundColor:w?"gray":void 0},jI):Nt.createElement(Vo,null,Nt.createElement(Dd,{line:S,width:S.kind==="code"?f:0,wrap:"truncate-end"})))});return Nt.createElement(Vo,{flexDirection:"column",paddingTop:1},Nt.createElement(Vo,null,Nt.createElement(ot,{isSelected:r}),Nt.createElement(Ud,{color:r?T.accent:T.secondary2},t)),Nt.createElement(Vo,{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 Wd}from"ink";import Fe,{useMemo as ns}from"react";var WI,qI,GI,zI,bf,xf=h(()=>{"use strict";K();ne();M();Ve();wd();Do();Vp();mf();Uo();ff();yf();Bd();WI=e=>Le(e,"description"),qI=e=>Le(e,"comments"),GI=e=>Le(e,"history"),zI=e=>Le(e,"attachments"),bf=({ticket:e,height:t})=>{let n=ns(()=>Hp(e),[e]),{selectedIndex:o,contextNode:r}=rt(),s=process.stdout.columns||120,i=ns(()=>WI(e.id),[e.id]),c=ns(()=>qI(e.id),[e.id]),u=ns(()=>GI(e.id),[e.id]),m=ns(()=>zI(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(uf,{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(zp,{ticket:e,width:s,height:H}))}if(I){let _=E.getNode(u),H=_&&at(_)?_.props.value??"":"",ie=Od(t);return Fe.createElement(lo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},_?Fe.createElement(Hd,{id:_.id,label:"Event log",text:H,selected:!1,maxWidth:s,rows:ie}):null)}let w=A.reduce((_,H)=>gr(H)||H.id===c||H.id===m||H.id===u?_+1:_,0),k=Od(t,w),D=(_,H)=>_.id===i?Fe.createElement(Hd,{key:_.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:H,maxWidth:s,rows:k}):gr(_)?Fe.createElement(pf,{key:_.id,parent:_,selected:H,selectedIndex:o}):_.id===c?Fe.createElement(lo,{key:_.id,paddingTop:1},Fe.createElement(ot,{isSelected:H}),Fe.createElement(Wd,{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(Wd,{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(Wd,{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 VI}from"ink";import Mi from"react";var KI,If,Ef=h(()=>{"use strict";K();jp();xf();KI=({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(VI,{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(bf,{height:i,ticket:f}))},If=Mi.memo(KI)});import Sf from"node:fs";import YI from"node:path";import XI from"react";import{render as JI}from"ink";import{Writable as QI}from"node:stream";var os,ZI,eE,tE,nE,Rf,Nf=h(()=>{"use strict";Ef();K();R();M();ae();We();os=e=>String(e).padStart(2,"0"),ZI=e=>{let t=e.getUTCFullYear(),n=os(e.getUTCMonth()+1),o=os(e.getUTCDate()),r=os(e.getUTCHours()),s=os(e.getUTCMinutes()),i=os(e.getUTCSeconds());return`${t}-${n}-${o}_${r}-${s}-${i}`},eE=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",tE=async(e,{width:t,height:n})=>{let o="",r=new QI({write(i,c,u){let m=nE(i.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(o=m),u()}});r.columns=t,r.rows=n,r.isTTY=!0;let s=JI(e,{stdout:r,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(i=>setTimeout(i,0)),s.unmount(),o},nE=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),Rf=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 tE(XI.createElement(If,{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=Ds(process.cwd());if(d(p))return a("Unable to export, epiq root not found");let f=new Date,y=ZI(f),I=`board_${eE(i.title)}_${y}.md`,S=tu(p.value);Sf.mkdirSync(S,{recursive:!0});let A=YI.join(S,I),w=`# Board - ${i.title}
|
|
51
|
+
`,"utf8"),r.push(`${o} (${m.length})`)}catch{continue}}return r},Hb=(e,t)=>{let n=new Set(_r(t));return _r(e).filter(r=>!n.has(r))},qb=(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(`
|
|
52
|
+
`),Tm=async({stateBranchRoot:e,relativePath:t,workingContent:n})=>{let r=await Oe({args:["show",`HEAD:${t}`],cwd:e});if(r.exitCode!==0)return l("No committed log to compare against",void 0);let o=Hb(r.stdout,n);return o.length>0?d(qb(t,o,_r(r.stdout).length)):l("Event log only grew",void 0)}});import hn from"node:fs";import vn from"node:path";var Gb,Mm,km,zb,sd,Ko,Vb,Kb,Pn,Yb,Xb,Jb,Qb,si,Pm,Lm,Dm,Yo,_m,Xo=h(()=>{"use strict";sr();S();rd();St();_s();Zn();od();et();Qe();Gb="[epiq:init-repo]",Mm=async e=>{let t=await Oe({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 d(["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(`
|
|
53
|
+
`));X.info("Creating initial commit");let r=await W({args:["hash-object","-w","-t","tree","/dev/null"],cwd:e});if(a(r))return d(r.message);let o=await W({args:["commit-tree",r.value.stdout.trim(),"-m",Gb],cwd:e});if(a(o))return d(o.message);let s=await W({args:["update-ref","HEAD",o.value.stdout.trim()],cwd:e});return a(s)?d(s.message):l("Created initial commit",!0)},km=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",zb=async e=>{let t=await Os(e);if(a(t))return d(t.message);let n=await tu(e);return a(n)?d(n.message):l("Built sync commit message",`[sync|branch:${km(t.value)}:sha:${km(n.value)}]`)},sd=async({repoRoot:e,stateBranchName:t})=>{X.info(`Creating ${t}`);let n=await W({args:["commit-tree",lu,"-m","[epiq:init-state-branch]"],cwd:e});if(a(n))return d(`Failed to create state branch commit
|
|
54
|
+
${n.message}`);let r=n.value.stdout.trim(),o=await W({args:["update-ref",`refs/heads/${t}`,r],cwd:e});return a(o)?d(`Failed to create ${t}
|
|
55
|
+
${o.message}`):l("Created state branch",!0)},Ko=async({repoRoot:e,stateBranchName:t})=>{let n=await Bs({repoRoot:e,branch:t});if(a(n))return d(`Ensure local state branch failed
|
|
56
|
+
`+n.message);if(n.value)return l("Local state branch already exists",!1);let r=await ln({repoRoot:e});if(a(r))return d(`Ensure local state branch failed
|
|
57
|
+
`+r.message);let o=r.value,s=o?await Po({repoRoot:e,branch:t}):l("No remote, no remote state branch",!1);if(a(s))return d(`Ensure local state branch failed
|
|
58
|
+
`+s.message);let i=s.value;if(o&&i){let c=await ue.fetch({cwd:e,remote:ft,branch:t});if(a(c))return d(`Failed to fetch ${t} from remote
|
|
59
|
+
${c.message}`)}if(i){let c=await W({args:["branch","--track",t,`${ft}/${t}`],cwd:e});return a(c)?d(`Failed to create local ${t} from remote
|
|
60
|
+
${c.message}`):l("Created local state branch from remote",!0)}return sd({repoRoot:e,stateBranchName:t})},Vb=async({repoRoot:e,branch:t})=>{let n=await W({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return d(n.message);let r=n.value.stdout.split(`
|
|
61
|
+
`),o=null;for(let s of r){if(s.startsWith("worktree ")){o=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&o)return l("Found worktree for branch",o)}return l("No worktree found for branch",null)},Kb=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=_o(vn.dirname(t));if(a(r))return d(`Failed to create state branch worktree
|
|
62
|
+
`+r.message);if(hn.existsSync(t)&&!hn.existsSync(vn.join(t,".git"))){let s=Nm(t);if(a(s))return d(s.message);if(s.value.length>0)return d([`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(`
|
|
63
|
+
`));X.info("Removing broken state branch worktree path"),fu(t)}X.info("Creating state branch worktree");let o=await ue.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return a(o)?d(`Failed to create state branch worktree
|
|
64
|
+
${o.message}`):l("Created state branch worktree",!0)},Pn=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await Xb({repoRoot:e,stateBranchRoot:t,stateBranchName:n});if(a(r))return r;let o=Sm({repoRoot:e,stateBranchRoot:t,stateBranch:n});return a(o)?d(o.message):(o.value==="stamped"&&X.info("Stamped the state branch with this project\u2019s identity"),r)},Yb=(e,t)=>{let n=Tr(er());return vn.dirname(e)===n&&vn.dirname(t)===n},Xb=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await Vb({repoRoot:e,branch:n});if(a(r))return d(r.message);let o=Tr(t),s=r.value?Tr(r.value):null;if(s&&s===o&&hn.existsSync(s))return l("State branch already checked out in expected worktree",!1);if(s&&s!==o&&Yb(s,o))return d([`The state branch ${n} is checked out under project ${vn.basename(s)}, but this checkout names project ${vn.basename(o)}.`,"","Two ids for one branch means a checkout minted a second identity for","a board that already existed. Nothing on the board is lost by it, but",`every checkout has to agree on one: compare ${$e} here`,`with \`git show ${n}:${$e}\`, and keep the branch's.`].join(`
|
|
65
|
+
`));if(s&&s!==o){let u=await su(s);if(a(u))return d(u.message);if(u.value||Mu(s))return d([`Refusing to move the state branch worktree away from ${s}.`,"","It holds changes that are not committed yet, which for this","branch means events no sync has published. Removing it would","destroy them outright \u2014 there is no stash or reflog to recover","a deleted worktree from.","",`This worktree is expected at ${o}, so something else is`,"using a different EPIQ_GLOBAL_DIR against the same repository.","Sync from that location first, or point both at the same one."].join(`
|
|
66
|
+
`));X.info("Moving state branch worktree to expected location");let m=await ue.worktreeRemove({cwd:e,worktreeRoot:s});if(a(m))return d(`Failed to remove existing state branch worktree
|
|
67
|
+
${m.message}`)}if(s&&!hn.existsSync(s)){X.info("Pruning stale state branch worktree");let u=await ue.worktreePrune({cwd:e});if(a(u))return d(`Failed to prune stale worktrees
|
|
68
|
+
${u.message}`)}let i=await eu({repoRoot:e,worktreeRoot:t});if(a(i))return d(i.message);let c=hn.existsSync(t);if(i.value&&c)return l("State branch worktree already exists",!1);if(i.value&&!c){X.info("Pruning missing registered state branch worktree");let u=await ue.worktreePrune({cwd:e});if(a(u))return d(`Failed to prune stale worktrees
|
|
69
|
+
${u.message}`)}return Kb({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},Jb=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await Os(e);if(a(n))return d(n.message);if(n.value===t)return l("State branch already checked out",!1);(await Oe({cwd:e,args:["rebase","--abort"]})).exitCode===0&&X.info("Aborted stale state branch rebase");let o=await ue.checkout({cwd:e,branch:t});return a(o)?d(`Failed to checkout ${t}
|
|
70
|
+
${o.message}`):l("Checked out state branch",!0)},Qb=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Ea(t);if(a(n))return d(n.message);if(n.value)return l("State branch upstream already configured",!1);let r=await ln({repoRoot:t});if(a(r))return d(r.message);if(!r.value)return l("No remote available for state branch upstream",!1);let o=qt(e);if(a(o))return o;let s=o.value,i=await Po({repoRoot:t,branch:s});if(a(i))return d(i.message);if(!i.value)return l("Remote state branch missing; upstream will be configured on first push",!1);X.info(`Configuring ${s} upstream`);let c=await ue.fetch({cwd:t,remote:ft,branch:s});if(a(c))return d(`Failed to fetch ${s}
|
|
71
|
+
${c.message}`);let u=await ue.setUpstream({cwd:t,branch:s,upstream:`${ft}/${s}`});return a(u)?d(`Failed to set state branch upstream
|
|
72
|
+
${u.message}`):l("Configured state branch upstream",!0)},si=async({stateBranchRoot:e,eventFileName:t})=>{let n=uu(t),r=vn.join(e,n);if(!hn.existsSync(r))return l("No event file to stage",null);let o=await Tm({stateBranchRoot:e,relativePath:n,workingContent:hn.readFileSync(r,"utf8")});if(a(o))return d(o.message);let s=await ue.stage({cwd:e,pathspec:[n]});return a(s)?d(`Failed to stage state branch event file
|
|
73
|
+
${s.message}`):l("Staged state branch event file",n)},Pm=async({stateBranchRoot:e})=>{let t=mu(),n=vn.join(e,t);if(!hn.existsSync(n))return l("No media directory to stage",null);let r=await ue.stage({cwd:e,pathspec:[t],ignoreRemoval:!0});return a(r)?d(`Failed to stage state branch media files
|
|
74
|
+
${r.message}`):l("Staged state branch media files",t)},Lm=async({stateBranchRoot:e})=>{let t=[Ra(),Sa(),$e].filter(r=>hn.existsSync(vn.join(e,r)));if(t.length===0)return l("No event log config to stage",[]);let n=await ue.stage({cwd:e,pathspec:t});return a(n)?d(`Failed to stage event log config
|
|
75
|
+
${n.message}`):l("Staged event log config",t)},Dm=async({repoRoot:e,stateBranchRoot:t,pathspec:n})=>{let r=await zb(e);return a(r)?d(`Create state branch sync commit failed
|
|
76
|
+
`+r.message):kr({cwd:t,message:r.value,pathspec:n})},Yo=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Ea(t);if(a(n))return d(n.message);let r=qt(e);if(a(r))return r;let o=r.value,s=n.value?await ue.push({cwd:t}):await ue.push({cwd:t,remote:ft,branch:o,setUpstream:!0});if(a(s))return d(`Failed during state branch push
|
|
77
|
+
${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)},_m=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=qt(e);if(a(o))return o;let s=o.value,i=[Fo(),await Ko({repoRoot:e,stateBranchName:s}),await Pn({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await Jb({stateBranchRoot:t,stateBranchName:s}),await hu(t),n?await Qb({stateBranchRoot:t,repoRoot:e}):l("Skipped state branch upstream bootstrap",!1)];for(let c of i){if(a(c))return d(c.message);r=r||!!c.value}return l(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)}});import ii from"node:fs";import ad from"node:os";import Zb from"node:path";var eI,Fm,tI,nI,rI,Om,id,Bm,oI,ai,dd=h(()=>{"use strict";S();Qe();St();eI="epiq-sync.lock",Fm=600*1e3,tI=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}},nI=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},rI=e=>e&&(e.hostname!==ad.hostname()||nI(e.pid))?Date.now()-e.startedAt>Fm:!0,Om=e=>`${e.operation} (pid ${e.pid} on ${e.hostname}, started ${new Date(e.startedAt).toISOString()})`,id=e=>{try{return tI(ii.readFileSync(e,"utf8"))}catch{return null}},Bm=(e,t)=>{let n={pid:process.pid,hostname:ad.hostname(),startedAt:Date.now(),operation:t};try{return ii.writeFileSync(e,JSON.stringify(n),{flag:"wx"}),!0}catch{return!1}},oI=async({worktreeRoot:e,operation:t})=>{let n=await xa(e);if(a(n))return d(n.message);let r=Zb.join(n.value,eI),o=()=>{try{let c=id(r);c&&c.pid===process.pid&&ii.rmSync(r)}catch{}};if(Bm(r,t))return l("Acquired sync lock",{acquired:!0,release:o});let s=id(r);if(!rI(s))return l("Sync lock is held",{acquired:!1,heldBy:s});X.info(`Breaking an abandoned sync lock: ${s?Om(s):"unreadable lock file"}`);try{ii.rmSync(r,{force:!0})}catch{}if(Bm(r,t))return l("Acquired sync lock after breaking a stale one",{acquired:!0,release:o});let i=id(r);return l("Sync lock taken by another process",{acquired:!1,heldBy:i??{pid:-1,hostname:ad.hostname(),startedAt:Date.now(),operation:"unknown"}})},ai=async({worktreeRoot:e,operation:t,fn:n})=>{let r=await oI({worktreeRoot:e,operation:t});if(a(r))return d(r.message);if(!r.value.acquired)return X.info(`Skipping ${t}: the state worktree is held by ${Om(r.value.heldBy)}`),l("State worktree is held by another process",null);let{release:o}=r.value;try{return l("Ran under the sync lock",await n())}finally{o()}}});import sI from"node:fs";var iI,aI,cd,Um,ld,di,ci=h(()=>{"use strict";S();zo();ri();Zn();et();Qe();Xo();od();sr();dd();iI=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=se("getRepoRootDir",await gt(e));if(a(n))return d(n.message);let r=n.value;logger.debug("[sync] repo root",r);let o=se("getStateBranchRoot",Ie({repoRoot:r}));if(a(o))return d(o.message);let s=o.value;logger.debug("[sync] state branch root",s),logger.debug("[sync] bootstrapping state branch storage",{repoRoot:r,stateBranchRoot:s,ensureUpstream:t});let i=se("bootstrapStateBranchStorage",await _m({repoRoot:r,stateBranchRoot:s,ensureUpstream:t}));if(a(i))return d(i.message);logger.debug("[sync] bootstrap result",{bootstrapped:i.value,stateBranchRoot:s}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:s});let c=se("hasInProgressGitOperation(stateBranchRoot)",await Fs(s));if(a(c))return d(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"),d("Cannot sync while a git operation is in progress in the state branch");logger.debug("[sync] ensuring state branch layout",{repoRoot:r,stateBranchRoot:s});let u=se("ensureStateBranchLayout",gu(r,s));return a(u)?d(u.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:r,stateBranchRoot:s,bootstrapped:i.value}),l("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:s,bootstrapped:i.value}))},aI=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{logger.debug("[sync] committing own event file from state branch",{ownEventFileName:n,stateBranchRoot:t}),logger.debug("[sync] staging own event file",{stateBranchRoot:t,ownEventFileName:n});let r=se("stageStateBranchOwnEventFile",await si({stateBranchRoot:t,eventFileName:n}));if(a(r))return d(r.message);let o=se("stageStateBranchMediaFiles",await Pm({stateBranchRoot:t}));if(a(o))return d(o.message);let s=se("stageStateBranchEventConfig",await Lm({stateBranchRoot:t}));if(a(s))return d(s.message);let i=[r.value,o.value,...s.value].filter(m=>m!==null);if(i.length===0)return l("Nothing to stage",{createdCommit:!1});let c=se("hasStagedChanges(after stage)",await iu(t,i));if(a(c))return d(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=se("createStateBranchSyncCommit",await Dm({repoRoot:e,stateBranchRoot:t,pathspec:i}));return a(u)?d(u.message):(logger.debug("[sync] created sync commit",u.value),l("Committed own event file",{createdCommit:!0,commitSha:u.value}))},cd=(e,t="offline")=>{let n=e.createdCommit?`Committed locally, ${t}`:t==="offline"?"Offline":"No remote";return ni(n),l(n,{...e,pulled:!1,pushed:!1,offline:!0})},Um=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}),d("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}),d("Own event file must end with .jsonl");Lr();let n=se("ensureSyncReady",await iI({cwd:e,ensureUpstream:!0}));if(a(n))return Se(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:s}=n.value,i=se("isDetachedHead(stateBranchRoot)",await au(o));if(a(i))return Se(i.message);if(logger.debug("[sync] detached state branch check result",{detached:i.value}),i.value)return Se("Cannot run :sync while the state branch is in detached HEAD state");let c=!1,u,m=!1,p=!1,f=se("getStateBranch",qt(r));if(a(f))return Se(f.message);let y=f.value;logger.debug("[sync] resolved state branch",{stateBranch:y,stateBranchRoot:o});let x=se("flushPendingLogs",Ks(o,t));a(x)&&logger.error(`[sync] ${x.message}`);let R=se("commitOwnEventFileToStateBranch",await aI({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(a(R))return Se(R.message);c=R.value.createdCommit,u=R.value.commitSha;let A=se("hasRemote",await ln({repoRoot:o}));if(a(A))return Se(A.message);if(!A.value)return cd({repoRoot:r,stateBranchRoot:o,createdCommit:c,commitSha:u,bootstrapped:s},"no remote");let w=se("pullBranchRebaseIfPresent",await Do({cwd:o,branch:y}));if(a(w))return Lo(w.message)?cd({repoRoot:r,stateBranchRoot:o,createdCommit:c,commitSha:u,bootstrapped:s}):Se(w.message);m=w.value;let k=se("isAheadOfUpstream",await ou(o));if(a(k))return Se(k.message);if(c||s||k.value){logger.info("[sync] pushing state branch",{createdCommit:c,bootstrapped:s,stateBranchRoot:o});let L=se("pushStateBranch",await Yo({stateBranchRoot:o,repoRoot:r}));if(a(L)&&nu(L.message)){let D=se("pullBranchRebaseIfPresent(retry)",await Do({cwd:o,branch:y}));if(a(D))return Se(D.message);m=m||D.value,L=se("pushStateBranch(retry)",await Yo({stateBranchRoot:o,repoRoot:r}))}if(a(L))return Lo(L.message)?cd({repoRoot:r,stateBranchRoot:o,createdCommit:c,commitSha:u,bootstrapped:s}):Se(L.message);p=L.value}if(c){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:o});let L=se("git rev-parse HEAD",await W({args:["rev-parse","HEAD"],cwd:o}));if(a(L))return Se(L.message);u=L.value.stdout.trim(),logger.debug("[sync] final sync commit sha",u)}return mr(p?"Synced and pushed":m||c?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),l("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:c,commitSha:u,pulled:m,pushed:p,bootstrapped:s,offline:!1})},ld=async(e,t)=>{let n=wm(e);try{return await t()}finally{let r=Am(e,n);r.length>0&&logger.error(`[sync] restored event log lines git dropped from the worktree: ${r.join(", ")}`)}},di=async e=>{let t=e.cwd??process.cwd(),n=await gt(t);if(a(n))return Se(n.message);let r=Ie({repoRoot:n.value});if(a(r))return Se(r.message);let o=r.value;if(!sI.existsSync(o))return Um(e);let s=await ai({worktreeRoot:o,operation:"sync",fn:()=>ld(o,()=>Um(e))});return a(s)?Se(s.message):s.value===null?l("Another process is syncing this board",{repoRoot:n.value,stateBranchRoot:o,createdCommit:!1,pulled:!1,pushed:!1,bootstrapped:!1,offline:!1,skipped:!0}):s.value}});var Jt,li,dI,ud,jm,ui=h(()=>{"use strict";vm();ur();wt();Ce();ve();S();M();zo();ri();ci();Jt=null,li=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!Jt,currentStatus:g().syncStatus?.status,currentMessage:g().syncStatus?.msg}),Jt)return logger.debug("[sync] syncAndReloadState joining existing promise"),Jt;logger.debug("[sync] syncAndReloadState creating promise"),Jt=dI();try{let e=await Jt;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"),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}),Jt||d(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:g().syncStatus?.status,statusMessageBeforeClear:g().syncStatus?.msg}),Jt=null}},dI=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:g().mode,syncStatus:g().syncStatus});let e=jm();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:g().mode,message:e.message,syncStatus:g().syncStatus}),e;if(Jt)return Jt;logger.debug("[sync] syncAndReloadState:start");let t=se("resolveActorId",oe());if(a(t)||!t.value)return logger.info("[sync] unable to resolve actor id",{message:a(t)?t.message:"Missing actor id"}),d("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=cr(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let r=se("syncEpiqWithRemote",await di({ownEventFileName:n}));if(logger.debug("[sync] syncEpiqWithRemote:result",{success:!a(r),message:(a(r),r.message)}),a(r))return logger.error("[sync] syncAndReloadState:sync failed",r.message),N({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:g().syncStatus}),Se(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o,offline:s}=r.value,i=ud(o);return a(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))},ud=e=>{logger.debug("[sync] loading merged events after sync",{stateBranchRoot:e});let t=se("loadMergedEvents",Ct(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 N({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:g().syncStatus}),d(`Unable to load events. ${t.message}`);logger.debug("[sync] loaded merged events after sync",{count:t.value.events.length});let n=jm();if(n)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:g().mode,message:n.message,syncStatus:g().syncStatus}),n;let r=fm(),o=g().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:r,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=se("bootStateFromEventLog",Yt(t.value.events,t.value.unreadable));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!a(i),message:(a(i),i.message)}),a(i))return N({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:g().syncStatus}),d(`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:o}),logger.debug("[sync] restoreNavigationAnchor:start");let s=se("restoreNavigationAnchor",hm(r));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)?(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)},jm=()=>g().mode===b.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:g().mode,syncStatus:g().syncStatus}),N({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),d("Will not re-materialize if not in default mode, to not lose edit data"))});var Fr,$m,Wm,md,pd,Jo,fd,cI,Hm,lI,qm,mi=h(()=>{"use strict";S();ze();M();ui();Fr=3e3,$m=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<Fr?null:t},Wm=0,pd=!1,Jo=!1,fd=()=>{if(pd)return!0;let e=Ye();return a(e)?!1:e.value.syncStatus.status==="syncing"},cI=()=>{let e=xe().autoSyncIntervalMs??1e4,t=Date.now()-Wm;return Math.max(0,e-t)},Hm=()=>{md||(md=setTimeout(async()=>{if(md=void 0,!!Nt()){if(fd()){Jo=!0;return}Jo=!1,await lI()}},cI()))},lI=async()=>{if(g().readOnly||g().timeMode==="peek"||g().timeMode==="replay")return d("Cannot auto-sync while peeking");if(!Nt())return d("Cannot auto-sync before state is initialized");if(fd())return Jo=!0,d("Sync already in progress");pd=!0,Wm=Date.now(),N({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await li()}finally{pd=!1,Jo&&Hm()}},qm=()=>{Nt()&&(Jo=!0,!fd()&&Hm())}});import Qo from"node:fs";import Zo from"node:path";import{z as Br}from"zod";var pi,uI,mI,pI,zm,Vm,Gm,Km,Ym,Xm,fI,fi,es,Or=h(()=>{"use strict";S();Ht();Ds();ie();pi="recent-projects.json",uI=20,mI=Br.object({projectId:Br.string().min(1),root:Br.string().min(1),lastOpenedAt:Br.number().finite()}),pI=Br.object({projects:Br.array(mI)}),zm=()=>Zo.join(an(),pi),Vm=e=>Zo.basename(e)||e,Gm=e=>{let t=Zo.resolve(e);try{return Qo.realpathSync(t)}catch{return t}},Km=(e,t)=>t.lastOpenedAt-e.lastOpenedAt,Ym=e=>{if(!Oo(e.root))return!1;let t=Mo(e.root);return!a(t)&&t.value===e.projectId},Xm=()=>{let e=zm();if(!Qo.existsSync(e))return l("No recent projects recorded",[]);let t;try{t=JSON.parse(Qo.readFileSync(e,"utf8"))}catch(r){return d(`Invalid ${pi}: ${r instanceof Error?r.message:String(r)}`)}let n=pI.safeParse(t);return n.success?l("Read recent projects",n.data.projects):d(`Invalid ${pi} shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},fI=e=>{let t=zm();try{Qo.mkdirSync(Zo.dirname(t),{recursive:!0}),Qo.writeFileSync(t,JSON.stringify({projects:e},null,2)+`
|
|
78
|
+
`,"utf8")}catch(n){return d(`Unable to write ${pi}: ${n instanceof Error?n.message:String(n)}`)}return l("Recorded recent project",e)},fi=({exclude:e}={})=>{let t=Xm();if(a(t))return t;let n=e===void 0?null:Gm(e);return l("Listed recent projects",t.value.filter(r=>n===null||Gm(r.root)!==n).filter(Ym).sort(Km))},es=({root:e,now:t=Date.now()})=>{let n=Zo.resolve(e),r=Mo(n);if(a(r))return d(r.message);let o=r.value,s=Xm(),i=a(s)?[]:s.value,c=[{projectId:o,root:n,lastOpenedAt:t},...i.filter(u=>u.projectId!==o&&u.root!==n)].filter(Ym).sort(Km).slice(0,uI);return fI(c)}});var gi,Jm,Qm,Zm,ts=h(()=>{"use strict";S();Ht();ze();ie();gi=()=>{let e=xe(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),r=e.autoSync===!0||e.autoSync===!1;return{isSetupDone:n&&t&&r,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:r}},Jm=()=>{let e=Me(process.cwd());if(a(e))return!1;let t=pt(e.value);return jt(t)},Qm=e=>e===!0?"on":e===!1?"off":null,Zm=e=>e==="on"?!0:e==="off"?!1:null});var We,T,Xe=h(()=>{"use strict";We={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:We.cyan,accent2:We.magenta,primary:We.white,secondary:We.grayDark,secondary2:We.grayLight,gray:We.gray,green:We.green,yellow:We.yellow,red:We.red}});var C,Ur,hi=h(()=>{"use strict";Xe();C={red:We.red,yellow:We.yellow,green:We.green,blue:We.blue,magenta:We.magenta,cyan:We.cyan},Ur={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 gI,hI,Ln,Dn,vi,yi,ns=h(()=>{"use strict";ee();S();re();M();gI=e=>e.props.tags??[],hI=e=>e.props.assignees??[],Ln=e=>gI(e).map(t=>E.getTag(t)).filter(t=>!!t),Dn=e=>hI(e).map(t=>E.getContributor(t)).filter(t=>!!t),vi=()=>{let{breadCrumb:e,selectedNode:t}=g(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!F(n)?d("Invalid untag target"):l("Retrieved tags from ticket in breadcrumb",Ln(n))},yi=()=>{let{breadCrumb:e,selectedNode:t}=g(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!F(n)?d("Invalid unassign target"):l("Retrieved assignees from ticket in breadcrumb",Dn(n))}});var I,pr=h(()=>{"use strict";I={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 vI,yI,bI,II,xI,fr,ep,bi,Ii,tp,EI,gd,rs=h(()=>{"use strict";vI=/^(\d+)(h|d|w|mo|y)$/,yI=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,bI=({year:e,month:t,day:n,hour:r=0,minute:o=0})=>{let s=new Date(e,t-1,n,r,o);return s.getFullYear()===e&&s.getMonth()===t-1&&s.getDate()===n&&s.getHours()===r&&s.getMinutes()===o},II=(e,t=new Date)=>{let n=e.match(vI);if(!n)return null;let[,r,o]=n,s=Number(r);if(!Number.isInteger(s)||s<=0)return null;let i=new Date(t);switch(o){case"h":return i.setHours(i.getHours()-s),i;case"d":return i.setDate(i.getDate()-s),i;case"w":return i.setDate(i.getDate()-s*7),i;case"mo":return i.setMonth(i.getMonth()-s),i;case"y":return i.setFullYear(i.getFullYear()-s),i;default:return null}},xI=e=>{let t=e.match(yI);if(!t)return null;let[,n,r,o,s,i]=t,c=Number(n),u=Number(r),m=Number(o),p=s?Number(s):0,f=i?Number(i):0;return bI({year:c,month:u,day:m,hour:p,minute:f})?new Date(c,u-1,m,p,f):null},fr=e=>{let t=e.trim().toLowerCase();return II(t)??xI(t)},ep=/^(\d+)(s|m)?$/,bi=e=>{let t=e.trim().toLowerCase().match(ep);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},Ii=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&ep.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},tp=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,EI=[{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}],gd=(e=EI)=>{let t=[];for(let{unit:n,from:r,to:o}of e)for(let s=r;s<=o;s++)t.push(`${s}${n}`);return t}});var RI,be,vt,we,SI,NI,vd,yd,op,gr,xi,hd,np,CI,wI,os,rp,AI,TI,bd,kI,Ae,yn=h(()=>{"use strict";mi();Or();S();ts();Bt();ee();re();M();hi();ns();pr();rs();RI=["BOARD","TICKET","SWIMLANE","COMMENT"],be={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",LOG_LEVEL:"logLevel"},vt={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},we={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},SI=[be.EDITOR,be.VIEW,be.USERNAME,be.AUTOSYNC,be.SYNC_DEBOUNCE_MS,be.ATTACHMENT_MAX_KB,be.LOG_LEVEL],NI=(e=g().selectedNode?.context)=>{switch(e){case"TICKET":return[vt.TITLE,vt.DESCRIPTION];case"BOARD":case"SWIMLANE":return[vt.TITLE];case"COMMENT":return[vt.COMMENT];default:return[]}},vd=[String(Fr),"5000","15000","30000","60000"],yd=["250","500","1000"],op=["10s","20s","30s","45s"],gr=[I.EXIT,I.SYNC,I.HELP,I.EXPORT,I.CONFIG,I.YANK],xi=[I.NEW,I.EDIT,I.DELETE,I.MOVE],hd=[I.TAG,I.UNTAG,I.ASSIGN,I.UNASSIGN,I.CLOSE_ISSUE,I.RE_OPEN_ISSUE,I.EDIT,I.COMMENT],np=[I.FILTER,I.PEEK,I.REPLAY],CI={WORKSPACE:[...gr,...xi],BOARD:[...np,...gr,...xi],SWIMLANE:[...np,...gr,...xi],TICKET:[...gr,...xi,...hd],FIELD:[...gr,...hd],FIELD_LIST:[...gr,...hd],TEXT:[...gr],COMMENT:[I.EDIT,I.DELETE,I.YANK]},wI=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],os=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&F(n)),rp=e=>e.parentNodeId===me,AI=({selectedNode:e,breadCrumb:t})=>{let n=NI(e?.context);return os({breadCrumb:t,selectedNode:e})?n.includes(vt.DESCRIPTION)?n:[...n,vt.DESCRIPTION]:n},TI=({selectedNode:e,breadCrumb:t})=>{let n=os({breadCrumb:t,selectedNode:e});return n?[we.REF,we.TITLE,...n.props?.description?.trim()?[we.DESCRIPTION]:[],...Ln(n).length>0?[we.TAGS]:[],...Dn(n).length>0?[we.ASSIGNEES]:[]]:e?[we.REF,we.TITLE]:[]},bd=()=>{let e=fi({exclude:process.cwd()});return a(e)?[]:[...e.value.map((t,n)=>String(n+1)),...e.value.map(t=>t.root)]},kI=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=gi();if(!r)return[I.HELP,I.CONFIG];if(!Jm())return[I.HELP,I.INIT,I.OPEN];if(t)return[I.HELP,I.PEEK,I.REPLAY,I.EXPORT,I.CONFIG,I.YANK];let o=e?.context,s=o&&RI.includes(o),i=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?CI[u]:[]))],c=os({breadCrumb:n,selectedNode:e});return i.filter(u=>u===I.MOVE?!1:u===I.YANK?!!(c??e):u===I.EDIT?s||!!c:u===I.DELETE?s:u===I.UNTAG?!!(c&&Ln(c).length>0):u===I.UNASSIGN?!!(c&&Dn(c).length>0):u===I.RE_OPEN_ISSUE?!!(c&&rp(c)):u===I.CLOSE_ISSUE?!!(c&&!rp(c)):!0)},Ae=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=g())=>{let s=t.context??"WORKSPACE";return{[I.NONE]:kI({breadCrumb:o,readOnly:r,selectedNode:n}),[I.EXIT]:["confirm"],[I.EXPORT]:[],[I.SYNC]:[],[I.INIT]:[],[I.OPEN]:e===I.OPEN?bd():[],[I.HELP]:[],[I.PEEK]:[...gd(),"now","prev","next"],[I.REPLAY]:[...gd()],[I.EDIT]:AI({selectedNode:n,breadCrumb:o}),[I.YANK]:TI({selectedNode:n,breadCrumb:o}),[I.COMMENT]:[],[I.DELETE]:["confirm"],[I.RE_OPEN_ISSUE]:["confirm"],[I.CLOSE_ISSUE]:["confirm"],[I.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[I.FILTER]:["tag","assignee","actor","description","title","ref","clear"],[I.TAG]:[...new Set([...Object.keys(Ur),...E.getExistingTags()])],[I.UNTAG]:[...vi()?.value?.map(({name:c})=>c)??[]],[I.UNASSIGN]:[...yi()?.value?.map(({name:c})=>c)??[]],[I.ASSIGN]:E.getExistingAssignees(),[I.NEW]:wI(s),[I.CONFIG]:[...SI]}[e]??[]}});var sp,ip=h(()=>{"use strict";sp=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"]});import{accessSync as MI,copyFileSync as PI,existsSync as Ei,mkdirSync as ap,readdirSync as dp,readFileSync as LI,renameSync as DI,rmSync as _I,statSync as cp,unlinkSync as FI,writeFileSync as BI}from"node:fs";import jr from"node:path";var Id,rt,Ri=h(()=>{"use strict";Id=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",rt={writeToFile:(e,t)=>{try{let n=jr.dirname(e);Ei(n)||ap(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);BI(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return LI(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=rt.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 Ei(e)&&cp(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await MI(e),!0}catch{return!1}},mkDir:e=>ap(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=jr.parse(t);for(;;){let r=jr.join(t,e);try{if(Ei(r)&&cp(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=jr.dirname(t)}return null},readFirstJSON(e){try{if(!rt.dirExists(e))return null;let t=dp(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=jr.join(e,t);return rt.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return rt.dirExists(e)?dp(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{FI(e)}catch(t){(!Id(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{_I(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(jr.dirname(t)),!n?.overwrite&&Ei(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{DI(e,t)}catch(r){if(Id(r)&&r.code==="EXDEV"){PI(e,t),this.rmFile(e);return}throw r}}}});import OI from"node:path";import{z as bn}from"zod";var UI,lp,jI,up,xd,Ed,$I,$r,mp,ot,ss,Qt=h(()=>{"use strict";zn();ie();S();Ri();UI={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},lp=bn.object({logLevel:bn.enum(["info","error","debug"]),preferredEditor:bn.string().optional(),userName:bn.string().optional(),userId:bn.string().optional(),autoSync:bn.boolean().nullable().optional(),autoSyncDebounceMs:bn.number().optional(),attachmentMaxKb:bn.number().optional(),viewMode:bn.enum(["dense","wide"]).optional()}).partial(),jI="config.json",up=an,xd=()=>OI.join(up(),jI),Ed=()=>{try{return rt.mkDir(up()),l(`Ensured ~/${Dt} exists`,null)}catch{return d(`Unable to create ~/${Dt}`)}},$I=e=>{let t;try{t=JSON.parse(e)}catch{return d(`Invalid ~/${Dt}/config.json JSON`)}let n=lp.safeParse(t??{});return n.success?l("Parsed config",n.data):d(`Invalid ~/${Dt}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},$r=()=>{let e=Ed();if(a(e))return d(e.message);let t=xd(),n=rt.readFile(t);return n==null||n.trim()===""?l("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):$I(n)},mp=e=>{let t=Ed();if(a(t))return d(t.message);let n=lp.safeParse(e);if(!n.success)return d(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=xd();try{return rt.writeToFile(r,JSON.stringify(n.data,null,2)+`
|
|
79
|
+
`),l("Config written",null)}catch{return d(`Unable to write ~/${Dt}/config.json`)}},ot=e=>{let t=$r();if(a(t))return d("Failed to read existing config");let n={...t.value,...e};return mp(n)},ss=()=>{let e=xd(),t=Ed();if(a(t))return d(`Unable to create ~/${Dt}`);if(!(rt.readFile(e)!==null)){let R=mp(UI);if(a(R))throw new Error(`Unable to create ~/${Dt}/config.json`)}let r=$r();if(a(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:i,autoSync:c,autoSyncDebounceMs:u,attachmentMaxKb:m,logLevel:p,viewMode:f}=r.value,y=la({userId:i,userName:s});if(a(y))return d(y.message);let x=y.value??{userId:i,userName:s};return!x.userName||!x.userId?d(`User name or ID not configured in ~/${Dt}/config.json`):(process.env.EPIQ_LOG_LEVEL=p,l("successfully loaded settings",{logLevel:p??"debug",preferredEditor:o??"",userName:x.userName,userId:x.userId,autoSync:c??!1,autoSyncIntervalMs:u??1e4,attachmentMaxKb:m??null,viewMode:f??"dense"}))}});var pp,fp,Rd,gp=h(()=>{"use strict";pp="/media/",fp=e=>`${pp}${e}`,Rd=(e,t)=>`})`});import WI from"node:crypto";import Sd from"node:fs";import HI from"node:path";var In,Wr,qI,GI,zI,hp,Hr=h(()=>{"use strict";$t();S();ie();gp();In=500,Wr=(e,t)=>`${e}.${t}`,qI=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"):d(`Unsupported image format. Allowed: ${Ll.join(", ")}`),GI=e=>WI.createHash("sha256").update(e).digest("hex"),zI=(e,t=In)=>{if(e.length===0)return d("Attachment is empty");if(e.length>t*1024)return d(`Attachment exceeds the ${t} KB size cap (${Math.ceil(e.length/1024)} KB)`);let n=qI(e);return a(n)?n:l("Validated attachment data",{hash:GI(e),ext:n.value,bytes:e.length})},hp=(e,t,n=In)=>{let r=zI(t,n);if(a(r))return r;let o=Us(e),s=HI.join(o,Wr(r.value.hash,r.value.ext));try{Sd.existsSync(s)||(Sd.mkdirSync(o,{recursive:!0}),Sd.writeFileSync(s,t))}catch(i){return d(`Unable to write attachment blob: ${i instanceof Error?i.message:String(i)}`)}return l("Wrote attachment blob",r.value)}});import VI from"zod";var is,as,vp,Nd=h(()=>{"use strict";Qt();Hr();ve();S();pe();ze();M();is=50,as=5e3,vp=()=>{let e=ce().commandMeta.inputString,t=VI.coerce.number().int().min(is).max(as).safeParse(e);if(!t.success)return d(`Attachment size cap must be ${is}-${as} KB (default ${In})`);let n=ot({attachmentMaxKb:t.data});return a(n)?n:(xt({attachmentMaxKb:t.data}),N({mode:b.DEFAULT}),l(`Attachment size cap set to ${t.data} KB`,null))}});import yp from"chalk";var wd,bp,Cd,Ip,KI,YI,xp,XI,JI,ds,Te,Ep,Rp,Si,QI,ZI,Ni,yt=h(()=>{"use strict";hi();wd={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},bp=(e,t,n)=>Math.max(t,Math.min(n,e)),Cd=(e,t,n)=>e+(t-e)*n,Ip=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},KI=e=>e.toLowerCase().trim(),YI=(e,t,n)=>{let r=t/100,o=n/100,s=(1-Math.abs(2*o-1))*r,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=o-s/2;return[Math.round((u+f)*255),Math.round((m+f)*255),Math.round((p+f)*255)]},xp=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,XI=(e,t,n)=>{let r=bp(n,0,1);return[Math.round(Cd(e[0],t[0],r)),Math.round(Cd(e[1],t[1],r)),Math.round(Cd(e[2],t[2],r))]},JI=(e,t,n)=>XI(e,t,n),ds=e=>{let t=Ip(e)%360,n=YI(t,wd.stringColor.saturation,wd.stringColor.lightness);return xp(n)},Te=(e,t=Ur)=>{let n=KI(e??"");return n&&t[n]?t[n]:ds(n)},Ep=e=>{let t=wd.gradient.stops,n=bp(e,0,1);if(t.length===0)return[0,0,0];if(t.length===1)return t[0];let r=t.length-1,o=n*r,s=Math.min(Math.floor(o),r-1),i=o-s;return JI(t[s],t[s+1],i)},Rp=e=>xp(Ep(e)),Si=e=>Ip(e.toLowerCase().trim())/4294967295,QI=e=>{let t=Si(e);return Ep(t)},ZI=e=>{let[t,n,r]=QI(e);return{normal:o=>yp.bgRgb(t,n,r).black(o),cursor:o=>yp.bgRgb(t,n,r).white.bold(o)}},Ni=e=>ZI(e).normal(` ${e} `)});var He,xn=h(()=>{"use strict";He=(e,t,n)=>t.length>n?`${e} cannot exceed ${n} characters (got ${t.length})`:null});import{createHash as ex}from"node:crypto";var tx,nx,Le,qr=h(()=>{"use strict";tx="0123456789ABCDEFGHJKMNPQRSTVWXYZ",nx=e=>{let t=ex("sha256").update(e).digest(),n=0n;for(let o=0;o<16;o++)n=n<<8n|BigInt(t[o]);let r="";for(let o=0;o<26;o++){let s=BigInt((25-o)*5);r+=tx[Number(n>>s&31n)]}return r},Le=(e,t)=>nx(`${e}:virtual:${t}`)});import Sp from"chalk";var fe,De,Ue,Np=h(()=>{"use strict";yt();Xe();fe=e=>Sp.dim(e),De=e=>Sp.hex(T.primary)(e),Ue=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:s=1})=>{let i=o.trim();if(i.length<s)return"";let p=[...t.filter(Boolean).filter(f=>f.startsWith(i))].sort((f,y)=>Si(f)-Si(y)).slice(0,r).map(f=>Ni(f)).join(" ");return p?`${fe(e)}${p}${fe(n)}`:""}});var _n,Ci=h(()=>{"use strict";_n={None:"none",Invalid:"invalid",Valid:"valid"}});import Ap from"chalk";var rx,Cp,he,te,G,zr,wp,wi,Ad,ox,Gr,sx,ix,ax,dx,cx,Tp,kp=h(()=>{"use strict";mi();ts();ip();Je();$t();S();re();ze();Nd();Hr();M();yt();xn();ns();qr();Np();pr();Ci();yn();rs();rx=["BOARD","TICKET","SWIMLANE"],Cp=()=>{let e=g().selectedNode;if(!e?.context)return G({message:fe("Missing target context")});if(rx.includes(e.context))return te();if(e.parentNodeId){let t=g().nodes[e.parentNodeId];if(t?.id===Le(t?.parentNodeId??"","comments"))return te()}return G({message:fe("Command not available in this context")})},he="<ENTER> to confirm",te=(e="",t=[])=>({message:fe(e),validity:_n.Valid,completionWordList:t}),G=({message:e,completionWordList:t=[]})=>({validity:_n.Invalid,message:e,completionWordList:t}),zr=e=>e.length===0,wp=(e,t)=>{let n=lt(g().breadCrumb,"BOARD");if(a(n))return G({message:De("Command is not applicable in this context")});let r=Pl(n.value.id);return a(r)?G({message:De(`Unable to ${t}: board id is not a valid ULID`)}):tp({date:e,horizonDate:r.value})?null:G({message:De(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},wi=e=>` ${Ap.hex("#000").bgHex(Te(e))(` ${e} `)} `,Ad=({modifier:e})=>{let t="confirm";return e===t?te(he):G({message:zr(e)?fe("if you are certain, enter ")+Ni(t):"",completionWordList:[t]})},ox=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?G({message:fe(n)}):te():G({message:zr(r)?t:"",completionWordList:[...e]}),Gr=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>zr(n)&&zr(r)?G({message:e,completionWordList:[]}):te(t??he),sx=({modifier:e,inputString:t})=>{let n=bd();return!zr(e)||!zr(t)?te(he):G({message:n.length?fe("number from the list, or a path"):fe("path to an epiq project"),completionWordList:n})},ix=({modifier:e,inputString:t})=>{let n=Ae(I.CONFIG);if(!n.includes(e))return G({message:Ue({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case be.EDITOR:{let r=[...sp];return t.trim()?r.includes(t.trim())?te(he):G({message:Ue({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):G({message:Ue({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case be.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?te(he):G({message:Ue({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case be.USERNAME:return t.trim()?te(he):G({message:De("Enter a user name. Saved in ")+Ap.bgBlack("~/.epiq-global/config.json")});case be.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?te(he):G({message:Ue({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case be.AUTOSYNC:{let r=["on","off"],o=xe().autoSync;if(!r.includes(t.trim())){let s=Qm(o);return G({message:Ue({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return te(he)}case be.ATTACHMENT_MAX_KB:{let r=xe().attachmentMaxKb,o=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(o)||o<is||o>as){let s=Ue({prefix:" examples: ",wordList:yd,minLengthForHints:0,inputString:t});return G({message:De(`provide a size cap in KB (${is}-${as}). current: ${r??In} KB.`)+s,completionWordList:yd})}return te(he)}case be.SYNC_DEBOUNCE_MS:{let r=xe().autoSyncIntervalMs,o=$m(t);if(!t.trim()||o===null||o<Fr){let s=Ue({prefix:" examples: ",wordList:vd,minLengthForHints:0,inputString:t});return G({message:De(`provide duration above ${Fr}ms. current duration: ${r}ms.`)+s,completionWordList:vd})}return te(he)}default:return G({message:De("Unknown config option"),completionWordList:n})}},ax=({modifier:e,inputString:t})=>{let n=Ae(I.EDIT);if(!n.length)return G({message:De("Command not available in this context")});if(!n.includes(e)){let r=Ue({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return G({message:r||De("Unknown edit option"),completionWordList:n})}switch(e){case vt.COMMENT:return t.trim()?te(he):G({message:fe("write a comment...")});case vt.TITLE:return te(he);case vt.DESCRIPTION:{let{preferredEditor:r}=xe();return r?te(fe("<ENTER> to edit in ")+r):G({message:"No editor selected"})}default:return G({message:De("Unknown edit option"),completionWordList:n})}},dx=({modifier:e})=>{let t=Ae(I.YANK);return t.length?t.includes(e)?te(he+fe(" 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")})},cx={[I.EXPORT]:()=>te(he+fe(", and create export markdown file")),[I.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return te(he);let n={message:fe("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=fr(r);if(!r||!o)return G(n);let s=wp(o,"peek");return s||te(he)},[I.REPLAY]:e=>{let{dateInput:t,durationInput:n}=Ii(e.modifier,e.inputString),r={message:fe("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=fr(t);if(!t||!o)return G(r);let s=wp(o,"replay");return s||(n&&bi(n)===null?G({message:De("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):te("<ENTER> to replay board history",n?op:[]))},[I.EXIT]:()=>te(he+fe(" and exit the application")),[I.INIT]:()=>te(he),[I.OPEN]:sx,[I.PALETTE]:()=>te(he),[I.FILTER]:e=>{if(e.modifier==="clear")return te(he);let t=s=>Ae(I.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return G({message:Ue({wordList:Ae(I.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:Ae(I.FILTER)});let n=Object.values(g().tags).map(s=>s.name),r=Object.values(g().contributors).map(s=>s.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?G({message:Ue({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):te():G({message:Ue({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[I.NONE]:e=>{let t=Ae(I.NONE);return G({message:Ue({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[I.NEW]:e=>ox({list:Ae(I.NEW),hint:Ue({wordList:Ae(I.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[I.HELP]:()=>te(he),[I.EDIT]:ax,[I.COMMENT]:e=>{let t=Gr({hint:fe(`write a comment (max ${4e3} char)...`),onOk:fe(`(${e.inputString.length}/${4e3})`)})(e);return t.validity===_n.Invalid?t:e.inputString.length>4e3?te(De("max input exceeded")):t},[I.CONFIG]:ix,[I.YANK]:dx,[I.DELETE]:e=>{let t=Cp();return t.validity==="invalid"?t:Ad(e)},[I.CLOSE_ISSUE]:e=>Ad(e),[I.RE_OPEN_ISSUE]:e=>Ad(e),[I.MOVE]:e=>{let t=Cp();return t.validity==="invalid"?t:Gr({hint:Ue({prefix:"hey hacker! These commands are blocked for you... ",wordList:Ae(I.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[I.TAG]:e=>{let n=E.getExistingTags().slice(0,10).map(wi).join("");return Gr({hint:n.length?fe("create tag or reuse:")+n+fe(""):fe("create tag ...")})(e)},[I.UNTAG]:e=>{let t=vi();if(a(t))return G({message:De("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(wi).slice(0,10);return n.length?Gr({hint:fe(" ... ")+n.join("")})(e):G({message:De("Issue has no tags"),completionWordList:[]})},[I.ASSIGN]:e=>{let t=E.getExistingAssignees().map(wi).slice(0,10);return Gr({hint:fe("assignees... ")+t.join("")})(e)},[I.UNASSIGN]:e=>{let t=yi();if(a(t))return G({message:De("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(wi).slice(0,10);return n.length?Gr({hint:fe("remove assignee... ")+n.join("")})(e):G({message:De("Issue has no assignees"),completionWordList:[]})},[I.SYNC]:()=>te(he)},Tp=Object.fromEntries(Object.entries(cx).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]))});var Ai,Mp=h(()=>{"use strict";Ai=["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 lx,ux,mx,px,fx,Pp,Lp,Dp,_p=h(()=>{"use strict";S();M();Mp();lx=3,ux=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"]),mx=e=>{let t=[];for(let n of Object.values(e.nodes)){n.title&&t.push(n.title);let r=n.props;typeof r.description=="string"&&t.push(r.description),typeof r.value=="string"&&t.push(r.value)}for(let n of Object.values(e.tags))t.push(n.name);for(let n of Object.values(e.contributors))t.push(n.name);for(let n of Object.values(e.comments))t.push(n.md);return t},px=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=lx&&!ux.has(t)&&!/^\d+$/.test(t)),fx=e=>{let t=new Map;for(let s of mx(e))for(let i of px(s))t.set(i,(t.get(i)??0)+1);let n=[...t.entries()].sort((s,i)=>i[1]-s[1]||s[0].localeCompare(i[0])).map(([s])=>s),r=new Set(n),o=Ai.filter(s=>!r.has(s));return[...n,...o]},Pp=Ai,Lp=-1,Dp=()=>{let e=Ye();if(a(e))return Ai;let t=e.value,n=t.eventLog.length;return n!==Lp&&(Pp=fx(t),Lp=n),Pp}});var Fp,Bp,Td=h(()=>{"use strict";ql();yn();pr();kp();_p();M();ve();Fp=e=>Object.values(I).includes(e),Bp=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:i,validity:c,completionWordList:u}=Tp[n].validate(n,r,s),m=n!==I.PEEK&&n!==I.REPLAY,p=o==="command"||o==="modifier"?Ae(n):m?Dp():[],{mode:f}=g(),y=f===b.COMMAND_LINE?i??"":"",x=[...u,...p];return{validity:c,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:y,autoCompletion:t?Hl(e,x):{hint:"",hints:[],remainder:"",overlap:0}}}});var Op,gx,hx,vx,Up=h(()=>{"use strict";Td();yn();Op=e=>{let t=e.trimStart(),n=hx(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),i=vx(e),c=Fp(r)?r:null,u=c!==null,m=r!=="",p=c?Ae(c)??[]:[],f=c&&p.includes(o)?o:"",y="word";n.length===0||n.length===1&&!s?y="command":(n.length===1&&s||n.length===2&&!s)&&(y="modifier");let x=s?"":i,R=gx(t,c,f);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:i,hasCommand:m,command:c,isCommandKeyword:u,isLastWordCompleted:s,modifier:f,target:y,inputToMatch:x,inputString:R}},gx=(e,t,n)=>{let r=e;return t&&r.startsWith(t)&&(r=r.slice(t.length)),r=r.replace(/^\s+/,""),n&&r.startsWith(n)&&(r=r.slice(n.length),r=r.replace(/^\s+/,"")),r},hx=e=>e.trim()?e.trim().split(/\s+/):[],vx=e=>e.trimEnd().split(/\s+/).at(-1)??""});import{useSyncExternalStore as GP}from"react";var Vr,kd,Kr,yx,jp,Zt,cs,Md,Pd,$p,Wp,Ti,Hp,ne,qp,Gp,zp,ce,ki,pe=h(()=>{"use strict";Td();Up();S();Ci();Vr=e=>e===kd||e===":",kd=" ",Kr={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:_n.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},yx=new Set,jp=()=>{for(let e of yx)e()},Zt=e=>{let n=e(Kr),r=Op(n.value),o=n.cursorPosition===n.value.length;Kr={...n,commandMeta:Bp(r,o)},jp()},cs=({message:e,status:t})=>{let n=structuredClone(Kr);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,Kr=n,jp(),l(e,null)},Md=e=>{Zt(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Pd=e=>{Zt(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&Vr(n[o-1]);)o--;for(;o>0&&!Vr(n[o-1]);)o--}else{for(;o<n.length&&!Vr(n[o]);)o++;for(;o<n.length&&Vr(n[o]);)o++}return{...t,cursorPosition:o}})},$p=()=>{Zt(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}})},Wp=()=>{Zt(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&Vr(t[r-1]);)r--;for(;r>0&&!Vr(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},Ti=e=>{Zt(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),r=t.value.slice(0,n),o=t.value.slice(n),s=e(r,t.commandMeta.autoCompletion),i=s+o,c=Math.max(0,Math.min(s.length,i.length));return{...t,value:i,cursorPosition:c,commandIsPending:!1}})},Hp=()=>{Zt(e=>({...e,commandIsPending:!0}))},ne=e=>{Zt(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},qp=({addToHistory:e=!0})=>{Zt(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},Gp=()=>{Zt(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}})},zp=()=>{Zt(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},ce=()=>Kr,ki=()=>{let[e,...t]=Kr.value.split(kd);return t.join(kd).trim()}});var B,Xn=h(()=>{"use strict";ve();_l();M();pe();ze();B={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 Vp,O,Ld=h(()=>{"use strict";M();pr();Vp=e=>{let{context:t}=g().contextNode;if(!t)return O.None;switch(e){case I.EXIT:return O.Exit;case I.EXPORT:return O.Export;case I.INIT:return O.Init;case I.OPEN:return O.OpenProject;case I.DELETE:return O.Delete;case I.EDIT:return O.Edit;case I.COMMENT:return O.Comment;case I.HELP:return O.ViewHelp;case I.RE_OPEN_ISSUE:return O.ReopenIssue;case I.CLOSE_ISSUE:return O.CloseIssue;case I.TAG:return O.TagTicket;case I.UNTAG:return O.UntagTicket;case I.ASSIGN:return O.AssignUserToTicket;case I.UNASSIGN:return O.UnassignUserFromTicket;case I.NEW:return O.NewItem;case I.FILTER:return O.Filter;case I.MOVE:return O.Move;case I.PEEK:return O.Peek;case I.REPLAY:return O.Replay;case I.CONFIG:return O.Config;case I.YANK:return O.Yank;case I.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 Kp}from"ink";import Yp,{useEffect as Xp,useState as bx}from"react";var Jp,it,Yr=h(()=>{"use strict";M();Xe();Jp={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},it=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=at(),r=Jp[n]??Jp.default,[o,s]=bx(0);if(Xp(()=>{s(0)},[r]),Xp(()=>{if(!e)return;let c=setInterval(()=>{s(u=>(u+1)%r.length)},500);return()=>clearInterval(c)},[e,r]),!e)return Yp.createElement(Kp,null,t);let i=r[o]??r[0]??t;return Yp.createElement(Kp,{color:T.accent,dimColor:o===1},i)}});import{Box as Dd,Text as Ix}from"ink";import Mi from"react";var xx,Fn,ls=h(()=>{"use strict";Xe();xx=(e,t,n,r)=>{let o=u=>Math.max(1,e[u]??1),s=n,i=n+1,c=o(n);for(;i<t&&c+o(i)<=r;)c+=o(i),i++;for(;s>0&&c+o(s-1)<=r;)s--,c+=o(s);return{start:s,end:i}},Fn=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,itemHeights:o,scrollByOne:s=!1})=>{if(e.length===0)return null;let i=Math.max(1,Math.floor(t)),c=Math.max(1,Math.ceil(r)),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}=o?xx(o,e.length,u,i):s?{start:Math.min(p,Math.max(0,u-m+1)),end:Math.min(p,Math.max(0,u-m+1))+m}:{start:Math.min(p,Math.floor(u/m)*m),end:Math.min(p,Math.floor(u/m)*m)+m},x=Math.max(1,y-f),R=e.slice(f,y),A=e.length>x,w=i,k=A?Math.max(1,Math.floor(x/e.length*w)):w,L=Math.max(0,w-k),D=Math.max(1,e.length-x),U=A?Math.floor(f/D*L):0;return Mi.createElement(Dd,{flexDirection:"row",height:i,width:"100%"},Mi.createElement(Dd,{flexDirection:"column",flexGrow:1,height:i},R),Mi.createElement(Dd,{flexDirection:"column",width:1,height:w},Array.from({length:w}).map((de,wn)=>Mi.createElement(Ix,{key:wn,color:A&&wn>=U&&wn<U+k?T.accent:T.secondary},A?"\u2502":" "))))}});var Qp,_d,Ex,Pi,Fd=h(()=>{"use strict";M();Ex=()=>{let{eventLog:e=[]}=g();if(_d&&Qp===e)return _d;let t=new Set;for(let n of e)n?.userId&&t.add(n.userId);return Qp=e,_d=t,t},Pi=e=>Ex().has(e)});import{Text as Rx}from"ink";import Sx from"react";var Nx,Cx,Xr,Li=h(()=>{"use strict";hi();yt();re();Fd();mt();Nx=e=>e.toLowerCase().trim(),Cx=(e,t=Ur)=>{let n=Nx(e);return t[n]?t[n]:ds(n)},Xr=({id:e,isSelected:t,maxWidth:n})=>{let r=E.getContributor(e);if(!r)return;let o=r.name,s=n===void 0?o:Jn(o,n);return Sx.createElement(Rx,{underline:t,color:Cx(o)},"@"+s,Pi(e)?"":"\u2197")}});import{Text as wx}from"ink";import Ax from"react";var Di,Bd=h(()=>{"use strict";re();Xe();yt();mt();Di=({id:e,isSelected:t,maxWidth:n})=>{let r=E.getTag(e);if(!r)return;let o=n===void 0?r.name:Jn(r.name,n);return Ax.createElement(wx,{underline:t,backgroundColor:Te(r.name),color:T.secondary}," "+o+" ")}});import{useEffect as Tx,useState as kx}from"react";var Mx,Zp,_i,us,Px,Lx,Jr,Fi=h(()=>{"use strict";yt();Mx=80,Zp=1400,_i=new Set,us=null,Px=e=>(_i.add(e),us||(us=setInterval(()=>{for(let t of _i)t()},Mx)),()=>{_i.delete(e),_i.size===0&&us&&(clearInterval(us),us=null)}),Lx=()=>{let e=Date.now()%Zp/Zp;return e<.5?e*2:(1-e)*2},Jr=e=>{let[,t]=kx(0);return Tx(()=>{if(e)return Px(()=>t(n=>n+1))},[e]),Rp(Lx())}});import{Box as Qr,Text as Zr}from"ink";import dt from"react";var Dx,ef,_x,Fx,tf,nf=h(()=>{"use strict";re();Xe();mt();Fd();tt();ns();Li();Bd();Fi();Dx=(e,t,n)=>{if(e.length<=t)return[e,null];let r=e.lastIndexOf(" ",t),o=r>0?r:t;return[e.slice(0,o),Jn(e.slice(o).trim(),n)]},ef=3,_x=2,Fx=(e,t)=>{let n=[],r=0;for(let[o,s]of e.entries()){let i=e.length-o-1,c=i>0?String(i).length+1:0;if(r+s.width+c>t)break;r+=s.width,n.push(s)}return{shown:n,hidden:e.length-n.length}},tf=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=Jr(r),s=e-4,i=s-7-1,[c,u]=Dx(le(t.title),i,s),m=u?null:Jn(le(t.props.description),s)||null,p=Ln(t),f=Dn(t).map(k=>({...k,name:k.name})),y=Math.max(1,s-ef),x=E.getCommentsByIssue(t.id),R=x.length?String(x.length).length+2+1:0,{shown:A,hidden:w}=Fx([...p.map(k=>({id:k.id,isTag:!0,width:Math.min(k.name.length,y)+ef})),...f.map(k=>({id:k.id,isTag:!1,width:Math.min(k.name.length,y)+_x+(Pi(k.id)?0:1)}))],s-R);return dt.createElement(Qr,{borderStyle:"round",height:5,flexDirection:"column",overflow:"hidden",borderDimColor:!n,borderColor:r?o:n?T.accent:T.secondary,justifyContent:"space-between"},dt.createElement(Qr,{paddingLeft:1,paddingRight:1,flexDirection:"column"},dt.createElement(Qr,{justifyContent:"space-between"},dt.createElement(Zr,{color:T.primary},c),dt.createElement(Zr,{color:T.secondary2,dimColor:!0},j(t.id))),u&&dt.createElement(Zr,{color:T.primary},u),m&&dt.createElement(Zr,{color:T.secondary2,dimColor:!0},m)),dt.createElement(Qr,{flexDirection:"row",paddingLeft:1,paddingRight:1,justifyContent:"space-between"},dt.createElement(Qr,{flexDirection:"row"},A.map(k=>dt.createElement(Qr,{paddingRight:1,key:k.id},k.isTag?dt.createElement(Di,{id:k.id,maxWidth:y}):dt.createElement(Xr,{id:k.id,maxWidth:y}))),w>0&&dt.createElement(Zr,{color:T.secondary2,dimColor:!0},"+",w)),x.length>0&&dt.createElement(Zr,{color:T.accent},"[",x.length,"]")))}});import{Box as hr,Text as ms}from"ink";import bt from"react";var Bx,rf,of=h(()=>{"use strict";ve();re();Xe();yt();Yr();Fi();Bx=(e,t)=>e.length>t?e.slice(0,Math.max(0,t-1))+"\u2026":e,rf=({index:e,labelWidth:t,width:n,ticket:r,isSelected:o,isFlashing:s=!1,mode:i})=>{let c=Jr(s),u=(r.props.tags??[]).map(de=>E.getTag(de)).filter(de=>!!de),m=(r.props.assignees??[]).map(de=>E.getContributor(de)).map(de=>de&&{...de,name:de.name}).filter(de=>!!de),p=1,f=u.length*(1+p),y=m.length*(2+p),x=u.map(de=>bt.createElement(hr,{key:de.id,paddingRight:p},bt.createElement(ms,{color:Te(de.name)},"\u25A0"))),R=m.map(de=>bt.createElement(hr,{key:de.id,paddingRight:p},bt.createElement(ms,{color:ds(de.name)},"@"+de.name.at(0)))),A=s?c:o?T.accent:i===b.MOVE?T.secondary:T.primary,w=E.getCommentsByIssue(r.id),k=w.length?String(w.length).length+2+p:0,L=w.length?bt.createElement(hr,{paddingRight:p},bt.createElement(ms,{color:T.accent},"[",w.length,"]")):null,D=f+y+k,U=Math.max(1,n-t-D-(D>0?1:0));return bt.createElement(hr,{justifyContent:"space-between"},bt.createElement(hr,null,bt.createElement(hr,{width:t},o?bt.createElement(it,{isSelected:!0}):bt.createElement(ms,{color:"gray",dimColor:!0},String(e+1).padStart(t-1)+" ")),bt.createElement(ms,{wrap:"truncate",color:A},Bx(r.title,U))),bt.createElement(hr,null,x,R,L))}});import Ox from"chalk";import{Box as Od,Text as Ux}from"ink";import en from"react";var jx,sf,af=h(()=>{"use strict";ee();M();Xe();Yr();ls();nf();of();Fi();jx=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:i,mode:c})=>{let{renderedChildrenIndex:u,replay:m}=at(),p=u[e.id]??[],f=m?new Set(m.flashNodeIds):null,y=f?.has(e.id)??!1,x=Jr(y),R=`${e.title} ${Ox.hex(T.secondary2).dim("("+p.length+")")}`,A=3,w=o?1:5,k=s&&i===-1,L=n-3-(o?1:0)-(k?2:0),D=Math.max(2,String(p.length).length+1),U=r-A-1,de=en.createElement(Od,{borderStyle:"round",borderColor:T.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1,marginRight:o?1:0},en.createElement(it,{isSelected:t}),en.createElement(Ux,{bold:!0,color:y?x:t?T.accent:T.primary},R," ",e.readonly?"\u{1F512}":"")),wn=(on,bo)=>{let Io=s&&i===bo;if(!F(on))return null;let xo=f?.has(on.id)??!1;return o?en.createElement(rf,{key:on.id,index:bo,labelWidth:D,width:L,ticket:on,isSelected:Io,isFlashing:xo,mode:c}):en.createElement(tf,{key:on.id,width:L,ticket:on,isSelected:Io,isFlashing:xo})};return en.createElement(Od,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?T.accent:T.secondary,paddingRight:0,paddingLeft:o?1:0,height:r},de,en.createElement(Od,null,p.length>0&&en.createElement(Fn,{selectedIndex:i,height:U,itemHeight:w},p.map(wn)),k&&en.createElement(it,{isSelected:!0})))},sf=en.memo(jx)});var df,cf,Ud=h(()=>{"use strict";tr();df=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},cf=(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 to,Bi=h(()=>{"use strict";to=e=>{let t=Date.now()-e,n=[{label:"y",ms:1e3*60*60*24*365},{label:"mo",ms:1e3*60*60*24*30},{label:"w",ms:1e3*60*60*24*7},{label:"d",ms:1e3*60*60*24},{label:"h",ms:1e3*60*60},{label:"m",ms:1e3*60},{label:"s",ms:1e3}];for(let{label:r,ms:o}of n){let s=Math.floor(t/o);if(s>=1)return`${s}${r} ago`}return"just now"}});import{Box as no,Text as En}from"ink";import qe,{useEffect as $x,useMemo as Wx,useRef as Hx}from"react";import{decodeTime as lf}from"ulid";function mf({ticket:e,width:t,height:n}){let r=Wx(()=>Gx(e),[e]),o=Hx([]);$x(()=>(uf(o.current),o.current=Vx(e,r),()=>{uf(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=at(),c=Math.max(1,n-4),u=Math.max(12,t-32);return r.length===0?qe.createElement(no,{flexDirection:"column",width:t,height:n,padding:1},qe.createElement(En,{color:T.primary},"No attachments yet."),qe.createElement(no,{paddingTop:1},qe.createElement(En,{color:T.primary},"Attach images from the browser GUI"),qe.createElement(En,{color:T.accent}," epiq gui "),qe.createElement(En,{color:T.primary},"by dropping or pasting them."))):qe.createElement(no,{flexDirection:"column",width:t,height:n},qe.createElement(no,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:T.secondary,borderStyle:"single",paddingBottom:1},qe.createElement(En,{color:T.secondary2},"Attachments (",r.length,") \u2014 enter to open"," ")),qe.createElement(Fn,{height:c,itemHeight:2,selectedIndex:s},r.map((m,p)=>{let f=p===s,y=m.name.length>u?m.name.slice(0,u-1)+"\u2026":m.name;return qe.createElement(no,{key:m.id,flexDirection:"row",paddingX:1,paddingBottom:1},qe.createElement(En,{color:T.accent},f?"\u276F ":" "),qe.createElement(no,{paddingLeft:1},qe.createElement(En,{color:T.secondary2},`#${p+1} `),qe.createElement(En,{color:f?T.accent:T.primary},y),qe.createElement(En,{color:T.secondary2}," "+Kx(m.bytes)+" "+to(Ge(m.id)))))})))}var qx,Gx,uf,zx,Vx,Kx,pf=h(()=>{"use strict";ht();Je();Bi();ee();S();re();tr();M();Xe();qr();ls();qx=e=>Le(e,"attachments"),Gx=e=>E.getAttachmentsByIssue(e.id).sort((t,n)=>lf(t.id)-lf(n.id)),uf=e=>{for(let t of e)E.deleteNode(t.id)},zx=(e,t,n)=>Pe.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),Vx=(e,t)=>{let n=E.getNode(qx(e.id));if(!n||!ut(n))return[];let r=t.map((o,s)=>zx(o,s,n.id)).map(o=>E.createNode(o)).filter(jt).map(({value:o})=>o).filter(ut);return t.length>0&&g().selectedIndex<0&&$.navigate({contextNode:n,selectedIndex:0}),r},Kx=e=>`${Math.max(1,Math.round(e/1024))} KB`});var gf,jd,ff,$d,hf,vf,Yx,yf,Xx,Wd,bf=h(()=>{"use strict";gf=/<!--\s*epiq-diff-comment:(.+?)-->\n?/,jd=e=>e.replace(gf,""),ff=e=>e==="additions"||e==="deletions",$d=e=>{let t=gf.exec(e);if(!t?.[1])return null;let n;try{n=JSON.parse(t[1])}catch{return null}let r=n;return typeof r?.filePath!="string"||typeof r.start!="number"||typeof r.end!="number"||typeof r.note!="string"||!ff(r.side)||!ff(r.endSide)||r.sha!==void 0&&typeof r.sha!="string"||r.issueRef!==void 0&&typeof r.issueRef!="string"?null:r},hf=/```\n([\s\S]*?)\n?```\s*$/,vf=e=>hf.exec(e)?.[1]??null,Yx=/`[^`\n]+`[^\n]*\n?$/,yf=e=>jd(e).replace(hf,"").replace(Yx,"").trim(),Xx=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} ${Xx(e)}`});var Jx,ps,Qx,Zx,eE,tE,xf,Hd,Ef,If,Rf,qd=h(()=>{"use strict";bf();Jx=(e,t)=>{let n=Math.max(1,Math.floor(t)),r=e.split(/\s+/).filter(Boolean);if(r.length===0)return[""];let o=[],s="";for(let i of r){let c=i;for(;c.length>n;)s&&(o.push(s),s=""),o.push(c.slice(0,n)),c=c.slice(n);s?s.length+1+c.length<=n?s=`${s} ${c}`:(o.push(s),s=c):s=c}return s&&o.push(s),o},ps=e=>{let t=e.split("`");return t.length%2===0?[{text:e}]:t.map((n,r)=>r%2===1?{text:n,code:!0}:{text:n}).filter(n=>n.text.length>0)},Qx=/!\[([^\]]*)\]\([^)]*\)/g,Zx=e=>e.replace(Qx,(t,n)=>n.trim()?`[image: ${n.trim()}]`:"[image]"),eE=e=>e.map(t=>t.code?`\`${t.text}\``:t.text).join(""),tE=4,xf=e=>e.replace(/\r$/,"").replaceAll(" "," ".repeat(tE)),Hd=e=>{let t=!1;return e.map(xf).map(n=>{if(/^\s*```/.test(n))return t=!t,{kind:"fence"};if(t)return{kind:"code",text:n};let r=$d(n);if(r)return{kind:"caption",text:Wd(r)};let o=Zx(n);if(o.trim()==="")return{kind:"blank"};let s=/^#{1,6}\s+(.*)$/.exec(o);return s?{kind:"heading",spans:ps(s[1]??"")}:{kind:"text",spans:ps(o)}})},Ef=(e,t)=>e.length<=t?[e]:e.match(new RegExp(`.{1,${t}}`,"g"))??[""],If=(e,t)=>{let n=[];for(let r of Hd(e))if(r.kind!=="fence"){if(r.kind==="blank"){n.length>0&&n[n.length-1]?.kind!=="blank"&&n.push(r);continue}if(r.kind==="code"){for(let o of Ef(r.text,t))n.push({kind:"code",text:o});continue}if(r.kind==="caption"){n.push(r);continue}for(let o of Jx(eE(r.spans),t))n.push({kind:r.kind,spans:ps(o)})}for(;n.length>0&&n[n.length-1]?.kind==="blank";)n.pop();return n},Rf=(e,t)=>{let n=$d(e),r=n?vf(e):null;if(!n||r===null)return If(jd(e).split(`
|
|
80
|
+
`),t);let o=yf(e),s=r.split(`
|
|
81
|
+
`).map(xf),i=n.side===n.endSide?n.start:void 0,c=i===void 0?0:String(i+s.length-1).length+3;return[...o?[...If(o.split(`
|
|
82
|
+
`),t),{kind:"blank"}]:[],{kind:"caption",text:Wd(n)},...s.flatMap((u,m)=>Ef(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 Sf,Text as vr}from"ink";import At from"react";var Nf,Gd,Cf,zd=h(()=>{"use strict";Xe();Nf=({spans:e,bold:t,wrap:n})=>At.createElement(vr,{color:T.primary,bold:t,wrap:n},e.map((r,o)=>r.code?At.createElement(vr,{key:o,color:T.yellow},r.text):At.createElement(vr,{key:o},r.text))),Gd=({line:e,width:t,gutter:n=0,wrap:r})=>{switch(e.kind){case"blank":return At.createElement(vr,null," ");case"fence":return At.createElement(vr,{color:T.secondary2},"```");case"caption":return At.createElement(vr,{color:T.accent,wrap:r},e.text);case"heading":return At.createElement(Nf,{spans:e.spans,bold:!0,wrap:r});case"text":return At.createElement(Nf,{spans:e.spans,wrap:r});case"code":{let o=n>0?`${e.number===void 0?"":String(e.number)}`.padStart(n-3)+" \u2502 ":"";return At.createElement(vr,{backgroundColor:T.secondary,color:T.primary,wrap:r},o,e.text.padEnd(Math.max(0,t-o.length)))}}},Cf=({lines:e,width:t})=>{let n=e.flatMap(o=>o.kind==="code"&&o.number!==void 0?[o.number]:[]),r=n.length>0?String(Math.max(...n)).length+3:0;return At.createElement(Sf,{flexDirection:"column"},e.map((o,s)=>At.createElement(Sf,{key:s},At.createElement(Gd,{line:o,width:t,gutter:r}))))}});import{Box as Bn,Text as On}from"ink";import ke,{useEffect as nE,useMemo as wf,useRef as rE}from"react";import{decodeTime as Af}from"ulid";function kf({ticket:e,width:t,height:n}){let r=wf(()=>iE(e),[e]),o=rE([]);nE(()=>(Tf(o.current),o.current=aE(e,r),()=>{Tf(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=at(),c=Math.max(1,n-4),u=Math.max(20,t-8),m=wf(()=>r.map(f=>{let y=Rf(f.md,u);return y.length>0?y:[{kind:"blank"}]}),[r,u]),p=m.map(f=>f.length+oE);return r.length===0?ke.createElement(Bn,{flexDirection:"column",width:t,height:n,padding:1},ke.createElement(On,{color:T.primary},"No comments yet."),ke.createElement(Bn,{paddingTop:1},ke.createElement(On,{color:T.primary},"Use"),ke.createElement(On,{color:T.accent}," :comment "),ke.createElement(On,{color:T.primary},"to add the first one."))):ke.createElement(Bn,{flexDirection:"column",width:t,height:n},ke.createElement(Bn,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:T.secondary,borderStyle:"single",paddingBottom:1},ke.createElement(On,{color:T.secondary2},"Comments (",r.length,") ")),ke.createElement(Fn,{height:c,itemHeights:p,selectedIndex:s},r.map((f,y)=>{let x=y===s;return ke.createElement(Bn,{key:f.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:T.secondary,borderStyle:"single"},ke.createElement(Bn,{flexDirection:"row",paddingBottom:1},ke.createElement(On,{color:T.accent},x?"\u276F ":" "),ke.createElement(Bn,{paddingLeft:1},ke.createElement(On,{color:T.secondary2},`#${y+1} `),ke.createElement(Xr,{id:f.authorId}),ke.createElement(On,{color:T.secondary2}," "+to(Ge(f.id))))),ke.createElement(Bn,{paddingLeft:3,paddingBottom:1},ke.createElement(Cf,{lines:m[y]??[],width:u})))})))}var oE,sE,iE,Tf,aE,Mf=h(()=>{"use strict";ht();Je();Bi();ee();S();re();M();Xe();qr();Li();ls();Ud();qd();zd();oE=4,sE=e=>Le(e,"comments"),iE=e=>E.getCommentsByIssue(e.id).sort((t,n)=>Af(t.id)-Af(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),Tf=e=>{for(let t of e)E.deleteNode(t.id)},aE=(e,t)=>{let n=E.getNode(sE(e.id));if(!n||!ut(n))return[];let r=t.map((o,s)=>cf(o,s,n.id)).map(E.createNode).filter(jt).map(({value:o})=>o).filter(Ao);return t.length>0&&g().selectedIndex<0&&$.navigate({contextNode:n,selectedIndex:0}),r}});import{Box as Oi,Text as dE}from"ink";import Rn from"react";var Pf,Lf=h(()=>{"use strict";ee();re();Mr();M();Xe();Li();Yr();Bd();Pf=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=at(),{title:o}=t,s=t.parentNodeId?E.getNode(t.parentNodeId):void 0,i=s&&F(s)?o===ge.ASSIGNEES?s.props.assignees??[]:o===ge.TAGS?(s.props.tags??[]).filter(c=>E.getTag(c)):[]:[];return Rn.createElement(Oi,{alignItems:"center",paddingTop:1},Rn.createElement(Oi,{minWidth:12},Rn.createElement(it,{isSelected:n}),Rn.createElement(dE,{color:n?T.accent:T.secondary2},o,":")),Rn.createElement(Oi,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((c,u)=>{let m=r.id===t.id&&u===e;return Rn.createElement(Oi,{key:`${o}-${c}`,paddingRight:2,minHeight:1},Rn.createElement(it,{isSelected:m}),o===ge.ASSIGNEES?Rn.createElement(Xr,{isSelected:m,id:c}):o===ge.TAGS?Rn.createElement(Di,{isSelected:m,id:c}):null)})))}});var Vd,Df,Kd,Yd=h(()=>{"use strict";Vd=e=>Math.max(5,String(Math.max(e,1)).length+3),Df=(e,t)=>Math.max(0,e-6-Vd(t)),Kd=(e,t=0)=>Math.max(1,e-5-2*t)});import{Box as ro,Text as Xd}from"ink";import Tt,{useEffect as cE,useMemo as Jd}from"react";var lE,_f,Qd,Ff,uE,Zd,Bf=h(()=>{"use strict";re();S();tr();M();Xe();mt();Yd();Yr();ls();zd();qd();wr();lE="\u2029",_f=(e,t)=>`${e}::inline-line::${t}`,Qd=new Map,Ff=e=>{let t=Qd.get(e)??[];Qd.delete(e);for(let n of t)E.deleteNode(n)},uE=(e,t)=>{Ff(e);let n=[];t.forEach((r,o)=>{let s=Et(BigInt(o+1));if(!jt(s))return;let i=E.createNode(Pe.text({id:_f(e,o),name:`Line ${o+1}`,parentNodeId:e,rank:s.value,props:{value:r},readonly:!0,isVirtual:!0}));jt(i)&&n.push(i.value.id)}),Qd.set(e,n)},Zd=({id:e,label:t,text:n,rows:r,selected:o,maxWidth:s})=>{let{selectedIndex:i,contextNode:c}=at(),u=Jd(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=Jd(()=>u.join("\0"),[u]);cE(()=>(uE(e,u),()=>{Ff(e)}),[e,m]);let p=Vd(u.length),f=Df(s,u.length),x=Jd(()=>Hd(u).map(R=>{if(R.kind==="code"||R.kind==="caption")return{...R,text:ga(R.text,f)};if(R.kind==="text"||R.kind==="heading"){let A=R.spans.map(w=>w.code?`\`${w.text}\``:w.text).join("");return{...R,spans:ps(ga(A,f))}}return R}),[u,f]).map((R,A)=>{let w=c.id===e&&i===A;return Tt.createElement(ro,{key:_f(e,A)},Tt.createElement(ro,{flexShrink:0},Tt.createElement(Xd,{color:w?T.primary:T.secondary2,dimColor:!w},`${A+1} `.padStart(p,"\xA0"))),R.kind==="blank"?Tt.createElement(Xd,{backgroundColor:w?"gray":void 0},lE):Tt.createElement(ro,null,Tt.createElement(Gd,{line:R,width:R.kind==="code"?f:0,wrap:"truncate-end"})))});return Tt.createElement(ro,{flexDirection:"column",paddingTop:1},Tt.createElement(ro,null,Tt.createElement(it,{isSelected:o}),Tt.createElement(Xd,{color:o?T.accent:T.secondary2},t)),Tt.createElement(ro,{flexDirection:"row",borderStyle:"round",borderColor:T.secondary,paddingLeft:1,marginLeft:1,overflowY:"hidden"},Tt.createElement(Fn,{scrollByOne:!0,height:r,selectedIndex:i,itemHeight:1},x)))}});import{Box as yr,Text as ec}from"ink";import _e,{useMemo as fs}from"react";var mE,pE,fE,gE,Of,Uf=h(()=>{"use strict";ee();re();M();Xe();Ud();qr();pf();Mf();Yr();Lf();Bf();Yd();mE=e=>Le(e,"description"),pE=e=>Le(e,"comments"),fE=e=>Le(e,"history"),gE=e=>Le(e,"attachments"),Of=({ticket:e,height:t})=>{let n=fs(()=>df(e),[e]),{selectedIndex:r,contextNode:o}=at(),s=process.stdout.columns||120,i=fs(()=>mE(e.id),[e.id]),c=fs(()=>pE(e.id),[e.id]),u=fs(()=>fE(e.id),[e.id]),m=fs(()=>gE(e.id),[e.id]),p=E.getAttachmentsByIssue(e.id).length,f=o.id===e.id,y=o.id===c||o.parentNodeId===c,x=o.id===u||o.parentNodeId===u,R=o.id===m||o.parentNodeId===m,A=ae(e.id);if(y){let U=t-3;return _e.createElement(yr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},_e.createElement(kf,{ticket:e,width:s,height:U}))}if(R){let U=t-3;return _e.createElement(yr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},_e.createElement(mf,{ticket:e,width:s,height:U}))}if(x){let D=E.getNode(u),U=D&&ut(D)?D.props.value??"":"",de=Kd(t);return _e.createElement(yr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},D?_e.createElement(Zd,{id:D.id,label:"Event log",text:U,selected:!1,maxWidth:s,rows:de}):null)}let w=A.reduce((D,U)=>wo(U)||U.id===c||U.id===m||U.id===u?D+1:D,0),k=Kd(t,w),L=(D,U)=>D.id===i?_e.createElement(Zd,{key:D.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:U,maxWidth:s,rows:k}):wo(D)?_e.createElement(Pf,{key:D.id,parent:D,selected:U,selectedIndex:r}):D.id===c?_e.createElement(yr,{key:D.id,paddingTop:1},_e.createElement(it,{isSelected:U}),_e.createElement(ec,{backgroundColor:T.secondary,color:U?T.accent:T.primary},` Comments (${n}) \u203A\u203A `)):D.id===m?_e.createElement(yr,{key:D.id,paddingTop:1},_e.createElement(it,{isSelected:U}),_e.createElement(ec,{backgroundColor:T.secondary,color:U?T.accent:T.primary},` Attachments (${p}) \u203A\u203A `)):D.id===u?_e.createElement(yr,{key:D.id,paddingTop:1},_e.createElement(it,{isSelected:U}),_e.createElement(ec,{backgroundColor:T.secondary,color:U?T.accent:T.primary}," History \u203A\u203A ")):null;return _e.createElement(yr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},A.map((D,U)=>L(D,f&&r===U)))}});import{Box as hE}from"ink";import Ui from"react";var vE,jf,$f=h(()=>{"use strict";ee();af();Uf();vE=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:i,width:c})=>{let u=t.context,m=u===Y.TICKET||u===Y.FIELD_LIST||u===Y.FIELD,p=u===Y.BOARD||u===Y.SWIMLANE,f=u===Y.TICKET?t:r.find(w=>w.context===Y.TICKET),y=Math.floor(c/3),x=Math.floor(c/Math.max(e.length,1)),R=Math.min(x,y),A=s==="dense";return Ui.createElement(hE,{flexDirection:"row",height:i},p&&e.map((w,k)=>{let L=t.id===w.id,D=L?n:-1,U=t.context===Y.BOARD&&n===k;return Ui.createElement(sf,{key:w.id,height:i,width:R,swimlane:w,isSelected:U,isDense:A,isFocused:L,listSelectedIndex:D,mode:o})}),m&&f&&Ui.createElement(Of,{height:i,ticket:f}))},jf=Ui.memo(vE)});import Wf from"node:fs";import yE from"node:path";import bE from"react";import{render as IE}from"ink";import{Writable as xE}from"node:stream";var gs,EE,RE,SE,NE,Hf,qf=h(()=>{"use strict";$f();ee();S();M();ie();ze();gs=e=>String(e).padStart(2,"0"),EE=e=>{let t=e.getUTCFullYear(),n=gs(e.getUTCMonth()+1),r=gs(e.getUTCDate()),o=gs(e.getUTCHours()),s=gs(e.getUTCMinutes()),i=gs(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${i}`},RE=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",SE=async(e,{width:t,height:n})=>{let r="",o=new xE({write(i,c,u){let m=NE(i.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=IE(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(i=>setTimeout(i,0)),s.unmount(),r},NE=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),Hf=async()=>{let{viewMode:e}=xe(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=g(),i=r.find(k=>k.context==="BOARD");if(!i)return d("No board found to export");let c=120,u=40,m=await SE(bE.createElement(jf,{height:u,width:c,swimlanes:(s[i.id]??[]).filter(k=>k!==void 0&&Kn(k)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:c,height:u});if(!m)return d("Failed to render board export");let p=js(process.cwd());if(a(p))return d("Unable to export, epiq root not found");let f=new Date,y=EE(f),x=`board_${RE(i.title)}_${y}.md`,R=vu(p.value);Wf.mkdirSync(R,{recursive:!0});let A=yE.join(R,x),w=`# Board - ${i.title}
|
|
80
83
|
Date: ${f.toISOString()}
|
|
81
84
|
|
|
82
85
|
\`\`\`text
|
|
83
86
|
${m}
|
|
84
87
|
\`\`\`
|
|
85
|
-
`;return
|
|
86
|
-
`).map(u=>u.trim()),s=
|
|
88
|
+
`;return Wf.writeFileSync(A,w,"utf8"),l("Exported board layout",A)}});import{useSyncExternalStore as N_}from"react";var tc,CE,wE,oo,AE,Un,ji=h(()=>{"use strict";S();CE=new Set,wE=()=>{for(let e of CE)e()},oo=()=>{if(!tc)throw new Error("Ui state not initialized. Call initUiState() first.");return tc},AE=e=>{let t=oo();return tc=e(t),wE(),l("UX state updated",null)},Un=e=>AE(t=>({...t,...e}))});import{spawn as k_,spawnSync as TE}from"node:child_process";import kE from"node:os";import Gf from"node:path";import{ulid as ME}from"ulid";function zf(e){let t=[],n="",r=!1,o=null;for(let s of e.trim()){if(o){s===o?o=null:n+=s;continue}if(s==='"'||s==="'"){o=s,r=!0;continue}if(/\s/.test(s)){r&&t.push(n),n="",r=!1;continue}n+=s,r=!0}return r&&t.push(n),t}function PE(e){let t=e.trim();return t==="$EDITOR"?process.env.EDITOR:t==="$VISUAL"?process.env.VISUAL:t}function Vf(){let{preferredEditor:e}=xe(),t=[e?PE(e):void 0,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function Kf(e){let[t=""]=zf(e);return/(^|\/)code(-insiders)?$/.test(t)}function LE(e,t){let[n="",...r]=zf(e);return{command:n,args:[...r,...t]}}function DE(e,t){return LE(e,Kf(e)?["--wait",t]:[t])}function Yf(e){let t=Gf.join(kE.tmpdir(),"epiq");rt.mkDir(t);let n=Gf.join(t,ME());rt.writeToFile(n,e??"");let r=Vf();for(let o of r){let{command:s,args:i}=DE(o,n);if(!s)continue;let c=TE(s,i,{stdio:"inherit"});if(!c.error&&c.status===0){let u=rt.readFile(n);if(u==null)return d("Unable to read edited file");let m=u.replace(/\r?\n$/,"");return l("Successfully edited",m)}}return d("Unable to open editor")}var nc=h(()=>{"use strict";S();ze();Ri()});import{ulid as rc}from"ulid";var Xf,_E,FE,Jf=h(()=>{"use strict";nc();Re();Ce();$t();ee();S();Mr();re();M();ie();yn();Xf=async e=>{let{contextNode:t,selectedIndex:n}=g(),r=ae(t.id)[n];if(e.modifier===vt.DESCRIPTION)return FE();if(r&&Ao(r))return _E(e);if(e.modifier===vt.TITLE){let o=oe();if(a(o))return d("Unable to resolve user ID");let s=r;if(!s)return d("Missing node");if(s.readonly)return d("Cannot rename readonly node");let i=e.inputString.trim();if(!i)return d("Provide a title");let c=await zt();return a(c)?c:P([{id:rc(),action:"edit.title",payload:{id:s.id,name:i},...o.value}],c.value)}return d("Unknown edit command")},_E=async e=>{let t=oe();if(a(t))return d("Unable to resolve user ID");let{contextNode:n,selectedIndex:r}=g(),o=ae(n.id)[r];if(!o||!Ao(o))return d("Select a comment first");if(o.readonly)return d("Cannot edit readonly comment");let s=n.parentNodeId;if(!s)return d("Unable to resolve comment issue");let i=g().nodes[s];if(!i||!F(i))return d("Unable to resolve comment issue");if(i.readonly)return d("Cannot edit readonly issue");let c=o.id.split(":").at(0)??"",u=E.getComment(c);if(!u||u.deleted)return d("Unable to resolve comment");if(u.issue!==i.id)return d("Comment does not belong to selected issue");if(u.authorId!==t.value.userId)return d("You can only edit your own comments"+u.authorId+"<->"+t.value.userId);let m=e.inputString.trim();if(!m)return d("Provide a comment");let p=await zt();if(a(p))return p;let f=p.value;return P([{id:rc(),action:"edit.issue.comment",payload:{id:u.id,issue:i.id,md:m},...t.value}],f)},FE=async()=>{let e=oe();if(a(e))return d("Unable to resolve user ID");let t=await zt();if(a(t))return t;let n=t.value,{breadCrumb:r,selectedNode:o}=g(),s=lt([...r,o],"TICKET");if(a(s))return d("Edit target must be an issue");let i=s.value;if(!F(i))return d("Edit target must be an issue");if(i.readonly)return d("Cannot edit readonly issue");let c=ae(i.id).find(f=>f.title===ge.DESCRIPTION);if(!c)return d("No target found");if(c.readonly)return d("Cannot edit readonly field");let u=i.props.description??"";if(typeof u!="string")return d("Selected field is not editable text");let m=Yf(u);if(a(m))return d("Failed to edit field");let p=m.value;return p===u?l("No changes made",null):P([{id:rc(),action:"edit.description",payload:{id:i.id,md:p},...e.value}],n)}});import oc from"node:fs";import BE from"node:path";var Qf,Zf=h(()=>{"use strict";S();St();Qf=async e=>{let t=BE.join(e,".gitignore"),n=oc.existsSync(t)?oc.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/log/"],o=n.split(`
|
|
89
|
+
`).map(u=>u.trim()),s=r.filter(u=>!o.some(m=>m===u||m===u.replace(/\/$/,"")||m==="/"+u||m==="/"+u.replace(/\/$/,"")));if(s.length===0)return l("Local epiq paths already ignored",!1);let c=["# [epiq]: local hydrated state is never committed",...s].join(`
|
|
87
90
|
`);return n=n.trimEnd()+`
|
|
88
91
|
|
|
89
92
|
${c}
|
|
90
|
-
`,
|
|
91
|
-
`).filter(n=>n.trim().length>0).map(n=>n.slice(3)))},
|
|
92
|
-
`));let u=ze();if(d(u))return rs(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)):rs(16,"Unable to resolve initialized root node")}});import{ulid as vE}from"ulid";function Xd(e){let t=Uf();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:jf(u.value)}function Jd(e){let t=Uf();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:jf(i.value)}var Bf,_n,ss,Uf,Yd,$f,jf,Qd=h(()=>{"use strict";ln();Ce();R();yt();M();Bf=null,_n=()=>structuredClone(Bf),ss=e=>{Bf=e},Uf=()=>{let{contextNode:e,selectedIndex:t}=g(),o=ge(e.id)[t];return o?l("Resolved selected child",o):a("Target node not found")},Yd=({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=Yd({parentId:t,id:e,position:n});return d(r)?r:l("Created pending move state",{id:vE(),...o.value,action:"move.node",payload:{id:e,parent:t,rank:r.value.rank}})},jf=e=>{ss(e);let t=Nn(e,!0);return d(t)?t:l("Node moved successfully",t.value)}});import{ulid as yE}from"ulid";var Hf,Di,Wf,qf=h(()=>{"use strict";ut();Qd();Se();Ce();pe();R();yt();ce();M();ae();Hf=()=>{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=Hf();return d(n)?n:(N({mode:b.MOVE}),l(t,null))},Wf=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=Yd({parentId:r.parentNodeId,id:r.id,position:m});return d(p)?p:(ss({id:yE(),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(Jd(1));if(t==="previous")return Di(Jd(-1));if(t==="to-next")return Di(Xd(1));if(t==="to-previous")return Di(Xd(-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=Hf();return d(u)?u:(ss(null),N({mode:b.DEFAULT}),l("Moved item",null))}return t==="cancel"?(ss(null),N({mode:b.DEFAULT}),l("Cancelling move",null)):a("Invalid move modifier")}});import{monotonicFactory as bE,ulid as xE}from"ulid";var IE,Fi,Zd=h(()=>{"use strict";R();IE=bE(),Fi=({name:e,parent:t,rank:n,user:{userId:o,userName:r}})=>{let s=IE();return l("Created issue events",[{id:xE(),userId:o,userName:r,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])}});import{ulid as _i}from"ulid";var Gf,zf=h(()=>{"use strict";ut();Zd();Se();Ce();Ft();R();ne();yt();M();ae();Gf=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 EE,Vf,SE,Kf,RE,Yf,Xf=h(()=>{"use strict";bo();Xe();ct();Br();oi();Ja();ti();wo();to();St();R();nn();M();Dr();ae();Xs();EE=e=>e.some(t=>t.action==="init.workspace"),Vf=async(e,t)=>{let n=Bt(e);return d(n)?a(n.message):Sr({cwd:t,branch:n.value})},SE=e=>{let t=Me(process.cwd());if(d(t))return!1;let n=be({repoRoot:t.value});return!d(n)&&n.value===e},Kf=async e=>{let t=be({repoRoot:e});if(d(t))return Ro(3,t.message);let n=t.value,o=await oo({repoRoot:e,stateBranchRoot:n,stateBranchName:Rs().stateBranch});if(d(o))return Ro(3,o.message);let r=Et(n);if(d(r))return Ro(3,r.message);if(!EE(r.value.events)){let m=await Vf(e,n);if(d(m)&&logger.info(3,m.message),r=Et(n),d(r))return Ro(3,r.message)}let{events:s,unreadable:i}=r.value,c=Wt(s,i);if(d(c))return Ro(4,c.message);N({hasProjectDefinition:!0,hasInitializingEvents:!!s.length});let u=Hr({root:e});return d(u)&&logger.info(u.message),l("Loaded project",void 0)},RE=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:()=>Za(n,()=>(So("Pulling"),Vf(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 Er(s.message)?(Ys("Offline"),l("Offline",void 0)):Re(s.message);if(!s.value)return no("Already synced"),l("Already synced",void 0);if(!SE(n))return l("Project changed during the pull",void 0);let i=ed(n);return d(i)?i:(no("Pulled"),l("Pulled and reloaded",void 0))},Yf=e=>{RE(e).then(t=>{d(t)&&logger.info(3,t.message)}).catch(t=>{logger.error(`[boot] pull failed: ${sm(t)}`)})}});import NE from"node:os";import Jf from"node:path";var CE,AE,Qf,Zf=h(()=>{"use strict";Xf();wo();R();ce();M();ae();CE=e=>e==="~"||e.startsWith("~/")?Jf.join(NE.homedir(),e.slice(1)):e,AE=(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(Jf.resolve(CE(n)));return d(o)?a(`No epiq project at ${n}`):l("Resolved project path",o.value)},Qf=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=AE(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 Kf(r);return d(i)?(process.chdir(s),a(i.message)):(Yf(r),l(`Opened ${wm(r)}`,null))}});var Oi,ec=h(()=>{"use strict";ut();St();ln();R();M();Oi=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:o})=>{let r=g(),s=Ua(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 eg,tg=h(()=>{"use strict";eg=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 wE,TE,kE,Bi,Ui,uo,ng,og,tc=h(()=>{"use strict";Ke();is();ln();pe();R();tg();M();wE=20,TE=16,kE=150,Bi=null,Ui=null,uo=()=>{Bi!==null&&(clearInterval(Bi),Bi=null),Ui!==null&&(clearTimeout(Ui),Ui=null)},ng=()=>{uo(),N({mode:b.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},og=({events:e,startTime:t,durationMs:n})=>{uo();let o=e.length,r=fr(e.map(f=>$n(f))).map(f=>f??t),s=r[o-1]??Date.now(),i=eg(r),c=Math.max(1,Math.round(n*wE/1e3)),u=Math.max(Math.round(n/c),TE),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(Tr(k)){p++;continue}ng();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)&&!Tr(k))break}let w=g().replay;N({unappliedEvents:[],replay:w&&{...w,progress:1,appliedCount:o}}),uo(),Ui=setTimeout(ng,kE);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?nc(I):A?.currentLabel??"",flashNodeIds:I?[...new Set(y)]:A?.flashNodeIds??[]}})},u)}});var rg,sg=h(()=>{"use strict";Xe();Ke();St();ln();pe();Ft();R();ce();M();Gr();ec();tc();rg=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=$a(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:pr(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 ig,ag=h(()=>{"use strict";Xe();Ft();R();ce();M();Gr();ec();tc();ig=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)):(og({events:y,startTime:m,durationMs:u}),l("Replaying board history",!0))}});import{spawn as PE}from"node:child_process";var LE,dg,cg=h(()=>{"use strict";R();LE=()=>{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"]}}},dg=async e=>new Promise(t=>{let{command:n,args:o}=LE();try{let r=PE(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 as,lg,ug=h(()=>{"use strict";R();M();cg();Je();qr();pn();as=async(e,t)=>{if(!e.trim())return a(`Nothing to copy: ${t} is empty`);let n=await dg(e);return d(n)?n:l(`Copied ${t} to clipboard`,null)},lg=async e=>{let{breadCrumb:t,selectedNode:n}=g(),o=zr({breadCrumb:t,selectedNode:n}),r=o??n;if(!r)return a("Nothing selected to copy from");switch(e.modifier){case Ae.REF:return as(j(r.id),"ref");case Ae.TITLE:return as(r.title,"title");case Ae.DESCRIPTION:return o?as(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 as(s.join(", "),"tags")}case Ae.ASSIGNEES:{if(!o)return a("No issue in scope");let s=kn(o).map(({name:i})=>i);return as(s.join(", "),"assignees")}default:return a("Yank one of: ref, title, description, tags, assignees")}}});var mg,pg=h(()=>{"use strict";oi();pe();R();ce();M();mg=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 fg}from"ulid";var DE,gg,hg=h(()=>{"use strict";Se();Ce();K();R();M();Yt();DE=e=>e.action==="add.issue.comment",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 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(DE).find(m=>m.payload.id===s);return u?u.payload.author!==e.value.userId?a("You can only delete your own comments"):L([{id:fg(),action:"delete.issue.comment",payload:{id:s,issue:i},...e.value}],r.value):a("Unable to resolve comment")}return L([{id:fg(),action:"delete.node",payload:{id:o.id},...e.value}],r.value)}});import{ulid as FE}from"ulid";var vg,yg=h(()=>{"use strict";Se();Ce();dn();K();R();yt();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("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:FE(),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,oc=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 _E}from"ulid";var bg,xg=h(()=>{"use strict";Se();Ce();oc();dn();K();R();ne();yt();M();Yt();bg=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:_E(),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 OE}from"ulid";var Ig,Eg=h(()=>{"use strict";Se();Ce();R();ce();M();Yt();Ig=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:OE(),action:"edit.title",payload:{id:o.id,name:r},...e.value}],s.value)}});import{ulid as BE}from"ulid";var Sg,Rg=h(()=>{"use strict";ne();Se();Ce();K();R();ce();M();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 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:BE(),action:"remove.issue.tag",payload:{id:c.id,tag:r.id},...e.value}],m.value)}});import{ulid as rc}from"ulid";var Ng,Cg=h(()=>{"use strict";ne();Se();Ce();K();R();ce();M();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 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??rc();return(i.props.tags??[]).includes(m)?a("Already tagged with that tag"):L([...u?[]:[{id:rc(),action:"create.tag",payload:{id:m,name:o},...e.value}],{id:rc(),action:"add.issue.tag",payload:{id:i.id,tag:m},...e.value}],c.value)}});var ji,sc=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 ic}from"ulid";var Ag,wg=h(()=>{"use strict";Se();Ce();K();R();ne();ce();M();sc();Yt();Ag=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??ic(),A=_?.name??s}if((p.props.assignees??[]).includes(S))return a("Assignee already assigned");let k=!!g().contributors[S];return L([...k?[]:[{id:ic(),action:"create.contributor",payload:{id:S,name:A},...e.value}],{id:ic(),action:"add.issue.assignee",payload:{id:p.id,assignee:S},...e.value}],f.value)}});import{ulid as UE}from"ulid";var Tg,kg=h(()=>{"use strict";Se();Ce();K();R();ne();ce();M();sc();Yt();Tg=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:UE(),action:"remove.issue.assignee",payload:{id:i.id,assignee:p},...e.value}],f.value)}});import{ulid as Mg}from"ulid";var Pg,Lg=h(()=>{"use strict";Se();Ce();Ft();K();R();ne();M();hn();Yt();Pg=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:Mg(),action:"add.issue.comment",payload:{id:Mg(),issue:u.id,author:n.value.userId,md:t},...n.value}],m.value)}});import $E from"zod";var Dg,Fg=h(()=>{"use strict";zt();pe();R();ce();We();M();Dg=()=>{let e=de().commandMeta.inputString,t=$E.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 _g,Og=h(()=>{"use strict";Wr();zt();pe();R();ce();We();M();_g=()=>{let e=de().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return a("Invalid response");let t=Dm(e),n=et({autoSync:t});return d(n)?n:(ht({autoSync:t}),N({mode:b.DEFAULT}),l(`Auto sync set to "${e}"`,null))}});var Bg,Ug=h(()=>{"use strict";zt();pe();R();ce();We();M();Bg=()=>{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 jE}from"ulid";var $g,jg=h(()=>{"use strict";Un();zt();pe();R();We();M();pn();Fg();fd();Og();Ug();$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=Mo();if(d(n))return n;let{userId:o,preferredEditor:r,userName:s}=n.value,i=t||s,c=o||jE();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 _g();case ve.LOG_LEVEL:return Bg();case ve.SYNC_DEBOUNCE_MS:return Dg();case ve.ATTACHMENT_MAX_KB:return Qm();default:return a("Unknown config command")}}});var Hg,Wg=h(()=>{"use strict";Nf();ut();pe();R();ce();M();Pi();ro();Ed();pn();Pf();Of();qf();zf();Zf();sg();ag();ug();pg();hg();yg();xg();Eg();Rg();Cg();wg();kg();Lg();jg();Hg=[{systemOnly:!0,intent:B.Move,description:"Internal move-state command",mode:b.COMMAND_LINE,action:Wf},{intent:B.Delete,description:"Delete the currently selected node",mode:b.COMMAND_LINE,action:gg,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:vg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:B.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:b.COMMAND_LINE,action:bg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:B.Init,description:"Initialize Epiq in the current git repository",mode:b.COMMAND_LINE,action:_f},{intent:B.OpenProject,description:"Open a recently used epiq project, by number or path",mode:b.COMMAND_LINE,action:Qf,onSuccess:()=>N({mode:b.DEFAULT})},{intent:B.NewItem,description:"Create a new board, swimlane, or issue",mode:b.COMMAND_LINE,action:Gf,onSuccess:()=>N({mode:b.DEFAULT})},{intent:B.Rename,description:"Rename the currently selected node",mode:b.COMMAND_LINE,action:Ig,onSuccess:()=>N({mode:b.DEFAULT})},{intent:B.UntagTicket,description:"Remove a tag from the selected issue",mode:b.COMMAND_LINE,action:Sg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:B.TagTicket,description:"Add or create a tag on the selected issue",mode:b.COMMAND_LINE,action:Ng,onSuccess:()=>N({mode:b.DEFAULT})},{intent:B.AssignUserToTicket,description:"Assign a user to the selected issue",mode:b.COMMAND_LINE,action:Ag,onSuccess:()=>N({mode:b.DEFAULT})},{intent:B.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:b.COMMAND_LINE,action:Tg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:B.Comment,description:"Add a comment to the selected issue",mode:b.COMMAND_LINE,action:async(e,t)=>Pg(t),onSuccess:()=>N({mode:b.DEFAULT})},{intent:B.Sync,description:"Pull, commit, and push Epiq state",mode:b.COMMAND_LINE,action:mg},{intent:B.Peek,description:"View board state at another point in time",mode:b.COMMAND_LINE,action:rg},{intent:B.Replay,description:"Replay board history forward from a point in time",mode:b.COMMAND_LINE,action:ig},{intent:B.Export,description:"Export the current board layout to markdown",mode:b.COMMAND_LINE,action:async()=>{let e=await Rf();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)=>Mf(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)=>lg(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 HE,Xt,ac=h(()=>{"use strict";ri();yi();Ed();Wg();R();ce();We();M();HE=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=wp(t);Rp();let{readOnly:i}=g();if(i&&!HE.has(s))return Jr({status:tn.Fail,message:"Command not available in readonly state",value:null});let c=Hg.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!c)return Jr({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 Jr({status:tn.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return d(u)?Jr(u):(Np({addToHistory:!e}),c.onSuccess?.(),Ie().autoSync&&Nm(),u)}});var Hi,Wi,qg,Gg=h(()=>{"use strict";R();pe();M();jn();ac();Qd();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")}],qg=[{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 zg,Vg=h(()=>{"use strict";K();Gg();zg={[V.WORKSPACE]:[...Hi,...Wi],[V.BOARD]:[...Hi,...Wi],[V.SWIMLANE]:[...Hi,...Wi,...qg],[V.TICKET]:[],[V.FIELD]:[],[V.FIELD_LIST]:[],[V.TEXT]:[],[V.COMMENT]:[]}});import{spawn as WE}from"node:child_process";function Kg(e){let t=process.platform,r=WE(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 Yg=h(()=>{"use strict"});import qE from"node:fs";import GE from"node:path";var Xg,Jg=h(()=>{"use strict";Xe();Lo();R();ae();Yg();Xg=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=Po(e.hash,e.ext),r=GE.join(Ls(n.value),o);return qE.existsSync(r)?(Kg(r),l(`Opened ${e.name}`,null)):a("Attachment file not found \u2014 run :sync to fetch it")}});var Qg,Zg,eh=h(()=>{"use strict";pe();R();ce();M();Pi();jn();ut();Qg=()=>{te("");let{pendingNavTarget:e}=Ko();N({mode:b.DEFAULT}),e&&U.navigate(e),Fn({pendingNavTarget:void 0})},Zg=[{intent:O.ExitCommandLine,mode:b.HELP,action:()=>(Qg(),l("Exiting help",null))},{intent:O.Exit,mode:b.HELP,action:()=>(Qg(),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 zE,th,nh,oh=h(()=>{"use strict";pe();K();R();ce();M();Pi();jn();ut();zE=e=>{N({mode:b.COMMAND_LINE});let{pendingNavTarget:t}=Ko();t&&U.navigate(t),Fn({pendingNavTarget:void 0}),te(`${e} `)},th=()=>{te("");let{pendingNavTarget:e}=Ko();e&&U.navigate(e),Fn({pendingNavTarget:void 0}),N({mode:b.DEFAULT})},nh=[{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||!vl(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?(zE(t),l("Selected command",t)):l("No command selected",null)}},{intent:O.ExitCommandLine,mode:b.PALETTE,action:()=>(th(),l("Exiting palette",null))},{intent:O.Exit,mode:b.PALETTE,action:()=>(th(),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 rh,sh=h(()=>{"use strict";ro();pn();pe();R();Io();ne();yt();ce();M();Jg();jn();eh();oh();ut();rh=[{intent:O.InitCommandLine,mode:b.DEFAULT,description:"[:] write command",action:()=>(N({mode:b.COMMAND_LINE}),te(""),l("Entering command line mode",null))},...Zg,...nh,{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 Xg(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 VE,KE,ih,ah=h(()=>{"use strict";ce();VE=500,KE=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),ih=e=>{let t=KE(e);t&&Ii(n=>(n+t).slice(0,VE))}});var YE,XE,dh,ch=h(()=>{"use strict";ah();pe();R();ce();M();jn();ac();YE=[b.COMMAND_LINE,b.PALETTE],XE=e=>[{intent:O.MoveCursorLeft,mode:e,action:()=>(xd(-1),l("Moving cursor left",null))},{intent:O.MoveCursorRight,mode:e,action:()=>(xd(1),l("Moving cursor right",null))},{intent:O.MoveCursorLeftOfWord,mode:e,action:()=>(Id("left"),l("Moving cursor left of word",null))},{intent:O.MoveCursorRightOfWord,mode:e,action:()=>(Id("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})=>(ih(n??""),l("Capturing input",null))},{intent:O.EraseInput,mode:e,action:()=>(Ep(),l("Erasing input",null))},{intent:O.EraseInputWord,mode:e,action:()=>(Sp(),l("Erasing input word",null))}],dh=[{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))},...YE.flatMap(XE),{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:()=>(Cp(),l("Getting last command from history",null))},{intent:O.GetNextCommandFromHistory,mode:b.COMMAND_LINE,action:()=>(Ap(),l("Getting next command from history",null))}]});var JE,lh,uh,mh=h(()=>{"use strict";JE=e=>{let t=/^\[(.+?)\]\s*(.+)$/.exec(e);return t?{keys:t[1]??"",label:t[2]??""}:null},lh=({keys:e})=>e.length===1?0:1,uh=(e,t)=>{let n=new Set;for(let o of e)o.mode!==t||!o.description||n.add(o.description);return[...n].map(JE).filter(o=>o!==null).sort((o,r)=>lh(o)-lh(r))}});function ph(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 fh=h(()=>{"use strict";R()});var gh,hh=h(()=>{"use strict";gh=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 QE}from"react";function uc(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=ph(t,r,o);if(d(u))return logger.error(u.message),u;let m=u.value,{context:p}=c,f=[...rh,...zg[p]??[],...dh],y=uh(f,n),I=gh(f),S=eS(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 kr(e){dc=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=uc(o);return d(r)?r:(Jt=r.value,lc(),l("State initialized",null))}function Ne(e){let t=g(),n=e(t);if(mo)return ds=n,Jt={...t,...n},l("State updated",null);let o=uc(n);return d(o)?a(o.message??"Unable to update state"):(Jt=o.value,lc(),l("State updated",null))}function au(e){if(mo)return l("Joined batch",e());mo=!0,ds=null;let t=()=>{let n=ds;if(mo=!1,ds=null,n===null)return null;let o=uc(n);return d(o)?a(o.message??"Unable to update state"):(Jt=o.value,lc(),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 ds=s,Jt={...o,...s},l("State updated",null)}var Jt,dc,cc,lc,ZE,g,ze,mo,ds,Vu,N,rt,eS,se,bn,It,M=h(()=>{"use strict";Vg();sh();ch();mh();nn();pe();R();ae();qa();fh();hh();cc=new Set,lc=()=>{for(let e of cc)e()},ZE=e=>(cc.add(e),()=>cc.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,ds=null;Vu=()=>mo,N=e=>Ne(t=>({...t,...e}));rt=()=>QE(ZE,g,g),eS=Wu,se=e=>g()?.renderedChildrenIndex[e]??[],bn=()=>dc?kr(dc):a("Cannot reset state: no initial workspace found"),It=()=>Jt!==void 0});var Ct,tS,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}`)},tS=(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(tS(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:xs,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 vh from"string-width";var nS,oS,mc,rS,sS,yh,bh,iS,aS,dS,cS,lS,nc,xh,is=h(()=>{"use strict";Ke();ne();M();pt();Ti();nS=(e,t)=>e+" ".repeat(Math.max(0,t-vh(e))),oS=(e,t)=>" ".repeat(Math.max(0,t-vh(e)))+e,mc=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`),rS=(e,t)=>t?e<t?"up":e>t?"down":null:null,sS=(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=rS(e.payload.rank,r.rank);if(s)return`Moved ${s} in ${o}`}return`Moved issue to ${o}`},yh=e=>`${Math.max(1,Math.round(e/1024))} KB`,bh=e=>E.getAttachment(e)?.name??"",iS=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(`(${yh(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=bh(e.payload.id);return t?`"${t}"`:""}default:return""}},aS=e=>{let t=Go(He(e));return Bn.gray(oS(t,8))},dS=12,cS=e=>nS(`${e}`,dS),lS=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}" (${yh(e.payload.bytes)})`;case"delete.issue.attachment":{let t=bh(e.payload.id);return t?`"${t}"`:""}default:return""}},nc=e=>[mc(e.action),lS(e)].filter(Boolean).join(" "),xh=(e,t)=>{let n=aS(e.id),o=cS(e.userName),r=Bn.dim("\u203A"),s=e.action==="move.node"?sS(e,t):[mc(e.action),iS(e)].filter(Boolean).join(" ");return`${o} ${n} ${r} ${s}`}});var Eh={};lr(Eh,{areVirtualNodesEnabled:()=>Os,createOrUpdateVirtualField:()=>cs,createOrUpdateVirtualFieldList:()=>pc,materializeTicketVirtualNodes:()=>_s,materializeVirtualNodes:()=>bS,setVirtualNodesEnabled:()=>yS});var uS,mS,pS,fS,gS,hS,cs,pc,_s,vS,Ih,yS,Os,bS,Na=h(()=>{"use strict";is();K();R();Io();ne();Gn();M();yo();Do();uS=e=>Le(e,"comments"),mS=e=>Le(e,"description"),pS=e=>Le(e,"assignees"),fS=e=>Le(e,"tags"),gS=e=>Le(e,"history"),hS=e=>Le(e,"attachments"),cs=({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)},pc=({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(!gr(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)},_s=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=cs({id:mS(e.id),name:ue.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(d(c))return c;let u=pc({id:pS(e.id),name:ue.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(d(u))return u;let m=pc({id:fS(e.id),name:ue.TAGS,parentNodeId:e.id,rank:o.value,readonly:!0});if(d(m))return m;let p=cs({id:uS(e.id),name:ue.COMMENTS,parentNodeId:e.id,rank:r.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(d(p))return p;let f=cs({id:hS(e.id),name:ue.ATTACHMENTS,parentNodeId:e.id,rank:s.value,value:"",readonly:!0,childRenderAxis:"vertical"});if(d(f))return f;let y=cs({id:gS(e.id),name:ue.HISTORY,parentNodeId:e.id,rank:i.value,value:vS(e),readonly:!0,childRenderAxis:"vertical"});return d(y)?y:l("Ticket virtual nodes materialized",void 0)},vS=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=>xh(o,n.get(o.action)??[])).join(`
|
|
93
|
-
`)},Ih=!0,yS=e=>{Ih=e},Os=()=>Ih,bS=()=>{let{nodes:e}=g();for(let t of Object.values(e)){if(!P(t))continue;let n=_s(t);if(d(n))return n}return l("Virtual nodes materialized",void 0)}});var xS,IS,qi,fc=h(()=>{"use strict";Ke();xS=e=>{switch(e.action){case"add.issue":case"move.node":case"close.issue":case"reopen.issue":return e.payload.parent;default:return null}},IS=(e,t)=>{let n=[];for(let o of e){let r=xS(o);if(r===null||r===n.at(-1)?.laneId)continue;let s=$n(o);n.push({laneId:r,enteredAt:s===null?t:pr(s)})}return n},qi=(e,t)=>IS(e,t).at(-1)?.enteredAt??t});var Sh=h(()=>{"use strict";R()});var ES,Rh,gc=h(()=>{"use strict";Ke();St();Eo();is();R();pt();ES=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)})},Rh=(e,t)=>{let n=ES(e);return e.filter((o,r)=>n[r]===t)}});var SS,Nh,Ah,RS,us,ls,Ch,NS,Yo,CS,wh,Xo=h(()=>{"use strict";Xe();ct();Je();Gd();St();ln();R();nn();gi();Sh();ae();M();gc();SS=null,Nh=Promise.resolve(),Ah=e=>{let t=Nh.then(e,e);return Nh=t.then(()=>{},()=>{}),t},RS=e=>{let t=Me(e??process.cwd());return d(t)?a(t.message):l("Resolved Epiq repo root",t.value)},us=()=>{if(!It())return{mode:"live",asOfTime:null};let{timeMode:e}=g();return e==="live"?{mode:"live",asOfTime:null}:{mode:"scrub",asOfTime:SS}},ls="",Ch="",NS=5e3,Yo=null,CS=async(e={})=>{let t=RS(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&&Yo&&Yo.repoRoot===t.value&&Yo.stateBranch===n.value.stateBranch&&Date.now()-Yo.fetchedAt<NS)return l("Computed commit timeline",Yo.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=${Ch}%H${ls}%at${ls}%an${ls}%s`]});if(d(r))return a(r.message);let s=r.value.stdout.split(Ch).filter(i=>i.trim().length>0).map(i=>{let[c,...u]=i.split(`
|
|
94
|
-
`),[m,p,f,...y]=(c??"").split(ls);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(ls),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&&(Yo={repoRoot:t.value,stateBranch:n.value.stateBranch,fetchedAt:Date.now(),result:s}),l("Computed commit timeline",s)},wh=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 CS({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 AS from"node:fs";var fo,Gi,Y,Q,X,xn=h(()=>{"use strict";Xe();ct();bo();Br();zt();to();Eo();ae();St();R();M();xt();Xo();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&&AS.existsSync(Wn(o.value)))){let p=await Ka({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(bu(o.value)===c&&It()&&us().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):(xu(o.value,c),l("Booted Epiq state",i))},Q=()=>{let e=Vr();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 Jo,Th,Qo,hc=h(()=>{"use strict";Ke();ne();pt();Jo=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)})),Th=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})),Qo=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 wS from"node:fs";import TS from"node:path";import{ulid as kh}from"ulid";var kS,Mh,vc,yc=h(()=>{"use strict";zt();Se();K();R();dt();Lo();xn();kS=e=>{if(e.filePath)try{return l("Read attachment file",{data:wS.readFileSync(e.filePath),name:e.name??TS.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")},Mh=()=>{let e=Vr();return d(e)?gn:e.value.attachmentMaxKb??gn},vc=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=kS(e);if(d(s))return s;let i=Jm(t.value.stateBranchRoot,s.value.data,Mh());if(d(i))return i;let c=fe(s.value.name).trim()||"image",u=kh(),m={id:kh(),...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=Po(i.value.hash,i.value.ext);return l("Added issue attachment",{id:u,issueId:e.issueId,fileName:f,bytes:i.value.bytes,markdown:md(c,f)})}});var bc,Eq,xc,Ph=h(()=>{"use strict";zt();Ke();dn();K();R();ne();wo();pt();fc();Je();dt();Lo();xt();Xo();xn();hc();yc();ti();Ce();Dr();bc=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})},Eq=365*24*60*60*1e3,xc=async(e={})=>{So();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)?(Ga(o.message),o):(no(),l("Synced",o.value))}});var ms,Zo,Ic,ps,Ec=h(()=>{"use strict";K();R();Je();xn();ms=e=>{let t=[...new Set([...e.issueIds??[],...e.issueId?[e.issueId]:[]])];return t.length?l("Resolved targets",t):a("Provide issueId or issueIds")},Zo=(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("; ")}`)},Ic=(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},ps=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 Rc(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||Jo(c).some(u=>Lh(u.name,e.tag))).filter(c=>!e.assignee||Qo(c).some(u=>Lh(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:Jo(c).map(u=>u.name),assignees:Qo(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:Jo(c),assignees:Qo(c)})))}async function Cc(e){let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=ms(e);if(d(o))return o;let r=s=>MS(s,n.value,t.value.stateBranchRoot);return e.issueIds?Zo("Closed",Ic(o.value,r)):r(o.value[0])}async function wc(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=ms(e);if(d(i))return i;let c=u=>PS(u,e,n.value,o.value);return e.issueIds?Zo("Moved",Ic(i.value,c)):c(i.value[0])}var Sc,Lh,Nc,MS,Ac,PS,Tc,kc,Dh=h(()=>{"use strict";Xe();Zd();Ke();to();St();Se();oc();dn();K();R();ne();yt();is();pt();hn();fc();Je();dt();xn();hc();Ec();Sc=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=>Ar(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:Jo(c),assignees:Qo(c),comments:Th(c.id)})},Lh=(e,t)=>e.trim().toLowerCase()===t.trim().toLowerCase();Nc=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})},MS=(e,t,n)=>{let o=ps(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)})};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("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})},PS=(e,t,n,o)=>{let r=ps(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})};Tc=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})},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.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 gs}from"ulid";var Mc,Pc,Lc,Dc,Fc,_c,Fh=h(()=>{"use strict";Xe();to();St();Se();dn();K();R();yt();hn();Je();dt();Xo();xn();Mc=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)},Pc=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)},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.boardId];if(!r)return a("Board not found");if(!hr(r))return a("Target parent must be a board");if(r.readonly)return a("Cannot add a swimlane to a readonly board");if(us().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=gs(),m={id:gs(),...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})},Dc=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:gs(),...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})},Fc=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:gs(),...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})},_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.nodes[e.swimlaneId];if(!r)return a("Swimlane not found");if(!Sn(r))return a("Delete target must be a swimlane");let s={id:gs(),...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 nr}from"ulid";async function Oc(e){let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=ms(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=ps(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(Zo("Tagged",i).message);let c=E.findTagByName(r),u=c?.id??nr(),m=[...c?[]:[{id:nr(),...n.value,action:"create.tag",payload:{id:u,name:r}}],...i.done.map(({id:I})=>({id:nr(),...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=Zo("Tagged",i);return d(y)?y:l(y.message,{...y.value,tag:f})}var Bc,Uc,$c,_h=h(()=>{"use strict";Se();K();R();ne();hn();Je();dt();xn();Ec();Bc=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:nr(),...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})},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.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:nr(),...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})},$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.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:nr(),...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 LS,Oh,jc,Bh,Hc,Wc,DS,qc,Gc,zc,Uh=h(()=>{"use strict";R();M();Ft();Un();St();Se();gc();K();pt();hn();Je();dt();xn();LS=()=>{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},Oh=(e,t)=>{let n=new Map(e);for(let o of Object.values(t))n.set(o.id,o.name);return n},jc=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})},Bh=async(e,t)=>{let n=Ba(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}},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=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 Bh(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=[...Oh(LS(),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}})},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;if(!o.value.contributors[e.contributorId])return a("Contributor not found");if(await Bh(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:xs})},DS=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},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.contributors[e.contributorId];if(!r)return a("Contributor not found");if(!r.tombstoned)return a("Contributor is not tombstoned");let s=await DS(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})},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=Jn(t.value.stateBranchRoot);if(d(r))return a(r.message);let s=e.boardId?Rh(r.value,e.boardId):r.value,i=new Map,c=new Set,u=new Set,m=Ba(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=[...Oh(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)},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.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 Vc,Kc,Yc,$h=h(()=>{"use strict";Se();K();R();hn();xn();Vc=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})},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.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})},Yc=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 jh=h(()=>{"use strict";Ph();Dh();Fh();_h();Uh();$h();yc()});import{ulid as FS}from"ulid";var Hh,Wh,qh,Gh=h(()=>{"use strict";Un();wo();zt();R();Kd();xt();Hh=[{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)"}],Wh=e=>e.trim().toLowerCase(),qh=async(e={})=>{let t=Mo();if(d(t))return a(t.message);let n=t.value,o=e.userName?.trim(),r=(process.env[gt]??"").trim();if(o&&r&&Wh(o)===Wh(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 Hh){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=FS()),Object.keys(c).length>0){let w=et(c);if(d(w))return a(w.message)}let u={...n,...c},m=Hh.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=Hr({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 _S,zh,Vh=h(()=>{"use strict";Yi();_S=e=>{let t=e.lastIndexOf("/");return t===-1?".":e.slice(0,t)},zh=({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=>_S(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,Xc,or,OS,$,Xi,Ji,Kh,BS,Yh,go,hs,US,$S,rr,jS,HS,WS,Lt,Xh,Jh,Qh,qS,GS,Zh,ev,sr=h(()=>{"use strict";Oe={line:["//"],block:[["/*","*/"]]},wt={line:["#"],block:[]},Xc={line:["--"],block:[]},or={line:[],block:[["<!--","-->"]]},OS={line:[],block:[]},$=(e,t)=>({name:e,comment:t}),Xi=$("TypeScript",Oe),Ji=$("JavaScript",Oe),Kh={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",Xc),hs:$("Haskell",Xc),sql:$("SQL",Xc),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",or),svelte:$("Svelte",or),html:$("HTML",or),xml:$("XML",or),md:$("Markdown",or),mdx:$("Markdown",or),css:$("CSS",{line:[],block:[["/*","*/"]]}),scss:$("CSS",Oe),less:$("CSS",Oe),yml:$("YAML",wt),yaml:$("YAML",wt),toml:$("TOML",wt),ini:$("INI",wt),json:$("JSON",OS)},BS="Other",Yh=e=>{let t=e.slice(e.lastIndexOf("/")+1),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()},go=e=>Kh[Yh(e)]?.name??BS,hs=e=>Kh[Yh(e)]?.comment??null,US=[/\.(test|spec)\.[a-z0-9]+$/i,/(^|\/)test_[^/]+\.py$/,/_test\.[a-z0-9]+$/i,/(^|\/)conftest\.py$/,/Tests?\.(java|kt|cs|scala)$/],$S=/(^|\/)(tests?|__tests__|spec|specs|e2e|src\/test|features)\//i,rr=e=>$S.test(e)||US.some(t=>t.test(e)),jS=/(^|\/)(package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|Cargo\.lock|go\.sum|poetry\.lock|Gemfile\.lock|composer\.lock)$/,HS=/(^|\/)(node_modules|dist|build|out|target|vendor|coverage|\.next|__snapshots__)\//,WS=/(\.min\.(js|css)|\.map|\.snap|\.pb\.go|_pb2\.py)$/,Lt=e=>jS.test(e)||HS.test(e)||WS.test(e),Xh=e=>/(^|\/)(package\.json|go\.mod|Cargo\.toml|requirements[^/]*\.txt|pyproject\.toml|Gemfile|composer\.json|pom\.xml|build\.gradle(\.kts)?)$/.test(e),Jh=e=>/(^|\/)\.github\/workflows\//.test(e)||/(^|\/)(Dockerfile|docker-compose[^/]*\.ya?ml|Makefile|Jenkinsfile|\.gitlab-ci\.yml)$/.test(e)||/\.tf$/.test(e),Qh=e=>/\.(md|mdx|rst|txt)$/i.test(e)||/(^|\/)docs?\//i.test(e),qS=/\b(it|test|describe|context|suite)\.skip\b|\bx(it|describe|test)\s*\(|@pytest\.mark\.skip|@unittest\.skip|\bt\.Skip\s*\(|@(Ignore|Disabled)\b/,GS=/\b(it|test|describe|context|suite)\.only\b|\bf(it|describe|test)\s*\(/,Zh=e=>qS.test(e),ev=e=>GS.test(e)});var tv,zS,Jc,VS,nv,Qc=h(()=>{"use strict";sr();tv=/\b(TODO|FIXME|HACK|XXX)\b/,zS=/[;{}]\s*$|^\s*(const|let|var|function|def|class|if|for|while|return|import|export|await|print)\b.*[=(]/,Jc=(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"},VS=(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},nv=({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=hs(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=Jc(S,f);if(tv.test(S)&&i++,A==="blank"){s++;continue}if(A==="comment"){o++,I.comment++,f&&zS.test(VS(S,f))&&u++;continue}r++,I.code++}for(let{text:S}of p.removedLines)tv.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 KS,Qi,Zc,YS,XS,JS,ov,rv=h(()=>{"use strict";sr();Yi();KS=/\bconsole\.(log|debug|dir)\s*\(|\bdebugger\b|^\s*print\s*\(|\bfmt\.Print(ln|f)?\s*\(|\bSystem\.out\.print|\bdbg!\s*\(/,Qi=6,Zc=10,YS=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)},XS=(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)},JS=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},ov=({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)),Xh(p.path)&&n.push(Zt(p)),Jh(p.path)&&o.push(Zt(p)),Qh(p.path)&&(r=!0),p.binary||Lt(p.path))continue;let f=p.added.map(S=>S.text),y=YS(f),I=p.status!=="deleted";for(let S of f){KS.test(S)&&s++;let A=XS(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,Zc),dependencyManifests:n.slice(0,Zc),buildOrCiPaths:o.slice(0,Zc),docsTouched:r,debugPrintLinesAdded:s,maxIndentLevels:i,deepestFile:c,duplicatedLines:JS(u)}}});var sv,iv=h(()=>{"use strict";sr();sv=({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,rr(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 QS,el,ZS,av,eR,tl,tR,nR,dv,cv,oR,rR,sR,lv,uv=h(()=>{"use strict";ct();R();QS=200,el=2e5,ZS=5e4,av=25,eR=64*1024*1024,tl="",tR=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/,nR=/^diff --git a\/(.+) b\/\1$/,dv=(e,t)=>e==="/dev/null"?null:e.startsWith(t)?e.slice(2):e,cv=(e,t)=>e===null?"added":t===null?"deleted":"modified",oR=()=>({byPath:new Map,insertions:0,deletions:0,selfChurn:0,retainedLines:0}),rR=(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
|
-
`))
|
|
97
|
-
`)){
|
|
98
|
-
`)){let k=Jc(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 fv,gv=h(()=>{"use strict";sr();Yi();fv=({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))&&rr(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)Zh(u)&&s++,ev(u)&&i++}return{testLinesAdded:t,testLinesRemoved:n,addedTestFiles:o,deletedTestFiles:r,skippedTestLinesAdded:s,focusedTestLinesAdded:i}}});var dR,hv,vv=h(()=>{"use strict";R();Vh();Qc();rv();iv();uv();pv();gv();dR=e=>e.reduce((t,n)=>t===null||n.time<t.time?n:t,null)?.sha??null,hv=async({repoRoot:e,ref:t,commits:n})=>{let o=await lv({repoRoot:e,shas:n.map(c=>c.sha)});if(d(o))return a(o.message);let r=o.value,s=dR(n),i=s?await mv({repoRoot:e,sha:s}):null;return l("Derived issue stats",{ref:t,shape:zh({commits:n,patch:r}),languages:sv({patch:r,languagesBefore:i?.languages??null}),tests:fv({patch:r}),comments:nv({patch:r,repoShareByLanguage:i?.commentShareByLanguage??null}),flags:ov({patch:r})})}});var cR,vs,lR,yv,bv=h(()=>{"use strict";R();vv();Je();ae();Xo();cR=32,vs=new Map,lR=(e,t)=>{if(vs.set(e,t),vs.size>cR){let n=vs.keys().next();n.done||vs.delete(n.value)}return t},yv=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 wh({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=vs.get(c);if(u)return l("Derived issue stats",u);let m=await hv({repoRoot:r,ref:n,commits:i});return d(m)?a(m.message):l("Derived issue stats",lR(c,m.value))}});var ir,nl,xv=h(()=>{"use strict";ir=".claude/skills/epiq/SKILL.md",nl="---\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 Iv from"node:path";var Ev,Sv=h(()=>{"use strict";Xe();R();xv();Ev=async(e={})=>{let t=await lt(e.repoRoot??process.cwd());if(d(t))return a(t.message);let n=Iv.join(t.value,ir);if(Zi.existsSync(n)){if(Zi.readFileSync(n,"utf8")===nl)return l("Skill already installed and up to date",{path:n,written:!1});if(!e.force)return a(`${ir} already exists and differs from the bundled skill. Pass force:true to overwrite it.`)}try{Zi.mkdirSync(Iv.dirname(n),{recursive:!0}),Zi.writeFileSync(n,nl,"utf8")}catch(o){return a(o instanceof Error?`Failed to write ${ir}: ${o.message}`:`Failed to write ${ir}`)}return l(`Installed skill at ${ir}`,{path:n,written:!0})}});var Nv={};lr(Nv,{createMcpServer:()=>Rv,resultJson:()=>ol,startMcpServer:()=>fR});import{McpServer as mR}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as pR}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as v}from"zod";var ol,Z,Rv,fR,Cv=h(()=>{"use strict";R();hn();jh();Gh();bv();Sv();Xo();ol=e=>({isError:d(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),Z=e=>t=>Ah(async()=>ol(await e(t))),Rv=()=>{let e=new mR({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(bc)),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(Rc)),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(Sc)),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=>ol(await yv(t))),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:v.object({repoRoot:v.string().optional()})},Z(Mc)),e.registerTool("epiq_swimlane_list",{description:"List Epiq swimlanes",inputSchema:v.object({repoRoot:v.string().optional(),boardId:v.string().optional()})},Z(Pc)),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(Lc)),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(Dc)),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(Fc)),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(_c)),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(Nc)),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(Tc)),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(kc)),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(Oc)),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($c)),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(Gc)),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(Wc)),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(Bc)),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(Uc)),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(qc)),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(Hc)),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(zc)),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(Vc)),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(vc)),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(Kc)),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(Yc)),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(Ac)),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(Cc)),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(wc)),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(jc)),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(qh)),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(Ev)),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(xc)),e},fR=async()=>{let e=Rv(),t=new pR;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:gR}=await Promise.resolve().then(()=>(Un(),ll)),{isFail:hR}=await Promise.resolve().then(()=>(R(),al)),{parseMcpArgs:vR}=await Promise.resolve().then(()=>(pl(),ml)),ar=vR(process.argv.slice(2));ar.kind==="error"&&(console.error(ar.message),process.exit(1));ar.kind==="print"&&(process.stdout.write(ar.text),process.exit(0));if(ar.kind==="name"){let e=gR(ar.name,"The name argument");hR(e)&&(console.error(e.message),process.exit(1))}var{setVirtualNodesEnabled:yR}=await Promise.resolve().then(()=>(Na(),Eh));yR(!1);var{startMcpServer:bR}=await Promise.resolve().then(()=>(Cv(),Nv));await bR();
|
|
93
|
+
`,oc.writeFileSync(t,n,"utf8"),X.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),l("Local epiq paths ignored",!0)}});import OE from"node:fs";import sc from"node:path";var UE,J,$i,jE,$E,ic=h(()=>{"use strict";Zf();_s();et();Qe();Xo();ur();Ce();sr();S();ie();Ht();rd();UE=async e=>{let t=await W({cwd:e,args:["status","--porcelain"]});return a(t)?t:l("Checked git diff",t.value.stdout.split(`
|
|
94
|
+
`).filter(n=>n.trim().length>0).map(n=>n.slice(3)))},J=(e,t)=>d(`[${e}] ${t}`),$i=async({cwd:e,user:t})=>{let n=Ls(),r=await gt(e);if(a(r))return J(1,r.message);let o=r.value,s=await Fs(o);if(a(s))return J(2,s.message);if(s.value)return J(2,`Cannot initialize Epiq while a git operation is in progress: ${s.value}`);let i=await UE(o);if(a(i))return J(2.5,i.message);if(i.value.length>0)return J(3,`Cannot initialize Epiq with uncommitted changes (${i.value.join(", ")}). Commit or stash your changes first.`);if(Oo(o))return J(4,"Epiq project already initialized");let{userId:c,userName:u}=t;if(!c||!u)return J(5,"Missing Epiq user id");let m=await Mm(o);if(a(m))return J(6,m.message);let p=n.stateBranch,f=await Bs({repoRoot:o,branch:p});if(a(f))return J(6,f.message);if(f.value)return J(6,`State branch already exists: ${p}`);let y=await jE({repoRoot:o,stateBranch:p});if(a(y))return J(6,y.message);if(y.value)return $E({repoRoot:o,stateBranch:p});let x=await sd({repoRoot:o,stateBranchName:p});if(a(x))return J(6,x.message);let R=Fo();if(a(R))return J(7,R.message);let A=sc.join(er(),n.projectId),w=await Pn({repoRoot:o,stateBranchRoot:A,stateBranchName:p});if(a(w))return J(8,w.message);let k=sc.join(A,".epiq");OE.mkdirSync(k,{recursive:!0});let L=ym({userId:c,userName:u});if(a(L))return J(9,L.message);for(let zv of L.value){let Rl=Qs({event:zv,rootDir:A});if(a(Rl))return J(9,Rl.message)}let D=cr({userId:c,userName:u}),U=Ks(A,D);if(a(U))return J(9,U.message);let de=nd(A,n);if(a(de))return J(9,de.message);let wn=await si({stateBranchRoot:A,eventFileName:D});if(a(wn))return J(10,wn.message);let on=await ue.stage({cwd:A,pathspec:[$e]});if(a(on))return J(10,on.message);let bo=await kr({cwd:A,message:"[epiq:init]"});if(a(bo))return J(10,bo.message);let Io=await Qf(o);if(a(Io))return J(11,Io.message);let xo=va({repoRoot:o,fileContents:n});if(a(xo))return J(12,xo.message);let bl=await ue.stage({cwd:o,pathspec:[".epiq/project.json",".gitignore"]});if(a(bl))return J(13,bl.message);let Il=await ue.commit({cwd:o,message:"[epiq:init-project]",pathspec:[".epiq/project.json",".gitignore"]});if(a(Il))return J(13,Il.message);let da=[],xl=await W({cwd:o,args:["push","-u","origin","HEAD"]});a(xl)&&da.push(`[init:14] ${xl.message}`);let El=await Yo({repoRoot:o,stateBranchRoot:A});return a(El)&&da.push(`[init:15] ${El.message}`),l("Project initialized",{repoRoot:o,projectId:n.projectId,stateBranch:p,stateBranchRoot:A,defaultEvents:L.value,warnings:da})},jE=async({repoRoot:e,stateBranch:t})=>{let n=await ln({repoRoot:e});if(a(n))return d(n.message);if(!n.value)return l("No remote",!1);let r=await Po({repoRoot:e,branch:t});return a(r)?d(`Could not ask origin whether ${t} exists: ${r.message}`):r},$E=async({repoRoot:e,stateBranch:t})=>{let n=await W({cwd:e,args:["fetch","origin",t]});if(a(n))return J(6,n.message);let r=await W({cwd:e,args:["show",`origin/${t}:${$e}`]});if(a(r))return J(6,[`This repository is already an epiq project: origin has the state branch ${t}.`,"Initialising again would mint a second id for the same board.","","The branch was written before branches carried their identity, so restore",`${$e} from a checkout that has it, for example:`,"",` git show origin/main:${$e} > ${$e}`,"","and commit it; every later boot then stamps the branch, and the next clone adopts it."].join(`
|
|
95
|
+
`));let o;try{o=JSON.parse(r.value.stdout)}catch(R){return J(6,`The identity on origin/${t} is not readable: ${R instanceof Error?R.message:String(R)}`)}let s=va({repoRoot:e,fileContents:o});if(a(s))return J(12,s.message);let i=await ue.stage({cwd:e,pathspec:[$e]});if(a(i))return J(13,i.message);let c=await ue.commit({cwd:e,message:"[epiq:adopt-project]",pathspec:[$e]});if(a(c))return J(13,c.message);let u=Fo();if(a(u))return J(7,u.message);let m=sc.join(er(),o.projectId),p=await Ko({repoRoot:e,stateBranchName:t});if(a(p))return J(8,p.message);let f=await Pn({repoRoot:e,stateBranchRoot:m,stateBranchName:t});if(a(f))return J(8,f.message);let y=[],x=await W({cwd:e,args:["push","-u","origin","HEAD"]});return a(x)&&y.push(`[init:14] ${x.message}`),l("Adopted the project origin already holds",{repoRoot:e,projectId:o.projectId,stateBranch:o.stateBranch,stateBranchRoot:m,defaultEvents:[],warnings:y})}});var hs,eg,tg=h(()=>{"use strict";ht();ts();pn();ve();S();ic();pe();ze();M();hs=(e,t)=>d(`[${e}] ${t}`),eg=async()=>{ne("");let e=gi();if(!e.isSetupDone||!e.userName)return hs(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let t=xe(),n=t.userName,r=t.userId;if(!r||!n)return hs(5,"Missing Epiq user id");let o=await $i({cwd:process.cwd(),user:{userId:r,userName:n}});if(a(o))return o;let s="Project initialized!";for(let y of o.value.warnings)s+=` Warn: ${y}`;let c=mn(o.value.defaultEvents).filter(a);if(c.length>0)return hs(16,c.map(y=>y.message).join(`
|
|
96
|
+
`));let u=Ye();if(a(u))return hs(16,u.message);let{rootNodeId:m,nodes:p}=u.value,f=p[m];return f?($.navigate({contextNode:f,selectedIndex:0}),N({hasProjectDefinition:!0,mode:b.DEFAULT}),l(s,null)):hs(16,"Unable to resolve initialized root node")}});import{ulid as WE}from"ulid";function dc(e){let t=rg();if(a(t))return t;let{contextNode:n,nodes:r}=g();if(!n.parentNodeId)return d("Missing parent node id");let o=r[n.parentNodeId];if(!o)return d("Missing parent node");let s=ye(o.id),i=s.findIndex(({id:m})=>m===n.id);if(i<0)return d("Current node not found among siblings");let c=s[i+e];if(!c)return d("Missing sibling node");let u=og({id:t.value.id,parentId:c.id,position:{at:"end"}});return a(u)?u:sg(u.value)}function cc(e){let t=rg();if(a(t))return t;let{contextNode:n,selectedIndex:r}=g(),s=ye(n.id)[r+e];if(!s)return d("Missing sibling node");let i=og({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return a(i)?i:sg(i.value)}var ng,jn,vs,rg,ac,og,sg,lc=h(()=>{"use strict";pn();Ce();S();Rt();M();ng=null,jn=()=>structuredClone(ng),vs=e=>{ng=e},rg=()=>{let{contextNode:e,selectedIndex:t}=g(),r=ye(e.id)[t];return r?l("Resolved selected child",r):d("Target node not found")},ac=({id:e,parentId:t,position:n={at:"end"}})=>{let r=ye(t).filter(o=>o.id!==e);return Zs(r,n)},og=({id:e,parentId:t,position:n={at:"end"}})=>{let r=oe();if(a(r))return d("Unable to resolve user ID");let o=ac({parentId:t,id:e,position:n});return a(o)?o:l("Created pending move state",{id:WE(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},sg=e=>{vs(e);let t=Tn(e,!0);return a(t)?t:l("Node moved successfully",t.value)}});import{ulid as HE}from"ulid";var ig,Wi,ag,dg=h(()=>{"use strict";ht();lc();Re();Ce();ve();S();Rt();pe();M();ie();ig=()=>{let e=jn();if(!e)return d("No pending move state");let t=e.payload.id,n=e.payload.parent,r=g().nodes[n];if(!r)return d("Move parent not found");let o=ye(n).findIndex(s=>s.id===t);return o===-1?d("Moved node not found among rendered children"):($.navigate({contextNode:r,selectedIndex:o}),l("Synchronized navigation to moved node",null))},Wi=(e,t="Moved preview")=>{if(a(e))return e;let n=ig();return a(n)?n:(N({mode:b.MOVE}),l(t,null))},ag=async()=>{let e=oe();if(a(e))return d("Unable to resolve user ID");let{modifier:t}=ce().commandMeta,{contextNode:n,selectedIndex:r}=g(),o=ye(n.id)[r];if(!o)return N({mode:b.DEFAULT}),d("No move target");if(t==="start"){if(o.readonly)return d("Target node is read-only");if(r===-1)return d("No item selected");if(!o.parentNodeId)return d("Target has no parent");let s=ye(o.parentNodeId),i=s.findIndex(({id:f})=>f===o.id);if(i===-1)return d("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=ac({parentId:o.parentNodeId,id:o.id,position:m});return a(p)?p:(vs({id:HE(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:p.value.rank},...e.value}),N({mode:b.MOVE}),l("Move initialized",null))}if(t==="next")return Wi(cc(1));if(t==="previous")return Wi(cc(-1));if(t==="to-next")return Wi(dc(1));if(t==="to-previous")return Wi(dc(-1));if(t==="confirm"){let s=jn();if(!s)return d("No pending move to confirm");let i=await zt();if(a(i))return i;let c=P([s],i.value);if(a(c))return c;let u=ig();return a(u)?u:(vs(null),N({mode:b.DEFAULT}),l("Moved item",null))}return t==="cancel"?(vs(null),N({mode:b.DEFAULT}),l("Cancelling move",null)):d("Invalid move modifier")}});import{monotonicFactory as qE,ulid as GE}from"ulid";var zE,Hi,uc=h(()=>{"use strict";S();zE=qE(),Hi=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let s=zE();return l("Created issue events",[{id:GE(),userId:r,userName:o,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])}});import{ulid as qi}from"ulid";var cg,lg=h(()=>{"use strict";ht();uc();Re();Ce();$t();S();re();Rt();M();ie();cg=async(e,t)=>{let n=oe();if(a(n))return d("Unable to resolve user ID");let r=await zt();if(a(r))return r;let o=r.value;if(!t.inputString)return d(`provide a name for your ${t.modifier}`);let{breadCrumb:s,contextNode:i,selectedIndex:c}=g(),u=m=>{let p=P([m],o);if(a(p))return p;let f=E.getNode(p.value[0].result.id);if(!f)return d("Created node not found");if(!f.parentNodeId)return p;let y=E.getNode(f.parentNodeId);return y?($.navigate({contextNode:y,selectedIndex:E.getSiblings(f.parentNodeId).findIndex(({id:x})=>x===f.id)}),p):d("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=g(),p=E.getNode(m);if(!p)return d("Workspace not found");let f=gn(p.id,n.value,o);return a(f)?f:u({id:qi(),action:"add.board",payload:{id:qi(),name:t.inputString,parent:p.id,rank:f.value},...n.value})}if(t.modifier==="swimlane"){let m=lt(s,"BOARD");if(a(m))return d("Unable to add swimlane in this context");let p=gn(m.value.id,n.value,o);return a(p)?p:u({id:qi(),action:"add.swimlane",payload:{id:qi(),name:t.inputString,parent:m.value.id,rank:p.value},...n.value})}if(t.modifier==="issue"){let m=ae(i.id)[c],p=i.context==="SWIMLANE"?i:i.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let L=lt(s,"SWIMLANE");return a(L)?null:L.value})();if(!p)return d("Unable to add issue in this context");let f=gn(p.id,n.value,o);if(a(f))return f;let y=Hi({name:t.inputString,parent:p.id,rank:f.value,user:n.value});if(a(y))return y;let x=y.value,R=P([...x],o);if(a(R))return R;if(!R.value[0])return d("Issue creation failed");let k=x.find(L=>L.action==="add.issue")?.payload.id;return k?($.navigate({contextNode:p,selectedIndex:E.getSiblings(p.id).findIndex(({id:L})=>L===k)}),l("Issue created",null)):d("Unable to determine ticket id")}return l("Success",null)}});var VE,ug,KE,mg,YE,pg,fg=h(()=>{"use strict";Zn();et();Qe();Xo();ui();dd();ci();Or();ur();wt();S();Ht();M();zo();ie();ri();VE=e=>e.some(t=>t.action==="init.workspace"),ug=async(e,t)=>{let n=qt(e);return a(n)?d(n.message):Do({cwd:t,branch:n.value})},KE=e=>{let t=Me(process.cwd());if(a(t))return!1;let n=Ie({repoRoot:t.value});return!a(n)&&n.value===e},mg=async e=>{let t=Ie({repoRoot:e});if(a(t))return Dr(3,t.message);let n=t.value,r=await Pn({repoRoot:e,stateBranchRoot:n,stateBranchName:Ls().stateBranch});if(a(r))return Dr(3,r.message);let o=Ct(n);if(a(o))return Dr(3,o.message);if(!VE(o.value.events)){let m=await ug(e,n);if(a(m)&&logger.info(3,m.message),o=Ct(n),a(o))return Dr(3,o.message)}let{events:s,unreadable:i}=o.value,c=Yt(s,i);if(a(c))return Dr(4,c.message);N({hasProjectDefinition:!0,hasInitializingEvents:!!s.length});let u=es({root:e});return a(u)&&logger.info(u.message),l("Loaded project",void 0)},YE=async e=>{let t=Ie({repoRoot:e});if(a(t))return d(t.message);let n=t.value,r=await ln({repoRoot:n});if(a(r))return d(r.message);if(!r.value)return l("No remote to pull",void 0);let o=await ai({worktreeRoot:n,operation:"boot pull",fn:()=>ld(n,()=>(Lr("Pulling"),ug(e,n)))});if(a(o))return Se(o.message);if(o.value===null)return l("Another process holds the state worktree",void 0);let s=o.value;if(a(s))return Lo(s.message)?(ni("Offline"),l("Offline",void 0)):Se(s.message);if(!s.value)return mr("Already synced"),l("Already synced",void 0);if(!KE(n))return l("Project changed during the pull",void 0);let i=ud(n);return a(i)?i:(mr("Pulled"),l("Pulled and reloaded",void 0))},pg=e=>{YE(e).then(t=>{a(t)&&logger.info(3,t.message)}).catch(t=>{logger.error(`[boot] pull failed: ${xm(t)}`)})}});import XE from"node:os";import gg from"node:path";var JE,QE,hg,vg=h(()=>{"use strict";fg();Or();S();pe();M();ie();JE=e=>e==="~"||e.startsWith("~/")?gg.join(XE.homedir(),e.slice(1)):e,QE=(e,t)=>{let n=e.trim();if(!n)return d("Provide a number from the list or a path to a project");if(/^\d+$/.test(n)){let o=t[Number(n)-1];return o?l("Resolved recent project",o.root):d(`No recent project #${n}`)}let r=Me(gg.resolve(JE(n)));return a(r)?d(`No epiq project at ${n}`):l("Resolved project path",r.value)},hg=async()=>{let e=ki();if(ne(""),g().hasProjectDefinition)return d("Already in a project; run epiq from another directory");let t=fi({exclude:process.cwd()}),n=a(t)?[]:t.value,r=QE(e,n);if(a(r))return d(r.message);let o=r.value,s=process.cwd();try{process.chdir(o)}catch(c){return d(`Unable to enter ${o}: ${c instanceof Error?c.message:String(c)}`)}let i=await mg(o);return a(i)?(process.chdir(s),d(i.message)):(pg(o),l(`Opened ${Vm(o)}`,null))}});var Gi,mc=h(()=>{"use strict";ht();wt();pn();S();M();Gi=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=g(),s=Ka(n,t);if(a(s))return d(s.message);let{appliedEvents:i,unappliedEvents:c}=s.value,u=Sn();if(a(u))return u;let m=mn(i),{fatal:p,skipped:f}=nr(m);if(p.length>0)return Sn(),N(o),d(p.map(x=>x.message).join(", "));rr(f);let y=g().nodes[e];return y?($.navigate({contextNode:y,selectedIndex:r}),l("",{unappliedEvents:c})):(Sn(),N(o),d("Board did not exist at that date"))}});var yg,bg=h(()=>{"use strict";yg=e=>{let t=[],n=0;for(let o=0;o<e.length;o++){let s=o===0?0:Math.max(0,e[o]-e[o-1]);n+=Math.sqrt(s),t[o]=n}let r=n;return t.map((o,s)=>r>0?o/r:(s+1)/e.length)}});var ZE,eR,tR,zi,Vi,br,Ig,xg,pc=h(()=>{"use strict";Je();ys();pn();ve();S();bg();M();ZE=20,eR=16,tR=150,zi=null,Vi=null,br=()=>{zi!==null&&(clearInterval(zi),zi=null),Vi!==null&&(clearTimeout(Vi),Vi=null)},Ig=()=>{br(),N({mode:b.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},xg=({events:e,startTime:t,durationMs:n})=>{br();let r=e.length,o=Co(e.map(f=>Vn(f))).map(f=>f??t),s=o[r-1]??Date.now(),i=yg(o),c=Math.max(1,Math.round(n*ZE/1e3)),u=Math.max(Math.round(n/c),eR),m=0,p=0;N({mode:b.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:r,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),zi=setInterval(()=>{m++;let f=m/c,y=[],x,R;for(;p<r&&i[p]<=f;){let w=e[p],k=Tn(w);if(a(k)){if($o(k)){p++;continue}Ig();return}y.push(...La(w)),x=w,R=o[p],p++}if(p>=r||m>=c){for(;p<r;p++){let k=Tn(e[p]);if(a(k)&&!$o(k))break}let w=g().replay;N({unappliedEvents:[],replay:w&&{...w,progress:1,appliedCount:r}}),br(),Vi=setTimeout(Ig,tR);return}let A=g().replay;N({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,f),appliedCount:p,totalCount:r,startTime:t,endTime:s,currentTime:x?R??A?.currentTime??t:A?.currentTime??t,currentLabel:x?fc(x):A?.currentLabel??"",flashNodeIds:x?[...new Set(y)]:A?.flashNodeIds??[]}})},u)}});var Eg,Rg=h(()=>{"use strict";et();Je();wt();pn();ve();$t();S();pe();M();rs();mc();pc();Eg=async()=>{let e=lt(g().breadCrumb,"BOARD");if(a(e))return e;let t=await gt(process.cwd());if(a(t))return d("Unable to locate repo root");let n=Ie({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=ce().commandMeta;if(br(),r==="now"){let c=ar(n.value);if(a(c))return d(c.message);let u=Sn();if(a(u))return u;let m=mn(c.value),{fatal:p,skipped:f}=nr(m);return p.length>0?d(p.map(y=>y.message).join(", ")):(rr(f),N({mode:b.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null}),l("Peeking now",!0))}let s;if(r==="prev"||r==="next"){let c=Ya(n.value);if(a(c))return c;let u=r==="prev"?g().eventLog.at(-1):g().unappliedEvents.at(0),m=u===void 0?null:Vn(u),p=(u===void 0?null:c.value.get(u.id)??null)??(m===null?null:No(m));if(p===null)return d(r==="prev"?"No previous event to peek":"No next event to peek");s=r==="prev"?p:p+1}else{let c=fr(r||o.trim());if(!c)return d("Invalid peek date");s=c.getTime()}let i=Gi({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return a(i)?i:(N({mode:b.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:i.value.unappliedEvents,replay:null}),l("Peeking",!0))}});var Sg,Ng=h(()=>{"use strict";et();$t();S();pe();M();rs();mc();pc();Sg=async()=>{let e=lt(g().breadCrumb,"BOARD");if(a(e))return e;let t=await gt(process.cwd());if(a(t))return d("Unable to locate repo root");let n=Ie({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=ce().commandMeta,{dateInput:s,durationInput:i}=Ii(r,o);if(br(),g().syncStatus.status==="syncing")return d("Cannot replay while syncing, try again in a moment");let c=fr(s);if(!c)return d("Invalid replay date");let u=i?bi(i):15e3;if(u===null)return d("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:y}=f.value;return y.length===0?(Sn(),N(p),l("Nothing to replay from that point",!0)):(xg({events:y,startTime:m,durationMs:u}),l("Replaying board history",!0))}});import{spawn as rR}from"node:child_process";var oR,Cg,wg=h(()=>{"use strict";S();oR=()=>{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"]}}},Cg=async e=>new Promise(t=>{let{command:n,args:r}=oR();try{let o=rR(n,r,{stdio:["pipe","ignore","ignore"]});o.on("error",()=>t(d(`Clipboard tool not available (${n})`))),o.on("close",s=>t(s===0?l("Copied to clipboard",null):d(`Clipboard tool failed (${n})`))),o.stdin.on("error",()=>{}),o.stdin.write(e),o.stdin.end()}catch{t(d(`Clipboard tool not available (${n})`))}})});var bs,Ag,Tg=h(()=>{"use strict";S();M();wg();tt();ns();yn();bs=async(e,t)=>{if(!e.trim())return d(`Nothing to copy: ${t} is empty`);let n=await Cg(e);return a(n)?n:l(`Copied ${t} to clipboard`,null)},Ag=async e=>{let{breadCrumb:t,selectedNode:n}=g(),r=os({breadCrumb:t,selectedNode:n}),o=r??n;if(!o)return d("Nothing selected to copy from");switch(e.modifier){case we.REF:return bs(j(o.id),"ref");case we.TITLE:return bs(o.title,"title");case we.DESCRIPTION:return r?bs(r.props?.description??"","description"):d("No issue in scope");case we.TAGS:{if(!r)return d("No issue in scope");let s=Ln(r).map(({name:i})=>i);return bs(s.join(", "),"tags")}case we.ASSIGNEES:{if(!r)return d("No issue in scope");let s=Dn(r).map(({name:i})=>i);return bs(s.join(", "),"assignees")}default:return d("Yank one of: ref, title, description, tags, assignees")}}});var kg,Mg=h(()=>{"use strict";ui();ve();S();pe();M();kg=async()=>{ne(""),N({mode:b.DEFAULT});let e=Ye();if(a(e))return d(e.message);if(e.value.syncStatus.status==="syncing")return d("Sync already in progress");N({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await li();return a(t)?(N({syncStatus:{msg:t.message,status:"failed"}}),t):(N({mode:b.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)}});var Fe,tn=h(()=>{"use strict";S();ie();Fe=async()=>{let e=await zt();return a(e)?e:l("Resolved persist root",e.value)}});import{ulid as Pg}from"ulid";var sR,Lg,Dg=h(()=>{"use strict";Re();Ce();ee();S();M();tn();sR=e=>e.action==="add.issue.comment",Lg=async()=>{let e=oe();if(a(e))return d("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=ae(t.id)[n];if(!r)return d("Unable to resolve child to delete");let o=await Fe();if(a(o))return o;if(r.context==="COMMENT"){let s=r.id,i=F(t)?t.id:t.parentNodeId;if(!i)return d("Unable to resolve comment issue");let c=g().nodes[i];if(!c||!F(c))return d("Unable to resolve comment issue");let u=c.log?.filter(sR).find(m=>m.payload.id===s);return u?u.payload.author!==e.value.userId?d("You can only delete your own comments"):P([{id:Pg(),action:"delete.issue.comment",payload:{id:s,issue:i},...e.value}],o.value):d("Unable to resolve comment")}return P([{id:Pg(),action:"delete.node",payload:{id:r.id},...e.value}],o.value)}});import{ulid as iR}from"ulid";var _g,Fg=h(()=>{"use strict";Re();Ce();Bt();ee();S();Rt();M();tn();_g=async()=>{let e=oe();if(a(e))return d("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=ae(t.id)[n];if(!r)return d("Unable to close issue, no target found");if(!F(r))return d("Cannot close in this context");let o=g().nodes[me];if(!o)return d("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return d("Issue is already closed");let s=await Fe();if(a(s))return s;let i=s.value,c=Vt(o.id,r.id,{at:"end"},e.value,i);if(a(c))return c;let u=P([{id:iR(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:c.value},...e.value}],i);return a(u)?u:l("Issue closed",null)}});var Ki,gc=h(()=>{"use strict";Ki=e=>{let t=e.log??[];for(let n=t.length-1;n>=0;n--){let r=t[n];if(r&&r.action==="close.issue"&&r.payload.id===e.id){for(let o=n-1;o>=0;o--){let s=t[o];if(s&&"id"in s.payload&&s.payload.id===e.id&&"parent"in s.payload&&s.payload.parent)return s.payload.parent}return null}}return null}});import{ulid as aR}from"ulid";var Bg,Og=h(()=>{"use strict";Re();Ce();gc();Bt();ee();S();re();Rt();M();tn();Bg=async()=>{let e=oe();if(a(e))return d("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=ae(t.id)[n];if(!r)return d("Unable to reopen issue, no target found");let o=r.context==="TICKET"?l("Resolved ticket",r):kt(r.id,"TICKET");if(a(o))return d("Cannot reopen in this context");let s=o.value,i=g().nodes[me];if(!i)return d("Unable to locate closed swimlane");if(s.parentNodeId!==i.id)return d("Issue is not closed");if(!F(s))return d("Target node is not issue");let c=Ki(s);if(!c)return d("Unable to resolve previous parent from issue history");if(c===i.id)return d("Previous parent resolves to closed swimlane");let u=g().nodes[c];if(!u)return d("Previous parent no longer exists");let m=await Fe();if(a(m))return m;let p=m.value,f=Vt(u.id,s.id,{at:"end"},e.value,p);if(a(f))return f;let y=P([{id:aR(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:f.value},...e.value}],p);return a(y)?y:l("Issue reopened",null)}});import{ulid as dR}from"ulid";var Ug,jg=h(()=>{"use strict";Re();Ce();S();pe();M();tn();Ug=async()=>{let e=oe();if(a(e))return d("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=ae(t.id)[n];if(!r)return d("Missing node");if(r.readonly)return d("Cannot rename readonly node");let o=ki();if(!o)return d("Provide a title");let s=await Fe();return a(s)?s:P([{id:dR(),action:"edit.title",payload:{id:r.id,name:o},...e.value}],s.value)}});import{ulid as cR}from"ulid";var $g,Wg=h(()=>{"use strict";re();Re();Ce();ee();S();pe();M();tn();$g=async()=>{let e=oe();if(a(e))return d("Unable to resolve user ID");let{modifier:t,inputString:n}=ce().commandMeta,r=(t||n).trim();if(!r)return d("Provide a tag");let o=E.findTagByName(r);if(!o)return d(`Tag "${r}" does not exist`);let{selectedNode:s}=g();if(!s)return d("Invalid untag target");let i=kt(s.id,"TICKET");if(a(i))return d("Unable to untag issue in this context");let c=i.value;if(!F(c))return d("Target node is not issue");if(!(c.props.tags??[]).includes(o.id))return d("Issue is not tagged with that tag");let m=await Fe();return a(m)?m:P([{id:cR(),action:"remove.issue.tag",payload:{id:c.id,tag:o.id},...e.value}],m.value)}});import{ulid as hc}from"ulid";var Hg,qg=h(()=>{"use strict";re();Re();Ce();ee();S();pe();M();tn();Hg=async()=>{let e=oe();if(a(e))return d("Unable to resolve user ID");let{modifier:t,inputString:n}=ce().commandMeta,r=(t||n).trim();if(!r)return d("Provide a tag");let{selectedNode:o}=g();if(!o)return d("Invalid tag target");let s=kt(o.id,"TICKET");if(a(s))return d("Unable to tag issue in this context");let i=s.value;if(!F(i))return d("Target node is not issue");let c=await Fe();if(a(c))return c;let u=E.findTagByName(r),m=u?.id??hc();return(i.props.tags??[]).includes(m)?d("Already tagged with that tag"):P([...u?[]:[{id:hc(),action:"create.tag",payload:{id:m,name:r},...e.value}],{id:hc(),action:"add.issue.tag",payload:{id:i.id,tag:m},...e.value}],c.value)}});var Yi,vc=h(()=>{"use strict";M();Yi=()=>{let{eventLog:e=[],contributors:t}=g(),n=new Map,r=new Set;for(let o of e)o.userId&&(n.set(o.userId,o.userName??""),r.add(o.userId));for(let o of Object.values(t))n.set(o.id,o.name);return[...n.entries()].map(([o,s])=>({id:o,name:s,isExternal:!r.has(o)}))}});import{ulid as yc}from"ulid";var Gg,zg=h(()=>{"use strict";Re();Ce();ee();S();re();pe();M();vc();tn();Gg=async()=>{let e=oe();if(a(e))return d("Unable to resolve user ID");let{modifier:t,inputString:n}=ce().commandMeta,r=(t||n).trim();if(!r)return d("Provide an assignee");let o=r.startsWith("!"),s=(o?r.slice(1):r).trim();if(!s)return d("Provide an assignee");let{selectedIndex:i,contextNode:c}=g(),u=ae(c.id)[i];if(!u)return d("Invalid assign target");let m=kt(u.id,"TICKET");if(a(m))return d("Unable to assign issue in this context");let p=m.value;if(!F(p))return d("Target node is not issue");let f=await Fe();if(a(f))return f;let y=Yi(),x=!o&&s.toLowerCase()==="me",R,A;if(x)R=e.value.userId,A=y.find(L=>L.id===R)?.name??e.value.userName;else{let L=y.filter(U=>U.name===s);if(L.length>1)return d(`"${s}" matches ${L.length} contributors (${L.map(U=>U.id).join(", ")}). Assign from the GUI to choose by id.`);let D=L[0];if(!D&&!o)return d(`No contributor named "${s}". Use "!${s}" to add them as an external assignee.`);R=D?.id??yc(),A=D?.name??s}if((p.props.assignees??[]).includes(R))return d("Assignee already assigned");let k=!!g().contributors[R];return P([...k?[]:[{id:yc(),action:"create.contributor",payload:{id:R,name:A},...e.value}],{id:yc(),action:"add.issue.assignee",payload:{id:p.id,assignee:R},...e.value}],f.value)}});import{ulid as lR}from"ulid";var Vg,Kg=h(()=>{"use strict";Re();Ce();ee();S();re();pe();M();vc();tn();Vg=async()=>{let e=oe();if(a(e))return d("Unable to resolve user ID");let{modifier:t,inputString:n}=ce().commandMeta,r=(t||n).trim();if(!r)return d("Provide an assignee to remove");let{selectedNode:o}=g();if(!o)return d("Invalid unassign target");let s=kt(o.id,"TICKET");if(a(s))return d("Unable to unassign in this context");let i=s.value;if(!F(i))return d("Target node is not issue");let c=i.props.assignees??[],u=r.toLowerCase()==="me",m=u?c.filter(y=>y===e.value.userId):Yi().filter(y=>y.name===r&&c.includes(y.id)).map(y=>y.id);if(m.length>1)return d(`"${r}" matches ${m.length} assignees (${m.join(", ")}). Unassign from the GUI to choose by id.`);let p=m[0];if(!p)return d(u?"Issue is not assigned to you":`Issue is not assigned to "${r}"`);let f=await Fe();return a(f)?f:P([{id:lR(),action:"remove.issue.assignee",payload:{id:i.id,assignee:p},...e.value}],f.value)}});import{ulid as Yg}from"ulid";var Xg,Jg=h(()=>{"use strict";Re();Ce();$t();ee();S();re();M();xn();tn();Xg=async e=>{let t=e.inputString.trim();if(!t)return d("Provide a comment");if(t.length>4e3)return d(`Cannot exceed ${4e3} characters`);let n=oe();if(a(n))return d("Unable to resolve user ID");let{breadCrumb:r,selectedNode:o}=g(),s=lt([...r,o],"TICKET");if(a(s))return d("Edit target must be an issue");let i=s.value;if(!i)return d("Invalid comment target");let c=i.context==="TICKET"?l("Resolved ticket",i):kt(i.id,"TICKET");if(a(c))return d("Unable to comment on issue in this context");let u=c.value;if(!F(u))return d("Target node is not issue");let m=await Fe();return a(m)?m:P([{id:Yg(),action:"add.issue.comment",payload:{id:Yg(),issue:u.id,author:n.value.userId,md:t},...n.value}],m.value)}});import uR from"zod";var Qg,Zg=h(()=>{"use strict";Qt();ve();S();pe();ze();M();Qg=()=>{let e=ce().commandMeta.inputString,t=uR.coerce.number().int().min(3e3).safeParse(e);if(!t.success)return d("Auto sync duration must be a number of at least 3000 ms");let n=ot({autoSyncDebounceMs:t.data});return a(n)?n:(xt({autoSyncIntervalMs:t.data}),N({mode:b.DEFAULT}),l(`Auto sync interval set to ${t.data}ms`,null))}});var eh,th=h(()=>{"use strict";ts();Qt();ve();S();pe();ze();M();eh=()=>{let e=ce().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return d("Invalid response");let t=Zm(e),n=ot({autoSync:t});return a(n)?n:(xt({autoSync:t}),N({mode:b.DEFAULT}),l(`Auto sync set to "${e}"`,null))}});var nh,rh=h(()=>{"use strict";Qt();ve();S();pe();ze();M();nh=()=>{let e=ce().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return d("Invalid response");let n=ot({logLevel:e});return a(n)?n:(xt({logLevel:e}),N({mode:b.DEFAULT}),l(`Auto sync set to "${e}"`,null))}});import{ulid as mR}from"ulid";var oh,sh=h(()=>{"use strict";zn();Qt();ve();S();ze();M();yn();Zg();Nd();th();rh();oh=e=>{let t=e.inputString.trim();switch(e.modifier){case be.USERNAME:{if(process.env[It])return d(`Cannot change the configured user while ${It} names this process`);let n=$r();if(a(n))return n;let{userId:r,preferredEditor:o,userName:s}=n.value,i=t||s,c=r||mR();if(!i||!c)return d("Unable to resolve user name or id");let u=ot({userName:i,userId:c,preferredEditor:o??""});return a(u)?u:(xt({userName:i,userId:c}),N({mode:b.DEFAULT}),l(`Username set to "${i}"`,null))}case be.EDITOR:{if(!t)return d("No editor provided");let n=ot({preferredEditor:t});return a(n)?n:(xt({preferredEditor:t}),N({mode:b.DEFAULT}),l(`Editor configuration set to "${t}"`,null))}case be.VIEW:{if(t!=="wide"&&t!=="dense")return d("Invalid view mode");let n=ot({viewMode:t});return a(n)?n:(xt({viewMode:t}),N({mode:b.DEFAULT}),l(`View set to "${t}"`,null))}case be.AUTOSYNC:return eh();case be.LOG_LEVEL:return nh();case be.SYNC_DEBOUNCE_MS:return Qg();case be.ATTACHMENT_MAX_KB:return vp();default:return d("Unknown config command")}}});var ih,ah=h(()=>{"use strict";qf();ht();ve();S();pe();M();ji();pr();Ld();yn();Jf();tg();dg();lg();vg();Rg();Ng();Tg();Mg();Dg();Fg();Og();jg();Wg();qg();zg();Kg();Jg();sh();ih=[{systemOnly:!0,intent:O.Move,description:"Internal move-state command",mode:b.COMMAND_LINE,action:ag},{intent:O.Delete,description:"Delete the currently selected node",mode:b.COMMAND_LINE,action:Lg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:O.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:b.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=ce().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(i=>Ae(I.FILTER).map(c=>c.split(n)[0]).includes(i))(r))return d("Invalid filter modifier");let s={target:r,operator:"=",value:t.trim()};return Ne(i=>({...i,filters:e==="clear"?[]:[...i.filters,s],mode:b.DEFAULT})),l("Filter updated",null)}},{intent:O.ViewHelp,description:"Open the help screen",mode:b.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=g();return Un({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),N({mode:b.HELP}),l("Viewing help",null)}},{intent:O.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:b.COMMAND_LINE,action:_g,onSuccess:()=>N({mode:b.DEFAULT})},{intent:O.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:b.COMMAND_LINE,action:Bg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:O.Init,description:"Initialize Epiq in the current git repository",mode:b.COMMAND_LINE,action:eg},{intent:O.OpenProject,description:"Open a recently used epiq project, by number or path",mode:b.COMMAND_LINE,action:hg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:O.NewItem,description:"Create a new board, swimlane, or issue",mode:b.COMMAND_LINE,action:cg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:O.Rename,description:"Rename the currently selected node",mode:b.COMMAND_LINE,action:Ug,onSuccess:()=>N({mode:b.DEFAULT})},{intent:O.UntagTicket,description:"Remove a tag from the selected issue",mode:b.COMMAND_LINE,action:$g,onSuccess:()=>N({mode:b.DEFAULT})},{intent:O.TagTicket,description:"Add or create a tag on the selected issue",mode:b.COMMAND_LINE,action:Hg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:O.AssignUserToTicket,description:"Assign a user to the selected issue",mode:b.COMMAND_LINE,action:Gg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:O.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:b.COMMAND_LINE,action:Vg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:O.Comment,description:"Add a comment to the selected issue",mode:b.COMMAND_LINE,action:async(e,t)=>Xg(t),onSuccess:()=>N({mode:b.DEFAULT})},{intent:O.Sync,description:"Pull, commit, and push Epiq state",mode:b.COMMAND_LINE,action:kg},{intent:O.Peek,description:"View board state at another point in time",mode:b.COMMAND_LINE,action:Eg},{intent:O.Replay,description:"Replay board history forward from a point in time",mode:b.COMMAND_LINE,action:Sg},{intent:O.Export,description:"Export the current board layout to markdown",mode:b.COMMAND_LINE,action:async()=>{let e=await Hf();return a(e)?e:(N({mode:b.DEFAULT}),l("Export successful",!0))}},{intent:O.Exit,description:"Exit the application",mode:b.COMMAND_LINE,action:async()=>($.exit(),l("Exit successful",!0))},{intent:O.Edit,description:"Edit title or description",mode:b.COMMAND_LINE,action:async(e,t)=>Xf(t),onSuccess:()=>N({mode:b.DEFAULT})},{intent:O.Yank,description:"Yank (copy) ref, title, description, tags, or assignees to the clipboard",mode:b.COMMAND_LINE,action:async(e,t)=>Ag(t),onSuccess:()=>N({mode:b.DEFAULT})},{intent:O.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:b.COMMAND_LINE,action:(e,t)=>oh(t)}]});var pR,nn,bc=h(()=>{"use strict";mi();Ci();Ld();ah();S();pe();ze();M();pR=new Set(["peek","replay","filter","view-help","yank"]),nn=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=ce();if(!t)return d("No command to confirm");if(!e&&n===_n.Invalid)return d("Invalid command");let s=Vp(t);Hp();let{readOnly:i}=g();if(i&&!pR.has(s))return cs({status:sn.Fail,message:"Command not available in readonly state",value:null});let c=ih.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!c)return cs({status:sn.Fail,message:"Command not found",value:null});let u;try{u=await c.action(c,{command:t,inputString:o,modifier:r})}catch(m){return cs({status:sn.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return a(u)?cs(u):(qp({addToHistory:!e}),c.onSuccess?.(),xe().autoSync&&qm(),u)}});var Xi,Ji,dh,ch=h(()=>{"use strict";S();ve();M();Xn();bc();lc();pe();Xi=[{intent:B.Exit,mode:b.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(N({mode:b.COMMAND_LINE}),ne("move cancel"),nn({isForceExecutedBySystem:!0}))},{intent:B.InitMove,mode:b.DEFAULT,description:"[m] move",action:()=>(N({mode:b.COMMAND_LINE}),ne("move start"),nn({isForceExecutedBySystem:!0}))},{intent:B.ConfirmMove,mode:b.MOVE,description:"[m] confirm move",action:()=>(N({mode:b.COMMAND_LINE}),ne("move confirm"),nn({isForceExecutedBySystem:!0}))}],Ji=[{intent:B.MovePreviousItem,mode:b.MOVE,action:()=>jn()?(N({mode:b.COMMAND_LINE}),ne("move previous"),nn({isForceExecutedBySystem:!0})):d("No pending move")},{intent:B.MoveNextItem,mode:b.MOVE,action:()=>jn()?(N({mode:b.COMMAND_LINE}),ne("move next"),nn({isForceExecutedBySystem:!0})):d("No pending move")}],dh=[{intent:B.MoveToNextContainer,mode:b.MOVE,action:()=>jn()?(N({mode:b.COMMAND_LINE}),ne("move to-next"),nn({isForceExecutedBySystem:!0})):d("No pending move")},{intent:B.MoveToPreviousContainer,mode:b.MOVE,action:()=>jn()?(N({mode:b.COMMAND_LINE}),ne("move to-previous"),nn({isForceExecutedBySystem:!0})):d("No pending move")}]});var lh,uh=h(()=>{"use strict";ee();ch();lh={[Y.WORKSPACE]:[...Xi,...Ji],[Y.BOARD]:[...Xi,...Ji],[Y.SWIMLANE]:[...Xi,...Ji,...dh],[Y.TICKET]:[],[Y.FIELD]:[],[Y.FIELD_LIST]:[],[Y.TEXT]:[],[Y.COMMENT]:[]}});import{spawn as fR}from"node:child_process";function mh(e){let t=process.platform,o=fR(t==="darwin"?"open":t==="win32"?"cmd":"xdg-open",t==="win32"?["/c","start","",e]:[e],{detached:!0,stdio:"ignore",shell:!1});return o.unref(),o.on("error",()=>{}),!0}var ph=h(()=>{"use strict"});import gR from"node:fs";import hR from"node:path";var fh,gh=h(()=>{"use strict";et();Hr();S();ie();ph();fh=e=>{let t=Me(process.cwd());if(a(t))return d("Unable to resolve project root");let n=Ie({repoRoot:t.value});if(a(n))return d(n.message);let r=Wr(e.hash,e.ext),o=hR.join(Us(n.value),r);return gR.existsSync(o)?(mh(o),l(`Opened ${e.name}`,null)):d("Attachment file not found \u2014 run :sync to fetch it")}});var hh,vh,yh=h(()=>{"use strict";ve();S();pe();M();ji();Xn();ht();hh=()=>{ne("");let{pendingNavTarget:e}=oo();N({mode:b.DEFAULT}),e&&$.navigate(e),Un({pendingNavTarget:void 0})},vh=[{intent:B.ExitCommandLine,mode:b.HELP,action:()=>(hh(),l("Exiting help",null))},{intent:B.Exit,mode:b.HELP,action:()=>(hh(),l("Closed help",null))},{intent:B.NavPreviousItem,mode:b.HELP,description:"[arrows/hjkl] navigate",action:()=>($.navigateToPreviousItem(),l("Navigating to previous help item",null))},{intent:B.NavNextItem,mode:b.HELP,action:()=>($.navigateToNextItem(),l("Navigating to next help item",null))},{intent:B.NavToPreviousContainer,mode:b.HELP,action:()=>($.navigateToPreviousContainer(),l("Navigating to previous help container",null))},{intent:B.NavToNextContainer,mode:b.HELP,action:()=>($.navigateToNextContainer(),l("Navigating to next help container",null))}]});var vR,bh,Ih,xh=h(()=>{"use strict";ve();ee();S();pe();M();ji();Xn();ht();vR=e=>{N({mode:b.COMMAND_LINE});let{pendingNavTarget:t}=oo();t&&$.navigate(t),Un({pendingNavTarget:void 0}),ne(`${e} `)},bh=()=>{ne("");let{pendingNavTarget:e}=oo();e&&$.navigate(e),Un({pendingNavTarget:void 0}),N({mode:b.DEFAULT})},Ih=[{intent:B.InitCommandPalette,mode:b.DEFAULT,description:"[?] command palette",action:()=>{ne("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=g();return Un({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),N({mode:b.PALETTE}),l("Opening command palette",null)}},{intent:B.Confirm,mode:b.PALETTE,action:()=>{let{selectedNode:e}=g();if(!e||!Dl(e))return d("Command only applicable on text nodes");if(e.props.disabled)return d("Command is not available in this context");let t=e.title;return t?(vR(t),l("Selected command",t)):l("No command selected",null)}},{intent:B.ExitCommandLine,mode:b.PALETTE,action:()=>(bh(),l("Exiting palette",null))},{intent:B.Exit,mode:b.PALETTE,action:()=>(bh(),l("Closed command palette",null))},{intent:B.NavPreviousItem,mode:b.PALETTE,description:"[arrows/hjkl] navigate",action:()=>($.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:B.NavNextItem,mode:b.PALETTE,action:()=>($.navigateToNextItem(),l("Navigating to next item",null))},{intent:B.NavToPreviousContainer,mode:b.PALETTE,action:()=>($.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:B.NavToNextContainer,mode:b.PALETTE,action:()=>($.navigateToNextContainer(),l("Navigating to next container",null))}]});var Eh,Rh=h(()=>{"use strict";pr();yn();ve();S();Mr();re();Rt();pe();M();gh();Xn();yh();xh();ht();Eh=[{intent:B.InitCommandLine,mode:b.DEFAULT,description:"[:] write command",action:()=>(N({mode:b.COMMAND_LINE}),ne(""),l("Entering command line mode",null))},...vh,...Ih,{intent:B.AddItem,mode:b.DEFAULT,description:"[n] new...",action:()=>(N({mode:b.COMMAND_LINE}),ne(`${I.NEW} `),l("Adding new item",null))},{intent:B.Delete,mode:b.DEFAULT,description:"[d] delete",action:()=>(N({mode:b.COMMAND_LINE}),ne(`${I.DELETE} `),l("Deleting item",null))},{intent:B.Confirm,mode:b.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=g();if(!ye(e?.id??"")?.length){let r=e?E.getAttachment(e.id):void 0;if(r)return fh(r);if(e?.title===ge.DESCRIPTION)return N({mode:b.COMMAND_LINE}),ne(`${I.EDIT} description `),l("Propose command",!0);if(e?.title===ge.ASSIGNEES)return N({mode:b.COMMAND_LINE}),ne(`${I.ASSIGN} `),l("Propose command",!0);if(e?.title===ge.TAGS)return N({mode:b.COMMAND_LINE}),ne(`${I.TAG} `),l("Propose command",!0);if(t.title===ge.DESCRIPTION&&e?.context==="TEXT")return N({mode:b.COMMAND_LINE}),ne(`${I.EDIT} description `),l("Propose command",!0)}return $.enterChildNode(),l("Entering context",null)}},{intent:B.Yank,mode:b.DEFAULT,description:"[y] yank",action:()=>{let{selectedNode:e}=g(),t=e?.title===ge.DESCRIPTION?we.DESCRIPTION:e?.title===ge.TAGS?we.TAGS:e?.title===ge.ASSIGNEES?we.ASSIGNEES:we.REF,r=Ae(I.YANK).includes(t)?t:we.REF;return N({mode:b.COMMAND_LINE}),ne(`${I.YANK} ${r}`),l("Propose command",!0)}},{intent:B.EditTitle,mode:b.DEFAULT,description:"[r] rename title",action:()=>(N({mode:b.COMMAND_LINE}),ne(`${I.EDIT} title ${g().selectedNode?.title}`),l("Exiting context",null))},{intent:B.EditDescription,mode:b.DEFAULT,description:"[e] edit desc",action:()=>(N({mode:b.COMMAND_LINE}),ne(`${I.EDIT} description `),l("Exiting context",null))},{intent:B.Exit,mode:b.DEFAULT,description:"[q] exit context",action:()=>($.enterParentNode(),l("Exiting context",null))},{intent:B.NavPreviousItem,mode:b.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>($.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:B.NavNextItem,mode:b.DEFAULT,action:()=>($.navigateToNextItem(),l("Navigating to next item",null))},{intent:B.NavToPreviousContainer,mode:b.DEFAULT,action:()=>($.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:B.NavToNextContainer,mode:b.DEFAULT,action:()=>($.navigateToNextContainer(),l("Navigating to next container",null))}]});var yR,bR,Sh,Nh=h(()=>{"use strict";pe();yR=500,bR=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Sh=e=>{let t=bR(e);t&&Ti(n=>(n+t).slice(0,yR))}});var IR,xR,Ch,wh=h(()=>{"use strict";Nh();ve();S();pe();M();Xn();bc();IR=[b.COMMAND_LINE,b.PALETTE],xR=e=>[{intent:B.MoveCursorLeft,mode:e,action:()=>(Md(-1),l("Moving cursor left",null))},{intent:B.MoveCursorRight,mode:e,action:()=>(Md(1),l("Moving cursor right",null))},{intent:B.MoveCursorLeftOfWord,mode:e,action:()=>(Pd("left"),l("Moving cursor left of word",null))},{intent:B.MoveCursorRightOfWord,mode:e,action:()=>(Pd("right"),l("Moving cursor right of word",null))},{intent:B.AutoCompleteCommand,mode:e,action:()=>(Ti((t,{remainder:n})=>{let r=n?t+n:t,o="";return r==="edit title "&&(o=g().selectedNode?.title??""),r+o}),l("Auto-completing command",null))},{intent:B.CaptureInput,mode:e,action:(t,{sequence:n})=>(Sh(n??""),l("Capturing input",null))},{intent:B.EraseInput,mode:e,action:()=>($p(),l("Erasing input",null))},{intent:B.EraseInputWord,mode:e,action:()=>(Wp(),l("Erasing input word",null))}],Ch=[{intent:B.Confirm,mode:b.COMMAND_LINE,action:()=>(nn(),l("Executing command",null))},{intent:B.ViewHelp,mode:b.DEFAULT,action:()=>(N({mode:b.HELP}),l("Viewing help",null))},...IR.flatMap(xR),{intent:B.ExitCommandLine,mode:b.COMMAND_LINE,action:()=>(N({mode:b.DEFAULT}),l("Exiting command line",null))},{intent:B.GetLastCommandFromHistory,mode:b.COMMAND_LINE,action:()=>(Gp(),l("Getting last command from history",null))},{intent:B.GetNextCommandFromHistory,mode:b.COMMAND_LINE,action:()=>(zp(),l("Getting next command from history",null))}]});var ER,Ah,Th,kh=h(()=>{"use strict";ER=e=>{let t=/^\[(.+?)\]\s*(.+)$/.exec(e);return t?{keys:t[1]??"",label:t[2]??""}:null},Ah=({keys:e})=>e.length===1?0:1,Th=(e,t)=>{let n=new Set;for(let r of e)r.mode!==t||!r.description||n.add(r.description);return[...n].map(ER).filter(r=>r!==null).sort((r,o)=>Ah(r)-Ah(o))}});function Mh(e,t,n){let r=t[e];if(!r)return d("buildBreadCrumb(): current node not found");let o=[],s=new Set,i=r;for(;i&&!s.has(i.id)&&(o.push(i),s.add(i.id),!(i.id===n||!i.parentNodeId));)i=t[i.parentNodeId];let c=o[o.length-1];return!c||c.id!==n?d("buildBreadCrumb(): node is not connected to root"):(o.reverse(),l("Breadcrumb built",o))}var Ph=h(()=>{"use strict";S()});var Lh,Dh=h(()=>{"use strict";Lh=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 RR}from"react";function Rc(e){let{contextNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:s}=e;if(!t)return d("derive(): contextNodeId is missing");if(!r)return d("derive(): rootNode is missing");if(!o[r])return d("derive(): unable to find root node");let c=o[t];if(!c)return d("Unable to derive state, contextNode not found");let u=Mh(t,o,r);if(a(u))return logger.error(u.message),u;let m=u.value,{context:p}=c,f=[...Eh,...lh[p]??[],...Ch],y=Th(f,n),x=Lh(f),R=NR(o,s),A=R[t]?.[e.selectedIndex]??null;return l("Derived successfully",{...e,contextNode:c,breadCrumb:m,availableHints:y,availableActions:f,actionIndex:x,selectedNode:A,renderedChildrenIndex:R})}function Wo(e){Ic=e;let t=Me(process.cwd()),n=!1;if(!a(t)){let s=pt(t.value);if(a(s))return d(s.message);n=!0}let r={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:{}},o=Rc(r);return a(o)?o:(Mt=o.value,Ec(),l("State initialized",null))}function Ne(e){let t=g(),n=e(t);if(Ir)return n.nodes!==t.nodes&&($n=null),Is=n,Mt={...t,...n},l("State updated",null);let r=Rc(n);return a(r)?d(r.message??"Unable to update state"):(Mt=r.value,Ec(),l("State updated",null))}function Ws(e){if(Ir)return l("Joined batch",e());Ir=!0,Is=null,$n=new Set;let t=()=>{let n=Is;if(Ir=!1,Is=null,n===null)return null;let r=Rc(n);return a(r)?d(r.message??"Unable to update state"):(Mt=r.value,Ec(),l("State updated",null))};try{let n=e(),r=t();return r&&a(r)?d(r.message):l("State updated",n)}finally{Ir&&t()}}function xr(e,t,n){if(!Ir)return Ne(i=>({...i,[e]:{...i[e]??{},[t]:n}}));let r=g(),o=r[e]??{};if(e==="nodes"){let i=o[t],c=n;i?.parentNodeId&&$n?.add(i.parentNodeId),c.parentNodeId&&$n?.add(c.parentNodeId)}o[t]=n;let s={...r,[e]:o};return Is=s,Mt={...r,...s},l("State updated",null)}var Mt,Ic,xc,Ec,SR,g,Ye,Ir,Is,cm,N,at,$n,_h,NR,ae,Sn,Nt,M=h(()=>{"use strict";uh();Rh();wh();kh();Ht();ve();S();ie();ed();Ph();Dh();xc=new Set,Ec=()=>{for(let e of xc)e()},SR=e=>(xc.add(e),()=>xc.delete(e));g=()=>{if(!Mt)throw new Error("State not initialized. Call initWorkspaceState() first.");return Mt},Ye=()=>Mt?l("Retrieved state",Mt):d("State not initialized. Call initWorkspaceState() first.");Ir=!1,Is=null;cm=()=>Ir,N=e=>Ne(t=>({...t,...e}));at=()=>RR(SR,g,g),$n=null,_h=null,NR=(e,t)=>{let n=Mt?.renderedChildrenIndex,r=n!==void 0&&$n!==null&&e===_h&&t.length===0&&Mt?.filters.length===0,o;if(r){o={...n};let s=sm(e,$n);for(let i of $n){let c=s[i];c?o[i]=c:delete o[i]}}else o=om(e,t);return _h=e,$n=new Set,o},ae=e=>g()?.renderedChildrenIndex[e]??[],Sn=()=>Ic?Wo(Ic):d("Cannot reset state: no initial workspace found"),Nt=()=>Mt!==void 0});var kt,CR,Wn,E,re=h(()=>{"use strict";$t();ee();S();M();Rt();kt=(e,t)=>{let{nodes:n}=g(),r=n[e];if(!r)return d("Node not found");if(r.context===t)return l("Resolved ancestor node",r);let o=new Set([r.id]),s=r.parentNodeId?n[r.parentNodeId]:void 0;for(;s&&!o.has(s.id);){if(s.context===t)return l("Resolved ancestor node",s);o.add(s.id),s=s.parentNodeId?n[s.parentNodeId]:void 0}return d(`No ancestor found for context: ${t}`)},CR=(e,t)=>{let{nodes:n}=g(),r=new Set,o=n[e];for(;o?.parentNodeId&&!r.has(o.id);){if(o.parentNodeId===t)return!0;r.add(o.id),o=n[o.parentNodeId]}return!1},Wn=(e,t)=>e?e.readonly?d({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node",delete:"Cannot delete readonly node"}[t]):null:d("Node not found"),E={linkUserId({contributorId:e,userId:t}){let n=this.getContributor(e);if(!n)return d("Contributor not found");if(n.userId&&n.userId!==t)return d("Contributor is already linked to another user");let r={...n,userId:t},o=Ne(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?d("Unable to link contributor to user"):l("Linked contributor to user",r)},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 d("Unable to create comment, missing issue");if(!F(t))return d("Can only comment on issues");let n=xr("comments",e.id,{...e,deleted:!1});return a(n)?d("Unable to create comment"):l("Created comment",{...e,deleted:!1})},editComment(e,t){let n=this.getComment(e);if(!n)return d("Unable to edit comment, missing comment");let r=this.getNode(n.issue);if(!r)return d("Unable to edit comment, missing issue");if(!F(r))return d("Can only edit issue comments");let o={...n,md:t,deleted:!1},s=xr("comments",e,o);return a(s)?d("Unable to edit comment"):l("Edited comment",o)},deleteComment(e){let t=this.getComment(e);if(!t)return d("Unable to delete comment, missing comment");let n={...t,deleted:!0},r=xr("comments",e,n);return a(r)?d("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 d("Unable to create attachment, missing issue");if(!F(t))return d("Can only attach to issues");let n=Ne(r=>({...r,attachments:{...r.attachments??{},[e.id]:{...e,deleted:!1}}}));return a(n)?d("Unable to create attachment"):l("Created attachment",{...e,deleted:!1})},deleteAttachment(e){let t=this.getAttachment(e);if(!t)return d("Unable to delete attachment, missing attachment");let n={...t,deleted:!0},r=Ne(o=>({...o,attachments:{...o.attachments??{},[e]:n}}));return a(r)?d("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(),r=n[e];if(!r)return d("Edit target node not found");let o=Wn(r,"edit");if(o)return o;let s={...r,props:{...r.props,description:t}};return this.updateNode(s),l("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return d("Rename target node not found");let r=Wn(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),l("Renamed node",o)},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 ye(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=g(),o=this.getNode(e),s=this.getNode(t);if(!o)return d("Node not found");if(!s)return d("Target parent not found");if(r===e)return d("Cannot move root node");if(e===t)return d("Cannot move node into itself");let i=Wn(o,"move");if(i)return i;if(CR(t,e))return d("Cannot move node into its own descendant");let c={...o,parentNodeId:t,rank:n};return this.updateNode(c),l("Moved node successfully",c)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:r}=g(),o=this.getNode(e);if(!o)return d("Node not found");if(r===e)return d("Cannot delete root node");let s=Wn(o,"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 ye(p.id))c(f.id)}};c(e);let u={...structuredClone(t)};for(let m of i){if(!u[m])return d("Unable to locate node to delete");u[m]={...u[m],isDeleted:!0}}return n?(N({nodes:u}),l("Successfully tomb stoned",o)):d("Unable to delete undefined")},tombstoneContributor(e){let t=this.getContributor(e);if(!t)return d("Contributor not found");let n={...t,name:Ts,tombstoned:!0},r=Ne(o=>({...o,contributors:{...o.contributors,[e]:n}}));return a(r)?d("Unable to remove contributor"):l("Tombstoned contributor",n)},renameContributor(e,t){let n=this.getContributor(e);if(!n)return d("Contributor not found");if(n.tombstoned)return d("Cannot rename a removed contributor");let r={...n,name:t},o=Ne(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?d("Unable to rename contributor"):l("Renamed contributor",r)},restoreContributor(e,t){let n=this.getContributor(e);if(!n)return d("Contributor not found");let r={...n,name:t,tombstoned:!1},o=Ne(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?d("Unable to restore contributor"):l("Restored contributor",r)},createContributor(e){let t=Ne(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return a(t)?d("Unable to create contributor"):l("Created contributor",e)},assign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return d("Unable to assign contributor, missing contributor");if(!r)return d("Unable to assign contributor, missing target");let o=Wn(r,"edit");if(o)return o;if(!F(r))return d("Target is not an issue");let s=r.props.assignees??[];if(s.includes(t))return d("Contributor already assigned");let i={...r,props:{...r.props,assignees:[...s,t]}};return this.updateNode(i),l("Assigned contributor",{assignee:t})},unassign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return d("Unable to unassign, missing contributor");if(!r)return d("Unable to unassign, missing target");let o=Wn(r,"edit");if(o)return o;if(!F(r))return d("Target is not an issue");let s=r.props.assignees??[];if(!s.includes(t))return l("Issue is not assigned to that contributor",{assignee:t});let i={...r,props:{...r.props,assignees:s.filter(c=>c!==t)}};return this.updateNode(i),l("Assignee removed",{assignee:t})},tag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return d("Unable to add tag, missing tag");if(!r)return d("Unable to add tag, missing target");let o=Wn(r,"edit");if(o)return o;if(!F(r))return d("Target is not an issue");let s=r.props.tags??[];if(s.includes(t))return d("Tag already assigned");let i={...r,props:{...r.props,tags:[...s,t]}};return this.updateNode(i),l("Tag added",{tag:t})},untag(e,t){let n=this.getTagRecord(t),r=this.getNode(e);if(!n)return d("Unable to remove tag, missing tag");if(!r)return d("Unable to remove tag, missing target");let o=Wn(r,"edit");if(o)return o;if(!F(r))return d("Target is not an issue");let s=r.props.tags??[];if(!s.includes(t))return l("Issue is not tagged with that tag",{tag:t});let i={...r,props:{...r.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 d("Tag not found");let n={...t,tombstoned:!0},r=Ne(o=>({...o,tags:{...o.tags,[e]:n}}));return a(r)?d("Unable to delete tag"):l("Tombstoned tag",n)},restoreTag(e,t){let n=this.getTagRecord(e);if(!n)return d("Tag not found");let r={...n,name:t,tombstoned:!1},o=Ne(s=>({...s,tags:{...s.tags,[e]:r}}));return a(o)?d("Unable to restore tag"):l("Restored tag",r)},createTag(e){let t=Ne(n=>({...n,tags:{...n.tags,[e.id]:e}}));return a(t)?d("Could not create tag"):l("Tag created",e)},createNode(e){let t=xr("nodes",e.id,e);return a(t)?d("Unable to create node"):l("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return d("Failed to locate node");let n={...t,readonly:!0},r=xr("nodes",e,n);return a(r)?d(r.message):l("Locked node",n)},updateNode(e){let t=xr("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 ye(e)}}});import Hn from"chalk";import Fh from"string-width";var wR,AR,Sc,TR,kR,Bh,Oh,MR,PR,LR,DR,_R,fc,Uh,ys=h(()=>{"use strict";Je();re();M();yt();Bi();wR=(e,t)=>e+" ".repeat(Math.max(0,t-Fh(e))),AR=(e,t)=>" ".repeat(Math.max(0,t-Fh(e)))+e,Sc=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`),TR=(e,t)=>t?e<t?"up":e>t?"down":null:null,kR=(e,t)=>{let n=E.getNode(e.payload.parent),r=n?Hn.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=TR(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},Bh=e=>`${Math.max(1,Math.round(e/1024))} KB`,Oh=e=>E.getAttachment(e)?.name??"",MR=e=>{switch(e.action){case"add.issue.tag":{let t=g().tags[e.payload.tag];return t?Hn.bgHex(Te(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=g().tags[e.payload.tag];return t?Hn.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?Hn.hex(Te(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?Hn.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}" ${Hn.dim(`(${Bh(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=Oh(e.payload.id);return t?`"${t}"`:""}default:return""}},PR=e=>{let t=to(Ge(e));return Hn.gray(AR(t,8))},LR=12,DR=e=>wR(`${e}`,LR),_R=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}" (${Bh(e.payload.bytes)})`;case"delete.issue.attachment":{let t=Oh(e.payload.id);return t?`"${t}"`:""}default:return""}},fc=e=>[Sc(e.action),_R(e)].filter(Boolean).join(" "),Uh=(e,t)=>{let n=PR(e.id),r=DR(e.userName),o=Hn.dim("\u203A"),s=e.action==="move.node"?kR(e,t):[Sc(e.action),MR(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`}});var $h={};Eo($h,{areVirtualNodesEnabled:()=>qs,createOrUpdateVirtualField:()=>xs,createOrUpdateVirtualFieldList:()=>Nc,materializeTicketVirtualNodes:()=>Hs,materializeVirtualNodes:()=>qR,setVirtualNodesEnabled:()=>HR});var FR,BR,OR,UR,jR,$R,xs,Nc,Hs,WR,jh,HR,qs,qR,Da=h(()=>{"use strict";ys();ee();S();Mr();re();tr();M();wr();qr();FR=e=>Le(e,"comments"),BR=e=>Le(e,"description"),OR=e=>Le(e,"assignees"),UR=e=>Le(e,"tags"),jR=e=>Le(e,"history"),$R=e=>Le(e,"attachments"),xs=({id:e,name:t,parentNodeId:n,rank:r,value:o,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:r,props:{value:o},isVirtual:!0}),readonly:s,childRenderAxis:i});return a(p)?p:l("Virtual field created",void 0)}if(!ut(c))return d(`Existing virtual node ${e} is not a field`);if(!(c.title!==t||c.parentNodeId!==n||c.rank!==r||c.props.value!==o||c.readonly!==s||c.childRenderAxis!==i))return l("Virtual field unchanged",void 0);let m=E.updateNode({...c,title:t,parentNodeId:n,rank:r,props:{...c.props,value:o},readonly:s,childRenderAxis:i});return a(m)?m:l("Virtual field updated",void 0)},Nc=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:s="horizontal"})=>{let i=E.getNode(e);if(!i){let m=E.createNode({...Pe.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:s});return a(m)?m:l("Virtual field list created",void 0)}if(!wo(i))return d(`Existing virtual node ${e} is not a field list`);if(!(i.title!==t||i.parentNodeId!==n||i.rank!==r||i.readonly!==o||i.childRenderAxis!==s))return l("Virtual field list unchanged",void 0);let u=E.updateNode({...i,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:s});return a(u)?u:l("Virtual field list updated",void 0)},Hs=e=>{let t=Et(Wt/4n),n=Et(Wt/2n),r=Et(Wt*3n/4n),o=Et(Wt*7n/8n),s=Et(Wt*15n/16n),i=Et(Wt*13n/16n);if(a(t))return t;if(a(n))return n;if(a(r))return r;if(a(o))return o;if(a(s))return s;if(a(i))return i;let c=xs({id:BR(e.id),name:ge.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(a(c))return c;let u=Nc({id:OR(e.id),name:ge.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(a(u))return u;let m=Nc({id:UR(e.id),name:ge.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0});if(a(m))return m;let p=xs({id:FR(e.id),name:ge.COMMENTS,parentNodeId:e.id,rank:o.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(a(p))return p;let f=xs({id:$R(e.id),name:ge.ATTACHMENTS,parentNodeId:e.id,rank:s.value,value:"",readonly:!0,childRenderAxis:"vertical"});if(a(f))return f;let y=xs({id:jR(e.id),name:ge.HISTORY,parentNodeId:e.id,rank:i.value,value:WR(e),readonly:!0,childRenderAxis:"vertical"});return a(y)?y:l("Ticket virtual nodes materialized",void 0)},WR=e=>{let t=[...e.log].reverse(),n=new Map;for(let r of t){let o=n.get(r.action)??[];o.push(r.payload),n.set(r.action,o)}return t.map(r=>Uh(r,n.get(r.action)??[])).join(`
|
|
97
|
+
`)},jh=!0,HR=e=>{jh=e},qs=()=>jh,qR=()=>{let{nodes:e}=g();for(let t of Object.values(e)){if(!F(t))continue;let n=Hs(t);if(a(n))return n}return l("Virtual nodes materialized",void 0)}});var GR,zR,Qi,Cc=h(()=>{"use strict";Je();GR=e=>{switch(e.action){case"add.issue":case"move.node":case"close.issue":case"reopen.issue":return e.payload.parent;default:return null}},zR=(e,t)=>{let n=[];for(let r of e){let o=GR(r);if(o===null||o===n.at(-1)?.laneId)continue;let s=Vn(r);n.push({laneId:o,enteredAt:s===null?t:No(s)})}return n},Qi=(e,t)=>zR(e,t).at(-1)?.enteredAt??t});var Wh=h(()=>{"use strict";S()});var VR,Hh,wc=h(()=>{"use strict";Je();wt();Pr();ys();S();yt();Bt();VR=e=>{let t=new Map,n=new Set,r=o=>{let s=new Set,i=o;for(;i&&!s.has(i);){if(n.has(i))return i;s.add(i),i=t.get(i)}return null};return e.map(o=>{let s=o.payload,i=s?.id;if(!i)return null;o.action==="add.board"&&n.add(i);let c=o.action==="close.issue"?r(i):null,u=s.parent??s.issue;return u&&t.set(i,u),c!==null?c:n.has(i)?i:r(i)})},Hh=(e,t)=>{let n=VR(e);return e.filter((r,o)=>n[o]===t)}});var KR,qh,zh,YR,Er,Es,Gh,XR,so,JR,Vh,io=h(()=>{"use strict";et();Qe();tt();nc();wt();pn();S();Ht();Ri();Wh();ie();M();Bt();wc();KR=null,qh=Promise.resolve(),zh=e=>{let t=qh.then(e,e);return qh=t.then(()=>{},()=>{}),t},YR=e=>{let t=Me(e??process.cwd());return a(t)?d(t.message):l("Resolved Epiq repo root",t.value)},Er=()=>{if(!Nt())return{mode:"live",asOfTime:null};let{timeMode:e}=g();return e==="live"?{mode:"live",asOfTime:null}:{mode:"scrub",asOfTime:KR}},Es="",Gh="",XR=5e3,so=null,JR=async(e={})=>{let t=YR(e.repoRoot);if(a(t))return d(t.message);let n=pt(t.value);if(a(n))return d(n.message);let r=e.start===void 0&&e.end===void 0;if(r&&so&&so.repoRoot===t.value&&so.stateBranch===n.value.stateBranch&&Date.now()-so.fetchedAt<XR)return l("Computed commit timeline",so.result);let o=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=${Gh}%H${Es}%at${Es}%an${Es}%s`]});if(a(o))return d(o.message);let s=o.value.stdout.split(Gh).filter(i=>i.trim().length>0).map(i=>{let[c,...u]=i.split(`
|
|
98
|
+
`),[m,p,f,...y]=(c??"").split(Es);if(!m||!p)return null;let x=u.join(" "),R=Number(/(\d+) insertion/.exec(x)?.[1]??0),A=Number(/(\d+) deletion/.exec(x)?.[1]??0);return{sha:m,time:Number(p)*1e3,author:f??"unknown",subject:y.join(Es),linesChanged:R+A,insertions:R,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 r&&(so={repoRoot:t.value,stateBranch:n.value.stateBranch,fetchedAt:Date.now(),result:s}),l("Computed commit timeline",s)},Vh=async e=>{let t=e.ref.trim();if(!t)return d("ref must not be empty");if(t.length!==7)return d(`"${t}" is ${t.length} characters; a ref is ${7}. Read it off the issue rather than slicing the id by hand.`);let n=await JR({repoRoot:e.repoRoot});if(a(n))return d(n.message);let r=`${t.toUpperCase()} `,o=c=>c.subject.toUpperCase().startsWith(r),s=n.value,i=[];for(let[c,u]of s.entries()){if(!o(u))continue;let m=s[c+1];i.push({...u,precedingSha:m&&o(m)?m.sha:null})}return l("Matched commits by ref",i)}});import QR from"node:fs";var Rr,Zi,K,Q,z,Nn=h(()=>{"use strict";et();Qe();Zn();Xo();Qt();ur();Pr();ie();wt();S();M();St();io();Rr=e=>{let t=Me(e??process.cwd());return a(t)?d(t.message):l("Resolved Epiq repo root",t.value)},Zi=null,K=async(e,t)=>{let n=Rr(e);if(a(n))return n;let r=Ie({repoRoot:n.value});if(a(r))return d(r.message);let o=qt(n.value);if(a(o))return d(o.message);if(!(Zi!==null&&Zi.repoRoot===n.value&&Zi.stateBranchRoot===r.value&&QR.existsSync(Qn(r.value)))){let p=await Ko({repoRoot:n.value,stateBranchName:o.value});if(a(p))return d(p.message);let f=await Pn({repoRoot:n.value,stateBranchRoot:r.value,stateBranchName:o.value});if(a(f))return d(f.message);Zi={repoRoot:n.value,stateBranchRoot:r.value}}if(t?.pull??!1){let p=await W({cwd:r.value,args:["pull","--ff-only"]});a(p)&&X.info(3,p.message)}let i={repoRoot:n.value,stateBranchRoot:r.value},c=ir(r.value);if(Du(r.value)===c&&Nt()&&Er().mode==="live")return l("Booted Epiq state, unchanged",i);let u=Ct(r.value);if(a(u))return d(u.message);let m=Yt(u.value.events,u.value.unreadable);return a(m)?d(m.message):(_u(r.value,c),l("Booted Epiq state",i))},Q=()=>{let e=ss();return a(e)?d(e.message):e.value.userId?e.value.userName?l("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):d("Unable to retrieve user name"):d("Unable to retrieve user id")},z=()=>{let e=Ye();return a(e)?d(e.message):e}});var ao,Kh,co,Ac=h(()=>{"use strict";Je();re();yt();ao=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)})),Kh=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:Ge(t.id),body:t.md})),co=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)}))});var je,qn,Tc,Sr=h(()=>{"use strict";ee();S();Nn();je=e=>{let t=z();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?d("Issue not found"):F(n)?n.readonly?d("Issue is readonly"):l("Found issue",n):d("Target must be an issue")},qn=e=>{let t=z();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?d("Swimlane not found"):Kn(n)?n.readonly?d("Swimlane is readonly"):l("Found swimlane",n):d("Target must be a swimlane")},Tc=e=>{let t=z();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?d("Board not found"):Yn(n)?n.readonly?d("Board is readonly"):l("Found board",n):d("Target must be a board")}});import ZR from"node:fs";import eS from"node:path";import{ulid as Yh}from"ulid";var tS,Xh,kc,Mc=h(()=>{"use strict";Qt();Re();S();mt();Sr();Hr();Nn();tS=e=>{if(e.filePath)try{return l("Read attachment file",{data:ZR.readFileSync(e.filePath),name:e.name??eS.basename(e.filePath)})}catch(t){return d(`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"}):d("Provide either filePath or dataBase64")},Xh=()=>{let e=ss();return a(e)?In:e.value.attachmentMaxKb??In},kc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=je(e.issueId);if(a(o))return o;let s=tS(e);if(a(s))return s;let i=hp(t.value.stateBranchRoot,s.value.data,Xh());if(a(i))return i;let c=le(s.value.name).trim()||"image",u=Yh(),m={id:Yh(),...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=P([m],t.value.stateBranchRoot);if(a(p))return d(p.message);let f=Wr(i.value.hash,i.value.ext);return l("Added issue attachment",{id:u,issueId:e.issueId,fileName:f,bytes:i.value.bytes,markdown:Rd(c,f)})}});var Pc,vG,Lc,Jh=h(()=>{"use strict";Qt();Je();Bt();ee();S();re();Or();yt();Cc();tt();mt();Hr();St();io();Nn();Ac();Mc();ci();Ce();zo();Pc=async(e={})=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=z();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})},vG=365*24*60*60*1e3,Lc=async(e={})=>{Lr();let t=Rr(e.repoRoot);if(a(t))return d("Sync failed");let n=Q();if(a(n))return n;let r=await di({cwd:t.value,ownEventFileName:cr(n.value)});return a(r)?(td(r.message),r):(mr(),l("Synced",r.value))}});var Rs,lo,Dc,_c=h(()=>{"use strict";S();tt();Rs=e=>{let t=[...new Set([...e.issueIds??[],...e.issueId?[e.issueId]:[]])];return t.length?l("Resolved targets",t):d("Provide issueId or issueIds")},lo=(e,t)=>{let n=t.done.length,r=`${e} ${n} issue${n===1?"":"s"}`+(t.failed.length?`, ${t.failed.length} failed`:"");return n?l(r,t):d(`${r}: ${t.failed.map(o=>`${o.ref} ${o.reason}`).join("; ")}`)},Dc=(e,t)=>{let n={done:[],failed:[]};for(let r of e){let o=t(r);a(o)?n.failed.push({id:r,ref:j(r),reason:o.message}):n.done.push({id:r,ref:j(r)})}return n}});import{ulid as Pt}from"ulid";async function Bc(e){let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=z();if(a(n))return n;let r=n.value.nodes,o=e.query?.trim().toLowerCase(),s=Object.values(r).filter(F).filter(c=>!c.isDeleted).filter(c=>e.includeClosed||c.parentNodeId!==me).filter(c=>e.boardId?(c.parentNodeId?r[c.parentNodeId]:void 0)?.parentNodeId===e.boardId:!0).filter(c=>!e.swimlaneId||c.parentNodeId===e.swimlaneId).filter(c=>!e.tag||ao(c).some(u=>Qh(u.name,e.tag))).filter(c=>!e.assignee||co(c).some(u=>Qh(u.name,e.assignee))).filter(c=>!o||c.title.toLowerCase().includes(o)||(c.props.description??"").toLowerCase().includes(o)),i=c=>le((c.parentNodeId?r[c.parentNodeId]?.title:void 0)??"");return e.brief?l("Listed issues",s.map(c=>({id:c.id,ref:j(c.id),title:le(c.title),swimlane:i(c),tags:ao(c).map(u=>u.name),assignees:co(c).map(u=>u.name)}))):l("Listed issues",s.map(c=>({id:c.id,ref:j(c.id),title:le(c.title),description:c.props.description??"",createdAt:Ge(c.id),enteredLaneAt:Qi(c.log??[],Ge(c.id)),parentNodeId:c.parentNodeId,isClosed:c.parentNodeId===me,readonly:!!c.readonly,tags:ao(c),assignees:co(c)})))}async function Uc(e){let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=Rs(e);if(a(r))return r;let o=s=>nS(s,n.value,t.value.stateBranchRoot);return e.issueIds?lo("Closed",Dc(r.value,o)):o(r.value[0])}async function $c(e){let t=Rr(e.repoRoot);if(a(t))return t;let n=Q();if(a(n))return n;let r=Ie({repoRoot:t.value});if(a(r))return r;let o=Ct(r.value);if(a(o))return o;let s=Yt(o.value.events,o.value.unreadable);if(a(s))return s;let i=Rs(e);if(a(i))return i;let c=u=>rS(u,e,n.value,r.value);return e.issueIds?lo("Moved",Dc(i.value,c)):c(i.value[0])}var Fc,Qh,Oc,nS,jc,rS,Wc,Hc,Zh=h(()=>{"use strict";et();uc();Je();ur();wt();Re();gc();Bt();ee();S();re();Rt();ys();yt();xn();Cc();tt();mt();Nn();Ac();_c();Sr();Fc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=z();if(a(n))return n;let r=e.idOrRef.trim();if(!r)return d("Provide an issue id or ref");let o=Object.values(n.value.nodes).filter(F).filter(u=>!u.isDeleted),s=o.find(u=>u.id===r),i=s?[s]:o.filter(u=>Uo(u.id,r));if(i.length===0)return d(`No issue matches "${r}"`);if(i.length>1)return d(`"${r}" matches ${i.length} issues: ${i.map(u=>`${j(u.id)} (${le(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:le(c.title),description:c.props.description??"",createdAt:Ge(c.id),enteredLaneAt:Qi(c.log??[],Ge(c.id)),parentNodeId:c.parentNodeId,isClosed:c.parentNodeId===me,readonly:!!c.readonly,tags:ao(c),assignees:co(c),comments:Kh(c.id)})},Qh=(e,t)=>e.trim().toLowerCase()===t.trim().toLowerCase();Oc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=le(e.title);if(!o)return d("Issue title cannot be empty");let s=e.description??"",i=He("Issue title",o,300)??He("Issue description",s,2e4);if(i)return d(i);if((e.tagNames?.length??0)>20)return d(`Cannot set more than ${20} tags at once`);if((e.assigneeNames?.length??0)>20)return d(`Cannot set more than ${20} assignees at once`);let c=qn(e.parentId);if(a(c))return c;let u=gn(e.parentId,n.value,t.value.stateBranchRoot);if(a(u))return u;let m=Hi({name:o,parent:e.parentId,user:n.value,rank:u.value});if(a(m))return m;let p=[...m.value],f=p.find(A=>A.action==="add.issue")?.payload.id;if(!f)return d("Unable to determine created issue id");s&&p.push({id:Pt(),...n.value,action:"edit.description",payload:{id:f,md:s}});let y=[];for(let A of e.tagNames??[]){let w=le(A).trim();if(!w||y.some(U=>U.name===w))continue;let k=He("Tag name",w,60);if(k)return d(k);let L=E.findTagByName(w),D=L?.id??Pt();L||p.push({id:Pt(),...n.value,action:"create.tag",payload:{id:D,name:w}}),p.push({id:Pt(),...n.value,action:"add.issue.tag",payload:{id:f,tag:D}}),y.push({id:D,name:w})}let x=[];for(let A of e.assigneeNames??[]){let w=le(A).trim();if(!w||x.some(U=>U.name===w))continue;let k=He("Assignee name",w,80);if(k)return d(k);let L=Object.values(r.value.contributors).find(U=>U.name===w),D=L?.id??Pt();L||p.push({id:Pt(),...n.value,action:"create.contributor",payload:{id:D,name:w}}),p.push({id:Pt(),...n.value,action:"add.issue.assignee",payload:{id:f,assignee:D}}),x.push({id:D,name:w})}let R=P(p,t.value.stateBranchRoot);return a(R)?d(R.message):l("Created issue",{id:f,ref:j(f),title:o,parentId:e.parentId,description:s,tags:y,assignees:x})},nS=(e,t,n)=>{let r=je(e);if(a(r))return r;let o=Vt(me,e,{at:"end"},t,n);if(a(o))return o;let s={id:Pt(),...t,action:"close.issue",payload:{id:e,parent:me,rank:o.value}},i=P([s],n);return a(i)?d(i.message):l("Closed issue",{id:e,ref:j(e)})};jc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o||o.isDeleted)return d("Issue not found");if(!F(o))return d("Target must be an issue");if(o.parentNodeId!==me)return d("Issue is not closed");let s=Ki(o);if(!s)return d("Unable to resolve previous parent from issue history");if(s===me)return d("Previous parent resolves to closed swimlane");let i=qn(s);if(a(i))return i;let c=i.value,u=Vt(c.id,o.id,{at:"end"},n.value,t.value.stateBranchRoot);if(a(u))return u;let m={id:Pt(),...n.value,action:"reopen.issue",payload:{id:o.id,parent:c.id,rank:u.value}},p=P([m],t.value.stateBranchRoot);return a(p)?d(p.message):l("Reopened issue",{id:o.id,ref:j(o.id),parentId:c.id})},rS=(e,t,n,r)=>{let o=je(e);if(a(o))return o;let s=qn(t.parentId);if(a(s))return s;let i=Vt(t.parentId,e,t.position??{at:"end"},n,r);if(a(i))return i;let c={id:Pt(),...n,action:"move.node",payload:{id:e,parent:t.parentId,rank:i.value}},u=P([c],r);return a(u)?d(u.message):l("Moved issue",{id:e,ref:j(e),parentId:t.parentId})};Wc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=je(e.issueId);if(a(o))return o;let s=o.value,i=He("Issue description",e.description,2e4);if(i)return d(i);let c=s.props.description??"";if(c===e.description)return l("No changes made",{id:e.issueId,ref:j(e.issueId),description:c});let u={id:Pt(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},m=P([u],t.value.stateBranchRoot);return a(m)?d(m.message):l("Edited issue description",{id:e.issueId,ref:j(e.issueId),description:e.description})},Hc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=je(e.issueId);if(a(o))return o;let s=o.value,i=le(e.title);if(!i.trim())return d("Issue title cannot be empty");let c=He("Issue title",i,300);if(c)return d(c);if(s.title===i)return l("No changes made",{id:e.issueId,ref:j(e.issueId),title:i});let u={id:Pt(),...n.value,action:"edit.title",payload:{id:e.issueId,name:i}},m=P([u],t.value.stateBranchRoot);return a(m)?d(m.message):l("Edited issue title",{id:e.issueId,ref:j(e.issueId),title:i})}});import{ulid as Gn}from"ulid";var qc,Gc,zc,Vc,Kc,Yc,Xc,Jc,ev=h(()=>{"use strict";et();ur();wt();Re();Bt();ee();S();Rt();xn();tt();mt();io();Nn();Sr();qc=async(e={})=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=z();if(a(n))return n;let r=Object.values(n.value.nodes).filter(o=>o.context==="BOARD"&&!o.isDeleted).map(o=>({id:o.id,ref:j(o.id),title:o.title,parentId:o.parentNodeId,readonly:!!o.readonly}));return l("Listed boards",r)},Gc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=r.value.nodes[r.value.rootNodeId];if(!o)return d("Workspace not found");if(Er().mode!=="live")return d("Cannot add a board while time travelling");let s=le(e.title);if(!s.trim())return d("Board title cannot be empty");let i=He("Board title",s,300);if(i)return d(i);let c=gn(o.id,n.value,t.value.stateBranchRoot);if(a(c))return c;let u=Gn(),m={id:Gn(),...n.value,action:"add.board",payload:{id:u,name:s,parent:o.id,rank:c.value}},p=P([m],t.value.stateBranchRoot);return a(p)?d(p.message):l("Created board",{id:u,ref:j(u),title:s})},zc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=r.value.nodes[e.boardId];if(!o||o.isDeleted)return d("Board not found");if(!Yn(o))return d("Edit target must be a board");if(o.readonly)return d("Cannot edit readonly board");if(Er().mode!=="live")return d("Cannot rename a board while time travelling");let s=le(e.title);if(!s.trim())return d("Board title cannot be empty");let i=He("Board title",s,300);if(i)return d(i);if(o.title===s)return l("No changes made",{id:e.boardId,ref:j(e.boardId),title:s});let c={id:Gn(),...n.value,action:"edit.title",payload:{id:e.boardId,name:s}},u=P([c],t.value.stateBranchRoot);return a(u)?d(u.message):l("Edited board title",{id:e.boardId,ref:j(e.boardId),title:s})},Vc=async(e={})=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=z();if(a(n))return n;let r=Object.values(n.value.nodes).filter(o=>o.context==="SWIMLANE"&&!o.isDeleted).filter(o=>!e.boardId||o.parentNodeId===e.boardId).map(o=>({id:o.id,title:o.title,boardId:o.parentNodeId,isClosed:o.id===me,readonly:!!o.readonly}));return l("Listed swimlanes",r)},Kc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=Tc(e.boardId);if(a(o))return o;if(Er().mode!=="live")return d("Cannot add a swimlane while time travelling");let s=le(e.title);if(!s.trim())return d("Swimlane title cannot be empty");let i=He("Swimlane title",s,300);if(i)return d(i);let c=gn(e.boardId,n.value,t.value.stateBranchRoot);if(a(c))return c;let u=Gn(),m={id:Gn(),...n.value,action:"add.swimlane",payload:{id:u,name:s,parent:e.boardId,rank:c.value}},p=P([m],t.value.stateBranchRoot);return a(p)?d(p.message):l("Created swimlane",{id:u,ref:j(u),title:s,boardId:e.boardId})},Yc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=qn(e.swimlaneId);if(a(o))return o;let s=o.value,i=le(e.title);if(!i.trim())return d("Swimlane title cannot be empty");let c=He("Swimlane title",i,300);if(c)return d(c);if(s.title===i)return l("No changes made",{id:e.swimlaneId,ref:j(e.swimlaneId),title:i});let u={id:Gn(),...n.value,action:"edit.title",payload:{id:e.swimlaneId,name:i}},m=P([u],t.value.stateBranchRoot);return a(m)?d(m.message):l("Edited swimlane title",{id:e.swimlaneId,ref:j(e.swimlaneId),title:i})},Xc=async e=>{let t=Rr(e.repoRoot);if(a(t))return t;let n=Q();if(a(n))return n;let r=Ie({repoRoot:t.value});if(a(r))return r;let o=Ct(r.value);if(a(o))return o;let s=Yt(o.value.events,o.value.unreadable);if(a(s))return s;let i=qn(e.swimlaneId);if(a(i))return i;let c=Tc(e.boardId);if(a(c))return c;let u=Vt(e.boardId,e.swimlaneId,e.position??{at:"end"},n.value,r.value);if(a(u))return u;let m={id:Gn(),...n.value,action:"move.node",payload:{id:e.swimlaneId,parent:e.boardId,rank:u.value}},p=P([m],r.value);return a(p)?d(p.message):l("Moved swimlane",{id:e.swimlaneId,ref:j(e.swimlaneId),boardId:e.boardId})},Jc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=qn(e.swimlaneId);if(a(o))return o;let s={id:Gn(),...n.value,action:"delete.node",payload:{id:e.swimlaneId}},i=P([s],t.value.stateBranchRoot);return a(i)?d(i.message):l("Deleted swimlane",{id:e.swimlaneId,ref:j(e.swimlaneId)})}});import{ulid as po}from"ulid";async function Qc(e){let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=Rs(e);if(a(r))return r;let o=le(e.tagName).trim();if(!o)return d("Tag name cannot be empty");let s=He("Tag name",o,60);if(s)return d(s);let i={done:[],failed:[]};for(let x of r.value){let R=je(x);a(R)?i.failed.push({id:x,ref:j(x),reason:R.message}):i.done.push({id:x,ref:j(x)})}if(!e.issueIds&&i.failed[0])return d(i.failed[0].reason);if(i.done.length===0)return d(lo("Tagged",i).message);let c=E.findTagByName(o),u=c?.id??po(),m=[...c?[]:[{id:po(),...n.value,action:"create.tag",payload:{id:u,name:o}}],...i.done.map(({id:x})=>({id:po(),...n.value,action:"add.issue.tag",payload:{id:x,tag:u}}))],p=P(m,t.value.stateBranchRoot);if(a(p))return d(p.message);let f={id:u,name:o};if(!e.issueIds)return l("Added issue tag",{...i.done[0],tag:f});let y=lo("Tagged",i);return a(y)?y:l(y.message,{...y.value,tag:f})}var Zc,el,tl,tv=h(()=>{"use strict";Re();S();re();xn();tt();mt();Nn();_c();Sr();Zc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=r.value.tags[e.tagId];if(!o)return d("Tag not found");if(o.tombstoned)return d("Tag is already deleted");let s=[{id:po(),...n.value,action:"tombstone.tag",payload:{id:e.tagId}}],i=P(s,t.value.stateBranchRoot);return a(i)?d(i.message):l("Deleted tag",{id:o.id,name:o.name})},el=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=r.value.tags[e.tagId];if(!o)return d("Tag not found");if(!o.tombstoned)return d("Tag is not deleted");if(E.findTagByName(o.name))return d(`Cannot restore: another tag is already named "${o.name}"`);let s=[{id:po(),...n.value,action:"restore.tag",payload:{id:e.tagId,name:o.name}}],i=P(s,t.value.stateBranchRoot);return a(i)?d(i.message):l("Restored tag",{id:o.id,name:o.name})},tl=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=je(e.issueId);if(a(o))return o;if(!r.value.tags[e.tagId])return d("Tag not found");let s={id:po(),...n.value,action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},i=P([s],t.value.stateBranchRoot);return a(i)?d(i.message):l("Removed issue tag",{id:e.issueId,ref:j(e.issueId),tagId:e.tagId})}});import{ulid as Cn}from"ulid";var oS,nv,nl,rv,rl,ol,sS,sl,il,al,ov=h(()=>{"use strict";S();M();$t();zn();wt();Re();wc();yt();xn();tt();mt();Nn();Sr();oS=()=>{let e=Ye(),t=a(e)?[]:e.value.eventLog??[],n=new Map;for(let r of t)r.userId&&r.userName&&n.set(r.userId,r.userName);return n},nv=(e,t)=>{let n=new Map(e);for(let r of Object.values(t))n.set(r.id,r.name);return n},nl=async e=>{let t=ua(e.name,"name");if(a(t))return d(t.message);let n=await K(e.repoRoot,{pull:!1});if(a(n))return n;let r=Q();if(a(r))return r;let o=z();if(a(o))return o;let s=r.value,i=!!o.value.contributors[s.userId];if(!i){let c=P([{id:Cn(),...s,action:"create.contributor",payload:{id:s.userId,name:s.userName}}],n.value.stateBranchRoot);if(a(c))return d(c.message)}return l(`Assumed ${s.userName}`,{...s,registered:!i})},rv=async(e,t)=>{let n=Va(e);if(a(n))return;let r;for(let o of n.value)o.userId===t&&(r=o.userName??r);return r===void 0?void 0:{id:t,name:r}},rl=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=je(e.issueId);if(a(o))return o;let s=e.self?n.value.userId:e.assigneeId;if(s){let w=r.value.contributors[s],k=w?void 0:await rv(t.value.stateBranchRoot,s);if(!w&&!k)return d("Unknown assignee id");let L=w??k,D=[...w?[]:[{id:Cn(),...n.value,action:"create.contributor",payload:{id:L.id,name:L.name}}],{id:Cn(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:L.id}}],U=P(D,t.value.stateBranchRoot);return a(U)?d(U.message):l("Added issue assignee",{id:e.issueId,ref:j(e.issueId),assignee:{id:L.id,name:L.name}})}let i=le(e.assigneeName??"").trim();if(!i)return d("Provide assigneeId, self or assigneeName");let c=He("Assignee name",i,80);if(c)return d(c);let m=[...nv(oS(),r.value.contributors).entries()].filter(([,w])=>w===i);if(m.length>1)return d(`"${i}" matches ${m.length} contributors (${m.map(([w])=>w).join(", ")}). Assign by assigneeId to choose.`);let p=m[0];if(!p&&!e.createUnlinked)return d(`No contributor named "${i}". Assign by id, or pass createUnlinked to add them as an external assignee.`);let[f=Cn(),y=i]=p??[],R=[...!!r.value.contributors[f]?[]:[{id:Cn(),...n.value,action:"create.contributor",payload:{id:f,name:y}}],{id:Cn(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:f}}],A=P(R,t.value.stateBranchRoot);return a(A)?d(A.message):l("Added issue assignee",{id:e.issueId,ref:j(e.issueId),assignee:{id:f,name:y}})},ol=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;if(!r.value.contributors[e.contributorId])return d("Contributor not found");if(await rv(t.value.stateBranchRoot,e.contributorId))return d("Cannot remove a contributor who has authored events \u2014 their name appears throughout the log");let i=[{id:Cn(),...n.value,action:"tombstone.contributor",payload:{id:e.contributorId}}],c=P(i,t.value.stateBranchRoot);return a(c)?d(c.message):l("Tombstoned contributor",{id:e.contributorId,name:Ts})},sS=async(e,t)=>{let n=ar(e);if(a(n))return;let r;for(let o of n.value){if(o.action!=="create.contributor")continue;let s=o.payload;s.id===t&&s.name&&(r=s.name)}return r},sl=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=r.value.contributors[e.contributorId];if(!o)return d("Contributor not found");if(!o.tombstoned)return d("Contributor is not tombstoned");let s=await sS(t.value.stateBranchRoot,e.contributorId);if(!s)return d("Cannot restore this contributor \u2014 no original name found in the event log");let i=[{id:Cn(),...n.value,action:"restore.contributor",payload:{id:e.contributorId,name:s}}],c=P(i,t.value.stateBranchRoot);return a(c)?d(c.message):l("Restored contributor",{id:e.contributorId,name:s})},il=async(e={})=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=ar(t.value.stateBranchRoot);if(a(o))return d(o.message);let s=e.boardId?Hh(o.value,e.boardId):o.value,i=new Map,c=new Set,u=new Set,m=Va(t.value.stateBranchRoot);if(a(m))return d(m.message);for(let x of m.value)x.userId&&u.add(x.userId);for(let x of s)x.userId&&(i.set(x.userId,x.userName??""),c.add(x.userId));let p=r.value.contributors,y=[...nv(i,p).entries()].map(([x,R])=>({id:x,name:R,color:Te(R),isSelf:x===n.value.userId,isExternal:!c.has(x),isRemoved:p[x]?.tombstoned===!0,hasAuthoredAnywhere:u.has(x)}));return l("Listed board contributors",y)},al=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=je(e.issueId);if(a(o))return o;if(!r.value.contributors[e.assigneeId])return d("Assignee not found");let s={id:Cn(),...n.value,action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},i=P([s],t.value.stateBranchRoot);return a(i)?d(i.message):l("Removed issue assignee",{id:e.issueId,ref:j(e.issueId),assigneeId:e.assigneeId})}});import{ulid as na}from"ulid";var dl,cl,ll,sv=h(()=>{"use strict";Re();S();xn();Nn();Sr();dl=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=je(e.issueId);if(a(o))return o;let s=e.body.trim();if(!s)return d("Comment cannot be empty");if(s.length>4e3)return d(`Comment cannot exceed ${4e3} characters (got ${s.length})`);let i=na(),c={id:na(),...n.value,action:"add.issue.comment",payload:{id:i,issue:e.issueId,md:s,author:n.value.userId}},u=P([c],t.value.stateBranchRoot);return a(u)?d(u.message):l("Added issue comment",{id:i,issueId:e.issueId,body:s})},cl=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=r.value.eventLog.find(m=>m.action==="add.issue.comment"&&m.payload.id===e.commentId);if(!o)return d("Unable to resolve comment");if(o.payload.author!==n.value.userId)return d("You can only delete your own comments");let s=je(o.payload.issue);if(a(s))return s;if(r.value.eventLog.some(m=>m.action==="delete.issue.comment"&&m.payload.id===e.commentId))return l("Comment already deleted",{id:e.commentId,issueId:o.payload.issue});let c={id:na(),...n.value,action:"delete.issue.comment",payload:{id:e.commentId,issue:o.payload.issue}},u=P([c],t.value.stateBranchRoot);return a(u)?d(u.message):l("Deleted issue comment",{id:e.commentId,issueId:o.payload.issue})},ll=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=r.value.eventLog.find(p=>p.action==="add.issue.comment"&&p.payload.id===e.commentId);if(!o)return d("Unable to resolve comment");if(o.payload.author!==n.value.userId)return d("You can only edit your own comments");let s=je(o.payload.issue);if(a(s))return s;if(r.value.eventLog.some(p=>p.action==="delete.issue.comment"&&p.payload.id===e.commentId))return d("Comment was deleted");let c=e.body.trim();if(!c)return d("Comment cannot be empty");if(c.length>4e3)return d(`Comment cannot exceed ${4e3} characters (got ${c.length})`);let u={id:na(),...n.value,action:"edit.issue.comment",payload:{id:e.commentId,issue:o.payload.issue,md:c}},m=P([u],t.value.stateBranchRoot);return a(m)?d(m.message):l("Edited issue comment",{id:e.commentId,issueId:o.payload.issue,body:c})}});var iv=h(()=>{"use strict";Jh();Zh();ev();tv();ov();sv();Mc()});import{ulid as iS}from"ulid";var av,dv,cv,lv=h(()=>{"use strict";zn();Or();Qt();S();ic();St();av=[{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)"}],dv=e=>e.trim().toLowerCase(),cv=async(e={})=>{let t=$r();if(a(t))return d(t.message);let n=t.value,r=e.userName?.trim(),o=(process.env[It]??"").trim();if(r&&o&&dv(r)===dv(o))return d(`userName "${r}" 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:r||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 av){let k=s[w.name],L=i[w.name];if(!(k===void 0||L===void 0||k===L))return d(`This machine is already set up with ${w.name} ${JSON.stringify(L)}; 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=iS()),Object.keys(c).length>0){let w=ot(c);if(a(w))return d(w.message)}let u={...n,...c},m=av.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 d(`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 d("Missing Epiq user id");let f=await $i({cwd:e.repoRoot??process.cwd(),user:p});if(a(f))return f;let{defaultEvents:y,...x}=f.value,R=es({root:x.repoRoot});a(R)&&X.info(R.message);let A=x.warnings.length===0?"Project initialized":`Project initialized, with warnings: ${x.warnings.join(" ")}`;return l(A,{...x,user:p})}});var rn,ra=h(()=>{"use strict";rn=e=>({path:e.path,sha:e.shas[e.shas.length-1]??""})});var aS,uv,mv=h(()=>{"use strict";ra();aS=e=>{let t=e.lastIndexOf("/");return t===-1?".":e.slice(0,t)},uv=({commits:e,patch:t})=>{let n=e.map(i=>i.time),o=t.files.map(i=>({...rn(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=>aS(i.path))).size,insertions:t.insertions,deletions:t.deletions,net:t.insertions-t.deletions,largestFile:o,concentration:o&&s>0?o.changed/s:0,selfChurn:t.selfChurn,truncated:t.truncated}}});var Be,Lt,ul,fo,dS,H,oa,sa,pv,cS,fv,Nr,Ns,lS,uS,go,mS,pS,fS,Ut,gv,hv,vv,gS,hS,yv,bv,ho=h(()=>{"use strict";Be={line:["//"],block:[["/*","*/"]]},Lt={line:["#"],block:[]},ul={line:["--"],block:[]},fo={line:[],block:[["<!--","-->"]]},dS={line:[],block:[]},H=(e,t)=>({name:e,comment:t}),oa=H("TypeScript",Be),sa=H("JavaScript",Be),pv={ts:oa,tsx:oa,mts:oa,cts:oa,js:sa,jsx:sa,mjs:sa,cjs:sa,py:H("Python",{line:["#"],block:[['"""','"""']]}),rb:H("Ruby",{line:["#"],block:[["=begin","=end"]]}),go:H("Go",Be),rs:H("Rust",Be),java:H("Java",Be),kt:H("Kotlin",Be),swift:H("Swift",Be),c:H("C",Be),h:H("C",Be),cc:H("C++",Be),cpp:H("C++",Be),hpp:H("C++",Be),cs:H("C#",Be),php:H("PHP",Be),scala:H("Scala",Be),dart:H("Dart",Be),lua:H("Lua",ul),hs:H("Haskell",ul),sql:H("SQL",ul),ex:H("Elixir",Lt),exs:H("Elixir",Lt),pl:H("Perl",Lt),r:H("R",Lt),jl:H("Julia",Lt),sh:H("Shell",Lt),bash:H("Shell",Lt),zsh:H("Shell",Lt),vue:H("Vue",fo),svelte:H("Svelte",fo),html:H("HTML",fo),xml:H("XML",fo),md:H("Markdown",fo),mdx:H("Markdown",fo),css:H("CSS",{line:[],block:[["/*","*/"]]}),scss:H("CSS",Be),less:H("CSS",Be),yml:H("YAML",Lt),yaml:H("YAML",Lt),toml:H("TOML",Lt),ini:H("INI",Lt),json:H("JSON",dS)},cS="Other",fv=e=>{let t=e.slice(e.lastIndexOf("/")+1),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()},Nr=e=>pv[fv(e)]?.name??cS,Ns=e=>pv[fv(e)]?.comment??null,lS=[/\.(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,go=e=>uS.test(e)||lS.some(t=>t.test(e)),mS=/(^|\/)(package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|Cargo\.lock|go\.sum|poetry\.lock|Gemfile\.lock|composer\.lock)$/,pS=/(^|\/)(node_modules|dist|build|out|target|vendor|coverage|\.next|__snapshots__)\//,fS=/(\.min\.(js|css)|\.map|\.snap|\.pb\.go|_pb2\.py)$/,Ut=e=>mS.test(e)||pS.test(e)||fS.test(e),gv=e=>/(^|\/)(package\.json|go\.mod|Cargo\.toml|requirements[^/]*\.txt|pyproject\.toml|Gemfile|composer\.json|pom\.xml|build\.gradle(\.kts)?)$/.test(e),hv=e=>/(^|\/)\.github\/workflows\//.test(e)||/(^|\/)(Dockerfile|docker-compose[^/]*\.ya?ml|Makefile|Jenkinsfile|\.gitlab-ci\.yml)$/.test(e)||/\.tf$/.test(e),vv=e=>/\.(md|mdx|rst|txt)$/i.test(e)||/(^|\/)docs?\//i.test(e),gS=/\b(it|test|describe|context|suite)\.skip\b|\bx(it|describe|test)\s*\(|@pytest\.mark\.skip|@unittest\.skip|\bt\.Skip\s*\(|@(Ignore|Disabled)\b/,hS=/\b(it|test|describe|context|suite)\.only\b|\bf(it|describe|test)\s*\(/,yv=e=>gS.test(e),bv=e=>hS.test(e)});var Iv,vS,ml,yS,xv,pl=h(()=>{"use strict";ho();Iv=/\b(TODO|FIXME|HACK|XXX)\b/,vS=/[;{}]\s*$|^\s*(const|let|var|function|def|class|if|for|while|return|import|export|await|print)\b.*[=(]/,ml=(e,t)=>{let n=e.trim();return n===""?"blank":t&&(t.line.some(r=>n.startsWith(r))||t.block.some(([r])=>n.startsWith(r))||t.block.some(([r])=>r==="/*")&&(n.startsWith("*")||n.startsWith("*/")))?"comment":"code"},yS=(e,t)=>{let n=e.trim();for(let r of[...t.line,...t.block.flat(),"*"])if(n.startsWith(r)){n=n.slice(r.length).trim();break}return n},xv=({patch:e,repoShareByLanguage:t})=>{let n=new Map,r=0,o=0,s=0,i=0,c=0,u=0;for(let p of e.files){if(p.binary||Ut(p.path))continue;let f=Ns(p.path);if(!f||f.line.length===0&&f.block.length===0)continue;let y=Nr(p.path),x=n.get(y)??{comment:0,code:0};for(let{text:R}of p.added){let A=ml(R,f);if(Iv.test(R)&&i++,A==="blank"){s++;continue}if(A==="comment"){r++,x.comment++,f&&vS.test(yS(R,f))&&u++;continue}o++,x.code++}for(let{text:R}of p.removedLines)Iv.test(R)&&c++;n.set(y,x)}let m=r+o;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:r,codeLines:o,blankLines:s,share:m===0?0:r/m,todoLinesAdded:i,todoLinesRemoved:c,commentedOutCodeLines:u}}});var bS,ia,fl,IS,xS,ES,Ev,Rv=h(()=>{"use strict";ho();ra();bS=/\bconsole\.(log|debug|dir)\s*\(|\bdebugger\b|^\s*print\s*\(|\bfmt\.Print(ln|f)?\s*\(|\bSystem\.out\.print|\bdbg!\s*\(/,ia=6,fl=10,IS=e=>{let t=0;for(let n of e){if(n.trim()===""||n.startsWith(" "))continue;let r=n.length-n.trimStart().length;r>0&&(t===0||r<t)&&(t=r)}return Math.min(Math.max(t,2),8)},xS=(e,t)=>{let n=e.length-e.trimStart().length;if(n===0)return 0;let r=e.slice(0,n).split(" ").length-1;return r>0?r:Math.floor(n/t)},ES=e=>{if(e.length<ia*2)return 0;let t=new Map,n=new Array(e.length).fill(!1);for(let r=0;r+ia<=e.length;r++){let o=e.slice(r,r+ia);if(o.some(c=>c.text.length<3))continue;let s=o.map(c=>c.text).join(`
|
|
99
|
+
`),i=t.get(s);if(i===void 0){t.set(s,{...o[0],at:r});continue}if(i.file!==o[0]?.file)for(let c=0;c<ia;c++)n[i.at+c]=!0,n[r+c]=!0}return n.filter(Boolean).length},Ev=({patch:e})=>{let t=[],n=[],r=[],o=!1,s=0,i=0,c=null,u=[];for(let[m,p]of e.files.entries()){if(Ut(p.path)&&t.push(rn(p)),gv(p.path)&&n.push(rn(p)),hv(p.path)&&r.push(rn(p)),vv(p.path)&&(o=!0),p.binary||Ut(p.path))continue;let f=p.added.map(R=>R.text),y=IS(f),x=p.status!=="deleted";for(let R of f){bS.test(R)&&s++;let A=xS(R,y);A>i&&(i=A,c=rn(p)),x&&u.push({text:R.trim(),file:m})}u.push({text:" ",file:m})}return{generatedPaths:t.slice(0,fl),dependencyManifests:n.slice(0,fl),buildOrCiPaths:r.slice(0,fl),docsTouched:o,debugPrintLinesAdded:s,maxIndentLevels:i,deepestFile:c,duplicatedLines:ES(u)}}});var Sv,Nv=h(()=>{"use strict";ho();Sv=({patch:e,languagesBefore:t})=>{let n=new Map,r=0;for(let i of e.files){if(i.binary)continue;let c=i.addedCount+i.removed;if(Ut(i.path)){r+=c;continue}let u=Nr(i.path),m=n.get(u)??{name:u,added:0,removed:0,addedInTests:0,share:0};m.added+=i.addedCount,m.removed+=i.removed,go(i.path)&&(m.addedInTests+=i.addedCount),n.set(u,m)}let o=[...n.values()].reduce((i,c)=>i+c.added+c.removed,0),s=[...n.values()].map(i=>({...i,share:o===0?0:(i.added+i.removed)/o})).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:r}}});var RS,gl,SS,Cv,NS,hl,CS,wS,wv,Av,AS,TS,kS,Tv,kv=h(()=>{"use strict";Qe();S();RS=200,gl=2e5,SS=5e4,Cv=25,NS=64*1024*1024,hl="",CS=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/,wS=/^diff --git a\/(.+) b\/\1$/,wv=(e,t)=>e==="/dev/null"?null:e.startsWith(t)?e.slice(2):e,Av=(e,t)=>e===null?"added":t===null?"deleted":"modified",AS=()=>({byPath:new Map,insertions:0,deletions:0,selfChurn:0,retainedLines:0}),TS=(e,t)=>{let n=e.byPath,r="",o=null,s=null,i=null,c=!1,u=0,m=(f,y)=>y==="modified"&&f==="added"?"added":y,p=(f,y)=>{let x=n.get(f);if(x)return x.entry.status=m(x.entry.status,y),x.entry.shas.includes(r)||x.entry.shas.push(r),x;let A={entry:{path:f,status:y,binary:!1,added:[],addedCount:0,removed:0,removedLines:[],shas:[r]},pendingByText:new Map};return n.set(f,A),A};for(let f of t.split(`
|
|
100
|
+
`)){if(f.startsWith(hl)){r=f.slice(hl.length).trim(),o=null,s=null,i=null,c=!1;continue}if(f.startsWith("diff --git ")){o=null,i=null,c=!0,s=wS.exec(f)?.[1]??null;continue}if(c&&f.startsWith("Binary files ")&&s){let[,x=""]=/^Binary files (.*) differ$/.exec(f)??[],[R="",A=""]=x.split(" and ");o=p(s,Av(R==="/dev/null"?null:R,A==="/dev/null"?null:A)),o.entry.binary=!0;continue}if(c&&f.startsWith("--- ")){i=wv(f.slice(4),"a/");continue}if(c&&f.startsWith("+++ ")){let x=wv(f.slice(4),"b/"),R=x??i??s;R&&(o=p(R,Av(i,x)));continue}let y=CS.exec(f);if(y){u=Number(y[1]),c=!1;continue}if(o){if(f.startsWith("+")){let x=f.slice(1);e.insertions++,o.entry.addedCount++,e.retainedLines<gl&&(o.entry.added.push({sha:r,line:u,text:x}),e.retainedLines++),o.pendingByText.size<SS&&o.pendingByText.set(x,(o.pendingByText.get(x)??0)+1),u++;continue}if(f.startsWith("-")){let x=f.slice(1);e.deletions++,o.entry.removed++,e.retainedLines<gl&&(o.entry.removedLines.push({sha:r,line:0,text:x}),e.retainedLines++);let R=o.pendingByText.get(x)??0;R>0&&x.trim().length>2&&(e.selfChurn++,o.pendingByText.set(x,R-1))}}}},kS=e=>({files:[...e.byPath.values()].map(t=>t.entry),insertions:e.insertions,deletions:e.deletions,selfChurn:e.selfChurn,retainedLines:e.retainedLines}),Tv=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,RS).reverse(),r=AS(),o=0,s=0,i=!1;for(let u=0;u<n.length;u+=Cv){let m=n.slice(u,u+Cv),p=await W({cwd:e,args:["-c","core.quotePath=false","show","--unified=0","--no-renames","--no-color",`--format=${hl}%H`,...m]});if(a(p))return d(p.message);if(TS(r,p.value.stdout),o+=p.value.stdout.length,s+=m.length,o>NS){i=!0;break}}let c=kS(r);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>=gl})}});var MS,PS,Mv,Pv=h(()=>{"use strict";Qe();S();pl();ho();MS=40,PS=/^\d{6} blob ([0-9a-f]{40})\t(.+)$/,Mv=async({repoRoot:e,sha:t})=>{let n=await Oe({cwd:e,args:["-c","core.quotePath=false","ls-tree","-r",`${t}~1`]});if(n.exitCode!==0)return null;let r=new Set,o=new Map;for(let p of n.stdout.split(`
|
|
101
|
+
`)){let f=PS.exec(p);if(!f)continue;let[,y="",x=""]=f;if(Ut(x))continue;let R=Nr(x);if(r.add(R),go(x)||!Ns(x))continue;let A=o.get(R)??[];A.length<MS&&(A.push({blob:y,path:x}),o.set(R,A))}let s=[...o.values()].flat(),i=await Ia(s.map(p=>p.blob),e);if(a(i))return{languages:r,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 x=Ns(f),R=Nr(f),A=u.get(R)??{comment:0,code:0};for(let w of y.split(`
|
|
102
|
+
`)){let k=ml(w,x);k==="comment"&&A.comment++,k==="code"&&A.code++}u.set(R,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:r,commentShareByLanguage:m}}});var Lv,Dv=h(()=>{"use strict";ho();ra();Lv=({patch:e})=>{let t=0,n=0,r=[],o=[],s=0,i=0;for(let c of e.files)if(!(c.binary||Ut(c.path))&&go(c.path)){t+=c.addedCount,n+=c.removed,c.status==="added"&&r.push(rn(c)),c.status==="deleted"&&o.push(rn(c));for(let{text:u}of c.added)yv(u)&&s++,bv(u)&&i++}return{testLinesAdded:t,testLinesRemoved:n,addedTestFiles:r,deletedTestFiles:o,skippedTestLinesAdded:s,focusedTestLinesAdded:i}}});var LS,_v,Fv=h(()=>{"use strict";S();mv();pl();Rv();Nv();kv();Pv();Dv();LS=e=>e.reduce((t,n)=>t===null||n.time<t.time?n:t,null)?.sha??null,_v=async({repoRoot:e,ref:t,commits:n})=>{let r=await Tv({repoRoot:e,shas:n.map(c=>c.sha)});if(a(r))return d(r.message);let o=r.value,s=LS(n),i=s?await Mv({repoRoot:e,sha:s}):null;return l("Derived issue stats",{ref:t,shape:uv({commits:n,patch:o}),languages:Sv({patch:o,languagesBefore:i?.languages??null}),tests:Lv({patch:o}),comments:xv({patch:o,repoShareByLanguage:i?.commentShareByLanguage??null}),flags:Ev({patch:o})})}});var DS,Cs,_S,Bv,Ov=h(()=>{"use strict";S();Fv();tt();ie();io();DS=32,Cs=new Map,_S=(e,t)=>{if(Cs.set(e,t),Cs.size>DS){let n=Cs.keys().next();n.done||Cs.delete(n.value)}return t},Bv=async(e={idOrRef:""})=>{let t=e.idOrRef.trim();if(!t)return d("idOrRef must not be empty");let n=t.length>7?j(t):t.toUpperCase(),r=Me(e.repoRoot??process.cwd());if(a(r))return d(r.message);let o=r.value,s=await Vh({repoRoot:o,ref:n});if(a(s))return d(s.message);let i=s.value.map(p=>({sha:p.sha,time:p.time,author:p.author,subject:p.subject})),c=[o,n,i.map(p=>p.sha).join(",")].join(" "),u=Cs.get(c);if(u)return l("Derived issue stats",u);let m=await _v({repoRoot:o,ref:n,commits:i});return a(m)?d(m.message):l("Derived issue stats",_S(c,m.value))}});var vo,vl,Uv=h(()=>{"use strict";vo=".claude/skills/epiq/SKILL.md",vl="---\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 aa from"node:fs";import jv from"node:path";var $v,Wv=h(()=>{"use strict";et();S();Uv();$v=async(e={})=>{let t=await gt(e.repoRoot??process.cwd());if(a(t))return d(t.message);let n=jv.join(t.value,vo);if(aa.existsSync(n)){if(aa.readFileSync(n,"utf8")===vl)return l("Skill already installed and up to date",{path:n,written:!1});if(!e.force)return d(`${vo} already exists and differs from the bundled skill. Pass force:true to overwrite it.`)}try{aa.mkdirSync(jv.dirname(n),{recursive:!0}),aa.writeFileSync(n,vl,"utf8")}catch(r){return d(r instanceof Error?`Failed to write ${vo}: ${r.message}`:`Failed to write ${vo}`)}return l(`Installed skill at ${vo}`,{path:n,written:!0})}});var qv={};Eo(qv,{createMcpServer:()=>Hv,resultJson:()=>yl,startMcpServer:()=>US});import{McpServer as BS}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as OS}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as v}from"zod";var yl,Z,Hv,US,Gv=h(()=>{"use strict";S();xn();iv();lv();Ov();Wv();io();yl=e=>({isError:a(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),Z=e=>t=>zh(async()=>yl(await e(t))),Hv=()=>{let e=new BS({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(Pc)),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(Bc)),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(Fc)),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=>yl(await Bv(t))),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:v.object({repoRoot:v.string().optional()})},Z(qc)),e.registerTool("epiq_board_create",{description:"Create an Epiq board. It comes out without swimlanes; add them with epiq_swimlane_create. Refused while time travelling.",inputSchema:v.object({repoRoot:v.string().optional(),title:v.string().min(1).max(300)})},Z(Gc)),e.registerTool("epiq_swimlane_list",{description:"List Epiq swimlanes",inputSchema:v.object({repoRoot:v.string().optional(),boardId:v.string().optional()})},Z(Vc)),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(Yc)),e.registerTool("epiq_board_title_edit",{description:"Edit an Epiq board title. Refused while time travelling.",inputSchema:v.object({repoRoot:v.string().optional(),boardId:v.string().min(1),title:v.string().min(1).max(300)})},Z(zc)),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(Xc)),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(Jc)),e.registerTool("epiq_issue_create",{description:"Create an Epiq issue in a swimlane: parentId is the swimlane id (epiq_swimlane_list), never a board id. 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(Oc)),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(Wc)),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(Hc)),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(Qc)),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(tl)),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(il)),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(ol)),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(Zc)),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(el)),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(sl)),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(rl)),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(al)),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(dl)),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(kc)),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(cl)),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(ll)),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(jc)),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(Uc)),e.registerTool("epiq_issue_move",{description:"Move an Epiq issue to another swimlane (parentId is the swimlane id), 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($c)),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(nl)),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(cv)),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($v)),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(Lc)),e},US=async()=>{let e=Hv(),t=new OS;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:jS}=await Promise.resolve().then(()=>(zn(),wl)),{isFail:$S}=await Promise.resolve().then(()=>(S(),Sl)),{parseMcpArgs:WS}=await Promise.resolve().then(()=>(kl(),Tl)),yo=WS(process.argv.slice(2));yo.kind==="error"&&(console.error(yo.message),process.exit(1));yo.kind==="print"&&(process.stdout.write(yo.text),process.exit(0));if(yo.kind==="name"){let e=jS(yo.name,"The name argument");$S(e)&&(console.error(e.message),process.exit(1))}var{setVirtualNodesEnabled:HS}=await Promise.resolve().then(()=>(Da(),$h));HS(!1);var{startMcpServer:qS}=await Promise.resolve().then(()=>(Gv(),qv));await qS();
|