infra-kit 0.1.101 → 0.1.102
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/.eslintcache +1 -1
- package/.turbo/turbo-test.log +2 -2
- package/dist/cli.js +39 -39
- package/dist/cli.js.map +4 -4
- package/dist/mcp.js +34 -34
- package/dist/mcp.js.map +4 -4
- package/package.json +1 -1
- package/src/commands/gh-release-deliver/gh-release-deliver.ts +30 -0
- package/src/commands/worktrees-remove/worktrees-remove.ts +2 -57
- package/src/lib/worktrees/index.ts +1 -0
- package/src/lib/worktrees/remove-worktrees.ts +65 -0
- package/tsconfig.tsbuildinfo +1 -1
package/dist/mcp.js
CHANGED
|
@@ -1,53 +1,53 @@
|
|
|
1
|
-
import{StdioServerTransport as
|
|
2
|
-
`)){let n=
|
|
1
|
+
import{StdioServerTransport as ns}from"@modelcontextprotocol/sdk/server/stdio.js";import qt from"node:process";import V from"node:process";import Jr from"node:process";import Ze from"pino";import Kt from"pino-pretty";var ge="/tmp/mcp-infra-kit.log",Vr=()=>{let e=Jr.argv.includes("--debug")?"debug":"info",r=Ze({level:e},Ze.destination({dest:ge}));return r.info(`Logger initialized with level: ${e}. Logging to: ${ge}`),r},Gt=()=>{let e=Jr.argv.includes("--debug")?"debug":"info",r=["time","pid","hostname"];return e==="debug"&&r.push("level"),Ze({level:e},Kt({destination:2,ignore:r.join(","),colorize:!0}))},i=Gt();var Lr=e=>{V.on("SIGINT",()=>{e.info({msg:"Received SIGINT. Shutting down..."}),V.exit(0)}),V.on("SIGTERM",()=>{e.info({msg:"Received SIGTERM. Shutting down..."}),V.exit(0)}),V.on("uncaughtException",r=>{e.fatal({err:r,msg:"Uncaught Exception"}),e.error(`Uncaught Exception! Check ${ge}. Shutting down...`),e.flush(),V.exit(1)}),V.on("unhandledRejection",(r,t)=>{e.fatal({reason:r,promise:t,msg:"Unhandled Rejection"}),e.error(`Unhandled Rejection! Check ${ge}. Shutting down...`),e.flush(),V.exit(1)})};import{McpServer as os}from"@modelcontextprotocol/sdk/server/mcp.js";var Br=async e=>{};var qr=async e=>{};import rr from"node:fs";import Kr from"node:path";import Xt from"node:process";import{z as je}from"zod/v4";import he from"node:fs";import zt from"node:os";import Qe from"node:path";import er from"node:process";var ee="env-load.sh",Ur="env-clear.sh",Ne="INFRA_KIT_SESSION",re="INFRA_KIT_ENV_CONFIG",te="INFRA_KIT_ENV_PROJECT",oe="INFRA_KIT_ENV_LOADED_AT",Me=/^([A-Z_]\w*)=/i,De=e=>{if(!he.existsSync(e))return[];let r=he.readFileSync(e,"utf-8"),t=[];for(let o of r.split(`
|
|
2
|
+
`)){let n=Me.exec(o);n&&t.push(n[1])}return t},Ht=()=>{let e=er.env.XDG_CACHE_HOME,r=e&&e.length>0?e:Qe.join(zt.homedir(),".cache");return Qe.join(r,"infra-kit")},ne=()=>{let e=er.env[Ne];if(!e)throw new Error(`${Ne} is not set. Run \`infra-kit init\` then \`source ~/.zshrc\`.`);return Qe.join(Ht(),e)},_e=(e,r,t)=>{let o=`${e}.tmp.${er.pid}`;he.writeFileSync(o,r,{mode:t});try{he.renameSync(o,e)}catch(n){throw he.rmSync(o,{force:!0}),n}},j="-worktrees";var w=e=>[{type:"text",text:e}],v=e=>e;var Gr=async()=>{let e=ne(),r=Kr.join(e,ee);if(!rr.existsSync(r))throw new Error("No loaded environment found. Run `env-load` first.");let t=De(r),o=[...t.map(a=>`unset ${a}`),`unset ${re}`,`unset ${te}`,`unset ${oe}`],n=Kr.resolve(e,Ur);rr.mkdirSync(e,{recursive:!0,mode:448}),_e(n,`${o.join(`
|
|
3
3
|
`)}
|
|
4
|
-
`,384),
|
|
5
|
-
`),
|
|
6
|
-
`).filter(Boolean),o={release:
|
|
7
|
-
`),i.info("Available configs:");for(let o of r)i.info(` - ${o}`);let t={project:e,configs:r};return{content:
|
|
4
|
+
`,384),Xt.stdout.write(`${n}
|
|
5
|
+
`),rr.unlinkSync(r);let s={filePath:n,variableCount:t.length,unsetStatements:o};return{content:w(JSON.stringify(s,null,2)),structuredContent:s}},tr=v({name:"env-clear",description:'Generate a shell script that unsets every env var previously loaded by env-load for this session, plus the infra-kit session metadata vars. Does NOT mutate the calling process. When `infra-kit init` has installed the zsh shell integration, the user\'s terminal auto-sources the unset script on its next prompt (precmd hook) \u2014 so calling this via MCP will clear the vars in the shell that launched Claude Code automatically. Other callers must source "<filePath>" themselves or surface it to the user. Errors if no env is currently loaded.',inputSchema:{},outputSchema:{filePath:je.string().describe("Path to the file that must be sourced to apply"),variableCount:je.number().describe("Number of variables cleared"),unsetStatements:je.array(je.string()).describe("Unset statements generated")},handler:Gr});import{z as nr}from"zod/v4";import or from"node:fs/promises";import eo from"node:os";import Fe from"node:path";import ro from"yaml";import{z as y}from"zod/v4";import Yt from"node:path";import{$ as zr}from"zx";var O=async e=>{let t=(await zr`git worktree list`).stdout.split(`
|
|
6
|
+
`).filter(Boolean),o={release:Zt,feature:Qt};return t.map(o[e]).filter(n=>n!==null)},Hr=e=>{let r=e.trimEnd();if(!r.endsWith("]"))return null;let t=r.lastIndexOf("[");if(t===-1)return null;let o=r.slice(t+1,-1);return o.length>0?o:null},Zt=e=>{let r=Hr(e);return r?.startsWith("release/v")?r:null},Qt=e=>{let r=Hr(e);return r?.startsWith("feature/")?r:null},E=async()=>(await zr`git rev-parse --show-toplevel`).stdout.trim(),A=async()=>{let e=await E();return Yt.basename(e)};var Xr="infra-kit.yml",to=".infra-kit",oo="config.yml",no="projects",so=y.object({provider:y.literal("doppler"),config:y.object({name:y.string().min(1)})}),io=y.discriminatedUnion("provider",[so]),ao=y.object({mode:y.enum(["workspace","windows"]).default("workspace"),workspaceConfigPath:y.string().min(1).optional()}).refine(e=>e.mode!=="workspace"||!!e.workspaceConfigPath,{message:'workspaceConfigPath is required when mode is "workspace"',path:["workspaceConfigPath"]}),co=y.object({provider:y.literal("cursor"),config:ao}),lo=y.discriminatedUnion("provider",[co]),po=y.object({provider:y.literal("jira"),config:y.object({baseUrl:y.string().url(),projectId:y.number().int().positive()})}),mo=y.discriminatedUnion("provider",[po]),uo=y.object({openInGithubDesktop:y.boolean().optional(),openInCmux:y.boolean().optional()}),Zr=y.object({environments:y.array(y.string().min(1)).min(1),envManagement:io,ide:lo.optional(),taskManager:mo.optional(),worktrees:uo.optional()}),fo=Zr.partial(),we=null,Qr=async()=>{let e=await E(),r=await A(),t=Fe.join(eo.homedir(),to);return{main:Fe.join(e,Xr),userGlobal:Fe.join(t,oo),userProject:Fe.join(t,no,r,Xr),projectName:r}},x=async()=>{let e=await Qr(),r;try{r=await or.stat(e.main)}catch{throw we=null,new Error(`infra-kit.yml not found at ${e.main}`)}let[t,o]=await Promise.all([Yr(e.userGlobal),Yr(e.userProject)]),n={main:Number(r.mtimeMs),userGlobal:t?Number(t.mtimeMs):null,userProject:o?Number(o.mtimeMs):null};if(we&&ho(we.mtimes,n))return we.value;let s=[{label:"infra-kit.yml",path:e.main,required:!0},{label:"~/.infra-kit/config.yml",path:e.userGlobal,required:!1},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.yml`,path:e.userProject,required:!1}],a={};for(let c of s){let p=await wo(c);p!==null&&(a={...a,...p})}let l=Zr.safeParse(a);if(!l.success)throw new Error(`Invalid merged infra-kit config: ${y.prettifyError(l.error)}`);return we={mtimes:n,value:l.data},l.data};var Yr=async e=>{try{return await or.stat(e)}catch{return null}},go=async e=>{try{return await or.readFile(e,"utf-8")}catch{return null}},ho=(e,r)=>{let t=Object.keys(e);return t.length!==Object.keys(r).length?!1:t.every(o=>e[o]===r[o])},wo=async e=>{let r=await go(e.path);if(r===null){if(e.required)throw new Error(`${e.label} not found at ${e.path}`);return null}let t=ro.parse(r)??{},o=fo.safeParse(t);if(!o.success)throw new Error(`Invalid ${e.label} at ${e.path}: ${y.prettifyError(o.error)}`);return o.data};var ve=async()=>{let{envManagement:e}=await x();return e.config.name};var et=async()=>{let e=await ve(),{environments:r}=await x();i.info(`Doppler project: ${e}
|
|
7
|
+
`),i.info("Available configs:");for(let o of r)i.info(` - ${o}`);let t={project:e,configs:r};return{content:w(JSON.stringify(t,null,2)),structuredContent:t}},sr=v({name:"env-list",description:"List the environments the project is configured to support. Returns the `environments` list declared in infra-kit.yml at the project root (not a live fetch from Doppler) plus the Doppler project name resolved from the same file. Read-only.",inputSchema:{},outputSchema:{project:nr.string().describe("Detected Doppler project name"),configs:nr.array(nr.string()).describe("Available environment configs")},handler:et});import yo from"@inquirer/select";import{Buffer as Ro}from"node:buffer";import ko from"node:fs";import bo from"node:path";import tt from"node:process";import{z as Re}from"zod/v4";import{$ as We}from"zx";import{$ as rt}from"zx";var ye=async()=>{try{await rt`doppler --version`}catch(e){throw new Error("Doppler CLI is not installed. Install it from: https://docs.doppler.com/docs/install-cli",{cause:e})}try{await rt`doppler me`}catch(e){throw new Error("Doppler CLI is not authenticated. Run: doppler login",{cause:e})}};var vo=()=>{let e="",r=[],t=!1;return{start(o){e=o,r=[],t=!1},setInteractive(){t=!0},addOption(o,n){r.push({flag:o,value:n})},print(){if(!t||r.length===0)return;let o=r.map(n=>typeof n.value=="boolean"?n.value?n.flag:"":Array.isArray(n.value)?`${n.flag} "${n.value.join(", ")}"`:`${n.flag} "${n.value}"`).filter(Boolean).join(" ");i.info(`\u{1F4DF} Equivalent command:
|
|
8
8
|
pnpm exec infra-kit ${e} ${o}
|
|
9
|
-
`)},reset(){e="",r=[],t=!1}}},
|
|
9
|
+
`)},reset(){e="",r=[],t=!1}}},d=vo();var nt=async e=>{await ye();let{config:r}=e;d.start("env-load");let t="";if(r)t=r;else{let{environments:f}=await x();d.setInteractive(),t=await yo({message:"Select environment config",choices:f.map(u=>({name:u,value:u}))},{output:tt.stderr})}d.addOption("--config",t);let o=await ve(),n=await Co(o,t);Eo(n);let s=new Date().toISOString(),a=["set -a",n,`${re}=${ir(t)}`,`${te}=${ir(o)}`,`${oe}=${ir(s)}`,"set +a"],l=ne(),c=bo.resolve(l,ee);ko.mkdirSync(l,{recursive:!0,mode:448}),_e(c,`${a.join(`
|
|
10
10
|
`)}
|
|
11
|
-
`,384),
|
|
12
|
-
`),
|
|
13
|
-
`).filter(r=>
|
|
14
|
-
`)){let t=r.trim();if(!(t.length===0
|
|
11
|
+
`,384),tt.stdout.write(`${c}
|
|
12
|
+
`),d.print();let p=Po(n),m={filePath:c,variableCount:p,project:o,config:t};return{content:w(JSON.stringify(m,null,2)),structuredContent:m}},ot=1024*1024,xo=3e4,Co=async(e,r)=>{let t=We.quiet;We.quiet=!0;try{let o=await We`doppler secrets download --no-file --format env --project ${e} --config ${r}`.timeout(xo);return To(o.stdout),o.stdout.trim()}finally{We.quiet=t}},To=e=>{let r=Ro.byteLength(e,"utf-8");if(r>ot)throw new Error(`doppler returned unexpectedly large output (${r} bytes > ${ot}) \u2014 refusing to write to disk`)},Po=e=>e.split(`
|
|
13
|
+
`).filter(r=>Me.test(r)).length,$o=new Set(["set -a","set +a"]),ir=e=>`'${e.replaceAll("'","'\\''")}'`,Eo=e=>{if(e.trim().length===0)throw new Error("doppler returned empty output for env-load");for(let r of e.split(`
|
|
14
|
+
`)){let t=r.trim();if(!(t.length===0||$o.has(t))&&!Me.test(t))throw new Error(`doppler returned unexpected output for env-load (expected KEY=value lines, got: ${JSON.stringify(t.slice(0,80))})`)}},ar=v({name:"env-load",description:'Download the env vars for a Doppler config and write them to a temporary shell script. Does NOT mutate the calling process \u2014 returns the path to a script that must be sourced ("source <filePath>") for the vars to take effect. The infra-kit shell wrapper auto-sources; direct MCP callers must handle sourcing themselves or surface filePath to the user. "config" is required when invoked via MCP (the CLI interactive picker is unreachable without a TTY).',inputSchema:{config:Re.string().describe('Doppler config / environment name to load (e.g. "dev", "arthur", "renana"). Required for MCP calls.')},outputSchema:{filePath:Re.string().describe("Path to the file that must be sourced to apply variables"),variableCount:Re.number().describe("Number of variables loaded"),project:Re.string().describe("Doppler project name"),config:Re.string().describe("Doppler config name")},handler:nt});import So from"node:path";import ke from"node:process";import{z as se}from"zod/v4";var st=async()=>{await ye(),i.info("Environment session status:");let e=ne(),r=ke.env[Ne],t=So.join(e,ee),o=0,n=0,s=ke.env[re]??null,a=ke.env[te]??null,l=ke.env[oe]??null;if(s){let p=De(t);p.length>0&&(n=p.length,o=p.filter(f=>f in ke.env).length);let m=l?.replace(/\.\d{3}Z$/,"")??null;if(i.info(` ${s}: ${o} of ${n} vars loaded (project: ${a}, loadedAt: ${m}, session: ${r})
|
|
15
15
|
`),n>0&&o<n){let f=n-o;i.warn(` ${f} cached var(s) are not present in the current process \u2014 env-load needs to be re-sourced, or vars were unset manually.`)}}else i.info(` Session ${r}: no env loaded
|
|
16
|
-
`);let c={sessionId:r,sessionLoadedCount:o,sessionTotalCount:n,sessionConfig:s,sessionProject:a,sessionLoadedAt:l};return{content:
|
|
17
|
-
`);throw new Error(a)}let s=Number.parseInt(t,10);if(Number.isNaN(s))throw new TypeError(`Invalid JIRA_PROJECT_ID: "${t}" must be a numeric value (e.g., 10001)`);return{baseUrl:e.replace(/\/$/,""),token:r,projectId:s,email:o}},z=async()=>{try{return await ae()}catch(e){return i.warn({error:e},"Jira configuration not available, skipping Jira integration"),null}};var
|
|
18
|
-
`).map(o=>{let n=o.indexOf(" ");return n===-1?"":o.slice(n+1).replace(/^refs\/heads\//,"")}).filter(Boolean)}finally{
|
|
16
|
+
`);let c={sessionId:r,sessionLoadedCount:o,sessionTotalCount:n,sessionConfig:s,sessionProject:a,sessionLoadedAt:l};return{content:w(JSON.stringify(c,null,2)),structuredContent:c}},cr=v({name:"env-status",description:"Report which Doppler project/config is currently loaded in the terminal session, when it was loaded, and how many variables are cached. Read-only \u2014 use env-load / env-clear to change the terminal session.",inputSchema:{},outputSchema:{sessionId:se.string().describe("Current terminal session ID"),sessionLoadedCount:se.number().describe("Number of cached vars active in the current session"),sessionTotalCount:se.number().describe("Total number of cached var names"),sessionConfig:se.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:se.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:se.string().nullable().describe("ISO 8601 timestamp of when the env was loaded")},handler:st});import jo from"@inquirer/checkbox";import Fo from"@inquirer/confirm";import Wo from"node:process";import{z as pe}from"zod/v4";import{$ as D}from"zx";import{$ as ji}from"zx";import Ke from"node:process";import{$ as I}from"zx";import{$ as xe}from"zx";import be from"node:process";var lr=async(e,r)=>{try{let{baseUrl:t,token:o,email:n,projectId:s}=r,a={name:e.name,projectId:e.projectId||s,description:e.description||"",released:e.released||!1,archived:e.archived||!1},l=`${t}/rest/api/3/version`,c=btoa(`${n}:${o}`),p=await fetch(l,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${c}`},body:JSON.stringify(a)});if(!p.ok){let f=await p.text();throw i.error({status:p.status,statusText:p.statusText,error:f},"Failed to create Jira version"),new Error(`HTTP ${p.status}: ${p.statusText}`)}return{success:!0,version:await p.json()}}catch(t){throw i.error({error:t},"Error creating Jira version"),t}},ie=async e=>{try{let{baseUrl:r,token:t,email:o,projectId:n}=e,s=`${r}/rest/api/3/project/${n}/versions`,a=btoa(`${o}:${t}`),l=await fetch(s,{method:"GET",headers:{Accept:"application/json",Authorization:`Basic ${a}`}});if(!l.ok){let p=await l.text();throw i.error({status:l.status,statusText:l.statusText,error:p},"Failed to get Jira project versions"),new Error(`HTTP ${l.status}: ${l.statusText}`)}return await l.json()}catch(r){throw i.error({error:r},"Error getting Jira project versions"),r}},Je=async(e,r)=>{try{return(await ie(r)).find(n=>n.name===e)||null}catch(t){throw i.error({error:t,versionName:e},"Error finding Jira version by name"),t}},Ve=async(e,r)=>{try{let{baseUrl:t,token:o,email:n}=r,s={};e.released!==void 0&&(s.released=e.released),e.archived!==void 0&&(s.archived=e.archived),e.releaseDate!==void 0&&(s.releaseDate=e.releaseDate),e.description!==void 0&&(s.description=e.description);let a=`${t}/rest/api/3/version/${e.versionId}`,l=btoa(`${n}:${o}`),c=await fetch(a,{method:"PUT",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${l}`},body:JSON.stringify(s)});if(!c.ok){let m=await c.text();throw i.error({status:c.status,statusText:c.statusText,error:m},"Failed to update Jira version"),new Error(`HTTP ${c.status}: ${c.statusText}`)}return{success:!0,version:await c.json()}}catch(t){throw i.error({error:t},"Error updating Jira version"),t}},pr=async(e,r)=>{try{let{versionName:t}=e,o=await Je(t,r);if(!o)throw i.error({versionName:t},"Jira version not found"),new Error(`Version "${t}" not found in Jira project`);return await Ve({versionId:o.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},r)}catch(t){throw i.error({error:t},"Error delivering Jira release"),t}},ae=async()=>{let e=be.env.JIRA_BASE_URL,r=be.env.JIRA_TOKEN||be.env.JIRA_API_TOKEN,t=be.env.JIRA_PROJECT_ID,o=be.env.JIRA_EMAIL,n=[];if(e||n.push("JIRA_BASE_URL (e.g., https://your-domain.atlassian.net)"),r||n.push("JIRA_TOKEN or JIRA_API_TOKEN (your Jira API token)"),t||n.push("JIRA_PROJECT_ID (numeric project ID)"),o||n.push("JIRA_EMAIL (your Jira email address)"),n.length>0){let a=["Jira configuration is required but incomplete.","Please configure the following environment variables:",...n.map(l=>` - ${l}`),"","You can set these in your .env file or as environment variables."].join(`
|
|
17
|
+
`);throw new Error(a)}let s=Number.parseInt(t,10);if(Number.isNaN(s))throw new TypeError(`Invalid JIRA_PROJECT_ID: "${t}" must be a numeric value (e.g., 10001)`);return{baseUrl:e.replace(/\/$/,""),token:r,projectId:s,email:o}},z=async()=>{try{return await ae()}catch(e){return i.warn({error:e},"Jira configuration not available, skipping Jira integration"),null}};var Le=e=>e==="hotfix"?"main":"dev",mr=async(e="regular")=>{let r=Le(e);xe.quiet=!0,await xe`git fetch origin`,await xe`git switch ${r}`,await xe`git pull origin ${r}`,xe.quiet=!1},dr=async e=>{let{version:r,jiraConfig:t,description:o,type:n="regular"}=e,s=`v${r}`,a=await lr({name:s,projectId:t.projectId,description:o||"",released:!1,archived:!1},t),l=`${t.baseUrl}/projects/${a.version.projectId}/versions/${a.version.id}/tab/release-report-all-issues`,c=await Be({version:r,jiraVersionUrl:l,type:n,description:o});return{version:r,type:n,branchName:c.branchName,prUrl:c.prUrl,jiraVersionUrl:l}},C=async()=>{let e=new Map,r=await z();if(!r)return e;try{let t=await ie(r);for(let o of t)o.description&&e.set(o.name,o.description)}catch{}return e},ce=(e,r,t)=>{let o=t?" ".repeat(t-e.length+3):" ",n=`[${r}]`.padEnd(11);return`${e}${o}${n}`},R=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",S=e=>{let{branches:r,descriptions:t,types:o}=e,n=r.map(a=>a.replace("release/v","")),s=Math.max(...n.map(a=>a.length));return r.map((a,l)=>{let c=n[l],p=o?o.get(a)||"regular":void 0,m=t.get(`v${c}`),f=" ".repeat(s-c.length+3),u=p?ce(c,p,s):c;return m&&(u=p?`${u} ${m}`:`${c}${f}${m}`),{name:u,value:a}})};import{$ as Ue}from"zx";var L=e=>e.replace("release/","").slice(1).split(".").map(Number),le=e=>[...e].sort((r,t)=>{let[o,n,s]=L(r),[a,l,c]=L(t);return o!==a?(o??0)-(a??0):n!==l?(n??0)-(l??0):(s??0)-(c??0)});var at="next",Oo=/^v?(\d+)\.(\d+)\.(\d+)$/,Ao=e=>e.replace(/^.*release\//,""),ct=e=>{let r=Ao(e.trim()),t=Oo.exec(r);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null},it=e=>`${e[0]}.${e[1]}.${e[2]}`,ur=e=>{let r=[...e.remoteBranches??[],...e.jiraVersions??[]],t=[],o=new Set;for(let n of r){let s=ct(n);if(!s)continue;let a=it(s);o.has(a)||(o.add(a),t.push(s))}return le(t.map(n=>it(n))).map(n=>L(`v${n}`))},H=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},qe=(e,r)=>{if(e.length===0)throw new H;let t=e[e.length-1];if(r==="hotfix"){let[s,a]=t,l=e.reduce((c,p)=>p[0]===s&&p[1]===a?Math.max(c,p[2]):c,0);return`${s}.${a}.${l+1}`}let[o,n]=t;return`${o}.${n+1}.0`},lt=e=>e.trim().toLowerCase()===at;var fr=(e,r)=>{let t=[...r];return e.map(o=>{let n=o.version.trim();if(n==="")throw new Error("Release entry has an empty version");if(lt(n)){let l=qe(t,o.type);return t.push(L(`v${l}`)),{...o,version:l}}let s=ct(n);if(!s)throw new Error(`Invalid version "${n}". Expected semver like "1.2.5" or the token "next".`);let a=`${s[0]}.${s[1]}.${s[2]}`;return t.push(s),{...o,version:a}})},gr=e=>e.some(r=>lt(r.version));var No=async()=>{let e=Ue.quiet;try{return Ue.quiet=!0,(await Ue`git ls-remote --heads origin 'release/v*'`).stdout.split(`
|
|
18
|
+
`).map(o=>{let n=o.indexOf(" ");return n===-1?"":o.slice(n+1).replace(/^refs\/heads\//,"")}).filter(Boolean)}finally{Ue.quiet=e}},Mo=async()=>{let e=await z();return e?(await ie(e)).map(t=>t.name):[]},hr=async()=>{let[e,r]=await Promise.allSettled([No(),Mo()]);return e.status==="rejected"&&i.warn({error:e.reason},"Failed to list remote release branches; continuing without them"),r.status==="rejected"&&i.warn({error:r.reason},"Failed to fetch Jira versions; continuing without them"),ur({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:r.status==="fulfilled"?r.value:[]})};var pt=async()=>{let e=await I`gh pr list --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName`,r=await I`gh pr list --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName`,t=[...JSON.parse(e.stdout),...JSON.parse(r.stdout)],o=new Set;return t.filter(n=>o.has(n.headRefName)?!1:(o.add(n.headRefName),!0))},Ge=async()=>{try{let e=await pt();return e.length===0&&(i.error("\u274C No release PRs found. Check the project folder for the script. Exiting..."),Ke.exit(1)),le(e.map(r=>r.headRefName))}catch(e){i.error({error:e},"\u274C Error fetching release PRs"),Ke.exit(1)}},k=async()=>{try{let e=await pt();e.length===0&&(i.error("\u274C No release PRs found. Check the project folder for the script. Exiting..."),Ke.exit(1));let r=le(e.map(o=>o.headRefName)),t=new Map(e.map(o=>[o.headRefName,o]));return r.map(o=>({branch:o,title:t.get(o).title}))}catch(e){i.error({error:e},"\u274C Error fetching release PRs"),Ke.exit(1)}},ze=async e=>{let{branch:r,body:t}=e;try{I.quiet=!0,await I`gh pr edit ${r} --body ${t}`,I.quiet=!1}catch(o){throw i.error({error:o,branch:r},`Error updating release PR body for ${r}`),o}},Be=async e=>{let{version:r,jiraVersionUrl:t,type:o,description:n}=e,s=o==="hotfix"?"Hotfix":"Release",a=Le(o),l=`release/v${r}`,c=n&&n.trim()!==""?`${t}
|
|
19
19
|
|
|
20
20
|
${n}`:`${t}
|
|
21
|
-
`;try{
|
|
21
|
+
`;try{I.quiet=!0,await I`git switch ${a}`,await I`git pull origin ${a}`,await I`git checkout -b ${l}`,await I`git push -u origin ${l}`,await I`git commit --allow-empty-message --allow-empty --message ''`,await I`git push origin ${l}`;let m=(await I`gh pr create --title "${s} v${r}" --body ${c} --base ${a} --head ${l}`).stdout.trim();return await I`git switch ${a}`,I.quiet=!1,{branchName:l,prUrl:m}}catch(p){throw i.error({error:p,branchName:l},`Error creating release branch ${l}`),p}};var Do=e=>{if(e===null||typeof e!="object")return;let r=e.stderr;return typeof r=="string"&&r.length>0?r:void 0},_o=(e,r)=>{let t=r.stderrExcerpt??Do(e),o=[`failed to ${r.operation}`];return t&&o.push(`stderr: ${t.slice(0,200).trim()}`),r.remediation&&o.push(`try: ${r.remediation}`),o.join(" \u2014 ")},h=class extends Error{operation;remediation;constructor(r,t){super(_o(r,t),{cause:r}),this.name="OperationError",this.operation=t.operation,this.remediation=t.remediation}};var mt=async e=>{let{all:r,confirmedCommand:t}=e;d.start("merge-dev");let n=(await k()).filter(m=>R(m.title)==="regular").map(m=>m.branch);if(n.length===0)return i.info("\u2139\uFE0F No open release branches found"),d.print(),{content:w(JSON.stringify({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0},null,2)),structuredContent:{successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0}};let s=[];if(r)s=n;else{d.setInteractive();let m=await C();s=await jo({required:!0,message:"\u{1F33F} Select release branches",choices:S({branches:n,descriptions:m})})}s.length===n.length?d.addOption("--all",!0):d.addOption("--versions",s.map(m=>m.replace("release/v","")));let l=t?!0:await Fo({message:`Are you sure you want to merge dev into these branches: ${s.join(", ")}?`});t||d.setInteractive(),l||(i.info("Operation cancelled. Exiting..."),Wo.exit(0)),t||d.addOption("--yes",!0),D.quiet=!0,await D`git fetch origin`,await D`git switch dev`,await D`git pull origin dev`;let c=[];for(let m of s)await Jo(m)||c.push(m);if(D.quiet=!1,c.length>0){i.info(`
|
|
22
22
|
\u26A0\uFE0F ${c.length} branch(es) failed to merge automatically.
|
|
23
|
-
`),i.info("\u{1F4CB} Manual merge script for failed branches:");for(let
|
|
23
|
+
`),i.info("\u{1F4CB} Manual merge script for failed branches:");for(let m of c)i.info(`# Merge dev into ${m} and resolve conflicts if any
|
|
24
24
|
|
|
25
|
-
git switch ${
|
|
26
|
-
git push origin ${
|
|
25
|
+
git switch ${m} && git pull origin ${m} && git merge origin/dev
|
|
26
|
+
git push origin ${m} && git switch dev
|
|
27
27
|
`);i.info(`\u2705 ${s.length-c.length}/${s.length} merges completed successfully.`)}else i.info(`\u2705 All merges completed successfully!
|
|
28
|
-
`);m.print();let p={successfulMerges:s.length-c.length,failedMerges:c.length,failedBranches:c,totalBranches:s.length};return{content:h(JSON.stringify(p,null,2)),structuredContent:p}},Wo=async e=>{try{return await D`git switch ${e}`,await D`git pull origin ${e}`,await D`git merge origin/dev --no-edit`,await D`git push origin ${e}`,await D`git switch dev`,i.info(`Successfully merged dev into ${e}`),!0}catch(r){let t=new w(r,{operation:`merge dev into ${e}`,remediation:"resolve conflicts manually or rerun after 'git fetch origin'"});return i.error({error:r,branch:e,msg:t.message}),await D`git reset --merge HEAD~1`,!1}},hr=v({name:"gh-merge-dev",description:"Merge origin/dev into every open regular (non-hotfix) release branch and push the result. Mutates local git state and the remote release branches. When invoked via MCP, pass all=true \u2014 the branch picker is unreachable without a TTY, and the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. Irreversible once pushed.",inputSchema:{all:pe.boolean().optional().describe("Target every open regular release branch. Must be true for MCP calls (the interactive picker is unavailable without a TTY).")},outputSchema:{successfulMerges:pe.number().describe("Number of successful merges"),failedMerges:pe.number().describe("Number of failed merges"),failedBranches:pe.array(pe.string()).describe("List of branches that failed to merge"),totalBranches:pe.number().describe("Total number of branches processed")},handler:pt});import Jo from"@inquirer/confirm";import Vo from"@inquirer/select";import Lo from"node:process";import{z as Ce}from"zod/v4";import{$ as O}from"zx";var dt=(e,r)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-r).trim()},wr=e=>{if(e===null||typeof e!="object")return{message:String(e)};let r=e,t={};e instanceof Error?(t.name=e.name,t.message=e.message):typeof r.message=="string"&&(t.message=r.message);let o=r.exitCode;(typeof o=="number"||o===null)&&(t.exitCode=o);let n=dt(r.stderr,500);n&&(t.stderr=n);let s=dt(r.stdout,200);return s&&(t.stdout=s),t};var de=async(e,r,t)=>{try{return await t()}catch(o){throw i.error({err:wr(o)},`\u274C Failed to ${e}`),new w(o,{operation:e,remediation:r})}},ut=async e=>{let r=await O`gh pr list --head ${e} --state all --json number,state,title --limit 1`;return JSON.parse(r.stdout)[0]??null},Bo=async e=>{let r=`Release v${e} (RC)`,t=await O`gh pr list --head dev --base main --state merged --json number,state,title --limit 20`;return JSON.parse(t.stdout).find(s=>s.title===r)??null},mt=async()=>{let e=await O`gh pr list --head dev --base main --state open --json number,state,title --limit 5`;return JSON.parse(e.stdout)[0]??null},qo=async e=>{let r=`release/v${e}`,t=await ut(r);if(!t)throw i.error(`\u274C No PR found for branch ${r}.`),new w(void 0,{operation:`deliver release ${r}`,remediation:`confirm a PR exists ('gh pr list --head ${r} --state all')`});return{selectedReleaseBranch:r,releasePrTitle:t.title}},Uo=async()=>{let e=await k(),r=e.map(a=>a.branch),t=new Map(e.map(a=>[a.branch,R(a.title)]));m.setInteractive();let o=await C(),n=await Vo({message:"\u{1F33F} Select release branch",choices:E({branches:r,descriptions:o,types:t})}),s=e.find(a=>a.branch===n);if(!s)throw i.error(`\u274C Release branch ${n} not found in open PRs.`),new w(void 0,{operation:`deliver release ${n}`,remediation:`confirm an open PR exists for ${n} ('gh pr list')`});return{selectedReleaseBranch:n,releasePrTitle:s.title}},Ko=async e=>{let{selectedReleaseBranch:r,releaseType:t}=e,o=t==="hotfix"?"main":"dev",n=await ut(r);if(!n)throw new w(void 0,{operation:`look up release PR for ${r}`,remediation:"verify the PR exists in GitHub"});if(n.state==="MERGED"){i.info(`\u2713 Release PR ${r} already merged \u2014 skipping`);return}if(n.state==="CLOSED")throw new w(void 0,{operation:`merge release PR ${r} into ${o}`,remediation:"the PR is closed without merge; reopen it or create a new release"});await de(`merge release PR ${r} into ${o}`,`check 'gh pr view ${r}' for mergeability and required reviews`,async()=>{await O`gh pr merge ${r} --squash --admin --delete-branch`})},Go=async e=>{let r=`Release v${e} (RC)`,t=await mt();if(t){let n=t.number;return t.title!==r&&(i.info(`Adopting open dev \u2192 main PR #${n} ("${t.title}") and retitling for v${e}`),await de(`retitle dev \u2192 main PR #${n} to "${r}"`,`update manually: gh pr edit ${n} --title "${r}"`,async()=>{await O`gh pr edit ${n} --title ${r}`})),n}await de(`create RC PR (dev \u2192 main) for v${e}`,"run 'gh pr create --base main --head dev' manually to surface the underlying error (e.g. no commits between dev and main)",async()=>{await O`gh pr create --base main --head dev --title ${r} --body ""`});let o=await mt();if(!o)throw new w(void 0,{operation:`look up RC PR for v${e}`,remediation:"verify the RC PR was created ('gh pr list --head dev --base main')"});return o.number},zo=async e=>{if(await Bo(e)){i.info(`\u2713 RC PR for v${e} already merged into main \u2014 skipping`);return}let t=await Go(e);await de(`merge RC PR #${t} (dev \u2192 main) for v${e}`,`check 'gh pr view ${t}' for mergeability and required reviews`,async()=>{await O`gh pr merge ${t} --squash --admin`})},Ho=async()=>{O.quiet=!1,await de("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await O`gh workflow run deploy-all.yml --ref main -f environment=prod`}),O.quiet=!0},Xo=async()=>{await de("sync main back into dev","run manually: git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push",async()=>{await O`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},Yo=async e=>{let r=await z();if(!r){i.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let t=e.replace("release/","");await lr({versionName:t},r)}catch(t){i.error({err:wr(t)},"Failed to deliver Jira release (non-blocking)")}},ft=async e=>{let{version:r,confirmedCommand:t}=e;m.start("release-deliver");let{selectedReleaseBranch:o,releasePrTitle:n}=r?await qo(r):await Uo(),s=o.replace("release/v","");m.addOption("--version",s);let a=R(n),l=t?!0:await Jo({message:`Are you sure you want to deliver version ${o} to production?`});t||m.setInteractive(),l||(i.info("Operation cancelled. Exiting..."),Lo.exit(0)),m.addOption("--yes",!0),O.quiet=!0,await Ko({selectedReleaseBranch:o,releaseType:a}),a!=="hotfix"&&await zo(s),await Ho(),await Xo(),O.quiet=!1,await Yo(o),i.info(`Successfully delivered ${o} to production!`),m.print();let c={releaseBranch:o,version:s,type:a,success:!0};return{content:h(JSON.stringify(c,null,2)),structuredContent:c}},vr=v({name:"gh-release-deliver",description:'Deliver a release to production. For hotfixes: squash-merges the release branch to main and dispatches the deploy-all workflow. For regular releases: squash-merges to dev, opens an RC PR, merges dev into main, dispatches the deploy-all workflow, then syncs main back to dev. Also releases the matching Jira fix version if Jira is configured. Dispatches the deploy workflow fire-and-forget \u2014 the tool returns once the workflow is accepted by GitHub, not when the deployment finishes. PR-merge steps are idempotent: re-running after a partial failure skips PRs that are already merged. Irreversible production operation: the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. "version" is required when invoked via MCP (the picker is unreachable without a TTY).',inputSchema:{version:Ce.string().describe('Release version to deliver to production (e.g., "1.2.5"). Required for MCP calls.')},outputSchema:{releaseBranch:Ce.string().describe("The release branch that was delivered"),version:Ce.string().describe("The version that was delivered"),type:Ce.enum(["regular","hotfix"]).describe("Release type"),success:Ce.boolean().describe("Whether the delivery was successful")},handler:ft});import gt from"@inquirer/select";import{z as B}from"zod/v4";import{$ as yr}from"zx";var ht=async e=>{let{version:r,env:t,skipTerraform:o}=e;m.start("release-deploy-all");let n="";if(r)n=r==="dev"?"dev":`release/v${r}`;else{m.setInteractive();let p=await k(),d=p.map(g=>g.branch),f=new Map(p.map(g=>[g.branch,R(g.title)])),u=await C();n=await gt({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...E({branches:d,descriptions:u,types:f})]})}let s=n==="dev"?"dev":n.replace("release/v","");m.addOption("--version",s);let{environments:a}=await x(),l="";if(t?l=t:(m.setInteractive(),l=await gt({message:"\u{1F9EA} Select environment",choices:a.map(p=>({name:p,value:p}))})),m.addOption("--env",l),!a.includes(l))throw new w(void 0,{operation:"launch deploy-all workflow",remediation:`pass one of: ${a.join(", ")}`,stderrExcerpt:`invalid environment: ${l}`});let c=o??!1;c&&m.addOption("--skip-terraform",!0);try{yr.quiet=!0,await yr`gh workflow run deploy-all.yml --ref ${n} -f environment=${l} ${c?["-f","skip_terraform_deploy=true"]:[]}`,yr.quiet=!1,i.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${n} and environment: ${l}`),m.print();let d={releaseBranch:n,version:n.replace("release/v",""),environment:l,skipTerraformDeploy:c,success:!0};return{content:h(JSON.stringify(d,null,2)),structuredContent:d}}catch(p){throw i.error({error:p},"\u274C Error launching workflow"),new w(p,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},Rr=v({name:"gh-release-deploy-all",description:'Dispatch the deploy-all.yml GitHub Actions workflow to deploy every service from a release branch to the given environment. Fire-and-forget \u2014 returns once GitHub accepts the workflow_dispatch, NOT when the deployment finishes; watch the workflow run for completion status. Use gh-release-deploy-selected for a subset of services. Pass version="dev" to deploy from the dev branch instead of a release branch. Both "version" and "env" are required when invoked via MCP (interactive pickers are unavailable without a TTY).',inputSchema:{version:B.string().describe('Release version to deploy from (e.g. "1.2.5") \u2014 resolves to the release/vX.Y.Z branch. Pass "dev" to deploy from the dev branch instead. Required for MCP calls.'),env:B.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),skipTerraform:B.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:B.string().describe("The release branch that was deployed"),version:B.string().describe("The version that was deployed"),environment:B.string().describe("The environment deployed to"),skipTerraformDeploy:B.boolean().describe("Whether terraform deployment was skipped"),success:B.boolean().describe("Whether the deployment was successful")},handler:ht});import Zo from"@inquirer/checkbox";import wt from"@inquirer/select";import Qo from"node:fs/promises";import{resolve as en}from"node:path";import rn from"yaml";import{z as A}from"zod/v4";import{$ as kr}from"zx";var vt=async e=>{let{version:r,env:t,services:o,skipTerraform:n}=e;m.start("release-deploy-selected");let s="";if(r)s=r==="dev"?"dev":`release/v${r}`;else{m.setInteractive();let g=await k(),T=g.map(Q=>Q.branch),P=new Map(g.map(Q=>[Q.branch,R(Q.title)])),_=await C();s=await wt({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...E({branches:T,descriptions:_,types:P})]})}let a=s==="dev"?"dev":s.replace("release/v","");m.addOption("--version",a);let{environments:l}=await x(),c="";if(t?c=t:(m.setInteractive(),c=await wt({message:"\u{1F9EA} Select environment",choices:l.map(g=>({name:g,value:g}))})),m.addOption("--env",c),!l.includes(c))throw new w(void 0,{operation:"launch deploy-selected workflow",remediation:`pass one of: ${l.join(", ")}`,stderrExcerpt:`invalid environment: ${c}`});let p=await tn();if(p.length===0)throw new w(void 0,{operation:"launch deploy-selected workflow",remediation:"check .github/workflows/deploy-selected-services.yml for boolean service inputs",stderrExcerpt:"no services found in workflow file"});let d=[];if(o&&o.length>0?d=o:(m.setInteractive(),d=await Zo({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:p.map(g=>({name:g,value:g}))})),m.addOption("--services",d),d.length===0)throw new w(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${p.join(", ")}`,stderrExcerpt:"no services selected"});let f=d.filter(g=>!p.includes(g));if(f.length>0)throw new w(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${p.join(", ")}`,stderrExcerpt:`invalid services: ${f.join(", ")}`});let u=n??!1;u&&m.addOption("--skip-terraform",!0);try{kr.quiet=!0;let g=d.flatMap(_=>["-f",`${_}=true`]);await kr`gh workflow run deploy-selected-services.yml --ref ${s} -f environment=${c} ${g} ${u?["-f","skip_terraform_deploy=true"]:[]}`,kr.quiet=!1,i.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${s}, environment: ${c}, services: ${d.join(", ")}`),m.print();let P={releaseBranch:s,version:s.replace("release/v",""),environment:c,services:d,skipTerraformDeploy:u,success:!0};return{content:h(JSON.stringify(P,null,2)),structuredContent:P}}catch(g){throw i.error({error:g},"\u274C Error launching workflow"),new w(g,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},tn=async()=>{let e=await I(),r=en(e,".github/workflows/deploy-selected-services.yml"),t=await Qo.readFile(r,"utf-8"),n=rn.parse(t).on.workflow_dispatch.inputs,s=[];for(let[a,l]of Object.entries(n))l.type==="boolean"&&a!=="skip_terraform_deploy"&&s.push(a);return s},br=v({name:"gh-release-deploy-selected",description:'Dispatch the deploy-selected-services.yml GitHub Actions workflow to deploy a chosen subset of services from a release branch to the given environment. Fire-and-forget \u2014 returns once GitHub accepts the workflow_dispatch, NOT when the deployment finishes; watch the workflow run for completion status. Service names are validated against the boolean inputs declared in the workflow. Use gh-release-deploy-all for every service. "version", "env", and "services" are all required when invoked via MCP (interactive pickers are unavailable without a TTY).',inputSchema:{version:A.string().describe('Release version to deploy from (e.g. "1.2.5") \u2014 resolves to the release/vX.Y.Z branch. Pass "dev" to deploy from the dev branch instead. Required for MCP calls.'),env:A.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),services:A.array(A.string()).describe('Service names to deploy. Each must match a boolean input declared in .github/workflows/deploy-selected-services.yml (e.g. "client-be", "client-fe"). Required for MCP calls.'),skipTerraform:A.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:A.string().describe("The release branch that was deployed"),version:A.string().describe("The version that was deployed"),environment:A.string().describe("The environment deployed to"),services:A.array(A.string()).describe("The services that were deployed"),skipTerraformDeploy:A.boolean().describe("Whether terraform deployment was skipped"),success:A.boolean().describe("Whether the deployment was successful")},handler:vt});import{z as me}from"zod/v4";var yt=async()=>{let r=(await k()).map(a=>({version:a.branch.replace("release/",""),type:R(a.title)})),t=await C(),o=Math.max(...r.map(a=>a.version.length)),n=r.map(a=>{let l=ce(a.version,a.type,o),c=t.get(a.version);return c?`${l} ${c}`:l});i.info(`All release branches:
|
|
28
|
+
`);d.print();let p={successfulMerges:s.length-c.length,failedMerges:c.length,failedBranches:c,totalBranches:s.length};return{content:w(JSON.stringify(p,null,2)),structuredContent:p}},Jo=async e=>{try{return await D`git switch ${e}`,await D`git pull origin ${e}`,await D`git merge origin/dev --no-edit`,await D`git push origin ${e}`,await D`git switch dev`,i.info(`Successfully merged dev into ${e}`),!0}catch(r){let t=new h(r,{operation:`merge dev into ${e}`,remediation:"resolve conflicts manually or rerun after 'git fetch origin'"});return i.error({error:r,branch:e,msg:t.message}),await D`git reset --merge HEAD~1`,!1}},wr=v({name:"gh-merge-dev",description:"Merge origin/dev into every open regular (non-hotfix) release branch and push the result. Mutates local git state and the remote release branches. When invoked via MCP, pass all=true \u2014 the branch picker is unreachable without a TTY, and the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. Irreversible once pushed.",inputSchema:{all:pe.boolean().optional().describe("Target every open regular release branch. Must be true for MCP calls (the interactive picker is unavailable without a TTY).")},outputSchema:{successfulMerges:pe.number().describe("Number of successful merges"),failedMerges:pe.number().describe("Number of failed merges"),failedBranches:pe.array(pe.string()).describe("List of branches that failed to merge"),totalBranches:pe.number().describe("Total number of branches processed")},handler:mt});import Uo from"@inquirer/confirm";import Ko from"@inquirer/select";import Go from"node:process";import{z as Ee}from"zod/v4";import{$ as N}from"zx";var dt=(e,r)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-r).trim()},vr=e=>{if(e===null||typeof e!="object")return{message:String(e)};let r=e,t={};e instanceof Error?(t.name=e.name,t.message=e.message):typeof r.message=="string"&&(t.message=r.message);let o=r.exitCode;(typeof o=="number"||o===null)&&(t.exitCode=o);let n=dt(r.stderr,500);n&&(t.stderr=n);let s=dt(r.stdout,200);return s&&(t.stdout=s),t};import{$ as Rr}from"zx";import{$ as ut}from"zx";var Ce=async e=>{try{let r=(await ut`cmux list-workspaces`.quiet()).stdout,t=Vo(r,e);if(!t)return;await ut`cmux close-workspace --workspace ${t}`.quiet()}catch(r){i.debug({error:r,title:e},"cmux: skipped closing workspace")}},Vo=(e,r)=>{for(let t of e.split(`
|
|
29
|
+
`)){let o=t.match(/^[* ]\s*(workspace:\d+)\s+(.+?)(?:\s+\[selected\])?\s*$/);if(!o)continue;let n=o[1];if((o[2]?.trim()??"")===r)return n}};import{$ as Lo}from"zx";var yr=async()=>{try{let e=(await Lo`cmux list-workspaces`.quiet()).stdout,r=new Set;for(let t of e.split(`
|
|
30
|
+
`)){let o=t.match(/^[* ]\s*workspace:\d+\s+(.+?)(?:\s+\[selected\])?\s*$/);if(!o)continue;let n=o[1]?.trim();n&&r.add(n)}return r}catch(e){return i.debug({error:e},"cmux: skipped listing workspace titles"),new Set}};import{$ as Te}from"zx";var Pe=async e=>{let{cwd:r,title:t}=e,o=(await Te`cmux new-workspace --cwd ${r}`).stdout,n=qo(o),s=(await Te`cmux list-pane-surfaces --workspace ${n}`).stdout,a=Bo(s);await Te`cmux new-split right --workspace ${n} --surface ${a}`,await Te`cmux new-split down --workspace ${n} --surface ${a}`,t&&await Te`cmux rename-workspace --workspace ${n} ${t}`},Bo=e=>{let r=e.match(/surface:\d+/);if(!r)throw new Error("cmux: could not locate initial surface in list-pane-surfaces output");return r[0]},qo=e=>{let r=e.match(/workspace:\d+/);if(!r)throw new Error("cmux: could not locate workspace ref in new-workspace output");return r[0]};var F=e=>{let{repoName:r,branch:t}=e,o=t.replace("release/","");return`${r} ${o}`};var $e=async e=>{let{branches:r,worktreeDir:t,repoName:o,pruneFolder:n=!1}=e,s=await Promise.allSettled(r.map(async l=>{let c=`${t}/${l}`,p=F({repoName:o,branch:l});return await Ce(p),await Rr`git worktree remove ${c}`,l})),a=[];for(let[l,c]of s.entries())if(c.status==="fulfilled")a.push(c.value);else{let p=r[l],m=new h(c.reason,{operation:`remove worktree for ${p}`,remediation:"check 'git worktree list' for the path; uncommitted changes block removal"});i.error({error:c.reason,msg:m.message})}return n&&a.length===r.length&&(await Rr`git worktree prune`,await Rr`rm -rf ${t}`,i.info(`\u{1F5D1}\uFE0F Removed worktree folder: ${t}`),i.info("")),a};var me=async(e,r,t)=>{try{return await t()}catch(o){throw i.error({err:vr(o)},`\u274C Failed to ${e}`),new h(o,{operation:e,remediation:r})}},gt=async e=>{let r=await N`gh pr list --head ${e} --state all --json number,state,title --limit 1`;return JSON.parse(r.stdout)[0]??null},zo=async e=>{let r=`Release v${e} (RC)`,t=await N`gh pr list --head dev --base main --state merged --json number,state,title --limit 20`;return JSON.parse(t.stdout).find(s=>s.title===r)??null},ft=async()=>{let e=await N`gh pr list --head dev --base main --state open --json number,state,title --limit 5`;return JSON.parse(e.stdout)[0]??null},Ho=async e=>{let r=`release/v${e}`,t=await gt(r);if(!t)throw i.error(`\u274C No PR found for branch ${r}.`),new h(void 0,{operation:`deliver release ${r}`,remediation:`confirm a PR exists ('gh pr list --head ${r} --state all')`});return{selectedReleaseBranch:r,releasePrTitle:t.title}},Xo=async()=>{let e=await k(),r=e.map(a=>a.branch),t=new Map(e.map(a=>[a.branch,R(a.title)]));d.setInteractive();let o=await C(),n=await Ko({message:"\u{1F33F} Select release branch",choices:S({branches:r,descriptions:o,types:t})}),s=e.find(a=>a.branch===n);if(!s)throw i.error(`\u274C Release branch ${n} not found in open PRs.`),new h(void 0,{operation:`deliver release ${n}`,remediation:`confirm an open PR exists for ${n} ('gh pr list')`});return{selectedReleaseBranch:n,releasePrTitle:s.title}},Yo=async e=>{if(!(await O("release")).includes(e))return;let[t,o]=await Promise.all([E(),A()]),n=`${t}${j}`;if((await $e({branches:[e],worktreeDir:n,repoName:o})).length===0)throw new h(void 0,{operation:`remove worktree for ${e} before merge`,remediation:`run manually: git worktree remove ${n}/${e} (use --force if uncommitted changes)`})},Zo=async e=>{let{selectedReleaseBranch:r,releaseType:t}=e,o=t==="hotfix"?"main":"dev",n=await gt(r);if(!n)throw new h(void 0,{operation:`look up release PR for ${r}`,remediation:"verify the PR exists in GitHub"});if(n.state==="MERGED"){i.info(`\u2713 Release PR ${r} already merged \u2014 skipping`);return}if(n.state==="CLOSED")throw new h(void 0,{operation:`merge release PR ${r} into ${o}`,remediation:"the PR is closed without merge; reopen it or create a new release"});await me(`merge release PR ${r} into ${o}`,`check 'gh pr view ${r}' for mergeability and required reviews`,async()=>{await N`gh pr merge ${r} --squash --admin --delete-branch`})},Qo=async e=>{let r=`Release v${e} (RC)`,t=await ft();if(t){let n=t.number;return t.title!==r&&(i.info(`Adopting open dev \u2192 main PR #${n} ("${t.title}") and retitling for v${e}`),await me(`retitle dev \u2192 main PR #${n} to "${r}"`,`update manually: gh pr edit ${n} --title "${r}"`,async()=>{await N`gh pr edit ${n} --title ${r}`})),n}await me(`create RC PR (dev \u2192 main) for v${e}`,"run 'gh pr create --base main --head dev' manually to surface the underlying error (e.g. no commits between dev and main)",async()=>{await N`gh pr create --base main --head dev --title ${r} --body ""`});let o=await ft();if(!o)throw new h(void 0,{operation:`look up RC PR for v${e}`,remediation:"verify the RC PR was created ('gh pr list --head dev --base main')"});return o.number},en=async e=>{if(await zo(e)){i.info(`\u2713 RC PR for v${e} already merged into main \u2014 skipping`);return}let t=await Qo(e);await me(`merge RC PR #${t} (dev \u2192 main) for v${e}`,`check 'gh pr view ${t}' for mergeability and required reviews`,async()=>{await N`gh pr merge ${t} --squash --admin`})},rn=async()=>{N.quiet=!1,await me("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await N`gh workflow run deploy-all.yml --ref main -f environment=prod`}),N.quiet=!0},tn=async()=>{await me("sync main back into dev","run manually: git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push",async()=>{await N`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},on=async e=>{let r=await z();if(!r){i.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let t=e.replace("release/","");await pr({versionName:t},r)}catch(t){i.error({err:vr(t)},"Failed to deliver Jira release (non-blocking)")}},ht=async e=>{let{version:r,confirmedCommand:t}=e;d.start("release-deliver");let{selectedReleaseBranch:o,releasePrTitle:n}=r?await Ho(r):await Xo(),s=o.replace("release/v","");d.addOption("--version",s);let a=R(n),l=t?!0:await Uo({message:`Are you sure you want to deliver version ${o} to production?`});t||d.setInteractive(),l||(i.info("Operation cancelled. Exiting..."),Go.exit(0)),d.addOption("--yes",!0),N.quiet=!0,await Yo(o),await Zo({selectedReleaseBranch:o,releaseType:a}),a!=="hotfix"&&await en(s),await rn(),await tn(),N.quiet=!1,await on(o),i.info(`Successfully delivered ${o} to production!`),d.print();let c={releaseBranch:o,version:s,type:a,success:!0};return{content:w(JSON.stringify(c,null,2)),structuredContent:c}},kr=v({name:"gh-release-deliver",description:'Deliver a release to production. For hotfixes: squash-merges the release branch to main and dispatches the deploy-all workflow. For regular releases: squash-merges to dev, opens an RC PR, merges dev into main, dispatches the deploy-all workflow, then syncs main back to dev. Also releases the matching Jira fix version if Jira is configured. Dispatches the deploy workflow fire-and-forget \u2014 the tool returns once the workflow is accepted by GitHub, not when the deployment finishes. PR-merge steps are idempotent: re-running after a partial failure skips PRs that are already merged. Irreversible production operation: the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. "version" is required when invoked via MCP (the picker is unreachable without a TTY).',inputSchema:{version:Ee.string().describe('Release version to deliver to production (e.g., "1.2.5"). Required for MCP calls.')},outputSchema:{releaseBranch:Ee.string().describe("The release branch that was delivered"),version:Ee.string().describe("The version that was delivered"),type:Ee.enum(["regular","hotfix"]).describe("Release type"),success:Ee.boolean().describe("Whether the delivery was successful")},handler:ht});import wt from"@inquirer/select";import{z as B}from"zod/v4";import{$ as br}from"zx";var vt=async e=>{let{version:r,env:t,skipTerraform:o}=e;d.start("release-deploy-all");let n="";if(r)n=r==="dev"?"dev":`release/v${r}`;else{d.setInteractive();let p=await k(),m=p.map(g=>g.branch),f=new Map(p.map(g=>[g.branch,R(g.title)])),u=await C();n=await wt({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...S({branches:m,descriptions:u,types:f})]})}let s=n==="dev"?"dev":n.replace("release/v","");d.addOption("--version",s);let{environments:a}=await x(),l="";if(t?l=t:(d.setInteractive(),l=await wt({message:"\u{1F9EA} Select environment",choices:a.map(p=>({name:p,value:p}))})),d.addOption("--env",l),!a.includes(l))throw new h(void 0,{operation:"launch deploy-all workflow",remediation:`pass one of: ${a.join(", ")}`,stderrExcerpt:`invalid environment: ${l}`});let c=o??!1;c&&d.addOption("--skip-terraform",!0);try{br.quiet=!0,await br`gh workflow run deploy-all.yml --ref ${n} -f environment=${l} ${c?["-f","skip_terraform_deploy=true"]:[]}`,br.quiet=!1,i.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${n} and environment: ${l}`),d.print();let m={releaseBranch:n,version:n.replace("release/v",""),environment:l,skipTerraformDeploy:c,success:!0};return{content:w(JSON.stringify(m,null,2)),structuredContent:m}}catch(p){throw i.error({error:p},"\u274C Error launching workflow"),new h(p,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},xr=v({name:"gh-release-deploy-all",description:'Dispatch the deploy-all.yml GitHub Actions workflow to deploy every service from a release branch to the given environment. Fire-and-forget \u2014 returns once GitHub accepts the workflow_dispatch, NOT when the deployment finishes; watch the workflow run for completion status. Use gh-release-deploy-selected for a subset of services. Pass version="dev" to deploy from the dev branch instead of a release branch. Both "version" and "env" are required when invoked via MCP (interactive pickers are unavailable without a TTY).',inputSchema:{version:B.string().describe('Release version to deploy from (e.g. "1.2.5") \u2014 resolves to the release/vX.Y.Z branch. Pass "dev" to deploy from the dev branch instead. Required for MCP calls.'),env:B.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),skipTerraform:B.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:B.string().describe("The release branch that was deployed"),version:B.string().describe("The version that was deployed"),environment:B.string().describe("The environment deployed to"),skipTerraformDeploy:B.boolean().describe("Whether terraform deployment was skipped"),success:B.boolean().describe("Whether the deployment was successful")},handler:vt});import nn from"@inquirer/checkbox";import yt from"@inquirer/select";import sn from"node:fs/promises";import{resolve as an}from"node:path";import cn from"yaml";import{z as M}from"zod/v4";import{$ as Cr}from"zx";var Rt=async e=>{let{version:r,env:t,services:o,skipTerraform:n}=e;d.start("release-deploy-selected");let s="";if(r)s=r==="dev"?"dev":`release/v${r}`;else{d.setInteractive();let g=await k(),T=g.map(Q=>Q.branch),P=new Map(g.map(Q=>[Q.branch,R(Q.title)])),_=await C();s=await yt({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...S({branches:T,descriptions:_,types:P})]})}let a=s==="dev"?"dev":s.replace("release/v","");d.addOption("--version",a);let{environments:l}=await x(),c="";if(t?c=t:(d.setInteractive(),c=await yt({message:"\u{1F9EA} Select environment",choices:l.map(g=>({name:g,value:g}))})),d.addOption("--env",c),!l.includes(c))throw new h(void 0,{operation:"launch deploy-selected workflow",remediation:`pass one of: ${l.join(", ")}`,stderrExcerpt:`invalid environment: ${c}`});let p=await ln();if(p.length===0)throw new h(void 0,{operation:"launch deploy-selected workflow",remediation:"check .github/workflows/deploy-selected-services.yml for boolean service inputs",stderrExcerpt:"no services found in workflow file"});let m=[];if(o&&o.length>0?m=o:(d.setInteractive(),m=await nn({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:p.map(g=>({name:g,value:g}))})),d.addOption("--services",m),m.length===0)throw new h(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${p.join(", ")}`,stderrExcerpt:"no services selected"});let f=m.filter(g=>!p.includes(g));if(f.length>0)throw new h(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${p.join(", ")}`,stderrExcerpt:`invalid services: ${f.join(", ")}`});let u=n??!1;u&&d.addOption("--skip-terraform",!0);try{Cr.quiet=!0;let g=m.flatMap(_=>["-f",`${_}=true`]);await Cr`gh workflow run deploy-selected-services.yml --ref ${s} -f environment=${c} ${g} ${u?["-f","skip_terraform_deploy=true"]:[]}`,Cr.quiet=!1,i.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${s}, environment: ${c}, services: ${m.join(", ")}`),d.print();let P={releaseBranch:s,version:s.replace("release/v",""),environment:c,services:m,skipTerraformDeploy:u,success:!0};return{content:w(JSON.stringify(P,null,2)),structuredContent:P}}catch(g){throw i.error({error:g},"\u274C Error launching workflow"),new h(g,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},ln=async()=>{let e=await E(),r=an(e,".github/workflows/deploy-selected-services.yml"),t=await sn.readFile(r,"utf-8"),n=cn.parse(t).on.workflow_dispatch.inputs,s=[];for(let[a,l]of Object.entries(n))l.type==="boolean"&&a!=="skip_terraform_deploy"&&s.push(a);return s},Tr=v({name:"gh-release-deploy-selected",description:'Dispatch the deploy-selected-services.yml GitHub Actions workflow to deploy a chosen subset of services from a release branch to the given environment. Fire-and-forget \u2014 returns once GitHub accepts the workflow_dispatch, NOT when the deployment finishes; watch the workflow run for completion status. Service names are validated against the boolean inputs declared in the workflow. Use gh-release-deploy-all for every service. "version", "env", and "services" are all required when invoked via MCP (interactive pickers are unavailable without a TTY).',inputSchema:{version:M.string().describe('Release version to deploy from (e.g. "1.2.5") \u2014 resolves to the release/vX.Y.Z branch. Pass "dev" to deploy from the dev branch instead. Required for MCP calls.'),env:M.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),services:M.array(M.string()).describe('Service names to deploy. Each must match a boolean input declared in .github/workflows/deploy-selected-services.yml (e.g. "client-be", "client-fe"). Required for MCP calls.'),skipTerraform:M.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:M.string().describe("The release branch that was deployed"),version:M.string().describe("The version that was deployed"),environment:M.string().describe("The environment deployed to"),services:M.array(M.string()).describe("The services that were deployed"),skipTerraformDeploy:M.boolean().describe("Whether terraform deployment was skipped"),success:M.boolean().describe("Whether the deployment was successful")},handler:Rt});import{z as de}from"zod/v4";var kt=async()=>{let r=(await k()).map(a=>({version:a.branch.replace("release/",""),type:R(a.title)})),t=await C(),o=Math.max(...r.map(a=>a.version.length)),n=r.map(a=>{let l=ce(a.version,a.type,o),c=t.get(a.version);return c?`${l} ${c}`:l});i.info(`All release branches:
|
|
29
31
|
`),i.info(`
|
|
30
32
|
${n.join(`
|
|
31
33
|
`)}
|
|
32
|
-
`);let s={releases:r.map(a=>({version:a.version,type:a.type,description:t.get(a.version)||null})),count:r.length};return{content:
|
|
33
|
-
- `),o=r?!0:await
|
|
34
|
+
`);let s={releases:r.map(a=>({version:a.version,type:a.type,description:t.get(a.version)||null})),count:r.length};return{content:w(JSON.stringify(s,null,2)),structuredContent:s}},Pr=v({name:"gh-release-list",description:"List every open release PR with its version, type (regular / hotfix), and associated Jira fix-version description. Read-only; sourced from GitHub and Jira.",inputSchema:{},outputSchema:{releases:de.array(de.object({version:de.string().describe("Release version"),type:de.enum(["regular","hotfix"]).describe("Release type"),description:de.string().nullable().describe("Jira version description")})).describe("List of all release branches"),count:de.number().describe("Number of release branches")},handler:kt});import Ct from"@inquirer/confirm";import pn from"@inquirer/select";import Tt from"node:process";import{z as b}from"zod/v4";import{question as bt}from"zx";var mn='"1.2.5" or "next"',dn=(e,r)=>{try{return qe(e,r)}catch(t){if(t instanceof H)return null;throw t}},Pt=(e,r)=>{try{return fr(e,r)}catch(t){throw t instanceof H?new h(t,{operation:"resolve release version",remediation:'pass an explicit version (e.g. "1.2.5") instead of "next" when there are no prior versions'}):t}},un=async e=>{d.setInteractive();let t=[...await e()],o=[],n=!0;for(;n;){let s=o.length+1,a=await pn({message:`Release #${s} \u2014 select type:`,choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"}),l=dn(t,a),c=l?` [${l}]`:"",p=(await bt(` Version (e.g. ${mn})${c}: `)).trim(),m=p===""?l??"":p;m===""&&(i.error("No version provided. Exiting..."),Tt.exit(1));let f=Pt([{version:m,type:a}],t)[0];t.push(L(`v${f.version}`));let u=(await bt(" Description (optional, press Enter to skip): ")).trim();o.push({...f,...u!==""?{description:u}:{}}),n=await Ct({message:"Add another release?",default:!1})}return o},fn=e=>{let r=[`v${e.version}`,e.type];return e.description&&r.push(e.description),r.join(" \xB7 ")},xt=e=>{for(let r of e){let t=r.description?`${r.version}:${r.type}:${r.description}`:`${r.version}:${r.type}`;d.addOption("--release",t)}},gn=async(e,r)=>{if(e&&e.length>0){let o=gr(e)?await r():[],n=Pt(e,o);return xt(n),n}let t=await un(r);return xt(t),t},hn=async(e,r)=>{let t=e.map(fn).join(`
|
|
35
|
+
- `),o=r?!0:await Ct({message:`Create the following ${e.length} release(s)?
|
|
34
36
|
- ${t}
|
|
35
|
-
`});r||
|
|
36
|
-
`),{result:o}}catch(o){let n=new
|
|
37
|
-
`),{failure:{version:r.version,error:n.message}}}},
|
|
37
|
+
`});r||d.setInteractive(),o||(i.info("Operation cancelled. Exiting..."),Tt.exit(0)),d.addOption("--yes",!0)},wn=async e=>{let{entry:r,jiraConfig:t}=e;try{await mr(r.type);let o=await dr({version:r.version,jiraConfig:t,description:r.description,type:r.type});return i.info(`\u2705 Successfully created release: v${r.version} (${r.type})`),i.info(`\u{1F517} GitHub PR: ${o.prUrl}`),i.info(`\u{1F517} Jira Version: ${o.jiraVersionUrl}
|
|
38
|
+
`),{result:o}}catch(o){let n=new h(o,{operation:`create release v${r.version} (${r.type})`,remediation:"verify the version is unique and the base branch is clean"});return i.error(`\u274C ${n.message}
|
|
39
|
+
`),{failure:{version:r.version,error:n.message}}}},vn=(e,r,t)=>{r===e?i.info(`\u2705 All ${e} release branch(es) were created successfully.`):r>0?(i.warn(`\u26A0\uFE0F ${r} of ${e} release branches were created successfully.`),i.warn(`\u274C ${t} release(s) failed.`)):i.error(`\u274C All ${e} release branch(es) failed to create.`)},$t=async e=>{let{releases:r,confirmedCommand:t}=e;d.start("release-create");let o=await ae(),n=null,a=await gn(r,async()=>(n===null&&(n=await hr()),n));if(a.length===0)throw new h(void 0,{operation:"create release",remediation:'pass at least one entry in "releases" (e.g. [{ version: "1.2.5", type: "regular" }])',stderrExcerpt:"no releases provided"});await hn(a,!!t);let l=[],c=[];for(let m of a){let{result:f,failure:u}=await wn({entry:m,jiraConfig:o});f&&l.push(f),u&&c.push(u)}vn(a.length,l.length,c.length),d.print();let p={createdBranches:l.map(m=>m.branchName),successCount:l.length,failureCount:c.length,releases:l,failedReleases:c};return{content:w(JSON.stringify(p,null,2)),structuredContent:p}},$r=v({name:"release-create",description:'Create one or more releases in a single call. Each entry in "releases" carries its own version, type (regular|hotfix, default regular), and optional description, so regular and hotfix releases can be mixed in the same invocation. For each release this tool switches to the appropriate base branch (dev for regular, main for hotfix), cuts the release branch, opens a GitHub release PR, and creates the matching Jira fix version. The literal token "next" auto-increments from the union of remote release branches and Jira fix versions (regular bumps minor + resets patch; hotfix bumps patch on the highest minor); multiple "next" tokens advance sequentially across mixed types. Confirmation is auto-skipped for MCP calls, so the caller is responsible for gating. Continues on per-release failure and reports successes/failures.',inputSchema:{releases:b.array(b.object({version:b.string().describe('Version to create (e.g., "1.2.5") or the literal token "next" for auto-increment.'),type:b.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" (branches off dev) or "hotfix" (branches off main).'),description:b.string().optional().describe("Optional description for the Jira version.")})).min(1).describe("One or more releases to create. Each entry has its own version, type, and optional description.")},outputSchema:{createdBranches:b.array(b.string()).describe("List of created release branch names"),successCount:b.number().describe("Number of releases created successfully"),failureCount:b.number().describe("Number of releases that failed"),releases:b.array(b.object({version:b.string().describe("Version number"),type:b.enum(["regular","hotfix"]).describe("Release type"),branchName:b.string().describe("Release branch name"),prUrl:b.string().describe("GitHub PR URL"),jiraVersionUrl:b.string().describe("Jira version URL")})).describe("Detailed information for each created release with URLs"),failedReleases:b.array(b.object({version:b.string().describe("Version number that failed"),error:b.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:$t});import yn from"@inquirer/confirm";import Rn from"@inquirer/select";import kn from"node:process";import{z as q}from"zod/v4";import{question as bn}from"zx";var Et=(e,r)=>`${e.baseUrl}/projects/${r.projectId}/versions/${r.id}/tab/release-report-all-issues`,xn=(e,r)=>r.trim()!==""?`${e}
|
|
38
40
|
|
|
39
41
|
${r}`:`${e}
|
|
40
|
-
`,
|
|
41
|
-
(press Enter to keep current): `)).replace(/\n$/,"");return o===""?e:o}
|
|
42
|
+
`,Cn=async()=>{let e=await k(),r=e.map(s=>s.branch),t=new Map(e.map(s=>[s.branch,R(s.title)])),o=await C(),n=await Rn({message:"\u{1F33F} Select release branch",choices:S({branches:r,descriptions:o,types:t})});return{branch:n,type:t.get(n)||"regular"}},Tn=async e=>{let t=(await k()).find(o=>o.branch===e);if(!t)throw new h(void 0,{operation:`edit description for ${e}`,remediation:`confirm an open PR exists for ${e} ('gh pr list')`});return R(t.title)},Pn=async e=>{let r=e===""?"(no current description)":`current: "${e}"`,o=(await bn(` New description ${r}
|
|
43
|
+
(press Enter to keep current): `)).replace(/\n$/,"");return o===""?e:o},St=async e=>{let{version:r,description:t,confirmedCommand:o}=e;d.start("release-desc-edit");let n=await ae(),s;r?(s=`release/v${r}`,await Tn(s)):(d.setInteractive(),s=(await Cn()).branch);let a=s.replace("release/v","");d.addOption("--version",a);let l=`v${a}`,c=await Je(l,n);if(!c)throw new h(void 0,{operation:`edit description for ${l}`,remediation:`create the Jira fix version "${l}" first or pick a different release`});let p=c.description??"",m;if(t!==void 0?(m=t,d.addOption("--description",m)):(d.setInteractive(),m=await Pn(p)),m===p){i.info(`No change \u2014 description for ${l} is already: "${p}"`),d.print();let P={version:a,branch:s,jiraVersionUrl:Et(n,c),previousDescription:p,newDescription:m,changed:!1};return{content:w(JSON.stringify(P,null,2)),structuredContent:P}}let f=o?!0:await yn({message:`Update description for ${l}?
|
|
42
44
|
from: "${p}"
|
|
43
|
-
to: "${
|
|
44
|
-
`});o||
|
|
45
|
-
`),
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
`,"utf-8"),{added:c,skipped:p}};import $n from"node:fs/promises";import Xe from"node:path";import At from"node:fs/promises";import He from"node:path";var X=async e=>{let{workspacePath:r,folderPaths:t}=e,o=He.dirname(r),n;try{n=await At.readFile(r,"utf-8")}catch(u){throw new Error(`Cursor workspace file not found at ${r}: ${u.message}`)}let s;try{s=JSON.parse(n)}catch(u){throw new Error(`Failed to parse ${r} as JSON. Comments (JSONC) are not supported. ${u.message}`)}let a=s.folders??[],l=new Set(t.map(u=>He.resolve(u))),c=new Set,p=a.filter(u=>{let g=He.resolve(o,u.path);return l.has(g)?(c.add(g),!1):!0});s.folders=p,await At.writeFile(r,`${JSON.stringify(s,null,2)}
|
|
49
|
-
`,"utf-8");let d=[],f=[];for(let u of t){let g=He.resolve(u);c.has(g)?d.push(u):f.push(u)}return{removed:d,notFound:f}};var Er=async e=>{let{workspacePath:r,worktreeDir:t,currentBranches:o}=e,n=Xe.dirname(r),s=Xe.resolve(`${t}/release`),a=await $n.readFile(r,"utf-8"),c=JSON.parse(a).folders??[],p=new Set(o.map(T=>Xe.resolve(`${t}/${T}`))),d=[];for(let T of c){let P=Xe.resolve(n,T.path);(P===s||P.startsWith(`${s}/`))&&!p.has(P)&&d.push(P)}let f=[];d.length>0&&(f=(await X({workspacePath:r,folderPaths:d})).removed);let u=o.map(T=>`${t}/${T}`),{added:g}=u.length>0?await Ee({workspacePath:r,folderPaths:u}):{added:[]};return{added:g,removed:f}};import Nt from"node:path";var F=(e,r)=>Nt.isAbsolute(e)?e:Nt.resolve(r,e);var On="feature",An="release",Nn="release/v",Dt=["workspace","windows","none"],_t=async e=>{let{confirmedCommand:r,all:t,versions:o,cursor:n,githubDesktop:s,cmux:a}=e;m.start("worktrees-add");try{let l=await N("release"),c=await I(),p=`${c}${V}`;await Mt(`${p}/${An}`),await Mt(`${p}/${On}`);let d=[];if(o)d=o.split(",").map($=>`release/v${$.trim()}`);else{let $=await k(),W=$.map(G=>G.branch);if(W.length===0)return i.info("\u2139\uFE0F No open release branches found"),m.print(),{content:h(JSON.stringify({createdWorktrees:[],count:0},null,2)),structuredContent:{createdWorktrees:[],count:0}};if(t)d=W;else{m.setInteractive();let G=new Map($.map(Oe=>[Oe.branch,R(Oe.title)])),Ie=await C();d=await En({required:!0,message:"\u{1F33F} Select release branches",choices:E({branches:W,descriptions:Ie,types:G})})}}t?m.addOption("--all",!0):m.addOption("--versions",d.map($=>$.replace("release/v","")));let f=r?!0:await Sr({message:"Are you sure you want to proceed with these worktree changes?"});r||m.setInteractive(),f||(i.info("Operation cancelled. Exiting..."),In.exit(0)),r||m.addOption("--yes",!0);let u=await x(),g=u.ide?.provider==="cursor"?u.ide.config:void 0,T=n??g?.mode??await Sn({message:"Cursor mode for created worktrees?",default:"workspace",choices:[{name:"Add to workspace file",value:"workspace",description:"Append each worktree as a folder in ide.config.workspaceConfigPath, then open the workspace"},{name:"Open separate windows",value:"windows",description:"Open each created worktree in its own Cursor window"},{name:"Skip",value:"none",description:"Do not open Cursor"}]});typeof n>"u"&&!g?.mode&&m.setInteractive(),m.addOption("--cursor",T);let P=s??u.worktrees?.openInGithubDesktop??await Sr({message:"Open created worktrees in GitHub Desktop?"});typeof s>"u"&&u.worktrees?.openInGithubDesktop===void 0&&m.setInteractive(),P?m.addOption("--github-desktop",!0):m.addOption("--no-github-desktop",!0);let _=a??u.worktrees?.openInCmux??await Sr({message:"Open created worktrees in cmux?"});typeof a>"u"&&u.worktrees?.openInCmux===void 0&&m.setInteractive(),_?m.addOption("--cmux",!0):m.addOption("--no-cmux",!0);let{branchesToCreate:Q}=Mn({selectedReleaseBranches:d,currentWorktrees:l}),K=await Dn(Q,p);if(_n(K),T==="workspace")if(!g?.workspaceConfigPath)i.warn("\u26A0\uFE0F Skipping Cursor: ide.config.workspaceConfigPath is not set in infra-kit config");else{let $=F(g.workspaceConfigPath,c),W=K.map(qt=>`${p}/${qt}`),{added:G,skipped:Ie}=await Ee({workspacePath:$,folderPaths:W}),Oe=Ie.length>0?` (${Ie.length} already present)`:"";i.info(`\u2705 Added ${G.length} folder(s) to ${$}${Oe}`),await Y`cursor ${$}`}else if(T==="windows")for(let $ of K)await Y`cursor ${p}/${$}`;if(P)for(let $ of K)await Y`github ${p}/${$}`,await Y`sleep 5`;if(_){let $=await M();for(let W of K){let G=j({repoName:$,branch:W});await $e({cwd:`${p}/${W}`,title:G})}}m.print();let Fr={createdWorktrees:K,count:K.length};return{content:h(JSON.stringify(Fr,null,2)),structuredContent:Fr}}catch(l){throw i.error({error:l},"\u274C Error managing worktrees"),new w(l,{operation:"create worktrees",remediation:"verify branches don't already exist as worktrees: 'git worktree list'"})}},Mt=async e=>{await Y`mkdir -p ${e}`},Mn=e=>{let{selectedReleaseBranches:r,currentWorktrees:t}=e,o=t.filter(s=>s.startsWith(Nn));return{branchesToCreate:r.filter(s=>!o.includes(s))}},Dn=async(e,r)=>{let t=await Promise.allSettled(e.map(async n=>{let s=`${r}/${n}`;return await Y`git worktree add ${s} ${n}`,await Y({cwd:s})`pnpm install`,n})),o=[];for(let[n,s]of t.entries())if(s.status==="fulfilled")o.push(s.value);else{let a=e[n],l=new w(s.reason,{operation:`git worktree add for ${a}`,remediation:"check the branch name and that the parent dir is writable"});i.error({error:s.reason,msg:l.message})}return o},_n=e=>{if(e.length>0){i.info("\u2705 Created git worktrees:");for(let r of e)i.info(r);i.info("")}else i.info("\u2139\uFE0F No new git worktrees to create")},Ir=v({name:"worktrees-add",description:'Create local git worktrees for release branches under the worktrees directory and run "pnpm install" in each. Mutates the local filesystem. When invoked via MCP, pass either "versions" (comma-separated) or all=true \u2014 the branch picker and "open in Cursor / GitHub Desktop / cmux" follow-up prompts are unreachable without a TTY, and the CLI confirmation is auto-skipped for MCP calls.',inputSchema:{all:U.boolean().optional().describe('Add worktrees for every open release branch. Either "all" or "versions" must be provided for MCP calls (the interactive picker is unavailable without a TTY). Ignored if "versions" is provided.'),versions:U.string().optional().describe('Comma-separated release versions to target (e.g. "1.2.5, 1.2.6"). Either "versions" or all=true must be provided for MCP calls. Overrides "all" when set.'),cursor:U.enum(Dt).optional().describe('Cursor open mode for created worktrees. "workspace" appends each worktree as a folder to "ide.config.workspaceConfigPath" in infra-kit config and opens the workspace. "windows" opens each worktree in its own Cursor window. "none" skips Cursor. Resolution order: this flag \u2192 "ide.config.mode" from infra-kit config \u2192 interactive prompt (CLI) / "none" (MCP, no TTY).'),githubDesktop:U.boolean().optional().describe('Open each created worktree in GitHub Desktop. Resolution order: this flag \u2192 "worktrees.openInGithubDesktop" from infra-kit config \u2192 interactive prompt (CLI) / false (MCP, no TTY).'),cmux:U.boolean().optional().describe('Open each created worktree in a new cmux workspace with a 3-pane layout (left-top, left-bottom, full-height right), all rooted at the worktree directory. Resolution order: this flag \u2192 "worktrees.openInCmux" from infra-kit config \u2192 interactive prompt (CLI) / false (MCP, no TTY).')},outputSchema:{createdWorktrees:U.array(U.string()).describe("List of created git worktree branches"),count:U.number().describe("Number of git worktrees created")},handler:_t});import{z as ue}from"zod/v4";var jt=async()=>{let e=await N("release");if(e.length===0)return i.info("\u2139\uFE0F No active worktrees found"),{content:h(JSON.stringify({worktrees:[],count:0},null,2)),structuredContent:{worktrees:[],count:0}};let[r,t]=await Promise.all([k(),C()]),o=new Map(r.map(c=>[c.branch,R(c.title)])),n=e.map(c=>{let p=c.replace("release/",""),d=o.get(c)||"regular",f=t.get(p)||null;return{version:p,type:d,description:f}}),s=Math.max(...n.map(c=>c.version.length)),a=n.map(c=>{let p=ce(c.version,c.type,s);return c.description?`${p} ${c.description}`:p});i.info("\u{1F33F} Active worktrees:"),i.info(`
|
|
45
|
+
to: "${m}"
|
|
46
|
+
`});o||d.setInteractive(),f||(i.info("Operation cancelled. Exiting..."),kn.exit(0)),d.addOption("--yes",!0),await Ve({versionId:c.id,description:m},n);let u=Et(n,c),g=xn(u,m);await ze({branch:s,body:g}),i.info(`\u2705 Updated description for ${l}`),i.info(`\u{1F517} Jira Version: ${u}`),i.info(`\u{1F517} PR branch: ${s}
|
|
47
|
+
`),d.print();let T={version:a,branch:s,jiraVersionUrl:u,previousDescription:p,newDescription:m,changed:!0};return{content:w(JSON.stringify(T,null,2)),structuredContent:T}},Er=v({name:"release-desc-edit",description:"Edit a release's description in Jira and in the matching GitHub release PR body. Targets the Jira fix version named `v<version>` and the open PR on branch `release/v<version>`. The PR body is rewritten canonically to `<jiraVersionUrl>\\n\\n<description>` \u2014 any prior manual edits to the body are overwritten. Both `version` and `description` are required for MCP calls (the picker/prompt are unreachable without a TTY). Empty `description` clears the description on both sides. Confirmation is auto-skipped for MCP, so the caller is responsible for gating.",inputSchema:{version:q.string().describe('Release version, e.g. "1.2.5".'),description:q.string().describe("New description. Empty string clears the description.")},outputSchema:{version:q.string().describe("Release version"),branch:q.string().describe('Release branch name (e.g. "release/v1.2.5")'),jiraVersionUrl:q.string().describe("Jira fix version URL"),previousDescription:q.string().describe("The description before the update"),newDescription:q.string().describe("The description after the update"),changed:q.boolean().describe("Whether the description actually changed")},handler:St});import{z as En}from"zod/v4";var It={name:"infra-kit",type:"module",version:"0.1.102",description:"infra-kit",main:"dist/cli.js",module:"dist/cli.js",bin:{"infra-kit":"dist/cli.js",ik:"dist/cli.js"},engines:{node:">=24.x"},scripts:{inspector:"npx @modelcontextprotocol/inspector node ./dist/mcp.js --debug",build:"pnpm run clean-artifacts && node ./scripts/build.js","clean-artifacts":"rm -rf dist","clean-cache":"rm -rf node_modules/.cache .eslintcache tsconfig.tsbuildinfo .turbo .swc","prettier-fix":"pnpm exec prettier **/* --write --no-error-on-unmatched-pattern --log-level silent --ignore-path ../../../.prettierignore","prettier-check":"pnpm exec prettier **/* --check --no-error-on-unmatched-pattern --log-level silent --ignore-path ../../../.prettierignore","eslint-check":"pnpm exec eslint --cache --quiet --report-unused-disable-directives ./src","eslint-fix":"pnpm exec eslint --cache --quiet --report-unused-disable-directives ./src --fix","ts-check":"tsc --noEmit",test:"pnpm exec vitest run --reporter=minimal","test-watch":"pnpm exec vitest --watch --silent passed-only","test-ui":"pnpm exec vitest --ui --silent passed-only","test-report":"pnpm exec vitest run --coverage --silent passed-only",qa:"pnpm run prettier-check && pnpm run eslint-check && pnpm run ts-check && pnpm run test && echo \u2705 Success",fix:"pnpm run prettier-fix && pnpm run eslint-fix && pnpm run qa"},dependencies:{"@inquirer/checkbox":"^5.1.5","@inquirer/confirm":"^6.0.13","@inquirer/select":"^5.1.5","@modelcontextprotocol/sdk":"^1.29.0",commander:"^14.0.3",pino:"^10.3.1","pino-pretty":"^13.1.3",yaml:"^2.9.0",zod:"^3.25.76",zx:"^8.8.5"},devDependencies:{"@pkg/eslint-config":"workspace:*","@pkg/vitest-config":"workspace:*",esbuild:"^0.28.0",typescript:"^6.0.3"}};var Ot=async()=>{let e=It.version;i.info(e);let r={version:e};return{content:w(JSON.stringify(r,null,2)),structuredContent:r}},Sr=v({name:"version",description:"Print the installed infra-kit CLI version",inputSchema:{},outputSchema:{version:En.string().describe("Installed infra-kit CLI version (from package.json)")},handler:Ot});import In from"@inquirer/checkbox";import Or from"@inquirer/confirm";import On from"@inquirer/select";import An from"node:process";import{z as U}from"zod/v4";import{$ as Y}from"zx";import At from"node:fs/promises";import He from"node:path";var Se=async e=>{let{workspacePath:r,folderPaths:t}=e,o=He.dirname(r),n;try{n=await At.readFile(r,"utf-8")}catch(m){throw new Error(`Cursor workspace file not found at ${r}: ${m.message}`)}let s;try{s=JSON.parse(n)}catch(m){throw new Error(`Failed to parse ${r} as JSON. Comments (JSONC) are not supported. ${m.message}`)}let a=s.folders??[],l=new Set(a.map(m=>He.resolve(o,m.path))),c=[],p=[];for(let m of t){let f=He.resolve(m);if(l.has(f)){p.push(m);continue}let u=He.relative(o,f);a.push({path:u}),l.add(f),c.push(m)}return s.folders=a,await At.writeFile(r,`${JSON.stringify(s,null,2)}
|
|
48
|
+
`,"utf-8"),{added:c,skipped:p}};import Sn from"node:fs/promises";import Ye from"node:path";import Nt from"node:fs/promises";import Xe from"node:path";var X=async e=>{let{workspacePath:r,folderPaths:t}=e,o=Xe.dirname(r),n;try{n=await Nt.readFile(r,"utf-8")}catch(u){throw new Error(`Cursor workspace file not found at ${r}: ${u.message}`)}let s;try{s=JSON.parse(n)}catch(u){throw new Error(`Failed to parse ${r} as JSON. Comments (JSONC) are not supported. ${u.message}`)}let a=s.folders??[],l=new Set(t.map(u=>Xe.resolve(u))),c=new Set,p=a.filter(u=>{let g=Xe.resolve(o,u.path);return l.has(g)?(c.add(g),!1):!0});s.folders=p,await Nt.writeFile(r,`${JSON.stringify(s,null,2)}
|
|
49
|
+
`,"utf-8");let m=[],f=[];for(let u of t){let g=Xe.resolve(u);c.has(g)?m.push(u):f.push(u)}return{removed:m,notFound:f}};var Ir=async e=>{let{workspacePath:r,worktreeDir:t,currentBranches:o}=e,n=Ye.dirname(r),s=Ye.resolve(`${t}/release`),a=await Sn.readFile(r,"utf-8"),c=JSON.parse(a).folders??[],p=new Set(o.map(T=>Ye.resolve(`${t}/${T}`))),m=[];for(let T of c){let P=Ye.resolve(n,T.path);(P===s||P.startsWith(`${s}/`))&&!p.has(P)&&m.push(P)}let f=[];m.length>0&&(f=(await X({workspacePath:r,folderPaths:m})).removed);let u=o.map(T=>`${t}/${T}`),{added:g}=u.length>0?await Se({workspacePath:r,folderPaths:u}):{added:[]};return{added:g,removed:f}};import Mt from"node:path";var W=(e,r)=>Mt.isAbsolute(e)?e:Mt.resolve(r,e);var Nn="feature",Mn="release",Dn="release/v",_t=["workspace","windows","none"],jt=async e=>{let{confirmedCommand:r,all:t,versions:o,cursor:n,githubDesktop:s,cmux:a}=e;d.start("worktrees-add");try{let l=await O("release"),c=await E(),p=`${c}${j}`;await Dt(`${p}/${Mn}`),await Dt(`${p}/${Nn}`);let m=[];if(o)m=o.split(",").map($=>`release/v${$.trim()}`);else{let $=await k(),J=$.map(G=>G.branch);if(J.length===0)return i.info("\u2139\uFE0F No open release branches found"),d.print(),{content:w(JSON.stringify({createdWorktrees:[],count:0},null,2)),structuredContent:{createdWorktrees:[],count:0}};if(t)m=J;else{d.setInteractive();let G=new Map($.map(Ae=>[Ae.branch,R(Ae.title)])),Oe=await C();m=await In({required:!0,message:"\u{1F33F} Select release branches",choices:S({branches:J,descriptions:Oe,types:G})})}}t?d.addOption("--all",!0):d.addOption("--versions",m.map($=>$.replace("release/v","")));let f=r?!0:await Or({message:"Are you sure you want to proceed with these worktree changes?"});r||d.setInteractive(),f||(i.info("Operation cancelled. Exiting..."),An.exit(0)),r||d.addOption("--yes",!0);let u=await x(),g=u.ide?.provider==="cursor"?u.ide.config:void 0,T=n??g?.mode??await On({message:"Cursor mode for created worktrees?",default:"workspace",choices:[{name:"Add to workspace file",value:"workspace",description:"Append each worktree as a folder in ide.config.workspaceConfigPath, then open the workspace"},{name:"Open separate windows",value:"windows",description:"Open each created worktree in its own Cursor window"},{name:"Skip",value:"none",description:"Do not open Cursor"}]});typeof n>"u"&&!g?.mode&&d.setInteractive(),d.addOption("--cursor",T);let P=s??u.worktrees?.openInGithubDesktop??await Or({message:"Open created worktrees in GitHub Desktop?"});typeof s>"u"&&u.worktrees?.openInGithubDesktop===void 0&&d.setInteractive(),P?d.addOption("--github-desktop",!0):d.addOption("--no-github-desktop",!0);let _=a??u.worktrees?.openInCmux??await Or({message:"Open created worktrees in cmux?"});typeof a>"u"&&u.worktrees?.openInCmux===void 0&&d.setInteractive(),_?d.addOption("--cmux",!0):d.addOption("--no-cmux",!0);let{branchesToCreate:Q}=_n({selectedReleaseBranches:m,currentWorktrees:l}),K=await jn(Q,p);if(Fn(K),T==="workspace")if(!g?.workspaceConfigPath)i.warn("\u26A0\uFE0F Skipping Cursor: ide.config.workspaceConfigPath is not set in infra-kit config");else{let $=W(g.workspaceConfigPath,c),J=K.map(Ut=>`${p}/${Ut}`),{added:G,skipped:Oe}=await Se({workspacePath:$,folderPaths:J}),Ae=Oe.length>0?` (${Oe.length} already present)`:"";i.info(`\u2705 Added ${G.length} folder(s) to ${$}${Ae}`),await Y`cursor ${$}`}else if(T==="windows")for(let $ of K)await Y`cursor ${p}/${$}`;if(P)for(let $ of K)await Y`github ${p}/${$}`,await Y`sleep 5`;if(_){let $=await A();for(let J of K){let G=F({repoName:$,branch:J});await Pe({cwd:`${p}/${J}`,title:G})}}d.print();let Wr={createdWorktrees:K,count:K.length};return{content:w(JSON.stringify(Wr,null,2)),structuredContent:Wr}}catch(l){throw i.error({error:l},"\u274C Error managing worktrees"),new h(l,{operation:"create worktrees",remediation:"verify branches don't already exist as worktrees: 'git worktree list'"})}},Dt=async e=>{await Y`mkdir -p ${e}`},_n=e=>{let{selectedReleaseBranches:r,currentWorktrees:t}=e,o=t.filter(s=>s.startsWith(Dn));return{branchesToCreate:r.filter(s=>!o.includes(s))}},jn=async(e,r)=>{let t=await Promise.allSettled(e.map(async n=>{let s=`${r}/${n}`;return await Y`git worktree add ${s} ${n}`,await Y({cwd:s})`pnpm install`,n})),o=[];for(let[n,s]of t.entries())if(s.status==="fulfilled")o.push(s.value);else{let a=e[n],l=new h(s.reason,{operation:`git worktree add for ${a}`,remediation:"check the branch name and that the parent dir is writable"});i.error({error:s.reason,msg:l.message})}return o},Fn=e=>{if(e.length>0){i.info("\u2705 Created git worktrees:");for(let r of e)i.info(r);i.info("")}else i.info("\u2139\uFE0F No new git worktrees to create")},Ar=v({name:"worktrees-add",description:'Create local git worktrees for release branches under the worktrees directory and run "pnpm install" in each. Mutates the local filesystem. When invoked via MCP, pass either "versions" (comma-separated) or all=true \u2014 the branch picker and "open in Cursor / GitHub Desktop / cmux" follow-up prompts are unreachable without a TTY, and the CLI confirmation is auto-skipped for MCP calls.',inputSchema:{all:U.boolean().optional().describe('Add worktrees for every open release branch. Either "all" or "versions" must be provided for MCP calls (the interactive picker is unavailable without a TTY). Ignored if "versions" is provided.'),versions:U.string().optional().describe('Comma-separated release versions to target (e.g. "1.2.5, 1.2.6"). Either "versions" or all=true must be provided for MCP calls. Overrides "all" when set.'),cursor:U.enum(_t).optional().describe('Cursor open mode for created worktrees. "workspace" appends each worktree as a folder to "ide.config.workspaceConfigPath" in infra-kit config and opens the workspace. "windows" opens each worktree in its own Cursor window. "none" skips Cursor. Resolution order: this flag \u2192 "ide.config.mode" from infra-kit config \u2192 interactive prompt (CLI) / "none" (MCP, no TTY).'),githubDesktop:U.boolean().optional().describe('Open each created worktree in GitHub Desktop. Resolution order: this flag \u2192 "worktrees.openInGithubDesktop" from infra-kit config \u2192 interactive prompt (CLI) / false (MCP, no TTY).'),cmux:U.boolean().optional().describe('Open each created worktree in a new cmux workspace with a 3-pane layout (left-top, left-bottom, full-height right), all rooted at the worktree directory. Resolution order: this flag \u2192 "worktrees.openInCmux" from infra-kit config \u2192 interactive prompt (CLI) / false (MCP, no TTY).')},outputSchema:{createdWorktrees:U.array(U.string()).describe("List of created git worktree branches"),count:U.number().describe("Number of git worktrees created")},handler:jt});import{z as ue}from"zod/v4";var Ft=async()=>{let e=await O("release");if(e.length===0)return i.info("\u2139\uFE0F No active worktrees found"),{content:w(JSON.stringify({worktrees:[],count:0},null,2)),structuredContent:{worktrees:[],count:0}};let[r,t]=await Promise.all([k(),C()]),o=new Map(r.map(c=>[c.branch,R(c.title)])),n=e.map(c=>{let p=c.replace("release/",""),m=o.get(c)||"regular",f=t.get(p)||null;return{version:p,type:m,description:f}}),s=Math.max(...n.map(c=>c.version.length)),a=n.map(c=>{let p=ce(c.version,c.type,s);return c.description?`${p} ${c.description}`:p});i.info("\u{1F33F} Active worktrees:"),i.info(`
|
|
50
50
|
${a.join(`
|
|
51
51
|
`)}
|
|
52
|
-
`);let l={worktrees:n,count:n.length};return{content:h(JSON.stringify(l,null,2)),structuredContent:l}},Or=v({name:"worktrees-list",description:"List existing release-branch worktrees with version, release type (regular / hotfix), and Jira fix-version description. Read-only.",inputSchema:{},outputSchema:{worktrees:ue.array(ue.object({version:ue.string().describe("Release version"),type:ue.enum(["regular","hotfix"]).describe("Release type"),description:ue.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:ue.number().describe("Number of worktrees")},handler:jt});import{z as fe}from"zod/v4";import{$ as jn}from"zx";var Ft=async()=>{m.start("worktrees-open");try{let e=await I(),r=`${e}${V}`,t=await N("release"),o=await Fn({projectRoot:e,worktreeDir:r,currentBranches:t}),n=await Wn({worktreeDir:r,currentBranches:t}),s={openedCmux:n.opened,skippedCmux:n.skipped,cursorFoldersAdded:o.added,cursorFoldersRemoved:o.removed};return Jn(s,{cursorRan:o.ran,cmuxRan:n.ran}),m.print(),{content:h(JSON.stringify(s,null,2)),structuredContent:{...s}}}catch(e){throw i.error({error:e},"\u274C Error opening worktrees"),new w(e,{operation:"open worktrees",remediation:"run 'worktrees-list' to confirm the branches exist"})}},Fn=async e=>{let{projectRoot:r,worktreeDir:t,currentBranches:o}=e,n=await x(),s=n.ide?.provider==="cursor"?n.ide.config:void 0;if(!s||s.mode!=="workspace"||!s.workspaceConfigPath)return i.warn('\u26A0\uFE0F Skipping Cursor: ide.provider must be "cursor", mode "workspace", and workspaceConfigPath set.'),{ran:!1,added:0,removed:0};let a=F(s.workspaceConfigPath,r);try{let{added:l,removed:c}=await Er({workspacePath:a,worktreeDir:t,currentBranches:o});return await jn`cursor ${a}`,{ran:!0,added:l.length,removed:c.length}}catch(l){return i.warn({error:l},`\u26A0\uFE0F Failed to reconcile/open Cursor workspace at ${a}`),{ran:!1,added:0,removed:0}}},Wn=async e=>{let{worktreeDir:r,currentBranches:t}=e;if(t.length===0)return{ran:!0,opened:[],skipped:[]};let o=await M(),n=await $r(),s=[],a=[];for(let l of t){let c=j({repoName:o,branch:l});if(n.has(c)){a.push(c);continue}try{await $e({cwd:`${r}/${l}`,title:c}),s.push(c)}catch(p){i.warn({error:p,title:c},`\u26A0\uFE0F Failed to open cmux workspace for ${l}`)}}return{ran:!0,opened:s,skipped:a}},Jn=(e,r)=>{if(r.cursorRan&&(e.cursorFoldersAdded>0&&i.info(`\u2705 Added ${e.cursorFoldersAdded} folder(s) to Cursor workspace`),e.cursorFoldersRemoved>0&&i.info(`\u{1F9F9} Removed ${e.cursorFoldersRemoved} dangling folder(s) from Cursor workspace`)),e.openedCmux.length>0){i.info("\u2705 Opened cmux workspaces:");for(let t of e.openedCmux)i.info(t)}e.skippedCmux.length>0&&i.info(`\u2139\uFE0F Skipped ${e.skippedCmux.length} cmux workspace(s) already open`),!r.cursorRan&&e.openedCmux.length===0&&e.skippedCmux.length===0&&e.cursorFoldersAdded===0&&e.cursorFoldersRemoved===0&&i.info("\u2139\uFE0F Nothing to open")},Ar=v({name:"worktrees-open",description:"Open Cursor against the configured workspace file and ensure a cmux workspace exists for each existing release worktree. Idempotent and additive \u2014 never removes worktrees, never recreates running cmux workspaces. Use after a cold start (Cursor + cmux closed). For stale-worktree cleanup, use worktrees-sync.",inputSchema:{},outputSchema:{openedCmux:fe.array(fe.string()).describe("Titles of cmux workspaces opened during this run"),skippedCmux:fe.array(fe.string()).describe("Titles of cmux workspaces that were already open"),cursorFoldersAdded:fe.number().describe("Number of worktree folders added to the Cursor workspace file"),cursorFoldersRemoved:fe.number().describe("Number of dangling worktree folders removed from the Cursor workspace file")},handler:Ft});import Vn from"@inquirer/checkbox";import Ln from"@inquirer/confirm";import Bn from"node:process";import{z as Se}from"zod/v4";import{$ as Nr}from"zx";var Wt=async e=>{let{confirmedCommand:r,all:t,versions:o}=e;m.start("worktrees-remove");try{let n=await N("release");if(n.length===0)return i.info("\u2139\uFE0F No active worktrees to remove"),m.print(),{content:h(JSON.stringify({removedWorktrees:[],count:0},null,2)),structuredContent:{removedWorktrees:[],count:0}};let s=await I(),a=`${s}${V}`,l=[];if(t)l=n;else if(o)l=o.split(",").map(g=>`release/v${g.trim()}`);else{m.setInteractive();let[g,T]=await Promise.all([C(),k()]),P=new Map(T.map(_=>[_.branch,R(_.title)]));l=await Vn({required:!0,message:"\u{1F33F} Select release branches",choices:E({branches:n,descriptions:g,types:P})})}let c=l.length===n.length;c?m.addOption("--all",!0):m.addOption("--versions",l.map(g=>g.replace("release/v","")));let p=r?!0:await Ln({message:"Are you sure you want to proceed with these worktree changes?"});r||m.setInteractive(),p||(i.info("Operation cancelled. Exiting..."),Bn.exit(0)),r||m.addOption("--yes",!0);let d=await M(),f=await qn({branches:l,worktreeDir:a,repoName:d,allSelected:c});await Un({removedWorktrees:f,worktreeDir:a,projectRoot:s}),Kn(f),m.print();let u={removedWorktrees:f,count:f.length};return{content:h(JSON.stringify(u,null,2)),structuredContent:u}}catch(n){throw i.error({error:n},"\u274C Error managing worktrees"),new w(n,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"})}},qn=async e=>{let{branches:r,worktreeDir:t,repoName:o,allSelected:n}=e,s=await Promise.allSettled(r.map(async l=>{let c=`${t}/${l}`,p=j({repoName:o,branch:l});return await Te(p),await Nr`git worktree remove ${c}`,l})),a=[];for(let[l,c]of s.entries())if(c.status==="fulfilled")a.push(c.value);else{let p=r[l],d=new w(c.reason,{operation:`remove worktree for ${p}`,remediation:"check 'git worktree list' for the path; uncommitted changes block removal"});i.error({error:c.reason,msg:d.message})}return n&&a.length===r.length&&(await Nr`git worktree prune`,await Nr`rm -rf ${t}`,i.info(`\u{1F5D1}\uFE0F Removed worktree folder: ${t}`),i.info("")),a},Un=async e=>{let{removedWorktrees:r,worktreeDir:t,projectRoot:o}=e;if(r.length===0)return;let n=await x(),s=n.ide?.provider==="cursor"?n.ide.config:void 0;if(!s||s.mode!=="workspace"||!s.workspaceConfigPath)return;let a=F(s.workspaceConfigPath,o),l=r.map(c=>`${t}/${c}`);try{let{removed:c}=await X({workspacePath:a,folderPaths:l});c.length>0&&i.info(`\u2705 Removed ${c.length} folder(s) from ${a}`)}catch(c){i.warn({error:c},`\u26A0\uFE0F Failed to update Cursor workspace at ${a}`)}},Kn=e=>{if(e.length>0){i.info("\u274C Removed worktrees:");for(let r of e)i.info(r);i.info("")}else i.info("\u2139\uFE0F No unused worktrees to remove")},Mr=v({name:"worktrees-remove",description:'Remove local git worktrees for release branches. When everything is removed, also runs "git worktree prune" and deletes the worktrees directory. When invoked via MCP, pass either "versions" (comma-separated) or all=true \u2014 the branch picker is unreachable without a TTY, and the CLI confirmation is auto-skipped for MCP calls, so the caller is responsible for gating.',inputSchema:{all:Se.boolean().optional().describe('Remove every existing worktree. Either "all" or "versions" must be provided for MCP calls (the interactive picker is unavailable without a TTY). Ignored if "versions" is provided.'),versions:Se.string().optional().describe('Comma-separated release versions to target (e.g. "1.2.5, 1.2.6"). Either "versions" or all=true must be provided for MCP calls. Overrides "all" when set.')},outputSchema:{removedWorktrees:Se.array(Se.string()).describe("List of removed git worktree branches"),count:Se.number().describe("Number of git worktrees removed")},handler:Wt});import Gn from"@inquirer/confirm";import zn from"node:process";import{z as Dr}from"zod/v4";import{$ as Hn}from"zx";var Xn="release/v",Jt=async e=>{let{confirmedCommand:r}=e;m.start("worktrees-sync");try{let t=await N("release"),o=await I(),n=`${o}${V}`,s=await Ke(),a=r?!0:await Gn({message:"Are you sure you want to proceed with these worktree changes?"});r||m.setInteractive(),a||(i.info("Operation cancelled. Exiting..."),zn.exit(0)),r||m.addOption("--yes",!0);let{branchesToRemove:l}=Yn({releasePRsList:s,currentWorktrees:t}),c=await M(),p=await Zn({branches:l,worktreeDir:n,repoName:c});await Qn({removedWorktrees:p,worktreeDir:n,projectRoot:o}),es(p),m.print();let d={removedWorktrees:p,count:p.length};return{content:h(JSON.stringify(d,null,2)),structuredContent:d}}catch(t){throw i.error({error:t},"\u274C Error managing worktrees"),new w(t,{operation:"sync worktrees with remote",remediation:"ensure 'gh auth status' is ok and you can reach origin"})}},Yn=e=>{let{releasePRsList:r,currentWorktrees:t}=e;return{branchesToRemove:t.filter(s=>s.startsWith(Xn)).filter(s=>!r.includes(s))}},Zn=async e=>{let{branches:r,worktreeDir:t,repoName:o}=e,n=[];for(let s of r)try{let a=`${t}/${s}`,l=j({repoName:o,branch:s});await Te(l),await Hn`git worktree remove ${a}`,n.push(s)}catch(a){let l=new w(a,{operation:`remove stale worktree for ${s}`,remediation:"inspect the worktree dir manually; rerun with the branch checked out elsewhere"});i.error({error:a,branch:s,msg:l.message})}return n},Qn=async e=>{let{removedWorktrees:r,worktreeDir:t,projectRoot:o}=e;if(r.length===0)return;let n=await x(),s=n.ide?.provider==="cursor"?n.ide.config:void 0;if(!s||s.mode!=="workspace"||!s.workspaceConfigPath)return;let a=F(s.workspaceConfigPath,o),l=r.map(c=>`${t}/${c}`);try{let{removed:c}=await X({workspacePath:a,folderPaths:l});c.length>0&&i.info(`\u2705 Removed ${c.length} folder(s) from ${a}`)}catch(c){i.warn({error:c},`\u26A0\uFE0F Failed to update Cursor workspace at ${a}`)}},es=e=>{if(e.length>0){i.info("\u274C Removed worktrees:");for(let r of e)i.info(r);i.info("")}else i.info("\u2139\uFE0F No unused worktrees to remove")},_r=v({name:"worktrees-sync",description:"Remove worktrees whose release PR is no longer open (stale cleanup). Only removes \u2014 never creates; use worktrees-add to create worktrees for new releases. The CLI confirmation is auto-skipped for MCP calls, so the caller is responsible for gating.",inputSchema:{},outputSchema:{removedWorktrees:Dr.array(Dr.string()).describe("List of removed worktree branches"),count:Dr.number().describe("Number of worktrees removed during sync")},handler:Jt});var jr=e=>async r=>{let{toolName:t,handler:o}=e;i.info({msg:`Tool execution started: ${t}`,params:r});try{let n=await o({...r,confirmedCommand:!0});return i.info({msg:`Tool execution successful: ${t}`}),n}catch(n){throw i.error({err:n,params:r,msg:`Tool execution failed: ${t}`}),n}};var rs=[ar,nr,ir,rr,hr,Cr,Tr,vr,Rr,br,xr,Pr,Ir,Or,Ar,Mr,_r],Vt=async e=>{for(let r of rs)e.registerTool(r.name,{description:r.description,inputSchema:r.inputSchema,outputSchema:r.outputSchema},jr({toolName:r.name,handler:r.handler}))};async function Lt(){let e=new ts({name:"infra-kit",version:"1.0.0"},{capabilities:{resources:{},tools:{},prompts:{}}});return await Lr(e),await Br(e),await Vt(e),e}var Z=Jr(),ns=async()=>{let e;try{e=await Lt(),Z.info("MCP Server instance created")}catch(r){Z.error({err:r,msg:"Failed to create MCP server"}),Z.error("Fatal error during server creation."),Bt.exit(1)}try{let r=new os;await e.connect(r),Z.info({msg:"Server connected to transport. Ready."})}catch(r){Z.error({err:r,msg:"Failed to initialize server"}),Z.error("Fatal error during server transport init."),Bt.exit(1)}};Vr(Z);ns();
|
|
52
|
+
`);let l={worktrees:n,count:n.length};return{content:w(JSON.stringify(l,null,2)),structuredContent:l}},Nr=v({name:"worktrees-list",description:"List existing release-branch worktrees with version, release type (regular / hotfix), and Jira fix-version description. Read-only.",inputSchema:{},outputSchema:{worktrees:ue.array(ue.object({version:ue.string().describe("Release version"),type:ue.enum(["regular","hotfix"]).describe("Release type"),description:ue.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:ue.number().describe("Number of worktrees")},handler:Ft});import{z as fe}from"zod/v4";import{$ as Wn}from"zx";var Wt=async()=>{d.start("worktrees-open");try{let e=await E(),r=`${e}${j}`,t=await O("release"),o=await Jn({projectRoot:e,worktreeDir:r,currentBranches:t}),n=await Vn({worktreeDir:r,currentBranches:t}),s={openedCmux:n.opened,skippedCmux:n.skipped,cursorFoldersAdded:o.added,cursorFoldersRemoved:o.removed};return Ln(s,{cursorRan:o.ran,cmuxRan:n.ran}),d.print(),{content:w(JSON.stringify(s,null,2)),structuredContent:{...s}}}catch(e){throw i.error({error:e},"\u274C Error opening worktrees"),new h(e,{operation:"open worktrees",remediation:"run 'worktrees-list' to confirm the branches exist"})}},Jn=async e=>{let{projectRoot:r,worktreeDir:t,currentBranches:o}=e,n=await x(),s=n.ide?.provider==="cursor"?n.ide.config:void 0;if(!s||s.mode!=="workspace"||!s.workspaceConfigPath)return i.warn('\u26A0\uFE0F Skipping Cursor: ide.provider must be "cursor", mode "workspace", and workspaceConfigPath set.'),{ran:!1,added:0,removed:0};let a=W(s.workspaceConfigPath,r);try{let{added:l,removed:c}=await Ir({workspacePath:a,worktreeDir:t,currentBranches:o});return await Wn`cursor ${a}`,{ran:!0,added:l.length,removed:c.length}}catch(l){return i.warn({error:l},`\u26A0\uFE0F Failed to reconcile/open Cursor workspace at ${a}`),{ran:!1,added:0,removed:0}}},Vn=async e=>{let{worktreeDir:r,currentBranches:t}=e;if(t.length===0)return{ran:!0,opened:[],skipped:[]};let o=await A(),n=await yr(),s=[],a=[];for(let l of t){let c=F({repoName:o,branch:l});if(n.has(c)){a.push(c);continue}try{await Pe({cwd:`${r}/${l}`,title:c}),s.push(c)}catch(p){i.warn({error:p,title:c},`\u26A0\uFE0F Failed to open cmux workspace for ${l}`)}}return{ran:!0,opened:s,skipped:a}},Ln=(e,r)=>{if(r.cursorRan&&(e.cursorFoldersAdded>0&&i.info(`\u2705 Added ${e.cursorFoldersAdded} folder(s) to Cursor workspace`),e.cursorFoldersRemoved>0&&i.info(`\u{1F9F9} Removed ${e.cursorFoldersRemoved} dangling folder(s) from Cursor workspace`)),e.openedCmux.length>0){i.info("\u2705 Opened cmux workspaces:");for(let t of e.openedCmux)i.info(t)}e.skippedCmux.length>0&&i.info(`\u2139\uFE0F Skipped ${e.skippedCmux.length} cmux workspace(s) already open`),!r.cursorRan&&e.openedCmux.length===0&&e.skippedCmux.length===0&&e.cursorFoldersAdded===0&&e.cursorFoldersRemoved===0&&i.info("\u2139\uFE0F Nothing to open")},Mr=v({name:"worktrees-open",description:"Open Cursor against the configured workspace file and ensure a cmux workspace exists for each existing release worktree. Idempotent and additive \u2014 never removes worktrees, never recreates running cmux workspaces. Use after a cold start (Cursor + cmux closed). For stale-worktree cleanup, use worktrees-sync.",inputSchema:{},outputSchema:{openedCmux:fe.array(fe.string()).describe("Titles of cmux workspaces opened during this run"),skippedCmux:fe.array(fe.string()).describe("Titles of cmux workspaces that were already open"),cursorFoldersAdded:fe.number().describe("Number of worktree folders added to the Cursor workspace file"),cursorFoldersRemoved:fe.number().describe("Number of dangling worktree folders removed from the Cursor workspace file")},handler:Wt});import Bn from"@inquirer/checkbox";import qn from"@inquirer/confirm";import Un from"node:process";import{z as Ie}from"zod/v4";var Jt=async e=>{let{confirmedCommand:r,all:t,versions:o}=e;d.start("worktrees-remove");try{let n=await O("release");if(n.length===0)return i.info("\u2139\uFE0F No active worktrees to remove"),d.print(),{content:w(JSON.stringify({removedWorktrees:[],count:0},null,2)),structuredContent:{removedWorktrees:[],count:0}};let s=await E(),a=`${s}${j}`,l=[];if(t)l=n;else if(o)l=o.split(",").map(g=>`release/v${g.trim()}`);else{d.setInteractive();let[g,T]=await Promise.all([C(),k()]),P=new Map(T.map(_=>[_.branch,R(_.title)]));l=await Bn({required:!0,message:"\u{1F33F} Select release branches",choices:S({branches:n,descriptions:g,types:P})})}let c=l.length===n.length;c?d.addOption("--all",!0):d.addOption("--versions",l.map(g=>g.replace("release/v","")));let p=r?!0:await qn({message:"Are you sure you want to proceed with these worktree changes?"});r||d.setInteractive(),p||(i.info("Operation cancelled. Exiting..."),Un.exit(0)),r||d.addOption("--yes",!0);let m=await A(),f=await $e({branches:l,worktreeDir:a,repoName:m,pruneFolder:c});await Kn({removedWorktrees:f,worktreeDir:a,projectRoot:s}),Gn(f),d.print();let u={removedWorktrees:f,count:f.length};return{content:w(JSON.stringify(u,null,2)),structuredContent:u}}catch(n){throw i.error({error:n},"\u274C Error managing worktrees"),new h(n,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"})}},Kn=async e=>{let{removedWorktrees:r,worktreeDir:t,projectRoot:o}=e;if(r.length===0)return;let n=await x(),s=n.ide?.provider==="cursor"?n.ide.config:void 0;if(!s||s.mode!=="workspace"||!s.workspaceConfigPath)return;let a=W(s.workspaceConfigPath,o),l=r.map(c=>`${t}/${c}`);try{let{removed:c}=await X({workspacePath:a,folderPaths:l});c.length>0&&i.info(`\u2705 Removed ${c.length} folder(s) from ${a}`)}catch(c){i.warn({error:c},`\u26A0\uFE0F Failed to update Cursor workspace at ${a}`)}},Gn=e=>{if(e.length>0){i.info("\u274C Removed worktrees:");for(let r of e)i.info(r);i.info("")}else i.info("\u2139\uFE0F No unused worktrees to remove")},Dr=v({name:"worktrees-remove",description:'Remove local git worktrees for release branches. When everything is removed, also runs "git worktree prune" and deletes the worktrees directory. When invoked via MCP, pass either "versions" (comma-separated) or all=true \u2014 the branch picker is unreachable without a TTY, and the CLI confirmation is auto-skipped for MCP calls, so the caller is responsible for gating.',inputSchema:{all:Ie.boolean().optional().describe('Remove every existing worktree. Either "all" or "versions" must be provided for MCP calls (the interactive picker is unavailable without a TTY). Ignored if "versions" is provided.'),versions:Ie.string().optional().describe('Comma-separated release versions to target (e.g. "1.2.5, 1.2.6"). Either "versions" or all=true must be provided for MCP calls. Overrides "all" when set.')},outputSchema:{removedWorktrees:Ie.array(Ie.string()).describe("List of removed git worktree branches"),count:Ie.number().describe("Number of git worktrees removed")},handler:Jt});import zn from"@inquirer/confirm";import Hn from"node:process";import{z as _r}from"zod/v4";import{$ as Xn}from"zx";var Yn="release/v",Vt=async e=>{let{confirmedCommand:r}=e;d.start("worktrees-sync");try{let t=await O("release"),o=await E(),n=`${o}${j}`,s=await Ge(),a=r?!0:await zn({message:"Are you sure you want to proceed with these worktree changes?"});r||d.setInteractive(),a||(i.info("Operation cancelled. Exiting..."),Hn.exit(0)),r||d.addOption("--yes",!0);let{branchesToRemove:l}=Zn({releasePRsList:s,currentWorktrees:t}),c=await A(),p=await Qn({branches:l,worktreeDir:n,repoName:c});await es({removedWorktrees:p,worktreeDir:n,projectRoot:o}),rs(p),d.print();let m={removedWorktrees:p,count:p.length};return{content:w(JSON.stringify(m,null,2)),structuredContent:m}}catch(t){throw i.error({error:t},"\u274C Error managing worktrees"),new h(t,{operation:"sync worktrees with remote",remediation:"ensure 'gh auth status' is ok and you can reach origin"})}},Zn=e=>{let{releasePRsList:r,currentWorktrees:t}=e;return{branchesToRemove:t.filter(s=>s.startsWith(Yn)).filter(s=>!r.includes(s))}},Qn=async e=>{let{branches:r,worktreeDir:t,repoName:o}=e,n=[];for(let s of r)try{let a=`${t}/${s}`,l=F({repoName:o,branch:s});await Ce(l),await Xn`git worktree remove ${a}`,n.push(s)}catch(a){let l=new h(a,{operation:`remove stale worktree for ${s}`,remediation:"inspect the worktree dir manually; rerun with the branch checked out elsewhere"});i.error({error:a,branch:s,msg:l.message})}return n},es=async e=>{let{removedWorktrees:r,worktreeDir:t,projectRoot:o}=e;if(r.length===0)return;let n=await x(),s=n.ide?.provider==="cursor"?n.ide.config:void 0;if(!s||s.mode!=="workspace"||!s.workspaceConfigPath)return;let a=W(s.workspaceConfigPath,o),l=r.map(c=>`${t}/${c}`);try{let{removed:c}=await X({workspacePath:a,folderPaths:l});c.length>0&&i.info(`\u2705 Removed ${c.length} folder(s) from ${a}`)}catch(c){i.warn({error:c},`\u26A0\uFE0F Failed to update Cursor workspace at ${a}`)}},rs=e=>{if(e.length>0){i.info("\u274C Removed worktrees:");for(let r of e)i.info(r);i.info("")}else i.info("\u2139\uFE0F No unused worktrees to remove")},jr=v({name:"worktrees-sync",description:"Remove worktrees whose release PR is no longer open (stale cleanup). Only removes \u2014 never creates; use worktrees-add to create worktrees for new releases. The CLI confirmation is auto-skipped for MCP calls, so the caller is responsible for gating.",inputSchema:{},outputSchema:{removedWorktrees:_r.array(_r.string()).describe("List of removed worktree branches"),count:_r.number().describe("Number of worktrees removed during sync")},handler:Vt});var Fr=e=>async r=>{let{toolName:t,handler:o}=e;i.info({msg:`Tool execution started: ${t}`,params:r});try{let n=await o({...r,confirmedCommand:!0});return i.info({msg:`Tool execution successful: ${t}`}),n}catch(n){throw i.error({err:n,params:r,msg:`Tool execution failed: ${t}`}),n}};var ts=[cr,sr,ar,tr,wr,$r,Er,kr,xr,Tr,Pr,Sr,Ar,Nr,Mr,Dr,jr],Lt=async e=>{for(let r of ts)e.registerTool(r.name,{description:r.description,inputSchema:r.inputSchema,outputSchema:r.outputSchema},Fr({toolName:r.name,handler:r.handler}))};async function Bt(){let e=new os({name:"infra-kit",version:"1.0.0"},{capabilities:{resources:{},tools:{},prompts:{}}});return await Br(e),await qr(e),await Lt(e),e}var Z=Vr(),ss=async()=>{let e;try{e=await Bt(),Z.info("MCP Server instance created")}catch(r){Z.error({err:r,msg:"Failed to create MCP server"}),Z.error("Fatal error during server creation."),qt.exit(1)}try{let r=new ns;await e.connect(r),Z.info({msg:"Server connected to transport. Ready."})}catch(r){Z.error({err:r,msg:"Failed to initialize server"}),Z.error("Fatal error during server transport init."),qt.exit(1)}};Lr(Z);ss();
|
|
53
53
|
//# sourceMappingURL=mcp.js.map
|