infra-kit 0.1.97 → 0.1.98
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-eslint-check.log +4 -5
- package/.turbo/turbo-prettier-check.log +4 -5
- package/.turbo/turbo-test.log +191 -18
- package/.turbo/turbo-ts-check.log +9 -5
- package/dist/cli.js +57 -37
- package/dist/cli.js.map +4 -4
- package/dist/mcp.js +29 -28
- package/dist/mcp.js.map +4 -4
- package/package.json +1 -1
- package/src/commands/config/config.ts +125 -0
- package/src/commands/config/index.ts +1 -0
- package/src/commands/doctor/doctor.ts +27 -18
- package/src/commands/init/init.ts +54 -1
- package/src/commands/release-create/release-create.ts +123 -72
- package/src/commands/release-create-batch/release-create-batch.ts +45 -21
- package/src/entry/cli.ts +26 -5
- package/src/lib/__tests__/infra-kit-config.test.ts +3 -1
- package/src/lib/infra-kit-config/index.ts +2 -2
- package/src/lib/infra-kit-config/infra-kit-config.ts +183 -37
- package/src/lib/version-utils/__tests__/next-version.test.ts +112 -0
- package/src/lib/version-utils/index.ts +11 -0
- package/src/lib/version-utils/load-existing-versions.ts +67 -0
- package/src/lib/version-utils/next-version.ts +148 -0
- package/tsconfig.tsbuildinfo +1 -1
package/dist/mcp.js
CHANGED
|
@@ -1,41 +1,42 @@
|
|
|
1
|
-
import{StdioServerTransport as
|
|
2
|
-
`)){let o=
|
|
1
|
+
import{StdioServerTransport as Is}from"@modelcontextprotocol/sdk/server/stdio.js";import At from"node:process";import W from"node:process";import Dr from"node:process";import Xe from"pino";import Ot from"pino-pretty";var ue="/tmp/mcp-infra-kit.log",Mr=()=>{let e=Dr.argv.includes("--debug")?"debug":"info",r=Xe({level:e},Xe.destination({dest:ue}));return r.info(`Logger initialized with level: ${e}. Logging to: ${ue}`),r},Ft=()=>{let e=Dr.argv.includes("--debug")?"debug":"info",r=["time","pid","hostname"];return e==="debug"&&r.push("level"),Xe({level:e},Ot({destination:2,ignore:r.join(","),colorize:!0}))},a=Ft();var jr=e=>{W.on("SIGINT",()=>{e.info({msg:"Received SIGINT. Shutting down..."}),W.exit(0)}),W.on("SIGTERM",()=>{e.info({msg:"Received SIGTERM. Shutting down..."}),W.exit(0)}),W.on("uncaughtException",r=>{e.fatal({err:r,msg:"Uncaught Exception"}),e.error(`Uncaught Exception! Check ${ue}. Shutting down...`),e.flush(),W.exit(1)}),W.on("unhandledRejection",(r,t)=>{e.fatal({reason:r,promise:t,msg:"Unhandled Rejection"}),e.error(`Unhandled Rejection! Check ${ue}. Shutting down...`),e.flush(),W.exit(1)})};import{McpServer as As}from"@modelcontextprotocol/sdk/server/mcp.js";var Wr=async e=>{};var Vr=async e=>{};import er from"node:fs";import Lr from"node:path";import Mt from"node:process";import{z as Me}from"zod/v4";import de from"node:fs";import _t from"node:os";import Ze from"node:path";import Qe from"node:process";var z="env-load.sh",Jr="env-clear.sh",Oe="INFRA_KIT_SESSION",Y="INFRA_KIT_ENV_CONFIG",X="INFRA_KIT_ENV_PROJECT",Z="INFRA_KIT_ENV_LOADED_AT",Fe=/^([A-Z_]\w*)=/i,_e=e=>{if(!de.existsSync(e))return[];let r=de.readFileSync(e,"utf-8"),t=[];for(let s of r.split(`
|
|
2
|
+
`)){let o=Fe.exec(s);o&&t.push(o[1])}return t},Dt=()=>{let e=Qe.env.XDG_CACHE_HOME,r=e&&e.length>0?e:Ze.join(_t.homedir(),".cache");return Ze.join(r,"infra-kit")},Q=()=>{let e=Qe.env[Oe];if(!e)throw new Error(`${Oe} is not set. Run \`infra-kit init\` then \`source ~/.zshrc\`.`);return Ze.join(Dt(),e)},De=(e,r,t)=>{let s=`${e}.tmp.${Qe.pid}`;de.writeFileSync(s,r,{mode:t});try{de.renameSync(s,e)}catch(o){throw de.rmSync(s,{force:!0}),o}},V="-worktrees";var Br=async()=>{let e=Q(),r=Lr.join(e,z);if(!er.existsSync(r))throw new Error("No loaded environment found. Run `env-load` first.");let t=_e(r),s=[...t.map(i=>`unset ${i}`),`unset ${Y}`,`unset ${X}`,`unset ${Z}`],o=Lr.resolve(e,Jr);er.mkdirSync(e,{recursive:!0,mode:448}),De(o,`${s.join(`
|
|
3
3
|
`)}
|
|
4
|
-
`,384)
|
|
5
|
-
`),
|
|
6
|
-
`).filter(Boolean),s={release:
|
|
7
|
-
`),
|
|
4
|
+
`,384),Mt.stdout.write(`${o}
|
|
5
|
+
`),er.unlinkSync(r);let n={filePath:o,variableCount:t.length,unsetStatements:s};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}},rr={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:Me.string().describe("Path to the file that must be sourced to apply"),variableCount:Me.number().describe("Number of variables cleared"),unsetStatements:Me.array(Me.string()).describe("Unset statements generated")},handler:Br};import{z as or}from"zod/v4";import tr from"node:fs/promises";import Jt from"node:os";import je from"node:path";import Lt from"yaml";import{z as h}from"zod/v4";import jt from"node:path";import{$ as qr}from"zx";var I=async e=>{let t=(await qr`git worktree list`).stdout.split(`
|
|
6
|
+
`).filter(Boolean),s={release:Wt,feature:Vt};return t.map(s[e]).filter(o=>o!==null)},Kr=e=>{let r=e.trimEnd();if(!r.endsWith("]"))return null;let t=r.lastIndexOf("[");if(t===-1)return null;let s=r.slice(t+1,-1);return s.length>0?s:null},Wt=e=>{let r=Kr(e);return r?.startsWith("release/v")?r:null},Vt=e=>{let r=Kr(e);return r?.startsWith("feature/")?r:null},T=async()=>(await qr`git rev-parse --show-toplevel`).stdout.trim(),N=async()=>{let e=await T();return jt.basename(e)};var Ur="infra-kit.yml",Bt=".infra-kit",qt="config.yml",Kt="projects",Ut=h.object({provider:h.literal("doppler"),config:h.object({name:h.string().min(1)})}),Gt=h.discriminatedUnion("provider",[Ut]),Ht=h.object({mode:h.enum(["workspace","windows"]).default("workspace"),workspaceConfigPath:h.string().min(1).optional()}).refine(e=>e.mode!=="workspace"||!!e.workspaceConfigPath,{message:'workspaceConfigPath is required when mode is "workspace"',path:["workspaceConfigPath"]}),zt=h.object({provider:h.literal("cursor"),config:Ht}),Yt=h.discriminatedUnion("provider",[zt]),Xt=h.object({provider:h.literal("jira"),config:h.object({baseUrl:h.string().url(),projectId:h.number().int().positive()})}),Zt=h.discriminatedUnion("provider",[Xt]),Hr=h.object({environments:h.array(h.string().min(1)).min(1),envManagement:Gt,ide:Yt.optional(),taskManager:Zt.optional()}),Qt=Hr.partial(),fe=null,zr=async()=>{let e=await T(),r=await N(),t=je.join(Jt.homedir(),Bt);return{main:je.join(e,Ur),userGlobal:je.join(t,qt),userProject:je.join(t,Kt,r,Ur),projectName:r}},v=async()=>{let e=await zr(),r;try{r=await tr.stat(e.main)}catch{throw fe=null,new Error(`infra-kit.yml not found at ${e.main}`)}let[t,s]=await Promise.all([Gr(e.userGlobal),Gr(e.userProject)]),o={main:Number(r.mtimeMs),userGlobal:t?Number(t.mtimeMs):null,userProject:s?Number(s.mtimeMs):null};if(fe&&ro(fe.mtimes,o))return fe.value;let n=[{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}],i={};for(let c of n){let p=await to(c);p!==null&&(i={...i,...p})}let l=Hr.safeParse(i);if(!l.success)throw new Error(`Invalid merged infra-kit config: ${h.prettifyError(l.error)}`);return fe={mtimes:o,value:l.data},l.data};var Gr=async e=>{try{return await tr.stat(e)}catch{return null}},eo=async e=>{try{return await tr.readFile(e,"utf-8")}catch{return null}},ro=(e,r)=>{let t=Object.keys(e);return t.length!==Object.keys(r).length?!1:t.every(s=>e[s]===r[s])},to=async e=>{let r=await eo(e.path);if(r===null){if(e.required)throw new Error(`${e.label} not found at ${e.path}`);return null}let t=Lt.parse(r)??{},s=Qt.safeParse(t);if(!s.success)throw new Error(`Invalid ${e.label} at ${e.path}: ${h.prettifyError(s.error)}`);return s.data};var ge=async()=>{let{envManagement:e}=await v();return e.config.name};var Yr=async()=>{let e=await ge(),{environments:r}=await v();a.info(`Doppler project: ${e}
|
|
7
|
+
`),a.info("Available configs:");for(let s of r)a.info(` - ${s}`);let t={project:e,configs:r};return{content:[{type:"text",text:JSON.stringify(t,null,2)}],structuredContent:t}},sr={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:or.string().describe("Detected Doppler project name"),configs:or.array(or.string()).describe("Available environment configs")},handler:Yr};import so from"@inquirer/select";import{Buffer as no}from"node:buffer";import io from"node:fs";import ao from"node:path";import Zr from"node:process";import{z as ve}from"zod/v4";import{$ as We}from"zx";import{$ as Xr}from"zx";var he=async()=>{try{await Xr`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 Xr`doppler me`}catch(e){throw new Error("Doppler CLI is not authenticated. Run: doppler login",{cause:e})}};var oo=()=>{let e="",r=[],t=!1;return{start(s){e=s,r=[],t=!1},setInteractive(){t=!0},addOption(s,o){r.push({flag:s,value:o})},print(){if(!t||r.length===0)return;let s=r.map(o=>typeof o.value=="boolean"?o.value?o.flag:"":Array.isArray(o.value)?`${o.flag} "${o.value.join(", ")}"`:`${o.flag} "${o.value}"`).filter(Boolean).join(" ");a.info(`\u{1F4DF} Equivalent command:
|
|
8
8
|
pnpm exec infra-kit ${e} ${s}
|
|
9
|
-
`)},reset(){e="",r=[],t=!1}}},
|
|
9
|
+
`)},reset(){e="",r=[],t=!1}}},m=oo();var et=async e=>{await he();let{config:r}=e;m.start("env-load");let t="";if(r)t=r;else{let{environments:d}=await v();m.setInteractive(),t=await so({message:"Select environment config",choices:d.map(g=>({name:g,value:g}))},{output:Zr.stderr})}m.addOption("--config",t);let s=await ge(),o=await lo(s,t);fo(o);let n=new Date().toISOString(),i=["set -a",o,`${Y}=${nr(t)}`,`${X}=${nr(s)}`,`${Z}=${nr(n)}`,"set +a"],l=Q(),c=ao.resolve(l,z);io.mkdirSync(l,{recursive:!0,mode:448}),De(c,`${i.join(`
|
|
10
10
|
`)}
|
|
11
|
-
`,384),
|
|
12
|
-
`),
|
|
13
|
-
`).filter(r=>
|
|
14
|
-
`)){let t=r.trim();if(!(t.length===0||
|
|
15
|
-
`),o>0&&s<o){let d=o-s;
|
|
16
|
-
`);let c={sessionId:r,sessionLoadedCount:s,sessionTotalCount:o,sessionConfig:n,sessionProject:
|
|
17
|
-
`);throw new Error(
|
|
11
|
+
`,384),Zr.stdout.write(`${c}
|
|
12
|
+
`),m.print();let p=mo(o),u={filePath:c,variableCount:p,project:s,config:t};return{content:[{type:"text",text:JSON.stringify(u,null,2)}],structuredContent:u}},Qr=1024*1024,co=3e4,lo=async(e,r)=>{let t=We.quiet;We.quiet=!0;try{let s=await We`doppler secrets download --no-file --format env --project ${e} --config ${r}`.timeout(co);return po(s.stdout),s.stdout.trim()}finally{We.quiet=t}},po=e=>{let r=no.byteLength(e,"utf-8");if(r>Qr)throw new Error(`doppler returned unexpectedly large output (${r} bytes > ${Qr}) \u2014 refusing to write to disk`)},mo=e=>e.split(`
|
|
13
|
+
`).filter(r=>Fe.test(r)).length,uo=new Set(["set -a","set +a"]),nr=e=>`'${e.replaceAll("'","'\\''")}'`,fo=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||uo.has(t))&&!Fe.test(t))throw new Error(`doppler returned unexpected output for env-load (expected KEY=value lines, got: ${JSON.stringify(t.slice(0,80))})`)}},ir={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:ve.string().describe('Doppler config / environment name to load (e.g. "dev", "arthur", "renana"). Required for MCP calls.')},outputSchema:{filePath:ve.string().describe("Path to the file that must be sourced to apply variables"),variableCount:ve.number().describe("Number of variables loaded"),project:ve.string().describe("Doppler project name"),config:ve.string().describe("Doppler config name")},handler:et};import go from"node:path";import we from"node:process";import{z as ee}from"zod/v4";var rt=async()=>{await he(),a.info("Environment session status:");let e=Q(),r=we.env[Oe],t=go.join(e,z),s=0,o=0,n=we.env[Y]??null,i=we.env[X]??null,l=we.env[Z]??null;if(n){let p=_e(t);p.length>0&&(o=p.length,s=p.filter(d=>d in we.env).length);let u=l?.replace(/\.\d{3}Z$/,"")??null;if(a.info(` ${n}: ${s} of ${o} vars loaded (project: ${i}, loadedAt: ${u}, session: ${r})
|
|
15
|
+
`),o>0&&s<o){let d=o-s;a.warn(` ${d} cached var(s) are not present in the current process \u2014 env-load needs to be re-sourced, or vars were unset manually.`)}}else a.info(` Session ${r}: no env loaded
|
|
16
|
+
`);let c={sessionId:r,sessionLoadedCount:s,sessionTotalCount:o,sessionConfig:n,sessionProject:i,sessionLoadedAt:l};return{content:[{type:"text",text:JSON.stringify(c,null,2)}],structuredContent:c}},ar={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:ee.string().describe("Current terminal session ID"),sessionLoadedCount:ee.number().describe("Number of cached vars active in the current session"),sessionTotalCount:ee.number().describe("Total number of cached var names"),sessionConfig:ee.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:ee.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:ee.string().nullable().describe("ISO 8601 timestamp of when the env was loaded")},handler:rt};import Co from"@inquirer/checkbox";import To from"@inquirer/confirm";import Po from"node:process";import{z as ce}from"zod/v4";import{$ as O}from"zx";import{$ as ii}from"zx";import qe from"node:process";import{$ as S}from"zx";import{$ as ke}from"zx";import ye from"node:process";var cr=async(e,r)=>{try{let{baseUrl:t,token:s,email:o,projectId:n}=r,i={name:e.name,projectId:e.projectId||n,description:e.description||"",released:e.released||!1,archived:e.archived||!1},l=`${t}/rest/api/3/version`,c=btoa(`${o}:${s}`),p=await fetch(l,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${c}`},body:JSON.stringify(i)});if(!p.ok){let d=await p.text();throw a.error({status:p.status,statusText:p.statusText,error:d},"Failed to create Jira version"),new Error(`HTTP ${p.status}: ${p.statusText}`)}return{success:!0,version:await p.json()}}catch(t){throw a.error({error:t},"Error creating Jira version"),t}},re=async e=>{try{let{baseUrl:r,token:t,email:s,projectId:o}=e,n=`${r}/rest/api/3/project/${o}/versions`,i=btoa(`${s}:${t}`),l=await fetch(n,{method:"GET",headers:{Accept:"application/json",Authorization:`Basic ${i}`}});if(!l.ok){let p=await l.text();throw a.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 a.error({error:r},"Error getting Jira project versions"),r}},vo=async(e,r)=>{try{return(await re(r)).find(o=>o.name===e)||null}catch(t){throw a.error({error:t,versionName:e},"Error finding Jira version by name"),t}},wo=async(e,r)=>{try{let{baseUrl:t,token:s,email:o}=r,n={released:e.released??!0,archived:e.archived??!1};e.releaseDate?n.releaseDate=e.releaseDate:e.released!==!1&&(n.releaseDate=new Date().toISOString().split("T")[0]),e.description!==void 0&&(n.description=e.description);let i=`${t}/rest/api/3/version/${e.versionId}`,l=btoa(`${o}:${s}`),c=await fetch(i,{method:"PUT",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${l}`},body:JSON.stringify(n)});if(!c.ok){let u=await c.text();throw a.error({status:c.status,statusText:c.statusText,error:u},"Failed to update Jira version"),new Error(`HTTP ${c.status}: ${c.statusText}`)}return{success:!0,version:await c.json()}}catch(t){throw a.error({error:t},"Error updating Jira version"),t}},lr=async(e,r)=>{try{let{versionName:t}=e,s=await vo(t,r);if(!s)throw a.error({versionName:t},"Jira version not found"),new Error(`Version "${t}" not found in Jira project`);return await wo({versionId:s.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},r)}catch(t){throw a.error({error:t},"Error delivering Jira release"),t}},te=async()=>{let e=ye.env.JIRA_BASE_URL,r=ye.env.JIRA_TOKEN||ye.env.JIRA_API_TOKEN,t=ye.env.JIRA_PROJECT_ID,s=ye.env.JIRA_EMAIL,o=[];if(e||o.push("JIRA_BASE_URL (e.g., https://your-domain.atlassian.net)"),r||o.push("JIRA_TOKEN or JIRA_API_TOKEN (your Jira API token)"),t||o.push("JIRA_PROJECT_ID (numeric project ID)"),s||o.push("JIRA_EMAIL (your Jira email address)"),o.length>0){let i=["Jira configuration is required but incomplete.","Please configure the following environment variables:",...o.map(l=>` - ${l}`),"","You can set these in your .env file or as environment variables."].join(`
|
|
17
|
+
`);throw new Error(i)}let n=Number.parseInt(t,10);if(Number.isNaN(n))throw new TypeError(`Invalid JIRA_PROJECT_ID: "${t}" must be a numeric value (e.g., 10001)`);return{baseUrl:e.replace(/\/$/,""),token:r,projectId:n,email:s}},K=async()=>{try{return await te()}catch(e){return a.warn({error:e},"Jira configuration not available, skipping Jira integration"),null}};var Ve=e=>e==="hotfix"?"main":"dev",Re=async(e="regular")=>{let r=Ve(e);ke.quiet=!0,await ke`git fetch origin`,await ke`git switch ${r}`,await ke`git pull origin ${r}`,ke.quiet=!1},be=async e=>{let{version:r,jiraConfig:t,description:s,type:o="regular"}=e,n=`v${r}`,i=await cr({name:n,projectId:t.projectId,description:s||"",released:!1,archived:!1},t),l=`${t.baseUrl}/projects/${i.version.projectId}/versions/${i.version.id}/tab/release-report-all-issues`,c=await Je({version:r,jiraVersionUrl:l,type:o,description:s});return{version:r,type:o,branchName:c.branchName,prUrl:c.prUrl,jiraVersionUrl:l}},R=async()=>{let e=new Map,r=await K();if(!r)return e;try{let t=await re(r);for(let s of t)s.description&&e.set(s.name,s.description)}catch{}return e},oe=(e,r,t)=>{let s=t?" ".repeat(t-e.length+3):" ",o=`[${r}]`.padEnd(11);return`${e}${s}${o}`},w=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",E=e=>{let{branches:r,descriptions:t,types:s}=e,o=r.map(i=>i.replace("release/v","")),n=Math.max(...o.map(i=>i.length));return r.map((i,l)=>{let c=o[l],p=s?s.get(i)||"regular":void 0,u=t.get(`v${c}`),d=" ".repeat(n-c.length+3),g=p?oe(c,p,n):c;return u&&(g=p?`${g} ${u}`:`${c}${d}${u}`),{name:g,value:i}})};import{$ as Be}from"zx";var se=e=>e.replace("release/","").slice(1).split(".").map(Number),ne=e=>[...e].sort((r,t)=>{let[s,o,n]=se(r),[i,l,c]=se(t);return s!==i?(s??0)-(i??0):o!==l?(o??0)-(l??0):(n??0)-(c??0)});var ie="next",yo=/^v?(\d+)\.(\d+)\.(\d+)$/,ko=e=>e.replace(/^.*release\//,""),ot=e=>{let r=ko(e.trim()),t=yo.exec(r);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null},tt=e=>`${e[0]}.${e[1]}.${e[2]}`,pr=e=>{let r=[...e.remoteBranches??[],...e.jiraVersions??[]],t=[],s=new Set;for(let o of r){let n=ot(o);if(!n)continue;let i=tt(n);s.has(i)||(s.add(i),t.push(n))}return ne(t.map(o=>tt(o))).map(o=>se(`v${o}`))},D=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},Le=(e,r)=>{if(e.length===0)throw new D;let t=e[e.length-1];if(r==="hotfix"){let[n,i]=t,l=e.reduce((c,p)=>p[0]===n&&p[1]===i?Math.max(c,p[2]):c,0);return`${n}.${i}.${l+1}`}let[s,o]=t;return`${s}.${o+1}.0`},Ro=e=>e.trim().toLowerCase()===ie,xe=(e,r,t)=>{let s=[...t],o=[];for(let n of e){let i=n.trim();if(i==="")continue;if(Ro(i)){let p=Le(s,r);o.push(p),s.push(se(`v${p}`));continue}let l=ot(i);if(!l)throw new Error(`Invalid version "${i}". Expected semver like "1.2.5" or the token "next".`);let c=`${l[0]}.${l[1]}.${l[2]}`;o.push(c),s.push(l)}return o},ae=e=>e.split(",").map(r=>r.trim()).filter(Boolean);var bo=async()=>{let e=Be.quiet;try{return Be.quiet=!0,(await Be`git ls-remote --heads origin 'release/v*'`).stdout.split(`
|
|
18
|
+
`).map(s=>{let o=s.indexOf(" ");return o===-1?"":s.slice(o+1).replace(/^refs\/heads\//,"")}).filter(Boolean)}finally{Be.quiet=e}},xo=async()=>{let e=await K();return e?(await re(e)).map(t=>t.name):[]},Ce=async()=>{let[e,r]=await Promise.allSettled([bo(),xo()]);return e.status==="rejected"&&a.warn({error:e.reason},"Failed to list remote release branches; continuing without them"),r.status==="rejected"&&a.warn({error:r.reason},"Failed to fetch Jira versions; continuing without them"),pr({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:r.status==="fulfilled"?r.value:[]})};var st=async()=>{let e=await S`gh pr list --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName`,r=await S`gh pr list --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName`,t=[...JSON.parse(e.stdout),...JSON.parse(r.stdout)],s=new Set;return t.filter(o=>s.has(o.headRefName)?!1:(s.add(o.headRefName),!0))},Ke=async()=>{try{let e=await st();return e.length===0&&(a.error("\u274C No release PRs found. Check the project folder for the script. Exiting..."),qe.exit(1)),ne(e.map(r=>r.headRefName))}catch(e){a.error({error:e},"\u274C Error fetching release PRs"),qe.exit(1)}},y=async()=>{try{let e=await st();e.length===0&&(a.error("\u274C No release PRs found. Check the project folder for the script. Exiting..."),qe.exit(1));let r=ne(e.map(s=>s.headRefName)),t=new Map(e.map(s=>[s.headRefName,s]));return r.map(s=>({branch:s,title:t.get(s).title}))}catch(e){a.error({error:e},"\u274C Error fetching release PRs"),qe.exit(1)}},Je=async e=>{let{version:r,jiraVersionUrl:t,type:s,description:o}=e,n=s==="hotfix"?"Hotfix":"Release",i=Ve(s),l=`release/v${r}`,c=o&&o.trim()!==""?`${t}
|
|
18
19
|
|
|
19
20
|
${o}`:`${t}
|
|
20
|
-
`;try{S.quiet=!0,await S`git switch ${
|
|
21
|
+
`;try{S.quiet=!0,await S`git switch ${i}`,await S`git pull origin ${i}`,await S`git checkout -b ${l}`,await S`git push -u origin ${l}`,await S`git commit --allow-empty-message --allow-empty --message ''`,await S`git push origin ${l}`;let u=(await S`gh pr create --title "${n} v${r}" --body ${c} --base ${i} --head ${l}`).stdout.trim();return await S`git switch ${i}`,S.quiet=!1,{branchName:l,prUrl:u}}catch(p){throw a.error({error:p,branchName:l},`Error creating release branch ${l}`),p}};var nt=async e=>{let{all:r,confirmedCommand:t}=e;m.start("merge-dev");let o=(await y()).filter(u=>w(u.title)==="regular").map(u=>u.branch);if(o.length===0)return a.info("\u2139\uFE0F No open release branches found"),m.print(),{content:[{type:"text",text:JSON.stringify({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0},null,2)}],structuredContent:{successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0}};let n=[];if(r)n=o;else{m.setInteractive();let u=await R();n=await Co({required:!0,message:"\u{1F33F} Select release branches",choices:E({branches:o,descriptions:u})})}n.length===o.length?m.addOption("--all",!0):m.addOption("--versions",n.map(u=>u.replace("release/v","")));let l=t?!0:await To({message:`Are you sure you want to merge dev into these branches: ${n.join(", ")}?`});t||m.setInteractive(),l||(a.info("Operation cancelled. Exiting..."),Po.exit(0)),t||m.addOption("--yes",!0),O.quiet=!0,await O`git fetch origin`,await O`git switch dev`,await O`git pull origin dev`;let c=[];for(let u of n)await $o(u)||c.push(u);if(O.quiet=!1,c.length>0){a.info(`
|
|
21
22
|
\u26A0\uFE0F ${c.length} branch(es) failed to merge automatically.
|
|
22
|
-
`),
|
|
23
|
+
`),a.info("\u{1F4CB} Manual merge script for failed branches:");for(let u of c)a.info(`# Merge dev into ${u} and resolve conflicts if any
|
|
23
24
|
|
|
24
25
|
git switch ${u} && git pull origin ${u} && git merge origin/dev
|
|
25
26
|
git push origin ${u} && git switch dev
|
|
26
|
-
`);
|
|
27
|
-
`);p.print();let m={successfulMerges:n.length-c.length,failedMerges:c.length,failedBranches:c,totalBranches:n.length};return{content:[{type:"text",text:JSON.stringify(m,null,2)}],structuredContent:m}},io=async e=>{try{return await O`git switch ${e}`,await O`git pull origin ${e}`,await O`git merge origin/dev --no-edit`,await O`git push origin ${e}`,await O`git switch dev`,i.info(`Successfully merged dev into ${e}`),!0}catch(r){return i.error({error:r,branch:e},`Error merging dev into ${e}`),await O`git reset --merge HEAD~1`,!1}},rr={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:te.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:te.number().describe("Number of successful merges"),failedMerges:te.number().describe("Number of failed merges"),failedBranches:te.array(te.string()).describe("List of branches that failed to merge"),totalBranches:te.number().describe("Total number of branches processed")},handler:Ur};import ao from"@inquirer/confirm";import co from"@inquirer/select";import tr from"node:process";import{z as ve}from"zod/v4";import{$ as P}from"zx";var Gr=async e=>{let{version:r,confirmedCommand:t}=e;p.start("release-deliver");let s=await y(),o=s.map(d=>d.branch),n=new Map(s.map(d=>[d.branch,w(d.title)])),a="";if(r)a=`release/v${r}`;else{p.setInteractive();let d=await R();a=await co({message:"\u{1F33F} Select release branch",choices:E({branches:o,descriptions:d,types:n})})}let l=a.replace("release/v","");p.addOption("--version",l);let c=s.find(d=>d.branch===a);c||(i.error(`\u274C Release branch ${a} not found in open PRs. Exiting...`),tr.exit(1));let m=w(c.title),u=t?!0:await ao({message:`Are you sure you want to deliver version ${a} to production?`});t||p.setInteractive(),u||(i.info("Operation cancelled. Exiting..."),tr.exit(0)),p.addOption("--yes",!0);try{P.quiet=!0,m==="hotfix"?(await P`gh pr merge ${a} --squash --admin --delete-branch`,P.quiet=!1,await P`gh workflow run deploy-all.yml --ref main -f environment=prod`,P.quiet=!0,await P`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`):(await P`gh pr merge ${a} --squash --admin --delete-branch`,await P`gh pr create --base main --head dev --title "Release v${l} (RC)" --body ""`,await P`gh pr merge dev --squash --admin`,P.quiet=!1,await P`gh workflow run deploy-all.yml --ref main -f environment=prod`,P.quiet=!0,await P`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`),P.quiet=!1;let d=await de();if(d)try{let f=a.replace("release/","");await Qe({versionName:f},d)}catch(f){i.error({error:f},"Failed to deliver Jira release (non-blocking)")}else i.info("\u{1F514} Jira is not configured, skipping Jira release delivery");i.info(`Successfully delivered ${a} to production!`),p.print();let h={releaseBranch:a,version:a.replace("release/v",""),type:m,success:!0};return{content:[{type:"text",text:JSON.stringify(h,null,2)}],structuredContent:h}}catch(d){i.error({error:d},"\u274C Error merging release branch into dev"),tr.exit(1)}},or={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. 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:ve.string().describe('Release version to deliver to production (e.g., "1.2.5"). Required for MCP calls.')},outputSchema:{releaseBranch:ve.string().describe("The release branch that was delivered"),version:ve.string().describe("The version that was delivered"),type:ve.enum(["regular","hotfix"]).describe("Release type"),success:ve.boolean().describe("Whether the delivery was successful")},handler:Gr};import Kr from"@inquirer/select";import zr from"node:process";import{z as L}from"zod/v4";import{$ as sr}from"zx";var Hr=async e=>{let{version:r,env:t,skipTerraform:s}=e;p.start("release-deploy-all");let o="";if(r)o=r==="dev"?"dev":`release/v${r}`;else{p.setInteractive();let m=await y(),u=m.map(f=>f.branch),d=new Map(m.map(f=>[f.branch,w(f.title)])),h=await R();o=await Kr({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...E({branches:u,descriptions:h,types:d})]})}let n=o==="dev"?"dev":o.replace("release/v","");p.addOption("--version",n);let{environments:a}=await v(),l="";t?l=t:(p.setInteractive(),l=await Kr({message:"\u{1F9EA} Select environment",choices:a.map(m=>({name:m,value:m}))})),p.addOption("--env",l),a.includes(l)||(i.error(`\u274C Invalid environment: ${l}. Exiting...`),zr.exit(1));let c=s??!1;c&&p.addOption("--skip-terraform",!0);try{sr.quiet=!0,await sr`gh workflow run deploy-all.yml --ref ${o} -f environment=${l} ${c?["-f","skip_terraform_deploy=true"]:[]}`,sr.quiet=!1,i.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${o} and environment: ${l}`),p.print();let u={releaseBranch:o,version:o.replace("release/v",""),environment:l,skipTerraformDeploy:c,success:!0};return{content:[{type:"text",text:JSON.stringify(u,null,2)}],structuredContent:u}}catch(m){i.error({error:m},"\u274C Error launching workflow"),zr.exit(1)}},nr={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:L.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:L.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),skipTerraform:L.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:L.string().describe("The release branch that was deployed"),version:L.string().describe("The version that was deployed"),environment:L.string().describe("The environment deployed to"),skipTerraformDeploy:L.boolean().describe("Whether terraform deployment was skipped"),success:L.boolean().describe("Whether the deployment was successful")},handler:Hr};import lo from"@inquirer/checkbox";import Yr from"@inquirer/select";import po from"node:fs/promises";import{resolve as mo}from"node:path";import we from"node:process";import uo from"yaml";import{z as A}from"zod/v4";import{$ as ir}from"zx";var Xr=async e=>{let{version:r,env:t,services:s,skipTerraform:o}=e;p.start("release-deploy-selected");let n="";if(r)n=r==="dev"?"dev":`release/v${r}`;else{p.setInteractive();let f=await y(),k=f.map(B=>B.branch),$=new Map(f.map(B=>[B.branch,w(B.title)])),x=await R();n=await Yr({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...E({branches:k,descriptions:x,types:$})]})}let a=n==="dev"?"dev":n.replace("release/v","");p.addOption("--version",a);let{environments:l}=await v(),c="";t?c=t:(p.setInteractive(),c=await Yr({message:"\u{1F9EA} Select environment",choices:l.map(f=>({name:f,value:f}))})),p.addOption("--env",c),l.includes(c)||(i.error(`\u274C Invalid environment: ${c}. Exiting...`),we.exit(1));let m=await fo();m.length===0&&(i.error("\u274C No services found in workflow file. Exiting..."),we.exit(1));let u=[];s&&s.length>0?u=s:(p.setInteractive(),u=await lo({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:m.map(f=>({name:f,value:f}))})),p.addOption("--services",u),u.length===0&&(i.error("\u274C No services selected. Exiting..."),we.exit(1));let d=u.filter(f=>!m.includes(f));d.length>0&&(i.error(`\u274C Invalid services: ${d.join(", ")}. Available services: ${m.join(", ")}`),we.exit(1));let h=o??!1;h&&p.addOption("--skip-terraform",!0);try{ir.quiet=!0;let f=u.flatMap(x=>["-f",`${x}=true`]);await ir`gh workflow run deploy-selected-services.yml --ref ${n} -f environment=${c} ${f} ${h?["-f","skip_terraform_deploy=true"]:[]}`,ir.quiet=!1,i.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${n}, environment: ${c}, services: ${u.join(", ")}`),p.print();let $={releaseBranch:n,version:n.replace("release/v",""),environment:c,services:u,skipTerraformDeploy:h,success:!0};return{content:[{type:"text",text:JSON.stringify($,null,2)}],structuredContent:$}}catch(f){i.error({error:f},"\u274C Error launching workflow"),we.exit(1)}},fo=async()=>{let e=await T(),r=mo(e,".github/workflows/deploy-selected-services.yml"),t=await po.readFile(r,"utf-8"),o=uo.parse(t).on.workflow_dispatch.inputs,n=[];for(let[a,l]of Object.entries(o))l.type==="boolean"&&a!=="skip_terraform_deploy"&&n.push(a);return n},ar={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:Xr};import{z as oe}from"zod/v4";var Zr=async()=>{let r=(await y()).map(a=>({version:a.branch.replace("release/",""),type:w(a.title)})),t=await R(),s=Math.max(...r.map(a=>a.version.length)),o=r.map(a=>{let l=re(a.version,a.type,s),c=t.get(a.version);return c?`${l} ${c}`:l});i.info(`All release branches:
|
|
28
|
-
`),
|
|
27
|
+
`);a.info(`\u2705 ${n.length-c.length}/${n.length} merges completed successfully.`)}else a.info(`\u2705 All merges completed successfully!
|
|
28
|
+
`);m.print();let p={successfulMerges:n.length-c.length,failedMerges:c.length,failedBranches:c,totalBranches:n.length};return{content:[{type:"text",text:JSON.stringify(p,null,2)}],structuredContent:p}},$o=async e=>{try{return await O`git switch ${e}`,await O`git pull origin ${e}`,await O`git merge origin/dev --no-edit`,await O`git push origin ${e}`,await O`git switch dev`,a.info(`Successfully merged dev into ${e}`),!0}catch(r){return a.error({error:r,branch:e},`Error merging dev into ${e}`),await O`git reset --merge HEAD~1`,!1}},mr={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:ce.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:ce.number().describe("Number of successful merges"),failedMerges:ce.number().describe("Number of failed merges"),failedBranches:ce.array(ce.string()).describe("List of branches that failed to merge"),totalBranches:ce.number().describe("Total number of branches processed")},handler:nt};import Eo from"@inquirer/confirm";import So from"@inquirer/select";import ur from"node:process";import{z as Te}from"zod/v4";import{$ as P}from"zx";var it=async e=>{let{version:r,confirmedCommand:t}=e;m.start("release-deliver");let s=await y(),o=s.map(d=>d.branch),n=new Map(s.map(d=>[d.branch,w(d.title)])),i="";if(r)i=`release/v${r}`;else{m.setInteractive();let d=await R();i=await So({message:"\u{1F33F} Select release branch",choices:E({branches:o,descriptions:d,types:n})})}let l=i.replace("release/v","");m.addOption("--version",l);let c=s.find(d=>d.branch===i);c||(a.error(`\u274C Release branch ${i} not found in open PRs. Exiting...`),ur.exit(1));let p=w(c.title),u=t?!0:await Eo({message:`Are you sure you want to deliver version ${i} to production?`});t||m.setInteractive(),u||(a.info("Operation cancelled. Exiting..."),ur.exit(0)),m.addOption("--yes",!0);try{P.quiet=!0,p==="hotfix"?(await P`gh pr merge ${i} --squash --admin --delete-branch`,P.quiet=!1,await P`gh workflow run deploy-all.yml --ref main -f environment=prod`,P.quiet=!0,await P`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`):(await P`gh pr merge ${i} --squash --admin --delete-branch`,await P`gh pr create --base main --head dev --title "Release v${l} (RC)" --body ""`,await P`gh pr merge dev --squash --admin`,P.quiet=!1,await P`gh workflow run deploy-all.yml --ref main -f environment=prod`,P.quiet=!0,await P`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`),P.quiet=!1;let d=await K();if(d)try{let f=i.replace("release/","");await lr({versionName:f},d)}catch(f){a.error({error:f},"Failed to deliver Jira release (non-blocking)")}else a.info("\u{1F514} Jira is not configured, skipping Jira release delivery");a.info(`Successfully delivered ${i} to production!`),m.print();let g={releaseBranch:i,version:i.replace("release/v",""),type:p,success:!0};return{content:[{type:"text",text:JSON.stringify(g,null,2)}],structuredContent:g}}catch(d){a.error({error:d},"\u274C Error merging release branch into dev"),ur.exit(1)}},dr={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. 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:Te.string().describe('Release version to deliver to production (e.g., "1.2.5"). Required for MCP calls.')},outputSchema:{releaseBranch:Te.string().describe("The release branch that was delivered"),version:Te.string().describe("The version that was delivered"),type:Te.enum(["regular","hotfix"]).describe("Release type"),success:Te.boolean().describe("Whether the delivery was successful")},handler:it};import at from"@inquirer/select";import ct from"node:process";import{z as J}from"zod/v4";import{$ as fr}from"zx";var lt=async e=>{let{version:r,env:t,skipTerraform:s}=e;m.start("release-deploy-all");let o="";if(r)o=r==="dev"?"dev":`release/v${r}`;else{m.setInteractive();let p=await y(),u=p.map(f=>f.branch),d=new Map(p.map(f=>[f.branch,w(f.title)])),g=await R();o=await at({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...E({branches:u,descriptions:g,types:d})]})}let n=o==="dev"?"dev":o.replace("release/v","");m.addOption("--version",n);let{environments:i}=await v(),l="";t?l=t:(m.setInteractive(),l=await at({message:"\u{1F9EA} Select environment",choices:i.map(p=>({name:p,value:p}))})),m.addOption("--env",l),i.includes(l)||(a.error(`\u274C Invalid environment: ${l}. Exiting...`),ct.exit(1));let c=s??!1;c&&m.addOption("--skip-terraform",!0);try{fr.quiet=!0,await fr`gh workflow run deploy-all.yml --ref ${o} -f environment=${l} ${c?["-f","skip_terraform_deploy=true"]:[]}`,fr.quiet=!1,a.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${o} and environment: ${l}`),m.print();let u={releaseBranch:o,version:o.replace("release/v",""),environment:l,skipTerraformDeploy:c,success:!0};return{content:[{type:"text",text:JSON.stringify(u,null,2)}],structuredContent:u}}catch(p){a.error({error:p},"\u274C Error launching workflow"),ct.exit(1)}},gr={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:J.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:J.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),skipTerraform:J.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:J.string().describe("The release branch that was deployed"),version:J.string().describe("The version that was deployed"),environment:J.string().describe("The environment deployed to"),skipTerraformDeploy:J.boolean().describe("Whether terraform deployment was skipped"),success:J.boolean().describe("Whether the deployment was successful")},handler:lt};import Ao from"@inquirer/checkbox";import pt from"@inquirer/select";import Io from"node:fs/promises";import{resolve as No}from"node:path";import Pe from"node:process";import Oo from"yaml";import{z as A}from"zod/v4";import{$ as hr}from"zx";var mt=async e=>{let{version:r,env:t,services:s,skipTerraform:o}=e;m.start("release-deploy-selected");let n="";if(r)n=r==="dev"?"dev":`release/v${r}`;else{m.setInteractive();let f=await y(),k=f.map(q=>q.branch),$=new Map(f.map(q=>[q.branch,w(q.title)])),x=await R();n=await pt({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...E({branches:k,descriptions:x,types:$})]})}let i=n==="dev"?"dev":n.replace("release/v","");m.addOption("--version",i);let{environments:l}=await v(),c="";t?c=t:(m.setInteractive(),c=await pt({message:"\u{1F9EA} Select environment",choices:l.map(f=>({name:f,value:f}))})),m.addOption("--env",c),l.includes(c)||(a.error(`\u274C Invalid environment: ${c}. Exiting...`),Pe.exit(1));let p=await Fo();p.length===0&&(a.error("\u274C No services found in workflow file. Exiting..."),Pe.exit(1));let u=[];s&&s.length>0?u=s:(m.setInteractive(),u=await Ao({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:p.map(f=>({name:f,value:f}))})),m.addOption("--services",u),u.length===0&&(a.error("\u274C No services selected. Exiting..."),Pe.exit(1));let d=u.filter(f=>!p.includes(f));d.length>0&&(a.error(`\u274C Invalid services: ${d.join(", ")}. Available services: ${p.join(", ")}`),Pe.exit(1));let g=o??!1;g&&m.addOption("--skip-terraform",!0);try{hr.quiet=!0;let f=u.flatMap(x=>["-f",`${x}=true`]);await hr`gh workflow run deploy-selected-services.yml --ref ${n} -f environment=${c} ${f} ${g?["-f","skip_terraform_deploy=true"]:[]}`,hr.quiet=!1,a.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${n}, environment: ${c}, services: ${u.join(", ")}`),m.print();let $={releaseBranch:n,version:n.replace("release/v",""),environment:c,services:u,skipTerraformDeploy:g,success:!0};return{content:[{type:"text",text:JSON.stringify($,null,2)}],structuredContent:$}}catch(f){a.error({error:f},"\u274C Error launching workflow"),Pe.exit(1)}},Fo=async()=>{let e=await T(),r=No(e,".github/workflows/deploy-selected-services.yml"),t=await Io.readFile(r,"utf-8"),o=Oo.parse(t).on.workflow_dispatch.inputs,n=[];for(let[i,l]of Object.entries(o))l.type==="boolean"&&i!=="skip_terraform_deploy"&&n.push(i);return n},vr={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:mt};import{z as le}from"zod/v4";var ut=async()=>{let r=(await y()).map(i=>({version:i.branch.replace("release/",""),type:w(i.title)})),t=await R(),s=Math.max(...r.map(i=>i.version.length)),o=r.map(i=>{let l=oe(i.version,i.type,s),c=t.get(i.version);return c?`${l} ${c}`:l});a.info(`All release branches:
|
|
29
|
+
`),a.info(`
|
|
29
30
|
${o.join(`
|
|
30
31
|
`)}
|
|
31
|
-
`);let n={releases:r.map(
|
|
32
|
-
`)}catch(u){let d=u instanceof Error?u.message:String(u);n.push({version:
|
|
33
|
-
`)}let
|
|
34
|
-
`)){let s=t.match(/^[* ]\s*(workspace:\d+)\s+(.+?)(?:\s+\[selected\])?\s*$/);if(!s)continue;let o=s[1];if((s[2]?.trim()??"")===r)return o}};import{$ as
|
|
35
|
-
`)){let s=t.match(/^[* ]\s*workspace:\d+\s+(.+?)(?:\s+\[selected\])?\s*$/);if(!s)continue;let o=s[1]?.trim();o&&r.add(o)}return r}catch(e){return
|
|
36
|
-
`,"utf-8"),{added:c,skipped:
|
|
37
|
-
`,"utf-8");let u=[],d=[];for(let
|
|
38
|
-
${
|
|
32
|
+
`);let n={releases:r.map(i=>({version:i.version,type:i.type,description:t.get(i.version)||null})),count:r.length};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}},wr={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:le.array(le.object({version:le.string().describe("Release version"),type:le.enum(["regular","hotfix"]).describe("Release type"),description:le.string().nullable().describe("Jira version description")})).describe("List of all release branches"),count:le.number().describe("Number of release branches")},handler:ut};import Vo from"@inquirer/confirm";import Jo from"@inquirer/select";import Rr from"node:process";import{z as L}from"zod/v4";import{question as dt}from"zx";import _o from"@inquirer/confirm";import Do from"@inquirer/select";import yr from"node:process";import{z as b}from"zod/v4";import{question as Mo}from"zx";var jo='"1.2.5, 1.2.6", "next,next", or "next,next,1.2.7"',Wo=async e=>{let{versions:r,type:t,confirmedCommand:s}=e,o=r,n=t||"regular";t||(m.setInteractive(),n=await Do({message:"Select release type:",choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"})),m.addOption("--type",n),o||(m.setInteractive(),o=await Mo(`Enter versions by comma (e.g. ${jo}): `));let i=ae(o);i.length===0&&(a.error("No versions provided. Exiting..."),yr.exit(1));let c=i.some(d=>d.toLowerCase()===ie)?await Ce():[],p;try{p=xe(i,n,c)}catch(d){throw d instanceof D&&(a.error(d.message),yr.exit(1)),d}m.addOption("--versions",p.join(", ")),p.length===1&&a.warn('\u{1F4A1} You are creating only one release. Consider using "create-release" command for single releases.');let u=s?!0:await _o({message:`Are you sure you want to create release branches for these versions: ${p.join(", ")}?`});return s||m.setInteractive(),u||(a.info("Operation cancelled. Exiting..."),yr.exit(0)),m.addOption("--yes",!0),{versionsList:p,type:n}},Ue=async e=>{m.start("release-create-batch");let r=await te(),{versionsList:t,type:s}=await Wo(e);await Re(s);let o=[],n=[];for(let p of t)try{let u=await be({version:p,jiraConfig:r,type:s});o.push(u),a.info(`\u2705 Successfully created release: v${p}`),a.info(`\u{1F517} GitHub PR: ${u.prUrl}`),a.info(`\u{1F517} Jira Version: ${u.jiraVersionUrl}
|
|
33
|
+
`)}catch(u){let d=u instanceof Error?u.message:String(u);n.push({version:p,error:d}),a.error(`\u274C Failed to create release: v${p}`),a.error(` Error: ${d}
|
|
34
|
+
`)}let i=o.length,l=n.length;i===t.length?a.info(`\u2705 All ${t.length} release branches were created successfully.`):i>0?(a.warn(`\u26A0\uFE0F ${i} of ${t.length} release branches were created successfully.`),a.warn(`\u274C ${l} release(s) failed.`)):a.error(`\u274C All ${t.length} release branches failed to create.`),m.print();let c={createdBranches:o.map(p=>p.branchName),successCount:i,failureCount:l,releases:o,failedReleases:n};return{content:[{type:"text",text:JSON.stringify(c,null,2)}],structuredContent:c}},kr={name:"release-create-batch",description:'Create several releases in one pass: for each comma-separated version in "versions", cuts the release branch off the appropriate base (dev for regular releases, main for hotfixes), opens a GitHub PR, and creates the Jira fix version. The literal token "next" auto-increments from the latest known version (regular bumps minor + resets patch; hotfix bumps patch on the highest minor); multiple "next" tokens advance sequentially. Existing versions are unioned from remote release branches and Jira fix versions. Continues on per-version failure and reports which versions succeeded and which failed. Confirmation is auto-skipped for MCP calls, so the caller is responsible for gating. "versions" is required when invoked via MCP (the interactive input prompt is unreachable without a TTY). Use release-create for a single version with optional checkout.',inputSchema:{versions:b.string().describe('Comma-separated versions to create (e.g., "1.2.5, 1.2.6", "next,next", or "next,next,1.2.7"). Required for MCP calls.'),type:b.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" or "hotfix" (default: "regular")')},outputSchema:{createdBranches:b.array(b.string()).describe("List of created release branches"),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:Ue};var Lo='"1.2.5", "next", or "next,next,1.2.7"',Bo=async()=>(m.setInteractive(),Jo({message:"Select release type:",choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"})),qo=(e,r)=>{try{return Le(e,r)}catch(t){if(t instanceof D)return null;throw t}},Ko=e=>{throw e instanceof D&&(a.error(e.message),Rr.exit(1)),e},Uo=async e=>{let{inputVersion:r,type:t,ensureKnown:s}=e;if(r&&r.trim()!=="")return ae(r);m.setInteractive();let o=qo(await s(),t),n=o?` [${o}]`:"",i=(await dt(`Enter version(s) (e.g. ${Lo})${n}: `)).trim();return i===""?o?[o]:[]:ae(i)},Go=async e=>{let r=await Uo(e);r.length===0&&(a.error("No version provided. Exiting..."),Rr.exit(1));let t=r.some(s=>s.toLowerCase()===ie);try{return xe(r,e.type,t?await e.ensureKnown():[])}catch(s){return Ko(s)}},Ho=async e=>e!==void 0?e:(m.setInteractive(),(await dt("Enter description (optional, press Enter to skip): ")).trim()),ft=async e=>{let{version:r,description:t,type:s,confirmedCommand:o}=e;m.start("release-create");let n=await te(),i=s??await Bo();m.addOption("--type",i);let l=null,p=await Go({inputVersion:r,type:i,ensureKnown:async()=>(l===null&&(l=await Ce()),l)});if(p.length>1)return a.info(`Detected ${p.length} versions, routing to release-create-batch...`),Ue({versions:p.join(","),type:i,confirmedCommand:o});let u=p[0];m.addOption("--version",u);let d=await Ho(t);d&&m.addOption("--description",d);let g=o?!0:await Vo({message:`Are you sure you want to create release branch for version ${u}?`});o||m.setInteractive(),g||(a.info("Operation cancelled. Exiting..."),Rr.exit(0)),m.addOption("--yes",!0),await Re(i);let f=await be({version:u,jiraConfig:n,description:d,type:i});a.info(`\u2705 Successfully created release: v${u}`),a.info(`\u{1F517} GitHub PR: ${f.prUrl}`),a.info(`\u{1F517} Jira Version: ${f.jiraVersionUrl}`),m.print();let k={version:u,type:i,branchName:f.branchName,prUrl:f.prUrl,jiraVersionUrl:f.jiraVersionUrl};return{content:[{type:"text",text:JSON.stringify(k,null,2)}],structuredContent:k}},br={name:"release-create",description:'Create a new release: cuts the release branch off the appropriate base (dev for regular releases, main for hotfixes), opens a GitHub release PR, and creates the matching Jira fix version. Does not switch the working tree to the new branch \u2014 the caller stays on the base branch. Confirmation is auto-skipped for MCP calls, so the caller is responsible for gating. "version" is required when invoked via MCP (the interactive input prompt is unreachable without a TTY); pass "next" to auto-compute the next version (regular bumps minor + resets patch; hotfix bumps patch on the highest minor) using the union of remote release branches and Jira fix versions. "type" / "description" default to regular / empty when omitted. For multiple versions in one call, prefer release-create-batch.',inputSchema:{version:L.string().describe('Version to create (e.g., "1.2.5") or the literal token "next" for auto-increment. Required for MCP calls.'),description:L.string().optional().describe("Optional description for the Jira version"),type:L.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" or "hotfix" (default: "regular")')},outputSchema:{version:L.string().describe("Version number"),type:L.enum(["regular","hotfix"]).describe("Release type"),branchName:L.string().describe("Release branch name"),prUrl:L.string().describe("GitHub PR URL"),jiraVersionUrl:L.string().describe("Jira version URL")},handler:ft};import{z as Yo}from"zod/v4";var gt={name:"infra-kit",type:"module",version:"0.1.98",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 warn --ignore-path ../../../.prettierignore","prettier-check":"pnpm exec prettier **/* --check --no-error-on-unmatched-pattern --log-level warn --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=dot","test-watch":"pnpm exec vitest --watch","test-ui":"pnpm exec vitest --ui","test-report":"pnpm exec vitest run --coverage",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.4","@inquirer/confirm":"^6.0.12","@inquirer/select":"^5.1.4","@modelcontextprotocol/sdk":"^1.29.0",commander:"^14.0.3",pino:"^10.3.1","pino-pretty":"^13.1.3",yaml:"^2.8.4",zod:"^3.25.76",zx:"^8.8.5"},devDependencies:{"@pkg/eslint-config":"workspace:*","@pkg/vitest-config":"workspace:*",esbuild:"^0.28.0",typescript:"catalog:"}};var ht=async()=>{let e=gt.version;a.info(e);let r={version:e};return{content:[{type:"text",text:JSON.stringify(r,null,2)}],structuredContent:r}},xr={name:"version",description:"Print the installed infra-kit CLI version",inputSchema:{},outputSchema:{version:Yo.string().describe("Installed infra-kit CLI version (from package.json)")},handler:ht};import ts from"@inquirer/checkbox";import Pr from"@inquirer/confirm";import os from"@inquirer/select";import ss from"node:process";import{z as B}from"zod/v4";import{$ as G}from"zx";import{$ as vt}from"zx";var $e=async e=>{try{let r=(await vt`cmux list-workspaces`.quiet()).stdout,t=Xo(r,e);if(!t)return;await vt`cmux close-workspace --workspace ${t}`.quiet()}catch(r){a.debug({error:r,title:e},"cmux: skipped closing workspace")}},Xo=(e,r)=>{for(let t of e.split(`
|
|
35
|
+
`)){let s=t.match(/^[* ]\s*(workspace:\d+)\s+(.+?)(?:\s+\[selected\])?\s*$/);if(!s)continue;let o=s[1];if((s[2]?.trim()??"")===r)return o}};import{$ as Zo}from"zx";var Cr=async()=>{try{let e=(await Zo`cmux list-workspaces`.quiet()).stdout,r=new Set;for(let t of e.split(`
|
|
36
|
+
`)){let s=t.match(/^[* ]\s*workspace:\d+\s+(.+?)(?:\s+\[selected\])?\s*$/);if(!s)continue;let o=s[1]?.trim();o&&r.add(o)}return r}catch(e){return a.debug({error:e},"cmux: skipped listing workspace titles"),new Set}};import{$ as Ee}from"zx";var Se=async e=>{let{cwd:r,title:t}=e,s=(await Ee`cmux new-workspace --cwd ${r}`).stdout,o=es(s),n=(await Ee`cmux list-pane-surfaces --workspace ${o}`).stdout,i=Qo(n);await Ee`cmux new-split right --workspace ${o} --surface ${i}`,await Ee`cmux new-split down --workspace ${o} --surface ${i}`,t&&await Ee`cmux rename-workspace --workspace ${o} ${t}`},Qo=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]},es=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 M=e=>{let{repoName:r,branch:t}=e,s=t.replace("release/","");return`${r} ${s}`};import wt from"node:fs/promises";import Ge from"node:path";var Ae=async e=>{let{workspacePath:r,folderPaths:t}=e,s=Ge.dirname(r),o;try{o=await wt.readFile(r,"utf-8")}catch(u){throw new Error(`Cursor workspace file not found at ${r}: ${u.message}`)}let n;try{n=JSON.parse(o)}catch(u){throw new Error(`Failed to parse ${r} as JSON. Comments (JSONC) are not supported. ${u.message}`)}let i=n.folders??[],l=new Set(i.map(u=>Ge.resolve(s,u.path))),c=[],p=[];for(let u of t){let d=Ge.resolve(u);if(l.has(d)){p.push(u);continue}let g=Ge.relative(s,d);i.push({path:g}),l.add(d),c.push(u)}return n.folders=i,await wt.writeFile(r,`${JSON.stringify(n,null,2)}
|
|
37
|
+
`,"utf-8"),{added:c,skipped:p}};import rs from"node:fs/promises";import ze from"node:path";import yt from"node:fs/promises";import He from"node:path";var U=async e=>{let{workspacePath:r,folderPaths:t}=e,s=He.dirname(r),o;try{o=await yt.readFile(r,"utf-8")}catch(g){throw new Error(`Cursor workspace file not found at ${r}: ${g.message}`)}let n;try{n=JSON.parse(o)}catch(g){throw new Error(`Failed to parse ${r} as JSON. Comments (JSONC) are not supported. ${g.message}`)}let i=n.folders??[],l=new Set(t.map(g=>He.resolve(g))),c=new Set,p=i.filter(g=>{let f=He.resolve(s,g.path);return l.has(f)?(c.add(f),!1):!0});n.folders=p,await yt.writeFile(r,`${JSON.stringify(n,null,2)}
|
|
38
|
+
`,"utf-8");let u=[],d=[];for(let g of t){let f=He.resolve(g);c.has(f)?u.push(g):d.push(g)}return{removed:u,notFound:d}};var Tr=async e=>{let{workspacePath:r,worktreeDir:t,currentBranches:s}=e,o=ze.dirname(r),n=ze.resolve(`${t}/release`),i=await rs.readFile(r,"utf-8"),c=JSON.parse(i).folders??[],p=new Set(s.map(k=>ze.resolve(`${t}/${k}`))),u=[];for(let k of c){let $=ze.resolve(o,k.path);($===n||$.startsWith(`${n}/`))&&!p.has($)&&u.push($)}let d=[];u.length>0&&(d=(await U({workspacePath:r,folderPaths:u})).removed);let g=s.map(k=>`${t}/${k}`),{added:f}=g.length>0?await Ae({workspacePath:r,folderPaths:g}):{added:[]};return{added:f,removed:d}};import kt from"node:path";var j=(e,r)=>kt.isAbsolute(e)?e:kt.resolve(r,e);var ns="feature",is="release",as="release/v",bt=["workspace","windows","none"],xt=async e=>{let{confirmedCommand:r,all:t,versions:s,cursor:o,githubDesktop:n,cmux:i}=e;m.start("worktrees-add");try{let l=await I("release"),c=await T(),p=`${c}${V}`;await Rt(`${p}/${is}`),await Rt(`${p}/${ns}`);let u=[];if(s)u=s.split(",").map(C=>`release/v${C.trim()}`);else{let C=await y(),F=C.map(_=>_.branch);if(F.length===0)return a.info("\u2139\uFE0F No open release branches found"),m.print(),{content:[{type:"text",text:JSON.stringify({createdWorktrees:[],count:0},null,2)}],structuredContent:{createdWorktrees:[],count:0}};if(t)u=F;else{m.setInteractive();let _=new Map(C.map(Ne=>[Ne.branch,w(Ne.title)])),Ye=await R();u=await ts({required:!0,message:"\u{1F33F} Select release branches",choices:E({branches:F,descriptions:Ye,types:_})})}}t?m.addOption("--all",!0):m.addOption("--versions",u.map(C=>C.replace("release/v","")));let d=r?!0:await Pr({message:"Are you sure you want to proceed with these worktree changes?"});r||m.setInteractive(),d||(a.info("Operation cancelled. Exiting..."),ss.exit(0)),r||m.addOption("--yes",!0);let g=o??await os({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 o>"u"&&m.setInteractive(),m.addOption("--cursor",g);let f=n??await Pr({message:"Open created worktrees in GitHub Desktop?"});typeof n>"u"&&m.setInteractive(),f?m.addOption("--github-desktop",!0):m.addOption("--no-github-desktop",!0);let k=i??await Pr({message:"Open created worktrees in cmux?"});typeof i>"u"&&m.setInteractive(),k?m.addOption("--cmux",!0):m.addOption("--no-cmux",!0);let{branchesToCreate:$}=cs({selectedReleaseBranches:u,currentWorktrees:l}),x=await ls($,p);if(ps(x),g==="workspace"){let C=await v(),F=C.ide?.provider==="cursor"?C.ide.config:void 0;if(!F?.workspaceConfigPath)a.warn("\u26A0\uFE0F Skipping Cursor: ide.config.workspaceConfigPath is not set in infra-kit.yml");else{let _=j(F.workspaceConfigPath,c),Ye=x.map(Nt=>`${p}/${Nt}`),{added:Ne,skipped:_r}=await Ae({workspacePath:_,folderPaths:Ye}),It=_r.length>0?` (${_r.length} already present)`:"";a.info(`\u2705 Added ${Ne.length} folder(s) to ${_}${It}`),await G`cursor ${_}`}}else if(g==="windows")for(let C of x)await G`cursor ${p}/${C}`;if(f)for(let C of x)await G`github ${p}/${C}`,await G`sleep 5`;if(k){let C=await N();for(let F of x){let _=M({repoName:C,branch:F});await Se({cwd:`${p}/${F}`,title:_})}}m.print();let q={createdWorktrees:x,count:x.length};return{content:[{type:"text",text:JSON.stringify(q,null,2)}],structuredContent:q}}catch(l){throw a.error({error:l},"\u274C Error managing worktrees"),l}},Rt=async e=>{await G`mkdir -p ${e}`},cs=e=>{let{selectedReleaseBranches:r,currentWorktrees:t}=e,s=t.filter(n=>n.startsWith(as));return{branchesToCreate:r.filter(n=>!s.includes(n))}},ls=async(e,r)=>{let t=await Promise.allSettled(e.map(async o=>{let n=`${r}/${o}`;return await G`git worktree add ${n} ${o}`,await G({cwd:n})`pnpm install`,o})),s=[];for(let[o,n]of t.entries())if(n.status==="fulfilled")s.push(n.value);else{let i=e[o];a.error({error:n.reason},`\u274C Failed to create worktree for ${i}`)}return s},ps=e=>{if(e.length>0){a.info("\u2705 Created git worktrees:");for(let r of e)a.info(r);a.info("")}else a.info("\u2139\uFE0F No new git worktrees to create")},$r={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:B.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:B.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:B.enum(bt).optional().describe('Cursor open mode for created worktrees. "workspace" (default behavior when set interactively) appends each worktree as a folder to "ide.config.workspaceConfigPath" in infra-kit.yml and opens the workspace. "windows" opens each worktree in its own Cursor window. "none" skips Cursor. Defaults to "none" in MCP mode (the follow-up prompt is not shown).'),githubDesktop:B.boolean().optional().describe("Open each created worktree in GitHub Desktop. Defaults to false in MCP mode (the follow-up prompt is not shown)."),cmux:B.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. Defaults to false in MCP mode (the follow-up prompt is not shown).")},outputSchema:{createdWorktrees:B.array(B.string()).describe("List of created git worktree branches"),count:B.number().describe("Number of git worktrees created")},handler:xt};import{z as pe}from"zod/v4";var Ct=async()=>{let e=await I("release");if(e.length===0)return a.info("\u2139\uFE0F No active worktrees found"),{content:[{type:"text",text:JSON.stringify({worktrees:[],count:0},null,2)}],structuredContent:{worktrees:[],count:0}};let[r,t]=await Promise.all([y(),R()]),s=new Map(r.map(c=>[c.branch,w(c.title)])),o=e.map(c=>{let p=c.replace("release/",""),u=s.get(c)||"regular",d=t.get(p)||null;return{version:p,type:u,description:d}}),n=Math.max(...o.map(c=>c.version.length)),i=o.map(c=>{let p=oe(c.version,c.type,n);return c.description?`${p} ${c.description}`:p});a.info("\u{1F33F} Active worktrees:"),a.info(`
|
|
39
|
+
${i.join(`
|
|
39
40
|
`)}
|
|
40
|
-
`);let l={worktrees:o,count:o.length};return{content:[{type:"text",text:JSON.stringify(l,null,2)}],structuredContent:l}},vr={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:se.array(se.object({version:se.string().describe("Release version"),type:se.enum(["regular","hotfix"]).describe("Release type"),description:se.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:se.number().describe("Number of worktrees")},handler:ft};import{z as ne}from"zod/v4";import{$ as Wo}from"zx";var ht=async()=>{p.start("worktrees-open");try{let e=await T(),r=`${e}${J}`,t=await I("release"),s=await Do({projectRoot:e,worktreeDir:r,currentBranches:t}),o=await _o({worktreeDir:r,currentBranches:t}),n={openedCmux:o.opened,skippedCmux:o.skipped,cursorFoldersAdded:s.added,cursorFoldersRemoved:s.removed};return jo(n,{cursorRan:s.ran,cmuxRan:o.ran}),p.print(),{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:{...n}}}catch(e){throw i.error({error:e},"\u274C Error opening worktrees"),e}},Do=async e=>{let{projectRoot:r,worktreeDir:t,currentBranches:s}=e,o=await v(),n=o.ide?.provider==="cursor"?o.ide.config:void 0;if(!n||n.mode!=="workspace"||!n.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=_(n.workspaceConfigPath,r);try{let{added:l,removed:c}=await fr({workspacePath:a,worktreeDir:t,currentBranches:s});return await Wo`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}}},_o=async e=>{let{worktreeDir:r,currentBranches:t}=e;if(t.length===0)return{ran:!0,opened:[],skipped:[]};let s=await W(),o=await dr(),n=[],a=[];for(let l of t){let c=D({repoName:s,branch:l});if(o.has(c)){a.push(c);continue}try{await Re({cwd:`${r}/${l}`,title:c}),n.push(c)}catch(m){i.warn({error:m,title:c},`\u26A0\uFE0F Failed to open cmux workspace for ${l}`)}}return{ran:!0,opened:n,skipped:a}},jo=(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")},wr={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:ne.array(ne.string()).describe("Titles of cmux workspaces opened during this run"),skippedCmux:ne.array(ne.string()).describe("Titles of cmux workspaces that were already open"),cursorFoldersAdded:ne.number().describe("Number of worktree folders added to the Cursor workspace file"),cursorFoldersRemoved:ne.number().describe("Number of dangling worktree folders removed from the Cursor workspace file")},handler:ht};import Jo from"@inquirer/checkbox";import Lo from"@inquirer/confirm";import Vo from"node:process";import{z as xe}from"zod/v4";import{$ as yr}from"zx";var gt=async e=>{let{confirmedCommand:r,all:t,versions:s}=e;p.start("worktrees-remove");try{let o=await I("release");if(o.length===0)return i.info("\u2139\uFE0F No active worktrees to remove"),p.print(),{content:[{type:"text",text:JSON.stringify({removedWorktrees:[],count:0},null,2)}],structuredContent:{removedWorktrees:[],count:0}};let n=await T(),a=`${n}${J}`,l=[];if(t)l=o;else if(s)l=s.split(",").map(f=>`release/v${f.trim()}`);else{p.setInteractive();let[f,k]=await Promise.all([R(),y()]),$=new Map(k.map(x=>[x.branch,w(x.title)]));l=await Jo({required:!0,message:"\u{1F33F} Select release branches",choices:E({branches:o,descriptions:f,types:$})})}let c=l.length===o.length;c?p.addOption("--all",!0):p.addOption("--versions",l.map(f=>f.replace("release/v","")));let m=r?!0:await Lo({message:"Are you sure you want to proceed with these worktree changes?"});r||p.setInteractive(),m||(i.info("Operation cancelled. Exiting..."),Vo.exit(0)),r||p.addOption("--yes",!0);let u=await W(),d=await Bo({branches:l,worktreeDir:a,repoName:u,allSelected:c});await qo({removedWorktrees:d,worktreeDir:a,projectRoot:n}),Uo(d),p.print();let h={removedWorktrees:d,count:d.length};return{content:[{type:"text",text:JSON.stringify(h,null,2)}],structuredContent:h}}catch(o){throw i.error({error:o},"\u274C Error managing worktrees"),o}},Bo=async e=>{let{branches:r,worktreeDir:t,repoName:s,allSelected:o}=e,n=await Promise.allSettled(r.map(async l=>{let c=`${t}/${l}`,m=D({repoName:s,branch:l});return await ye(m),await yr`git worktree remove ${c}`,l})),a=[];for(let[l,c]of n.entries())if(c.status==="fulfilled")a.push(c.value);else{let m=r[l];i.error({error:c.reason},`\u274C Failed to remove worktree for ${m}`)}return o&&a.length===r.length&&(await yr`git worktree prune`,await yr`rm -rf ${t}`,i.info(`\u{1F5D1}\uFE0F Removed worktree folder: ${t}`),i.info("")),a},qo=async e=>{let{removedWorktrees:r,worktreeDir:t,projectRoot:s}=e;if(r.length===0)return;let o=await v(),n=o.ide?.provider==="cursor"?o.ide.config:void 0;if(!n||n.mode!=="workspace"||!n.workspaceConfigPath)return;let a=_(n.workspaceConfigPath,s),l=r.map(c=>`${t}/${c}`);try{let{removed:c}=await q({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}`)}},Uo=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")},kr={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:xe.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:xe.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:xe.array(xe.string()).describe("List of removed git worktree branches"),count:xe.number().describe("Number of git worktrees removed")},handler:gt};import Go from"@inquirer/confirm";import Ko from"node:process";import{z as Rr}from"zod/v4";import{$ as zo}from"zx";var Ho="release/v",vt=async e=>{let{confirmedCommand:r}=e;p.start("worktrees-sync");try{let t=await I("release"),s=await T(),o=`${s}${J}`,n=await De(),a=r?!0:await Go({message:"Are you sure you want to proceed with these worktree changes?"});r||p.setInteractive(),a||(i.info("Operation cancelled. Exiting..."),Ko.exit(0)),r||p.addOption("--yes",!0);let{branchesToRemove:l}=Yo({releasePRsList:n,currentWorktrees:t}),c=await W(),m=await Xo({branches:l,worktreeDir:o,repoName:c});await Zo({removedWorktrees:m,worktreeDir:o,projectRoot:s}),Qo(m),p.print();let u={removedWorktrees:m,count:m.length};return{content:[{type:"text",text:JSON.stringify(u,null,2)}],structuredContent:u}}catch(t){throw i.error({error:t},"\u274C Error managing worktrees"),t}},Yo=e=>{let{releasePRsList:r,currentWorktrees:t}=e;return{branchesToRemove:t.filter(n=>n.startsWith(Ho)).filter(n=>!r.includes(n))}},Xo=async e=>{let{branches:r,worktreeDir:t,repoName:s}=e,o=[];for(let n of r)try{let a=`${t}/${n}`,l=D({repoName:s,branch:n});await ye(l),await zo`git worktree remove ${a}`,o.push(n)}catch(a){i.error({error:a,branch:n},`\u274C Failed to remove worktree for ${n}`)}return o},Zo=async e=>{let{removedWorktrees:r,worktreeDir:t,projectRoot:s}=e;if(r.length===0)return;let o=await v(),n=o.ide?.provider==="cursor"?o.ide.config:void 0;if(!n||n.mode!=="workspace"||!n.workspaceConfigPath)return;let a=_(n.workspaceConfigPath,s),l=r.map(c=>`${t}/${c}`);try{let{removed:c}=await q({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}`)}},Qo=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")},br={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:Rr.array(Rr.string()).describe("List of removed worktree branches"),count:Rr.number().describe("Number of worktrees removed during sync")},handler:vt};var xr=e=>async r=>{let{toolName:t,handler:s}=e;i.info({msg:`Tool execution started: ${t}`,params:r});try{let o=await s({...r,confirmedCommand:!0});return i.info({msg:`Tool execution successful: ${t}`}),o}catch(o){throw i.error({err:o,params:r,msg:`Tool execution failed: ${t}`}),o}};var es=[Xe,ze,Ye,Ge,rr,pr,mr,or,nr,ar,cr,ur,gr,vr,wr,kr,br],wt=async e=>{for(let r of es)e.registerTool(r.name,{description:r.description,inputSchema:r.inputSchema,outputSchema:r.outputSchema},xr({toolName:r.name,handler:r.handler}))};async function yt(){let e=new rs({name:"infra-kit",version:"1.0.0"},{capabilities:{resources:{},tools:{},prompts:{}}});return await Er(e),await Sr(e),await wt(e),e}var G=Pr(),os=async()=>{let e;try{e=await yt(),G.info("MCP Server instance created")}catch(r){G.error({err:r,msg:"Failed to create MCP server"}),G.error("Fatal error during server creation."),kt.exit(1)}try{let r=new ts;await e.connect(r),G.info({msg:"Server connected to transport. Ready."})}catch(r){G.error({err:r,msg:"Failed to initialize server"}),G.error("Fatal error during server transport init."),kt.exit(1)}};$r(G);os();
|
|
41
|
+
`);let l={worktrees:o,count:o.length};return{content:[{type:"text",text:JSON.stringify(l,null,2)}],structuredContent:l}},Er={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:pe.array(pe.object({version:pe.string().describe("Release version"),type:pe.enum(["regular","hotfix"]).describe("Release type"),description:pe.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:pe.number().describe("Number of worktrees")},handler:Ct};import{z as me}from"zod/v4";import{$ as ms}from"zx";var Tt=async()=>{m.start("worktrees-open");try{let e=await T(),r=`${e}${V}`,t=await I("release"),s=await us({projectRoot:e,worktreeDir:r,currentBranches:t}),o=await ds({worktreeDir:r,currentBranches:t}),n={openedCmux:o.opened,skippedCmux:o.skipped,cursorFoldersAdded:s.added,cursorFoldersRemoved:s.removed};return fs(n,{cursorRan:s.ran,cmuxRan:o.ran}),m.print(),{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:{...n}}}catch(e){throw a.error({error:e},"\u274C Error opening worktrees"),e}},us=async e=>{let{projectRoot:r,worktreeDir:t,currentBranches:s}=e,o=await v(),n=o.ide?.provider==="cursor"?o.ide.config:void 0;if(!n||n.mode!=="workspace"||!n.workspaceConfigPath)return a.warn('\u26A0\uFE0F Skipping Cursor: ide.provider must be "cursor", mode "workspace", and workspaceConfigPath set.'),{ran:!1,added:0,removed:0};let i=j(n.workspaceConfigPath,r);try{let{added:l,removed:c}=await Tr({workspacePath:i,worktreeDir:t,currentBranches:s});return await ms`cursor ${i}`,{ran:!0,added:l.length,removed:c.length}}catch(l){return a.warn({error:l},`\u26A0\uFE0F Failed to reconcile/open Cursor workspace at ${i}`),{ran:!1,added:0,removed:0}}},ds=async e=>{let{worktreeDir:r,currentBranches:t}=e;if(t.length===0)return{ran:!0,opened:[],skipped:[]};let s=await N(),o=await Cr(),n=[],i=[];for(let l of t){let c=M({repoName:s,branch:l});if(o.has(c)){i.push(c);continue}try{await Se({cwd:`${r}/${l}`,title:c}),n.push(c)}catch(p){a.warn({error:p,title:c},`\u26A0\uFE0F Failed to open cmux workspace for ${l}`)}}return{ran:!0,opened:n,skipped:i}},fs=(e,r)=>{if(r.cursorRan&&(e.cursorFoldersAdded>0&&a.info(`\u2705 Added ${e.cursorFoldersAdded} folder(s) to Cursor workspace`),e.cursorFoldersRemoved>0&&a.info(`\u{1F9F9} Removed ${e.cursorFoldersRemoved} dangling folder(s) from Cursor workspace`)),e.openedCmux.length>0){a.info("\u2705 Opened cmux workspaces:");for(let t of e.openedCmux)a.info(t)}e.skippedCmux.length>0&&a.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&&a.info("\u2139\uFE0F Nothing to open")},Sr={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:me.array(me.string()).describe("Titles of cmux workspaces opened during this run"),skippedCmux:me.array(me.string()).describe("Titles of cmux workspaces that were already open"),cursorFoldersAdded:me.number().describe("Number of worktree folders added to the Cursor workspace file"),cursorFoldersRemoved:me.number().describe("Number of dangling worktree folders removed from the Cursor workspace file")},handler:Tt};import gs from"@inquirer/checkbox";import hs from"@inquirer/confirm";import vs from"node:process";import{z as Ie}from"zod/v4";import{$ as Ar}from"zx";var Pt=async e=>{let{confirmedCommand:r,all:t,versions:s}=e;m.start("worktrees-remove");try{let o=await I("release");if(o.length===0)return a.info("\u2139\uFE0F No active worktrees to remove"),m.print(),{content:[{type:"text",text:JSON.stringify({removedWorktrees:[],count:0},null,2)}],structuredContent:{removedWorktrees:[],count:0}};let n=await T(),i=`${n}${V}`,l=[];if(t)l=o;else if(s)l=s.split(",").map(f=>`release/v${f.trim()}`);else{m.setInteractive();let[f,k]=await Promise.all([R(),y()]),$=new Map(k.map(x=>[x.branch,w(x.title)]));l=await gs({required:!0,message:"\u{1F33F} Select release branches",choices:E({branches:o,descriptions:f,types:$})})}let c=l.length===o.length;c?m.addOption("--all",!0):m.addOption("--versions",l.map(f=>f.replace("release/v","")));let p=r?!0:await hs({message:"Are you sure you want to proceed with these worktree changes?"});r||m.setInteractive(),p||(a.info("Operation cancelled. Exiting..."),vs.exit(0)),r||m.addOption("--yes",!0);let u=await N(),d=await ws({branches:l,worktreeDir:i,repoName:u,allSelected:c});await ys({removedWorktrees:d,worktreeDir:i,projectRoot:n}),ks(d),m.print();let g={removedWorktrees:d,count:d.length};return{content:[{type:"text",text:JSON.stringify(g,null,2)}],structuredContent:g}}catch(o){throw a.error({error:o},"\u274C Error managing worktrees"),o}},ws=async e=>{let{branches:r,worktreeDir:t,repoName:s,allSelected:o}=e,n=await Promise.allSettled(r.map(async l=>{let c=`${t}/${l}`,p=M({repoName:s,branch:l});return await $e(p),await Ar`git worktree remove ${c}`,l})),i=[];for(let[l,c]of n.entries())if(c.status==="fulfilled")i.push(c.value);else{let p=r[l];a.error({error:c.reason},`\u274C Failed to remove worktree for ${p}`)}return o&&i.length===r.length&&(await Ar`git worktree prune`,await Ar`rm -rf ${t}`,a.info(`\u{1F5D1}\uFE0F Removed worktree folder: ${t}`),a.info("")),i},ys=async e=>{let{removedWorktrees:r,worktreeDir:t,projectRoot:s}=e;if(r.length===0)return;let o=await v(),n=o.ide?.provider==="cursor"?o.ide.config:void 0;if(!n||n.mode!=="workspace"||!n.workspaceConfigPath)return;let i=j(n.workspaceConfigPath,s),l=r.map(c=>`${t}/${c}`);try{let{removed:c}=await U({workspacePath:i,folderPaths:l});c.length>0&&a.info(`\u2705 Removed ${c.length} folder(s) from ${i}`)}catch(c){a.warn({error:c},`\u26A0\uFE0F Failed to update Cursor workspace at ${i}`)}},ks=e=>{if(e.length>0){a.info("\u274C Removed worktrees:");for(let r of e)a.info(r);a.info("")}else a.info("\u2139\uFE0F No unused worktrees to remove")},Ir={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:Pt};import Rs from"@inquirer/confirm";import bs from"node:process";import{z as Nr}from"zod/v4";import{$ as xs}from"zx";var Cs="release/v",$t=async e=>{let{confirmedCommand:r}=e;m.start("worktrees-sync");try{let t=await I("release"),s=await T(),o=`${s}${V}`,n=await Ke(),i=r?!0:await Rs({message:"Are you sure you want to proceed with these worktree changes?"});r||m.setInteractive(),i||(a.info("Operation cancelled. Exiting..."),bs.exit(0)),r||m.addOption("--yes",!0);let{branchesToRemove:l}=Ts({releasePRsList:n,currentWorktrees:t}),c=await N(),p=await Ps({branches:l,worktreeDir:o,repoName:c});await $s({removedWorktrees:p,worktreeDir:o,projectRoot:s}),Es(p),m.print();let u={removedWorktrees:p,count:p.length};return{content:[{type:"text",text:JSON.stringify(u,null,2)}],structuredContent:u}}catch(t){throw a.error({error:t},"\u274C Error managing worktrees"),t}},Ts=e=>{let{releasePRsList:r,currentWorktrees:t}=e;return{branchesToRemove:t.filter(n=>n.startsWith(Cs)).filter(n=>!r.includes(n))}},Ps=async e=>{let{branches:r,worktreeDir:t,repoName:s}=e,o=[];for(let n of r)try{let i=`${t}/${n}`,l=M({repoName:s,branch:n});await $e(l),await xs`git worktree remove ${i}`,o.push(n)}catch(i){a.error({error:i,branch:n},`\u274C Failed to remove worktree for ${n}`)}return o},$s=async e=>{let{removedWorktrees:r,worktreeDir:t,projectRoot:s}=e;if(r.length===0)return;let o=await v(),n=o.ide?.provider==="cursor"?o.ide.config:void 0;if(!n||n.mode!=="workspace"||!n.workspaceConfigPath)return;let i=j(n.workspaceConfigPath,s),l=r.map(c=>`${t}/${c}`);try{let{removed:c}=await U({workspacePath:i,folderPaths:l});c.length>0&&a.info(`\u2705 Removed ${c.length} folder(s) from ${i}`)}catch(c){a.warn({error:c},`\u26A0\uFE0F Failed to update Cursor workspace at ${i}`)}},Es=e=>{if(e.length>0){a.info("\u274C Removed worktrees:");for(let r of e)a.info(r);a.info("")}else a.info("\u2139\uFE0F No unused worktrees to remove")},Or={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:Nr.array(Nr.string()).describe("List of removed worktree branches"),count:Nr.number().describe("Number of worktrees removed during sync")},handler:$t};var Fr=e=>async r=>{let{toolName:t,handler:s}=e;a.info({msg:`Tool execution started: ${t}`,params:r});try{let o=await s({...r,confirmedCommand:!0});return a.info({msg:`Tool execution successful: ${t}`}),o}catch(o){throw a.error({err:o,params:r,msg:`Tool execution failed: ${t}`}),o}};var Ss=[ar,sr,ir,rr,mr,br,kr,dr,gr,vr,wr,xr,$r,Er,Sr,Ir,Or],Et=async e=>{for(let r of Ss)e.registerTool(r.name,{description:r.description,inputSchema:r.inputSchema,outputSchema:r.outputSchema},Fr({toolName:r.name,handler:r.handler}))};async function St(){let e=new As({name:"infra-kit",version:"1.0.0"},{capabilities:{resources:{},tools:{},prompts:{}}});return await Wr(e),await Vr(e),await Et(e),e}var H=Mr(),Ns=async()=>{let e;try{e=await St(),H.info("MCP Server instance created")}catch(r){H.error({err:r,msg:"Failed to create MCP server"}),H.error("Fatal error during server creation."),At.exit(1)}try{let r=new Is;await e.connect(r),H.info({msg:"Server connected to transport. Ready."})}catch(r){H.error({err:r,msg:"Failed to initialize server"}),H.error("Fatal error during server transport init."),At.exit(1)}};jr(H);Ns();
|
|
41
42
|
//# sourceMappingURL=mcp.js.map
|