infra-kit 0.1.87 → 0.1.89

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mcp.js CHANGED
@@ -1,33 +1,33 @@
1
- import{StdioServerTransport as jt}from"@modelcontextprotocol/sdk/server/stdio.js";import Mr from"node:process";import N from"node:process";import Xe from"node:process";import we from"pino";import jr from"pino-pretty";var Y="/tmp/mcp-infra-kit.log",Ze=()=>{let e=Xe.argv.includes("--debug")?"debug":"info",r=we({level:e},we.destination({dest:Y}));return r.info(`Logger initialized with level: ${e}. Logging to: ${Y}`),r},Lr=()=>{let e=Xe.argv.includes("--debug")?"debug":"info",r=["time","pid","hostname"];return e==="debug"&&r.push("level"),we({level:e},jr({destination:2,ignore:r.join(","),colorize:!0}))},s=Lr();var Qe=e=>{N.on("SIGINT",()=>{e.info({msg:"Received SIGINT. Shutting down..."}),N.exit(0)}),N.on("SIGTERM",()=>{e.info({msg:"Received SIGTERM. Shutting down..."}),N.exit(0)}),N.on("uncaughtException",r=>{e.fatal({err:r,msg:"Uncaught Exception"}),e.error(`Uncaught Exception! Check ${Y}. Shutting down...`),e.flush(),N.exit(1)}),N.on("unhandledRejection",(r,t)=>{e.fatal({reason:r,promise:t,msg:"Unhandled Rejection"}),e.error(`Unhandled Rejection! Check ${Y}. Shutting down...`),e.flush(),N.exit(1)})};import{McpServer as Jt}from"@modelcontextprotocol/sdk/server/mcp.js";var er=async e=>{};var rr=async e=>{};import le from"node:fs";import sr from"node:path";import Wr from"node:process";import{z as pe}from"zod";import tr from"node:fs";import Vr from"node:path";import Fr from"node:process";var P=["dev","arthur","renana","roman","eliran","oriana"],Re={"hulyo-monorepo":"hulyo","travelist-monorepo":"travelist"},Br="./node_modules/.cache/infra-kit",J="env-load.sh",or="env-clear.sh",be="INFRA_KIT_SESSION",j="INFRA_KIT_ENV_CONFIG",L="INFRA_KIT_ENV_PROJECT",V="INFRA_KIT_ENV_LOADED_AT",ce=e=>tr.existsSync(e)?tr.readFileSync(e,"utf-8").split(`
2
- `).filter(t=>t.includes("=")&&!t.startsWith("set ")).map(t=>t.split("=")[0]):[],F=()=>{let e=Fr.env[be];if(!e)throw new Error("INFRA_KIT_SESSION is not set. Run `source ~/.zshrc` or `infra-kit init` first.");return Vr.join(Br,e)},B="-worktrees";var nr=async()=>{let e=F(),r=sr.join(e,J);if(!le.existsSync(r))return s.error("No loaded environment found. Run `env-load` first."),{content:[{type:"text",text:"No loaded environment found. Run `env-load` first."}]};let t=ce(r),n=[...t.map(i=>`unset ${i}`),`unset ${j}`,`unset ${L}`,`unset ${V}`],o=sr.resolve(e,or);le.mkdirSync(e,{recursive:!0}),le.writeFileSync(o,`${n.join(`
1
+ import{StdioServerTransport as qt}from"@modelcontextprotocol/sdk/server/stdio.js";import Jr from"node:process";import O from"node:process";import Ze from"node:process";import Re from"pino";import Lr from"pino-pretty";var Z="/tmp/mcp-infra-kit.log",Qe=()=>{let e=Ze.argv.includes("--debug")?"debug":"info",r=Re({level:e},Re.destination({dest:Z}));return r.info(`Logger initialized with level: ${e}. Logging to: ${Z}`),r},Vr=()=>{let e=Ze.argv.includes("--debug")?"debug":"info",r=["time","pid","hostname"];return e==="debug"&&r.push("level"),Re({level:e},Lr({destination:2,ignore:r.join(","),colorize:!0}))},s=Vr();var er=e=>{O.on("SIGINT",()=>{e.info({msg:"Received SIGINT. Shutting down..."}),O.exit(0)}),O.on("SIGTERM",()=>{e.info({msg:"Received SIGTERM. Shutting down..."}),O.exit(0)}),O.on("uncaughtException",r=>{e.fatal({err:r,msg:"Uncaught Exception"}),e.error(`Uncaught Exception! Check ${Z}. Shutting down...`),e.flush(),O.exit(1)}),O.on("unhandledRejection",(r,t)=>{e.fatal({reason:r,promise:t,msg:"Unhandled Rejection"}),e.error(`Unhandled Rejection! Check ${Z}. Shutting down...`),e.flush(),O.exit(1)})};import{McpServer as Wt}from"@modelcontextprotocol/sdk/server/mcp.js";var rr=async e=>{};var tr=async e=>{};import me from"node:fs";import nr from"node:path";import qr from"node:process";import{z as ue}from"zod";import or from"node:fs";import Fr from"node:path";import Br from"node:process";var Wr="./node_modules/.cache/infra-kit",L="env-load.sh",sr="env-clear.sh",be="INFRA_KIT_SESSION",V="INFRA_KIT_ENV_CONFIG",F="INFRA_KIT_ENV_PROJECT",B="INFRA_KIT_ENV_LOADED_AT",pe=e=>or.existsSync(e)?or.readFileSync(e,"utf-8").split(`
2
+ `).filter(t=>t.includes("=")&&!t.startsWith("set ")).map(t=>t.split("=")[0]):[],W=()=>{let e=Br.env[be];if(!e)throw new Error("INFRA_KIT_SESSION is not set. Run `source ~/.zshrc` or `infra-kit init` first.");return Fr.join(Wr,e)},q="-worktrees";var ir=async()=>{let e=W(),r=nr.join(e,L);if(!me.existsSync(r))return s.error("No loaded environment found. Run `env-load` first."),{content:[{type:"text",text:"No loaded environment found. Run `env-load` first."}]};let t=pe(r),n=[...t.map(a=>`unset ${a}`),`unset ${V}`,`unset ${F}`,`unset ${B}`],o=nr.resolve(e,sr);me.mkdirSync(e,{recursive:!0}),me.writeFileSync(o,`${n.join(`
3
3
  `)}
4
- `),Wr.stdout.write(`${o}
5
- `),le.unlinkSync(r);let a={filePath:o,variableCount:t.length,unsetStatements:n};return{content:[{type:"text",text:JSON.stringify(a,null,2)}],structuredContent:a}},xe={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 \u2014 returns the path to a script that must be sourced ("source <filePath>") for the unsets to take effect. The infra-kit shell wrapper auto-sources; direct MCP callers must handle sourcing themselves or surface filePath to the user. Errors if no env is currently loaded.',inputSchema:{},outputSchema:{filePath:pe.string().describe("Path to the file that must be sourced to apply"),variableCount:pe.number().describe("Number of variables cleared"),unsetStatements:pe.array(pe.string()).describe("Unset statements generated")},handler:nr};import{z as Te}from"zod";import ir from"node:process";import{$ as ar}from"zx";var _=async()=>{try{await ar`doppler --version`}catch(e){s.error({error:e},"Error: Doppler CLI is not installed."),s.error("Please install it from: https://docs.doppler.com/docs/install-cli"),ir.exit(1)}try{await ar`doppler me`}catch(e){s.error({error:e},"Error: Doppler CLI is not authenticated."),s.error("Please authenticate by running: doppler login"),ir.exit(1)}};import Gr from"node:path";import{$ as cr}from"zx";var I=async e=>{let t=(await cr`git worktree list`).stdout.split(`
6
- `).filter(Boolean),n={release:qr,feature:Ur};return t.map(n[e]).filter(o=>o!==null)},qr=e=>{let r=e.split(" ").filter(Boolean);return r.length<3||!r[0]?.includes("release/v")?null:`release/${r[0]?.split("/").pop()||""}`},Ur=e=>{let r=e.split(" ").filter(Boolean);return r.length<3||!r[0]?.includes("feature/")?null:`feature/${r[0]?.split("/").pop()||""}`},E=async()=>(await cr`git rev-parse --show-toplevel`).stdout.trim();var X=async()=>{let e=await E(),r=Gr.basename(e),t=Re[r];if(!t)throw new Error(`Could not determine Doppler project for directory "${r}". Expected one of: ${Object.keys(Re).join(", ")}`);return t};var lr=async()=>{await _();let e=await X();s.info(`Doppler project: ${e}
7
- `),s.info("Available configs:");for(let t of P)s.info(` - ${t}`);let r={project:e,configs:P};return{content:[{type:"text",text:JSON.stringify(r,null,2)}],structuredContent:r}},ke={name:"env-list",description:"List the environments the project is configured to support. Returns a static list defined in infra-kit constants (not a live fetch from Doppler) plus the Doppler project name auto-detected from the current directory. Read-only.",inputSchema:{},outputSchema:{project:Te.string().describe("Detected Doppler project name"),configs:Te.array(Te.string()).describe("Available environment configs")},handler:lr};import zr from"@inquirer/select";import pr from"node:fs";import Kr from"node:path";import mr from"node:process";import{z as Z}from"zod";import{$ as Ce}from"zx";var Hr=()=>{let e="",r=[],t=!1;return{start(n){e=n,r=[],t=!1},setInteractive(){t=!0},addOption(n,o){r.push({flag:n,value:o})},print(){if(!t||r.length===0)return;let n=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(" ");s.info(`\u{1F4DF} Equivalent command:
4
+ `),qr.stdout.write(`${o}
5
+ `),me.unlinkSync(r);let i={filePath:o,variableCount:t.length,unsetStatements:n};return{content:[{type:"text",text:JSON.stringify(i,null,2)}],structuredContent:i}},xe={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:ue.string().describe("Path to the file that must be sourced to apply"),variableCount:ue.number().describe("Number of variables cleared"),unsetStatements:ue.array(ue.string()).describe("Unset statements generated")},handler:ir};import{z as ke}from"zod";import ar from"node:process";import{$ as cr}from"zx";var M=async()=>{try{await cr`doppler --version`}catch(e){s.error({error:e},"Error: Doppler CLI is not installed."),s.error("Please install it from: https://docs.doppler.com/docs/install-cli"),ar.exit(1)}try{await cr`doppler me`}catch(e){s.error({error:e},"Error: Doppler CLI is not authenticated."),s.error("Please authenticate by running: doppler login"),ar.exit(1)}};import Kr from"node:fs/promises";import Hr from"node:path";import zr from"yaml";import{z as D}from"zod";import{$ as lr}from"zx";var A=async e=>{let t=(await lr`git worktree list`).stdout.split(`
6
+ `).filter(Boolean),n={release:Ur,feature:Gr};return t.map(n[e]).filter(o=>o!==null)},Ur=e=>{let r=e.split(" ").filter(Boolean);return r.length<3||!r[0]?.includes("release/v")?null:`release/${r[0]?.split("/").pop()||""}`},Gr=e=>{let r=e.split(" ").filter(Boolean);return r.length<3||!r[0]?.includes("feature/")?null:`feature/${r[0]?.split("/").pop()||""}`},P=async()=>(await lr`git rev-parse --show-toplevel`).stdout.trim();var Yr="infra-kit.yml",Xr=D.object({dopplerProjectName:D.string().min(1),environments:D.array(D.string().min(1)).min(1),taskManagerProvider:D.union([D.string(),D.literal(!1)])}),Te=null,E=async()=>(Te||(Te=Zr()),Te),Zr=async()=>{let e=await P(),r=Hr.join(e,Yr),t;try{t=await Kr.readFile(r,"utf-8")}catch{throw new Error(`infra-kit.yml not found at ${r}`)}let n=zr.parse(t),o=Xr.safeParse(n);if(!o.success)throw new Error(`Invalid infra-kit.yml at ${r}: ${o.error.message}`);return o.data};var Q=async()=>{let{dopplerProjectName:e}=await E();return e};var pr=async()=>{await M();let e=await Q(),{environments:r}=await E();s.info(`Doppler project: ${e}
7
+ `),s.info("Available configs:");for(let n of r)s.info(` - ${n}`);let t={project:e,configs:r};return{content:[{type:"text",text:JSON.stringify(t,null,2)}],structuredContent:t}},Ce={name:"env-list",description:"List the environments the project is configured to support. Returns a static list defined in infra-kit constants (not a live fetch from Doppler) plus the Doppler project name auto-detected from the current directory. Read-only.",inputSchema:{},outputSchema:{project:ke.string().describe("Detected Doppler project name"),configs:ke.array(ke.string()).describe("Available environment configs")},handler:pr};import et from"@inquirer/select";import mr from"node:fs";import rt from"node:path";import ur from"node:process";import{z as ee}from"zod";import{$ as Pe}from"zx";var Qr=()=>{let e="",r=[],t=!1;return{start(n){e=n,r=[],t=!1},setInteractive(){t=!0},addOption(n,o){r.push({flag:n,value:o})},print(){if(!t||r.length===0)return;let n=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(" ");s.info(`\u{1F4DF} Equivalent command:
8
8
  pnpm exec infra-kit ${e} ${n}
9
- `)},reset(){e="",r=[],t=!1}}},l=Hr();var ur=async e=>{await _();let{config:r}=e;l.start("env-load");let t="";r?t=r:(l.setInteractive(),t=await zr({message:"Select environment config",choices:P.map(f=>({name:f,value:f}))},{output:mr.stderr})),l.addOption("--config",t);let n=await X();Ce.quiet=!0;let o=await Ce`doppler secrets download --no-file --format env --project ${n} --config ${t}`;Ce.quiet=!1;let a=o.stdout.trim(),i=new Date().toISOString(),p=["set -a",a,`${j}=${t}`,`${L}=${n}`,`${V}=${i}`,"set +a"],c=F(),m=Kr.resolve(c,J);pr.mkdirSync(c,{recursive:!0}),pr.writeFileSync(m,`${p.join(`
9
+ `)},reset(){e="",r=[],t=!1}}},l=Qr();var fr=async e=>{await M();let{config:r}=e;l.start("env-load");let t="";if(r)t=r;else{let{environments:h}=await E();l.setInteractive(),t=await et({message:"Select environment config",choices:h.map(d=>({name:d,value:d}))},{output:ur.stderr})}l.addOption("--config",t);let n=await Q();Pe.quiet=!0;let o=await Pe`doppler secrets download --no-file --format env --project ${n} --config ${t}`;Pe.quiet=!1;let i=o.stdout.trim(),a=new Date().toISOString(),p=["set -a",i,`${V}=${t}`,`${F}=${n}`,`${B}=${a}`,"set +a"],c=W(),m=rt.resolve(c,L);mr.mkdirSync(c,{recursive:!0}),mr.writeFileSync(m,`${p.join(`
10
10
  `)}
11
- `),mr.stdout.write(`${m}
12
- `);let u=a.split(`
13
- `).filter(f=>f.includes("=")).length,d={filePath:m,variableCount:u,project:n,config:t};return{content:[{type:"text",text:JSON.stringify(d,null,2)}],structuredContent:d}},Pe={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:Z.string().describe('Doppler config / environment name to load (e.g. "dev", "arthur", "renana"). Required for MCP calls.')},outputSchema:{filePath:Z.string().describe("Path to the file that must be sourced to apply variables"),variableCount:Z.number().describe("Number of variables loaded"),project:Z.string().describe("Doppler project name"),config:Z.string().describe("Doppler config name")},handler:ur};import Yr from"node:path";import Q from"node:process";import{z as W}from"zod";var dr=async()=>{await _(),s.info("Environment session status:");let e=F(),r=Q.env[be],t=Yr.join(e,J),n=0,o=0,a=Q.env[j]??null,i=Q.env[L]??null,p=Q.env[V]??null;if(a){let m=ce(t);m.length>0&&(o=m.length,n=m.filter(d=>d in Q.env).length);let u=p?.replace(/\.\d{3}Z$/,"")??null;s.info(` ${a}: ${n} of ${o} vars loaded (project: ${i}, loadedAt: ${u}, session: ${r})
11
+ `),ur.stdout.write(`${m}
12
+ `);let u=i.split(`
13
+ `).filter(h=>h.includes("=")).length,f={filePath:m,variableCount:u,project:n,config:t};return{content:[{type:"text",text:JSON.stringify(f,null,2)}],structuredContent:f}},$e={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:ee.string().describe('Doppler config / environment name to load (e.g. "dev", "arthur", "renana"). Required for MCP calls.')},outputSchema:{filePath:ee.string().describe("Path to the file that must be sourced to apply variables"),variableCount:ee.number().describe("Number of variables loaded"),project:ee.string().describe("Doppler project name"),config:ee.string().describe("Doppler config name")},handler:fr};import tt from"node:path";import re from"node:process";import{z as U}from"zod";var dr=async()=>{await M(),s.info("Environment session status:");let e=W(),r=re.env[be],t=tt.join(e,L),n=0,o=0,i=re.env[V]??null,a=re.env[F]??null,p=re.env[B]??null;if(i){let m=pe(t);m.length>0&&(o=m.length,n=m.filter(f=>f in re.env).length);let u=p?.replace(/\.\d{3}Z$/,"")??null;s.info(` ${i}: ${n} of ${o} vars loaded (project: ${a}, loadedAt: ${u}, session: ${r})
14
14
  `)}else s.info(` Session ${r}: no env loaded
15
- `);let c={sessionId:r,sessionLoadedCount:n,sessionTotalCount:o,sessionConfig:a,sessionProject:i,sessionLoadedAt:p};return{content:[{type:"text",text:JSON.stringify(c,null,2)}],structuredContent:c}},Ee={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:W.string().describe("Current terminal session ID"),sessionLoadedCount:W.number().describe("Number of cached vars active in the current session"),sessionTotalCount:W.number().describe("Total number of cached var names"),sessionConfig:W.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:W.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:W.string().nullable().describe("ISO 8601 timestamp of when the env was loaded")},handler:dr};import et from"@inquirer/checkbox";import rt from"@inquirer/confirm";import tt from"node:process";import{z as G}from"zod";import{$}from"zx";import{$ as ns}from"zx";import he from"node:process";import{$ as k}from"zx";import{$ as te}from"zx";import ee from"node:process";var $e=async(e,r)=>{try{let{baseUrl:t,token:n,email:o,projectId:a}=r,i={name:e.name,projectId:e.projectId||a,description:e.description||"",released:e.released||!1,archived:e.archived||!1},p=`${t}/rest/api/3/version`,c=btoa(`${o}:${n}`),m=await fetch(p,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${c}`},body:JSON.stringify(i)});if(!m.ok){let d=await m.text();throw s.error({status:m.status,statusText:m.statusText,error:d},"Failed to create Jira version"),new Error(`HTTP ${m.status}: ${m.statusText}`)}return{success:!0,version:await m.json()}}catch(t){throw s.error({error:t},"Error creating Jira version"),t}},me=async e=>{try{let{baseUrl:r,token:t,email:n,projectId:o}=e,a=`${r}/rest/api/3/project/${o}/versions`,i=btoa(`${n}:${t}`),p=await fetch(a,{method:"GET",headers:{Accept:"application/json",Authorization:`Basic ${i}`}});if(!p.ok){let m=await p.text();throw s.error({status:p.status,statusText:p.statusText,error:m},"Failed to get Jira project versions"),new Error(`HTTP ${p.status}: ${p.statusText}`)}return await p.json()}catch(r){throw s.error({error:r},"Error getting Jira project versions"),r}},Zr=async(e,r)=>{try{return(await me(r)).find(o=>o.name===e)||null}catch(t){throw s.error({error:t,versionName:e},"Error finding Jira version by name"),t}},Qr=async(e,r)=>{try{let{baseUrl:t,token:n,email:o}=r,a={released:e.released??!0,archived:e.archived??!1};e.releaseDate?a.releaseDate=e.releaseDate:e.released!==!1&&(a.releaseDate=new Date().toISOString().split("T")[0]),e.description!==void 0&&(a.description=e.description);let i=`${t}/rest/api/3/version/${e.versionId}`,p=btoa(`${o}:${n}`),c=await fetch(i,{method:"PUT",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${p}`},body:JSON.stringify(a)});if(!c.ok){let u=await c.text();throw s.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 s.error({error:t},"Error updating Jira version"),t}},Ae=async(e,r)=>{try{let{versionName:t}=e,n=await Zr(t,r);if(!n)throw s.error({versionName:t},"Jira version not found"),new Error(`Version "${t}" not found in Jira project`);return await Qr({versionId:n.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},r)}catch(t){throw s.error({error:t},"Error delivering Jira release"),t}},q=async()=>{let e=ee.env.JIRA_BASE_URL,r=ee.env.JIRA_TOKEN||ee.env.JIRA_API_TOKEN,t=ee.env.JIRA_PROJECT_ID,n=ee.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)"),n||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(p=>` - ${p}`),"","You can set these in your .env file or as environment variables."].join(`
16
- `);throw new Error(i)}let a=Number.parseInt(t,10);if(Number.isNaN(a))throw new TypeError(`Invalid JIRA_PROJECT_ID: "${t}" must be a numeric value (e.g., 10001)`);return{baseUrl:e.replace(/\/$/,""),token:r,projectId:a,email:n}},re=async()=>{try{return await q()}catch(e){return s.warn({error:e},"Jira configuration not available, skipping Jira integration"),null}};var ue=e=>e==="hotfix"?"main":"dev",oe=async(e="regular")=>{let r=ue(e);te.quiet=!0,await te`git fetch origin`,await te`git switch ${r}`,await te`git pull origin ${r}`,te.quiet=!1},se=async e=>{let{version:r,jiraConfig:t,description:n,type:o="regular"}=e,a=`v${r}`,i=await $e({name:a,projectId:t.projectId,description:n||"",released:!1,archived:!1},t),p=`${t.baseUrl}/projects/${i.version.projectId}/versions/${i.version.id}/tab/release-report-all-issues`,c=await de({version:r,jiraVersionUrl:p,type:o});return{version:r,type:o,branchName:c.branchName,prUrl:c.prUrl,jiraVersionUrl:p}},y=async()=>{let e=new Map,r=await re();if(!r)return e;try{let t=await me(r);for(let n of t)n.description&&e.set(n.name,n.description)}catch{}return e},U=(e,r,t)=>{let n=t?" ".repeat(t-e.length+3):" ",o=`[${r}]`.padEnd(11);return`${e}${n}${o}`},g=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",T=e=>{let{branches:r,descriptions:t,types:n}=e,o=r.map(i=>i.replace("release/v","")),a=Math.max(...o.map(i=>i.length));return r.map((i,p)=>{let c=o[p],m=n?n.get(i)||"regular":void 0,u=t.get(`v${c}`),d=" ".repeat(a-c.length+3),f=m?U(c,m,a):c;return u&&(f=m?`${f} ${u}`:`${c}${d}${u}`),{name:f,value:i}})};var Se=e=>e.replace("release/","").slice(1).split(".").map(Number),fe=e=>[...e].sort((r,t)=>{let[n,o,a]=Se(r),[i,p,c]=Se(t);return n!==i?(n??0)-(i??0):o!==p?(o??0)-(p??0):(a??0)-(c??0)});var fr=async()=>{let e=await k`gh pr list --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName`,r=await k`gh pr list --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName`,t=[...JSON.parse(e.stdout),...JSON.parse(r.stdout)],n=new Set;return t.filter(o=>n.has(o.headRefName)?!1:(n.add(o.headRefName),!0))},ge=async()=>{try{let e=await fr();return e.length===0&&(s.error("\u274C No release PRs found. Check the project folder for the script. Exiting..."),he.exit(1)),fe(e.map(r=>r.headRefName))}catch(e){s.error({error:e},"\u274C Error fetching release PRs"),he.exit(1)}},v=async()=>{try{let e=await fr();e.length===0&&(s.error("\u274C No release PRs found. Check the project folder for the script. Exiting..."),he.exit(1));let r=fe(e.map(n=>n.headRefName)),t=new Map(e.map(n=>[n.headRefName,n]));return r.map(n=>({branch:n,title:t.get(n).title}))}catch(e){s.error({error:e},"\u274C Error fetching release PRs"),he.exit(1)}},de=async e=>{let{version:r,jiraVersionUrl:t,type:n}=e,o=n==="hotfix"?"Hotfix":"Release",a=ue(n),i=`release/v${r}`;try{k.quiet=!0,await k`git switch ${a}`,await k`git pull origin ${a}`,await k`git checkout -b ${i}`,await k`git push -u origin ${i}`,await k`git commit --allow-empty-message --allow-empty --message ''`,await k`git push origin ${i}`;let c=(await k`gh pr create --title "${o} v${r}" --body "${t} \n" --base ${a} --head ${i}`).stdout.trim();return await k`git switch ${a}`,k.quiet=!1,{branchName:i,prUrl:c}}catch(p){throw s.error({error:p,branchName:i},`Error creating release branch ${i}`),p}};var hr=async e=>{let{all:r,confirmedCommand:t}=e;l.start("merge-dev");let o=(await v()).filter(u=>g(u.title)==="regular").map(u=>u.branch);if(o.length===0)return s.info("\u2139\uFE0F No open release branches found"),l.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 a=[];if(r)a=o;else{l.setInteractive();let u=await y();a=await et({required:!0,message:"\u{1F33F} Select release branches",choices:T({branches:o,descriptions:u})})}a.length===o.length?l.addOption("--all",!0):l.addOption("--versions",a.map(u=>u.replace("release/v","")));let p=t?!0:await rt({message:`Are you sure you want to merge dev into these branches: ${a.join(", ")}?`});t||l.setInteractive(),p||(s.info("Operation cancelled. Exiting..."),tt.exit(0)),t||l.addOption("--yes",!0),$.quiet=!0,await $`git fetch origin`,await $`git switch dev`,await $`git pull origin dev`;let c=[];for(let u of a)await ot(u)||c.push(u);if($.quiet=!1,c.length>0){s.info(`
15
+ `);let c={sessionId:r,sessionLoadedCount:n,sessionTotalCount:o,sessionConfig:i,sessionProject:a,sessionLoadedAt:p};return{content:[{type:"text",text:JSON.stringify(c,null,2)}],structuredContent:c}},Ie={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:U.string().describe("Current terminal session ID"),sessionLoadedCount:U.number().describe("Number of cached vars active in the current session"),sessionTotalCount:U.number().describe("Total number of cached var names"),sessionConfig:U.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:U.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:U.string().nullable().describe("ISO 8601 timestamp of when the env was loaded")},handler:dr};import it from"@inquirer/checkbox";import at from"@inquirer/confirm";import ct from"node:process";import{z as H}from"zod";import{$}from"zx";import{$ as gs}from"zx";import ve from"node:process";import{$ as k}from"zx";import{$ as se}from"zx";import te from"node:process";var Ee=async(e,r)=>{try{let{baseUrl:t,token:n,email:o,projectId:i}=r,a={name:e.name,projectId:e.projectId||i,description:e.description||"",released:e.released||!1,archived:e.archived||!1},p=`${t}/rest/api/3/version`,c=btoa(`${o}:${n}`),m=await fetch(p,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${c}`},body:JSON.stringify(a)});if(!m.ok){let f=await m.text();throw s.error({status:m.status,statusText:m.statusText,error:f},"Failed to create Jira version"),new Error(`HTTP ${m.status}: ${m.statusText}`)}return{success:!0,version:await m.json()}}catch(t){throw s.error({error:t},"Error creating Jira version"),t}},fe=async e=>{try{let{baseUrl:r,token:t,email:n,projectId:o}=e,i=`${r}/rest/api/3/project/${o}/versions`,a=btoa(`${n}:${t}`),p=await fetch(i,{method:"GET",headers:{Accept:"application/json",Authorization:`Basic ${a}`}});if(!p.ok){let m=await p.text();throw s.error({status:p.status,statusText:p.statusText,error:m},"Failed to get Jira project versions"),new Error(`HTTP ${p.status}: ${p.statusText}`)}return await p.json()}catch(r){throw s.error({error:r},"Error getting Jira project versions"),r}},st=async(e,r)=>{try{return(await fe(r)).find(o=>o.name===e)||null}catch(t){throw s.error({error:t,versionName:e},"Error finding Jira version by name"),t}},nt=async(e,r)=>{try{let{baseUrl:t,token:n,email:o}=r,i={released:e.released??!0,archived:e.archived??!1};e.releaseDate?i.releaseDate=e.releaseDate:e.released!==!1&&(i.releaseDate=new Date().toISOString().split("T")[0]),e.description!==void 0&&(i.description=e.description);let a=`${t}/rest/api/3/version/${e.versionId}`,p=btoa(`${o}:${n}`),c=await fetch(a,{method:"PUT",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${p}`},body:JSON.stringify(i)});if(!c.ok){let u=await c.text();throw s.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 s.error({error:t},"Error updating Jira version"),t}},Se=async(e,r)=>{try{let{versionName:t}=e,n=await st(t,r);if(!n)throw s.error({versionName:t},"Jira version not found"),new Error(`Version "${t}" not found in Jira project`);return await nt({versionId:n.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},r)}catch(t){throw s.error({error:t},"Error delivering Jira release"),t}},G=async()=>{let e=te.env.JIRA_BASE_URL,r=te.env.JIRA_TOKEN||te.env.JIRA_API_TOKEN,t=te.env.JIRA_PROJECT_ID,n=te.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)"),n||o.push("JIRA_EMAIL (your Jira email address)"),o.length>0){let a=["Jira configuration is required but incomplete.","Please configure the following environment variables:",...o.map(p=>` - ${p}`),"","You can set these in your .env file or as environment variables."].join(`
16
+ `);throw new Error(a)}let i=Number.parseInt(t,10);if(Number.isNaN(i))throw new TypeError(`Invalid JIRA_PROJECT_ID: "${t}" must be a numeric value (e.g., 10001)`);return{baseUrl:e.replace(/\/$/,""),token:r,projectId:i,email:n}},oe=async()=>{try{return await G()}catch(e){return s.warn({error:e},"Jira configuration not available, skipping Jira integration"),null}};var de=e=>e==="hotfix"?"main":"dev",ne=async(e="regular")=>{let r=de(e);se.quiet=!0,await se`git fetch origin`,await se`git switch ${r}`,await se`git pull origin ${r}`,se.quiet=!1},ie=async e=>{let{version:r,jiraConfig:t,description:n,type:o="regular"}=e,i=`v${r}`,a=await Ee({name:i,projectId:t.projectId,description:n||"",released:!1,archived:!1},t),p=`${t.baseUrl}/projects/${a.version.projectId}/versions/${a.version.id}/tab/release-report-all-issues`,c=await he({version:r,jiraVersionUrl:p,type:o});return{version:r,type:o,branchName:c.branchName,prUrl:c.prUrl,jiraVersionUrl:p}},y=async()=>{let e=new Map,r=await oe();if(!r)return e;try{let t=await fe(r);for(let n of t)n.description&&e.set(n.name,n.description)}catch{}return e},K=(e,r,t)=>{let n=t?" ".repeat(t-e.length+3):" ",o=`[${r}]`.padEnd(11);return`${e}${n}${o}`},g=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",T=e=>{let{branches:r,descriptions:t,types:n}=e,o=r.map(a=>a.replace("release/v","")),i=Math.max(...o.map(a=>a.length));return r.map((a,p)=>{let c=o[p],m=n?n.get(a)||"regular":void 0,u=t.get(`v${c}`),f=" ".repeat(i-c.length+3),h=m?K(c,m,i):c;return u&&(h=m?`${h} ${u}`:`${c}${f}${u}`),{name:h,value:a}})};var Ae=e=>e.replace("release/","").slice(1).split(".").map(Number),ge=e=>[...e].sort((r,t)=>{let[n,o,i]=Ae(r),[a,p,c]=Ae(t);return n!==a?(n??0)-(a??0):o!==p?(o??0)-(p??0):(i??0)-(c??0)});var hr=async()=>{let e=await k`gh pr list --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName`,r=await k`gh pr list --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName`,t=[...JSON.parse(e.stdout),...JSON.parse(r.stdout)],n=new Set;return t.filter(o=>n.has(o.headRefName)?!1:(n.add(o.headRefName),!0))},ye=async()=>{try{let e=await hr();return e.length===0&&(s.error("\u274C No release PRs found. Check the project folder for the script. Exiting..."),ve.exit(1)),ge(e.map(r=>r.headRefName))}catch(e){s.error({error:e},"\u274C Error fetching release PRs"),ve.exit(1)}},v=async()=>{try{let e=await hr();e.length===0&&(s.error("\u274C No release PRs found. Check the project folder for the script. Exiting..."),ve.exit(1));let r=ge(e.map(n=>n.headRefName)),t=new Map(e.map(n=>[n.headRefName,n]));return r.map(n=>({branch:n,title:t.get(n).title}))}catch(e){s.error({error:e},"\u274C Error fetching release PRs"),ve.exit(1)}},he=async e=>{let{version:r,jiraVersionUrl:t,type:n}=e,o=n==="hotfix"?"Hotfix":"Release",i=de(n),a=`release/v${r}`;try{k.quiet=!0,await k`git switch ${i}`,await k`git pull origin ${i}`,await k`git checkout -b ${a}`,await k`git push -u origin ${a}`,await k`git commit --allow-empty-message --allow-empty --message ''`,await k`git push origin ${a}`;let c=(await k`gh pr create --title "${o} v${r}" --body "${t} \n" --base ${i} --head ${a}`).stdout.trim();return await k`git switch ${i}`,k.quiet=!1,{branchName:a,prUrl:c}}catch(p){throw s.error({error:p,branchName:a},`Error creating release branch ${a}`),p}};var gr=async e=>{let{all:r,confirmedCommand:t}=e;l.start("merge-dev");let o=(await v()).filter(u=>g(u.title)==="regular").map(u=>u.branch);if(o.length===0)return s.info("\u2139\uFE0F No open release branches found"),l.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 i=[];if(r)i=o;else{l.setInteractive();let u=await y();i=await it({required:!0,message:"\u{1F33F} Select release branches",choices:T({branches:o,descriptions:u})})}i.length===o.length?l.addOption("--all",!0):l.addOption("--versions",i.map(u=>u.replace("release/v","")));let p=t?!0:await at({message:`Are you sure you want to merge dev into these branches: ${i.join(", ")}?`});t||l.setInteractive(),p||(s.info("Operation cancelled. Exiting..."),ct.exit(0)),t||l.addOption("--yes",!0),$.quiet=!0,await $`git fetch origin`,await $`git switch dev`,await $`git pull origin dev`;let c=[];for(let u of i)await lt(u)||c.push(u);if($.quiet=!1,c.length>0){s.info(`
17
17
  \u26A0\uFE0F ${c.length} branch(es) failed to merge automatically.
18
18
  `),s.info("\u{1F4CB} Manual merge script for failed branches:");for(let u of c)s.info(`# Merge dev into ${u} and resolve conflicts if any
19
19
 
20
20
  git switch ${u} && git pull origin ${u} && git merge origin/dev
21
21
  git push origin ${u} && git switch dev
22
- `);s.info(`\u2705 ${a.length-c.length}/${a.length} merges completed successfully.`)}else s.info(`\u2705 All merges completed successfully!
23
- `);l.print();let m={successfulMerges:a.length-c.length,failedMerges:c.length,failedBranches:c,totalBranches:a.length};return{content:[{type:"text",text:JSON.stringify(m,null,2)}],structuredContent:m}},ot=async e=>{try{return await $`git switch ${e}`,await $`git pull origin ${e}`,await $`git merge origin/dev --no-edit`,await $`git push origin ${e}`,await $`git switch dev`,s.info(`Successfully merged dev into ${e}`),!0}catch(r){return s.error({error:r,branch:e},`Error merging dev into ${e}`),await $`git reset --merge HEAD~1`,!1}},Ie={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:G.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:G.number().describe("Number of successful merges"),failedMerges:G.number().describe("Number of failed merges"),failedBranches:G.array(G.string()).describe("List of branches that failed to merge"),totalBranches:G.number().describe("Total number of branches processed")},handler:hr};import st from"@inquirer/confirm";import nt from"@inquirer/select";import Ne from"node:process";import{z as ne}from"zod";import{$ as x}from"zx";var gr=async e=>{let{version:r,confirmedCommand:t}=e;l.start("release-deliver");let n=await v(),o=n.map(d=>d.branch),a=new Map(n.map(d=>[d.branch,g(d.title)])),i="";if(r)i=`release/v${r}`;else{l.setInteractive();let d=await y();i=await nt({message:"\u{1F33F} Select release branch",choices:T({branches:o,descriptions:d,types:a})})}let p=i.replace("release/v","");l.addOption("--version",p);let c=n.find(d=>d.branch===i);c||(s.error(`\u274C Release branch ${i} not found in open PRs. Exiting...`),Ne.exit(1));let m=g(c.title),u=t?!0:await st({message:`Are you sure you want to deliver version ${i} to production?`});t||l.setInteractive(),u||(s.info("Operation cancelled. Exiting..."),Ne.exit(0)),l.addOption("--yes",!0);try{x.quiet=!0,m==="hotfix"?(await x`gh pr merge ${i} --squash --admin --delete-branch`,x.quiet=!1,await x`gh workflow run deploy-all.yml --ref main -f environment=prod`,x.quiet=!0,await x`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`):(await x`gh pr merge ${i} --squash --admin --delete-branch`,await x`gh pr create --base main --head dev --title "Release v${p} (RC)" --body ""`,await x`gh pr merge dev --squash --admin`,x.quiet=!1,await x`gh workflow run deploy-all.yml --ref main -f environment=prod`,x.quiet=!0,await x`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`),x.quiet=!1;let d=await re();if(d)try{let h=i.replace("release/","");await Ae({versionName:h},d)}catch(h){s.error({error:h},"Failed to deliver Jira release (non-blocking)")}else s.info("\u{1F514} Jira is not configured, skipping Jira release delivery");s.info(`Successfully delivered ${i} to production!`),l.print();let f={releaseBranch:i,version:i.replace("release/v",""),type:m,success:!0};return{content:[{type:"text",text:JSON.stringify(f,null,2)}],structuredContent:f}}catch(d){s.error({error:d},"\u274C Error merging release branch into dev"),Ne.exit(1)}},Oe={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:ne.string().describe('Release version to deliver to production (e.g., "1.2.5"). Required for MCP calls.')},outputSchema:{releaseBranch:ne.string().describe("The release branch that was delivered"),version:ne.string().describe("The version that was delivered"),type:ne.enum(["regular","hotfix"]).describe("Release type"),success:ne.boolean().describe("Whether the delivery was successful")},handler:gr};import vr from"@inquirer/select";import yr from"node:process";import{z as O}from"zod";import{$ as _e}from"zx";var wr=async e=>{let{version:r,env:t,skipTerraform:n}=e;l.start("release-deploy-all");let o="";if(r)o=r==="dev"?"dev":`release/v${r}`;else{l.setInteractive();let c=await v(),m=c.map(f=>f.branch),u=new Map(c.map(f=>[f.branch,g(f.title)])),d=await y();o=await vr({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...T({branches:m,descriptions:d,types:u})]})}let a=o==="dev"?"dev":o.replace("release/v","");l.addOption("--version",a);let i="";t?i=t:(l.setInteractive(),i=await vr({message:"\u{1F9EA} Select environment",choices:P.map(c=>({name:c,value:c}))})),l.addOption("--env",i),P.includes(i)||(s.error(`\u274C Invalid environment: ${i}. Exiting...`),yr.exit(1));let p=n??!1;p&&l.addOption("--skip-terraform",!0);try{_e.quiet=!0,await _e`gh workflow run deploy-all.yml --ref ${o} -f environment=${i} ${p?["-f","skip_terraform_deploy=true"]:[]}`,_e.quiet=!1,s.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${o} and environment: ${i}`),l.print();let m={releaseBranch:o,version:o.replace("release/v",""),environment:i,skipTerraformDeploy:p,success:!0};return{content:[{type:"text",text:JSON.stringify(m,null,2)}],structuredContent:m}}catch(c){s.error({error:c},"\u274C Error launching workflow"),yr.exit(1)}},De={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:O.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:O.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),skipTerraform:O.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:O.string().describe("The release branch that was deployed"),version:O.string().describe("The version that was deployed"),environment:O.string().describe("The environment deployed to"),skipTerraformDeploy:O.boolean().describe("Whether terraform deployment was skipped"),success:O.boolean().describe("Whether the deployment was successful")},handler:wr};import it from"@inquirer/checkbox";import Rr from"@inquirer/select";import at from"node:fs/promises";import{resolve as ct}from"node:path";import ie from"node:process";import lt from"yaml";import{z as C}from"zod";import{$ as Me}from"zx";var br=async e=>{let{version:r,env:t,services:n,skipTerraform:o}=e;l.start("release-deploy-selected");let a="";if(r)a=r==="dev"?"dev":`release/v${r}`;else{l.setInteractive();let f=await v(),h=f.map(b=>b.branch),R=new Map(f.map(b=>[b.branch,g(b.title)])),S=await y();a=await Rr({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...T({branches:h,descriptions:S,types:R})]})}let i=a==="dev"?"dev":a.replace("release/v","");l.addOption("--version",i);let p="";t?p=t:(l.setInteractive(),p=await Rr({message:"\u{1F9EA} Select environment",choices:P.map(f=>({name:f,value:f}))})),l.addOption("--env",p),P.includes(p)||(s.error(`\u274C Invalid environment: ${p}. Exiting...`),ie.exit(1));let c=await pt();c.length===0&&(s.error("\u274C No services found in workflow file. Exiting..."),ie.exit(1));let m=[];n&&n.length>0?m=n:(l.setInteractive(),m=await it({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:c.map(f=>({name:f,value:f}))})),l.addOption("--services",m),m.length===0&&(s.error("\u274C No services selected. Exiting..."),ie.exit(1));let u=m.filter(f=>!c.includes(f));u.length>0&&(s.error(`\u274C Invalid services: ${u.join(", ")}. Available services: ${c.join(", ")}`),ie.exit(1));let d=o??!1;d&&l.addOption("--skip-terraform",!0);try{Me.quiet=!0;let f=m.flatMap(S=>["-f",`${S}=true`]);await Me`gh workflow run deploy-selected-services.yml --ref ${a} -f environment=${p} ${f} ${d?["-f","skip_terraform_deploy=true"]:[]}`,Me.quiet=!1,s.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${a}, environment: ${p}, services: ${m.join(", ")}`),l.print();let R={releaseBranch:a,version:a.replace("release/v",""),environment:p,services:m,skipTerraformDeploy:d,success:!0};return{content:[{type:"text",text:JSON.stringify(R,null,2)}],structuredContent:R}}catch(f){s.error({error:f},"\u274C Error launching workflow"),ie.exit(1)}},pt=async()=>{let e=await E(),r=ct(e,".github/workflows/deploy-selected-services.yml"),t=await at.readFile(r,"utf-8"),o=lt.parse(t).on.workflow_dispatch.inputs,a=[];for(let[i,p]of Object.entries(o))p.type==="boolean"&&i!=="skip_terraform_deploy"&&a.push(i);return a},Je={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:C.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:C.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),services:C.array(C.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:C.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:C.string().describe("The release branch that was deployed"),version:C.string().describe("The version that was deployed"),environment:C.string().describe("The environment deployed to"),services:C.array(C.string()).describe("The services that were deployed"),skipTerraformDeploy:C.boolean().describe("Whether terraform deployment was skipped"),success:C.boolean().describe("Whether the deployment was successful")},handler:br};import{z as H}from"zod";var xr=async()=>{let r=(await v()).map(i=>({version:i.branch.replace("release/",""),type:g(i.title)})),t=await y(),n=Math.max(...r.map(i=>i.version.length)),o=r.map(i=>{let p=U(i.version,i.type,n),c=t.get(i.version);return c?`${p} ${c}`:p});s.info(`All release branches:
22
+ `);s.info(`\u2705 ${i.length-c.length}/${i.length} merges completed successfully.`)}else s.info(`\u2705 All merges completed successfully!
23
+ `);l.print();let m={successfulMerges:i.length-c.length,failedMerges:c.length,failedBranches:c,totalBranches:i.length};return{content:[{type:"text",text:JSON.stringify(m,null,2)}],structuredContent:m}},lt=async e=>{try{return await $`git switch ${e}`,await $`git pull origin ${e}`,await $`git merge origin/dev --no-edit`,await $`git push origin ${e}`,await $`git switch dev`,s.info(`Successfully merged dev into ${e}`),!0}catch(r){return s.error({error:r,branch:e},`Error merging dev into ${e}`),await $`git reset --merge HEAD~1`,!1}},Ne={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:H.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:H.number().describe("Number of successful merges"),failedMerges:H.number().describe("Number of failed merges"),failedBranches:H.array(H.string()).describe("List of branches that failed to merge"),totalBranches:H.number().describe("Total number of branches processed")},handler:gr};import pt from"@inquirer/confirm";import mt from"@inquirer/select";import Oe from"node:process";import{z as ae}from"zod";import{$ as b}from"zx";var vr=async e=>{let{version:r,confirmedCommand:t}=e;l.start("release-deliver");let n=await v(),o=n.map(f=>f.branch),i=new Map(n.map(f=>[f.branch,g(f.title)])),a="";if(r)a=`release/v${r}`;else{l.setInteractive();let f=await y();a=await mt({message:"\u{1F33F} Select release branch",choices:T({branches:o,descriptions:f,types:i})})}let p=a.replace("release/v","");l.addOption("--version",p);let c=n.find(f=>f.branch===a);c||(s.error(`\u274C Release branch ${a} not found in open PRs. Exiting...`),Oe.exit(1));let m=g(c.title),u=t?!0:await pt({message:`Are you sure you want to deliver version ${a} to production?`});t||l.setInteractive(),u||(s.info("Operation cancelled. Exiting..."),Oe.exit(0)),l.addOption("--yes",!0);try{b.quiet=!0,m==="hotfix"?(await b`gh pr merge ${a} --squash --admin --delete-branch`,b.quiet=!1,await b`gh workflow run deploy-all.yml --ref main -f environment=prod`,b.quiet=!0,await b`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`):(await b`gh pr merge ${a} --squash --admin --delete-branch`,await b`gh pr create --base main --head dev --title "Release v${p} (RC)" --body ""`,await b`gh pr merge dev --squash --admin`,b.quiet=!1,await b`gh workflow run deploy-all.yml --ref main -f environment=prod`,b.quiet=!0,await b`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`),b.quiet=!1;let f=await oe();if(f)try{let d=a.replace("release/","");await Se({versionName:d},f)}catch(d){s.error({error:d},"Failed to deliver Jira release (non-blocking)")}else s.info("\u{1F514} Jira is not configured, skipping Jira release delivery");s.info(`Successfully delivered ${a} to production!`),l.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(f){s.error({error:f},"\u274C Error merging release branch into dev"),Oe.exit(1)}},_e={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:ae.string().describe('Release version to deliver to production (e.g., "1.2.5"). Required for MCP calls.')},outputSchema:{releaseBranch:ae.string().describe("The release branch that was delivered"),version:ae.string().describe("The version that was delivered"),type:ae.enum(["regular","hotfix"]).describe("Release type"),success:ae.boolean().describe("Whether the delivery was successful")},handler:vr};import yr from"@inquirer/select";import wr from"node:process";import{z as _}from"zod";import{$ as Me}from"zx";var Rr=async e=>{let{version:r,env:t,skipTerraform:n}=e;l.start("release-deploy-all");let o="";if(r)o=r==="dev"?"dev":`release/v${r}`;else{l.setInteractive();let m=await v(),u=m.map(d=>d.branch),f=new Map(m.map(d=>[d.branch,g(d.title)])),h=await y();o=await yr({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...T({branches:u,descriptions:h,types:f})]})}let i=o==="dev"?"dev":o.replace("release/v","");l.addOption("--version",i);let{environments:a}=await E(),p="";t?p=t:(l.setInteractive(),p=await yr({message:"\u{1F9EA} Select environment",choices:a.map(m=>({name:m,value:m}))})),l.addOption("--env",p),a.includes(p)||(s.error(`\u274C Invalid environment: ${p}. Exiting...`),wr.exit(1));let c=n??!1;c&&l.addOption("--skip-terraform",!0);try{Me.quiet=!0,await Me`gh workflow run deploy-all.yml --ref ${o} -f environment=${p} ${c?["-f","skip_terraform_deploy=true"]:[]}`,Me.quiet=!1,s.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${o} and environment: ${p}`),l.print();let u={releaseBranch:o,version:o.replace("release/v",""),environment:p,skipTerraformDeploy:c,success:!0};return{content:[{type:"text",text:JSON.stringify(u,null,2)}],structuredContent:u}}catch(m){s.error({error:m},"\u274C Error launching workflow"),wr.exit(1)}},De={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:_.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:_.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),skipTerraform:_.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:_.string().describe("The release branch that was deployed"),version:_.string().describe("The version that was deployed"),environment:_.string().describe("The environment deployed to"),skipTerraformDeploy:_.boolean().describe("Whether terraform deployment was skipped"),success:_.boolean().describe("Whether the deployment was successful")},handler:Rr};import ut from"@inquirer/checkbox";import br from"@inquirer/select";import ft from"node:fs/promises";import{resolve as dt}from"node:path";import ce from"node:process";import ht from"yaml";import{z as C}from"zod";import{$ as Je}from"zx";var xr=async e=>{let{version:r,env:t,services:n,skipTerraform:o}=e;l.start("release-deploy-selected");let i="";if(r)i=r==="dev"?"dev":`release/v${r}`;else{l.setInteractive();let d=await v(),x=d.map(N=>N.branch),I=new Map(d.map(N=>[N.branch,g(N.title)])),R=await y();i=await br({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...T({branches:x,descriptions:R,types:I})]})}let a=i==="dev"?"dev":i.replace("release/v","");l.addOption("--version",a);let{environments:p}=await E(),c="";t?c=t:(l.setInteractive(),c=await br({message:"\u{1F9EA} Select environment",choices:p.map(d=>({name:d,value:d}))})),l.addOption("--env",c),p.includes(c)||(s.error(`\u274C Invalid environment: ${c}. Exiting...`),ce.exit(1));let m=await gt();m.length===0&&(s.error("\u274C No services found in workflow file. Exiting..."),ce.exit(1));let u=[];n&&n.length>0?u=n:(l.setInteractive(),u=await ut({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:m.map(d=>({name:d,value:d}))})),l.addOption("--services",u),u.length===0&&(s.error("\u274C No services selected. Exiting..."),ce.exit(1));let f=u.filter(d=>!m.includes(d));f.length>0&&(s.error(`\u274C Invalid services: ${f.join(", ")}. Available services: ${m.join(", ")}`),ce.exit(1));let h=o??!1;h&&l.addOption("--skip-terraform",!0);try{Je.quiet=!0;let d=u.flatMap(R=>["-f",`${R}=true`]);await Je`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${c} ${d} ${h?["-f","skip_terraform_deploy=true"]:[]}`,Je.quiet=!1,s.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${c}, services: ${u.join(", ")}`),l.print();let I={releaseBranch:i,version:i.replace("release/v",""),environment:c,services:u,skipTerraformDeploy:h,success:!0};return{content:[{type:"text",text:JSON.stringify(I,null,2)}],structuredContent:I}}catch(d){s.error({error:d},"\u274C Error launching workflow"),ce.exit(1)}},gt=async()=>{let e=await P(),r=dt(e,".github/workflows/deploy-selected-services.yml"),t=await ft.readFile(r,"utf-8"),o=ht.parse(t).on.workflow_dispatch.inputs,i=[];for(let[a,p]of Object.entries(o))p.type==="boolean"&&a!=="skip_terraform_deploy"&&i.push(a);return i},je={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:C.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:C.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),services:C.array(C.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:C.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:C.string().describe("The release branch that was deployed"),version:C.string().describe("The version that was deployed"),environment:C.string().describe("The environment deployed to"),services:C.array(C.string()).describe("The services that were deployed"),skipTerraformDeploy:C.boolean().describe("Whether terraform deployment was skipped"),success:C.boolean().describe("Whether the deployment was successful")},handler:xr};import{z}from"zod";var Tr=async()=>{let r=(await v()).map(a=>({version:a.branch.replace("release/",""),type:g(a.title)})),t=await y(),n=Math.max(...r.map(a=>a.version.length)),o=r.map(a=>{let p=K(a.version,a.type,n),c=t.get(a.version);return c?`${p} ${c}`:p});s.info(`All release branches:
24
24
  `),s.info(`
25
25
  ${o.join(`
26
26
  `)}
27
- `);let a={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(a,null,2)}],structuredContent:a}},je={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:H.array(H.object({version:H.string().describe("Release version"),type:H.enum(["regular","hotfix"]).describe("Release type"),description:H.string().nullable().describe("Jira version description")})).describe("List of all release branches"),count:H.number().describe("Number of release branches")},handler:xr};import Tr from"@inquirer/confirm";import mt from"@inquirer/select";import kr from"node:process";import{z as A}from"zod";import{$ as Le,question as Cr}from"zx";var Pr=async e=>{let{version:r,description:t,type:n,confirmedCommand:o,checkout:a}=e;l.start("release-create");let i=r,p=t,c=n||"regular",m=a,u=await q();i||(l.setInteractive(),i=await Cr("Enter version (e.g. 1.2.5): ")),(!i||i.trim()==="")&&(s.error("No version provided. Exiting..."),kr.exit(1));let d=i.trim();l.addOption("--version",d),n||(l.setInteractive(),c=await mt({message:"Select release type:",choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"})),l.addOption("--type",c),p===void 0&&(l.setInteractive(),p=await Cr("Enter description (optional, press Enter to skip): "),p.trim()===""&&(p="")),p&&l.addOption("--description",p);let f=o?!0:await Tr({message:`Are you sure you want to create release branch for version ${d}?`});o||l.setInteractive(),f||(s.info("Operation cancelled. Exiting..."),kr.exit(0)),l.addOption("--yes",!0),await oe(c);let h=await se({version:d,jiraConfig:u,description:p,type:c});s.info(`\u2705 Successfully created release: v${d}`),s.info(`\u{1F517} GitHub PR: ${h.prUrl}`),s.info(`\u{1F517} Jira Version: ${h.jiraVersionUrl}`),m===void 0&&(l.setInteractive(),m=await Tr({message:`Do you want to checkout to the created branch ${h.branchName}?`,default:!0})),m||l.addOption("--no-checkout",!0),m&&(Le.quiet=!0,await Le`git switch ${h.branchName}`,Le.quiet=!1,s.info(`\u{1F504} Switched to branch ${h.branchName}`)),l.print();let R={version:d,type:c,branchName:h.branchName,prUrl:h.prUrl,jiraVersionUrl:h.jiraVersionUrl,isCheckedOut:m};return{content:[{type:"text",text:JSON.stringify(R,null,2)}],structuredContent:R}},Ve={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, creates the matching Jira fix version, and optionally checks out to the new 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); "type" / "description" / "checkout" default to regular / empty / true when omitted.',inputSchema:{version:A.string().describe('Version to create (e.g., "1.2.5"). Required for MCP calls.'),description:A.string().optional().describe("Optional description for the Jira version"),type:A.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" or "hotfix" (default: "regular")'),checkout:A.boolean().optional().default(!0).describe("Checkout to the created branch (default: true)")},outputSchema:{version:A.string().describe("Version number"),type:A.enum(["regular","hotfix"]).describe("Release type"),branchName:A.string().describe("Release branch name"),prUrl:A.string().describe("GitHub PR URL"),jiraVersionUrl:A.string().describe("Jira version URL"),isCheckedOut:A.boolean().describe("Whether the branch was checked out")},handler:Pr};import ut from"@inquirer/confirm";import dt from"@inquirer/select";import Er from"node:process";import{z as w}from"zod";import{question as ft}from"zx";var ht=async e=>{let{versions:r,type:t,confirmedCommand:n}=e,o=r,a=t||"regular";o||(l.setInteractive(),o=await ft("Enter versions by comma (e.g. 1.2.5, 1.2.6): "));let i=o.split(",").map(c=>c.trim()).filter(Boolean);l.addOption("--versions",i.join(", ")),i.length===0&&(s.error("No versions provided. Exiting..."),Er.exit(1)),t||(l.setInteractive(),a=await dt({message:"Select release type:",choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"})),l.addOption("--type",a),i.length===1&&s.warn('\u{1F4A1} You are creating only one release. Consider using "create-release" command for single releases.');let p=n?!0:await ut({message:`Are you sure you want to create release branches for these versions: ${i.join(", ")}?`});return n||l.setInteractive(),p||(s.info("Operation cancelled. Exiting..."),Er.exit(0)),l.addOption("--yes",!0),{versionsList:i,type:a}},$r=async e=>{l.start("release-create-batch");let r=await q(),{versionsList:t,type:n}=await ht(e);await oe(n);let o=[],a=[];for(let m of t)try{let u=await se({version:m,jiraConfig:r,type:n});o.push(u),s.info(`\u2705 Successfully created release: v${m}`),s.info(`\u{1F517} GitHub PR: ${u.prUrl}`),s.info(`\u{1F517} Jira Version: ${u.jiraVersionUrl}
28
- `)}catch(u){let d=u instanceof Error?u.message:String(u);a.push({version:m,error:d}),s.error(`\u274C Failed to create release: v${m}`),s.error(` Error: ${d}
29
- `)}let i=o.length,p=a.length;i===t.length?s.info(`\u2705 All ${t.length} release branches were created successfully.`):i>0?(s.warn(`\u26A0\uFE0F ${i} of ${t.length} release branches were created successfully.`),s.warn(`\u274C ${p} release(s) failed.`)):s.error(`\u274C All ${t.length} release branches failed to create.`),l.print();let c={createdBranches:o.map(m=>m.branchName),successCount:i,failureCount:p,releases:o,failedReleases:a};return{content:[{type:"text",text:JSON.stringify(c,null,2)}],structuredContent:c}},Fe={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. 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:w.string().describe('Comma-separated list of versions to create (e.g., "1.2.5, 1.2.6"). Required for MCP calls.'),type:w.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" or "hotfix" (default: "regular")')},outputSchema:{createdBranches:w.array(w.string()).describe("List of created release branches"),successCount:w.number().describe("Number of releases created successfully"),failureCount:w.number().describe("Number of releases that failed"),releases:w.array(w.object({version:w.string().describe("Version number"),type:w.enum(["regular","hotfix"]).describe("Release type"),branchName:w.string().describe("Release branch name"),prUrl:w.string().describe("GitHub PR URL"),jiraVersionUrl:w.string().describe("Jira version URL")})).describe("Detailed information for each created release with URLs"),failedReleases:w.array(w.object({version:w.string().describe("Version number that failed"),error:w.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:$r};import gt from"@inquirer/checkbox";import Be from"@inquirer/confirm";import vt from"node:process";import{z as D}from"zod";import{$ as z}from"zx";var yt="feature",wt="release",Rt="release/v",Sr=async e=>{let{confirmedCommand:r,all:t,versions:n,cursor:o,githubDesktop:a}=e;l.start("worktrees-add");try{let i=await I("release"),c=`${await E()}${B}`;await Ar(`${c}/${wt}`),await Ar(`${c}/${yt}`);let m=[];if(n)m=n.split(",").map(b=>`release/v${b.trim()}`);else{let b=await v(),ve=b.map(ye=>ye.branch);if(ve.length===0)return s.info("\u2139\uFE0F No open release branches found"),l.print(),{content:[{type:"text",text:JSON.stringify({createdWorktrees:[],count:0},null,2)}],structuredContent:{createdWorktrees:[],count:0}};if(t)m=ve;else{l.setInteractive();let ye=new Map(b.map(Ye=>[Ye.branch,g(Ye.title)])),Jr=await y();m=await gt({required:!0,message:"\u{1F33F} Select release branches",choices:T({branches:ve,descriptions:Jr,types:ye})})}}t?l.addOption("--all",!0):l.addOption("--versions",m.map(b=>b.replace("release/v","")));let u=r?!0:await Be({message:"Are you sure you want to proceed with these worktree changes?"});r||l.setInteractive(),u||(s.info("Operation cancelled. Exiting..."),vt.exit(0)),r||l.addOption("--yes",!0);let d=o??await Be({message:"Open created worktrees in Cursor?"});typeof o>"u"&&l.setInteractive(),d?l.addOption("--cursor",!0):l.addOption("--no-cursor",!0);let f=a??await Be({message:"Open created worktrees in GitHub Desktop?"});typeof a>"u"&&l.setInteractive(),f?l.addOption("--github-desktop",!0):l.addOption("--no-github-desktop",!0);let{branchesToCreate:h}=bt({selectedReleaseBranches:m,currentWorktrees:i}),R=await xt(h,c);if(Tt(R),d)for(let b of R)await z`cursor ${c}/${b}`;if(f)for(let b of R)await z`github ${c}/${b}`,await z`sleep 5`;l.print();let S={createdWorktrees:R,count:R.length};return{content:[{type:"text",text:JSON.stringify(S,null,2)}],structuredContent:S}}catch(i){throw s.error({error:i},"\u274C Error managing worktrees"),i}},Ar=async e=>{await z`mkdir -p ${e}`},bt=e=>{let{selectedReleaseBranches:r,currentWorktrees:t}=e,n=t.filter(a=>a.startsWith(Rt));return{branchesToCreate:r.filter(a=>!n.includes(a))}},xt=async(e,r)=>{let t=await Promise.allSettled(e.map(async o=>{let a=`${r}/${o}`;return await z`git worktree add ${a} ${o}`,await z({cwd:a})`pnpm install`,o})),n=[];for(let[o,a]of t.entries())if(a.status==="fulfilled")n.push(a.value);else{let i=e[o];s.error({error:a.reason},`\u274C Failed to create worktree for ${i}`)}return n},Tt=e=>{if(e.length>0){s.info("\u2705 Created git worktrees:");for(let r of e)s.info(r);s.info("")}else s.info("\u2139\uFE0F No new git worktrees to create")},We={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" follow-up prompts are unreachable without a TTY, and the CLI confirmation is auto-skipped for MCP calls.',inputSchema:{all:D.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:D.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:D.boolean().optional().describe("Open each created worktree in Cursor. Defaults to false in MCP mode (the follow-up prompt is not shown)."),githubDesktop:D.boolean().optional().describe("Open each created worktree in GitHub Desktop. Defaults to false in MCP mode (the follow-up prompt is not shown).")},outputSchema:{createdWorktrees:D.array(D.string()).describe("List of created git worktree branches"),count:D.number().describe("Number of git worktrees created")},handler:Sr};import{z as K}from"zod";var Ir=async()=>{let e=await I("release");if(e.length===0)return s.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([v(),y()]),n=new Map(r.map(c=>[c.branch,g(c.title)])),o=e.map(c=>{let m=c.replace("release/",""),u=n.get(c)||"regular",d=t.get(m)||null;return{version:m,type:u,description:d}}),a=Math.max(...o.map(c=>c.version.length)),i=o.map(c=>{let m=U(c.version,c.type,a);return c.description?`${m} ${c.description}`:m});s.info("\u{1F33F} Active worktrees:"),s.info(`
30
- ${i.join(`
27
+ `);let i={releases:r.map(a=>({version:a.version,type:a.type,description:t.get(a.version)||null})),count:r.length};return{content:[{type:"text",text:JSON.stringify(i,null,2)}],structuredContent:i}},Le={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:z.array(z.object({version:z.string().describe("Release version"),type:z.enum(["regular","hotfix"]).describe("Release type"),description:z.string().nullable().describe("Jira version description")})).describe("List of all release branches"),count:z.number().describe("Number of release branches")},handler:Tr};import kr from"@inquirer/confirm";import vt from"@inquirer/select";import Cr from"node:process";import{z as S}from"zod";import{$ as Ve,question as Pr}from"zx";var $r=async e=>{let{version:r,description:t,type:n,confirmedCommand:o,checkout:i}=e;l.start("release-create");let a=r,p=t,c=n||"regular",m=i,u=await G();a||(l.setInteractive(),a=await Pr("Enter version (e.g. 1.2.5): ")),(!a||a.trim()==="")&&(s.error("No version provided. Exiting..."),Cr.exit(1));let f=a.trim();l.addOption("--version",f),n||(l.setInteractive(),c=await vt({message:"Select release type:",choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"})),l.addOption("--type",c),p===void 0&&(l.setInteractive(),p=await Pr("Enter description (optional, press Enter to skip): "),p.trim()===""&&(p="")),p&&l.addOption("--description",p);let h=o?!0:await kr({message:`Are you sure you want to create release branch for version ${f}?`});o||l.setInteractive(),h||(s.info("Operation cancelled. Exiting..."),Cr.exit(0)),l.addOption("--yes",!0),await ne(c);let d=await ie({version:f,jiraConfig:u,description:p,type:c});s.info(`\u2705 Successfully created release: v${f}`),s.info(`\u{1F517} GitHub PR: ${d.prUrl}`),s.info(`\u{1F517} Jira Version: ${d.jiraVersionUrl}`),m===void 0&&(l.setInteractive(),m=await kr({message:`Do you want to checkout to the created branch ${d.branchName}?`,default:!0})),m||l.addOption("--no-checkout",!0),m&&(Ve.quiet=!0,await Ve`git switch ${d.branchName}`,Ve.quiet=!1,s.info(`\u{1F504} Switched to branch ${d.branchName}`)),l.print();let x={version:f,type:c,branchName:d.branchName,prUrl:d.prUrl,jiraVersionUrl:d.jiraVersionUrl,isCheckedOut:m};return{content:[{type:"text",text:JSON.stringify(x,null,2)}],structuredContent:x}},Fe={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, creates the matching Jira fix version, and optionally checks out to the new 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); "type" / "description" / "checkout" default to regular / empty / true when omitted.',inputSchema:{version:S.string().describe('Version to create (e.g., "1.2.5"). Required for MCP calls.'),description:S.string().optional().describe("Optional description for the Jira version"),type:S.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" or "hotfix" (default: "regular")'),checkout:S.boolean().optional().default(!0).describe("Checkout to the created branch (default: true)")},outputSchema:{version:S.string().describe("Version number"),type:S.enum(["regular","hotfix"]).describe("Release type"),branchName:S.string().describe("Release branch name"),prUrl:S.string().describe("GitHub PR URL"),jiraVersionUrl:S.string().describe("Jira version URL"),isCheckedOut:S.boolean().describe("Whether the branch was checked out")},handler:$r};import yt from"@inquirer/confirm";import wt from"@inquirer/select";import Ir from"node:process";import{z as w}from"zod";import{question as Rt}from"zx";var bt=async e=>{let{versions:r,type:t,confirmedCommand:n}=e,o=r,i=t||"regular";o||(l.setInteractive(),o=await Rt("Enter versions by comma (e.g. 1.2.5, 1.2.6): "));let a=o.split(",").map(c=>c.trim()).filter(Boolean);l.addOption("--versions",a.join(", ")),a.length===0&&(s.error("No versions provided. Exiting..."),Ir.exit(1)),t||(l.setInteractive(),i=await wt({message:"Select release type:",choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"})),l.addOption("--type",i),a.length===1&&s.warn('\u{1F4A1} You are creating only one release. Consider using "create-release" command for single releases.');let p=n?!0:await yt({message:`Are you sure you want to create release branches for these versions: ${a.join(", ")}?`});return n||l.setInteractive(),p||(s.info("Operation cancelled. Exiting..."),Ir.exit(0)),l.addOption("--yes",!0),{versionsList:a,type:i}},Er=async e=>{l.start("release-create-batch");let r=await G(),{versionsList:t,type:n}=await bt(e);await ne(n);let o=[],i=[];for(let m of t)try{let u=await ie({version:m,jiraConfig:r,type:n});o.push(u),s.info(`\u2705 Successfully created release: v${m}`),s.info(`\u{1F517} GitHub PR: ${u.prUrl}`),s.info(`\u{1F517} Jira Version: ${u.jiraVersionUrl}
28
+ `)}catch(u){let f=u instanceof Error?u.message:String(u);i.push({version:m,error:f}),s.error(`\u274C Failed to create release: v${m}`),s.error(` Error: ${f}
29
+ `)}let a=o.length,p=i.length;a===t.length?s.info(`\u2705 All ${t.length} release branches were created successfully.`):a>0?(s.warn(`\u26A0\uFE0F ${a} of ${t.length} release branches were created successfully.`),s.warn(`\u274C ${p} release(s) failed.`)):s.error(`\u274C All ${t.length} release branches failed to create.`),l.print();let c={createdBranches:o.map(m=>m.branchName),successCount:a,failureCount:p,releases:o,failedReleases:i};return{content:[{type:"text",text:JSON.stringify(c,null,2)}],structuredContent:c}},Be={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. 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:w.string().describe('Comma-separated list of versions to create (e.g., "1.2.5, 1.2.6"). Required for MCP calls.'),type:w.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" or "hotfix" (default: "regular")')},outputSchema:{createdBranches:w.array(w.string()).describe("List of created release branches"),successCount:w.number().describe("Number of releases created successfully"),failureCount:w.number().describe("Number of releases that failed"),releases:w.array(w.object({version:w.string().describe("Version number"),type:w.enum(["regular","hotfix"]).describe("Release type"),branchName:w.string().describe("Release branch name"),prUrl:w.string().describe("GitHub PR URL"),jiraVersionUrl:w.string().describe("Jira version URL")})).describe("Detailed information for each created release with URLs"),failedReleases:w.array(w.object({version:w.string().describe("Version number that failed"),error:w.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:Er};import xt from"@inquirer/checkbox";import We from"@inquirer/confirm";import Tt from"node:process";import{z as J}from"zod";import{$ as Y}from"zx";var kt="feature",Ct="release",Pt="release/v",Ar=async e=>{let{confirmedCommand:r,all:t,versions:n,cursor:o,githubDesktop:i}=e;l.start("worktrees-add");try{let a=await A("release"),c=`${await P()}${q}`;await Sr(`${c}/${Ct}`),await Sr(`${c}/${kt}`);let m=[];if(n)m=n.split(",").map(R=>`release/v${R.trim()}`);else{let R=await v(),N=R.map(we=>we.branch);if(N.length===0)return s.info("\u2139\uFE0F No open release branches found"),l.print(),{content:[{type:"text",text:JSON.stringify({createdWorktrees:[],count:0},null,2)}],structuredContent:{createdWorktrees:[],count:0}};if(t)m=N;else{l.setInteractive();let we=new Map(R.map(Xe=>[Xe.branch,g(Xe.title)])),jr=await y();m=await xt({required:!0,message:"\u{1F33F} Select release branches",choices:T({branches:N,descriptions:jr,types:we})})}}t?l.addOption("--all",!0):l.addOption("--versions",m.map(R=>R.replace("release/v","")));let u=r?!0:await We({message:"Are you sure you want to proceed with these worktree changes?"});r||l.setInteractive(),u||(s.info("Operation cancelled. Exiting..."),Tt.exit(0)),r||l.addOption("--yes",!0);let f=o??await We({message:"Open created worktrees in Cursor?"});typeof o>"u"&&l.setInteractive(),f?l.addOption("--cursor",!0):l.addOption("--no-cursor",!0);let h=i??await We({message:"Open created worktrees in GitHub Desktop?"});typeof i>"u"&&l.setInteractive(),h?l.addOption("--github-desktop",!0):l.addOption("--no-github-desktop",!0);let{branchesToCreate:d}=$t({selectedReleaseBranches:m,currentWorktrees:a}),x=await It(d,c);if(Et(x),f)for(let R of x)await Y`cursor ${c}/${R}`;if(h)for(let R of x)await Y`github ${c}/${R}`,await Y`sleep 5`;l.print();let I={createdWorktrees:x,count:x.length};return{content:[{type:"text",text:JSON.stringify(I,null,2)}],structuredContent:I}}catch(a){throw s.error({error:a},"\u274C Error managing worktrees"),a}},Sr=async e=>{await Y`mkdir -p ${e}`},$t=e=>{let{selectedReleaseBranches:r,currentWorktrees:t}=e,n=t.filter(i=>i.startsWith(Pt));return{branchesToCreate:r.filter(i=>!n.includes(i))}},It=async(e,r)=>{let t=await Promise.allSettled(e.map(async o=>{let i=`${r}/${o}`;return await Y`git worktree add ${i} ${o}`,await Y({cwd:i})`pnpm install`,o})),n=[];for(let[o,i]of t.entries())if(i.status==="fulfilled")n.push(i.value);else{let a=e[o];s.error({error:i.reason},`\u274C Failed to create worktree for ${a}`)}return n},Et=e=>{if(e.length>0){s.info("\u2705 Created git worktrees:");for(let r of e)s.info(r);s.info("")}else s.info("\u2139\uFE0F No new git worktrees to create")},qe={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" follow-up prompts are unreachable without a TTY, and the CLI confirmation is auto-skipped for MCP calls.',inputSchema:{all:J.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:J.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:J.boolean().optional().describe("Open each created worktree in Cursor. Defaults to false in MCP mode (the follow-up prompt is not shown)."),githubDesktop:J.boolean().optional().describe("Open each created worktree in GitHub Desktop. Defaults to false in MCP mode (the follow-up prompt is not shown).")},outputSchema:{createdWorktrees:J.array(J.string()).describe("List of created git worktree branches"),count:J.number().describe("Number of git worktrees created")},handler:Ar};import{z as X}from"zod";var Nr=async()=>{let e=await A("release");if(e.length===0)return s.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([v(),y()]),n=new Map(r.map(c=>[c.branch,g(c.title)])),o=e.map(c=>{let m=c.replace("release/",""),u=n.get(c)||"regular",f=t.get(m)||null;return{version:m,type:u,description:f}}),i=Math.max(...o.map(c=>c.version.length)),a=o.map(c=>{let m=K(c.version,c.type,i);return c.description?`${m} ${c.description}`:m});s.info("\u{1F33F} Active worktrees:"),s.info(`
30
+ ${a.join(`
31
31
  `)}
32
- `);let p={worktrees:o,count:o.length};return{content:[{type:"text",text:JSON.stringify(p,null,2)}],structuredContent:p}},qe={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:K.array(K.object({version:K.string().describe("Release version"),type:K.enum(["regular","hotfix"]).describe("Release type"),description:K.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:K.number().describe("Number of worktrees")},handler:Ir};import kt from"@inquirer/checkbox";import Ct from"@inquirer/confirm";import Pt from"node:process";import{z as ae}from"zod";import{$ as Ue}from"zx";var Nr=async e=>{let{confirmedCommand:r,all:t,versions:n}=e;l.start("worktrees-remove");try{let o=await I("release");if(o.length===0)return s.info("\u2139\uFE0F No active worktrees to remove"),l.print(),{content:[{type:"text",text:JSON.stringify({removedWorktrees:[],count:0},null,2)}],structuredContent:{removedWorktrees:[],count:0}};let i=`${await E()}${B}`,p=[];if(t)p=o;else if(n)p=n.split(",").map(f=>`release/v${f.trim()}`);else{l.setInteractive();let[f,h]=await Promise.all([y(),v()]),R=new Map(h.map(S=>[S.branch,g(S.title)]));p=await kt({required:!0,message:"\u{1F33F} Select release branches",choices:T({branches:o,descriptions:f,types:R})})}p.length===o.length?l.addOption("--all",!0):l.addOption("--versions",p.map(f=>f.replace("release/v","")));let m=r?!0:await Ct({message:"Are you sure you want to proceed with these worktree changes?"});r||l.setInteractive(),m||(s.info("Operation cancelled. Exiting..."),Pt.exit(0)),r||l.addOption("--yes",!0);let u=await Et(p,i);$t(u),l.print();let d={removedWorktrees:u,count:u.length};return{content:[{type:"text",text:JSON.stringify(d,null,2)}],structuredContent:d}}catch(o){throw s.error({error:o},"\u274C Error managing worktrees"),o}},Et=async(e,r)=>{let t=await Promise.allSettled(e.map(async o=>{let a=`${r}/${o}`;return await Ue`git worktree remove ${a}`,o})),n=[];for(let[o,a]of t.entries())if(a.status==="fulfilled")n.push(a.value);else{let i=e[o];s.error({error:a.reason},`\u274C Failed to remove worktree for ${i}`)}return n.length===e.length&&(await Ue`git worktree prune`,await Ue`rm -rf ${r}`,s.info(`\u{1F5D1}\uFE0F Removed worktree folder: ${r}`),s.info("")),n},$t=e=>{if(e.length>0){s.info("\u274C Removed worktrees:");for(let r of e)s.info(r);s.info("")}else s.info("\u2139\uFE0F No unused worktrees to remove")},Ge={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:ae.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:ae.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:ae.array(ae.string()).describe("List of removed git worktree branches"),count:ae.number().describe("Number of git worktrees removed")},handler:Nr};import At from"@inquirer/confirm";import St from"node:process";import{z as He}from"zod";import{$ as It}from"zx";var Nt="release/v",Or=async e=>{let{confirmedCommand:r}=e;l.start("worktrees-sync");try{let t=await I("release"),o=`${await E()}${B}`,a=await ge(),i=r?!0:await At({message:"Are you sure you want to proceed with these worktree changes?"});r||l.setInteractive(),i||(s.info("Operation cancelled. Exiting..."),St.exit(0)),r||l.addOption("--yes",!0);let{branchesToRemove:p}=Ot({releasePRsList:a,currentWorktrees:t}),c=await _t(p,o);Dt(c),l.print();let m={removedWorktrees:c,count:c.length};return{content:[{type:"text",text:JSON.stringify(m,null,2)}],structuredContent:m}}catch(t){throw s.error({error:t},"\u274C Error managing worktrees"),t}},Ot=e=>{let{releasePRsList:r,currentWorktrees:t}=e;return{branchesToRemove:t.filter(a=>a.startsWith(Nt)).filter(a=>!r.includes(a))}},_t=async(e,r)=>{let t=[];for(let n of e)try{let o=`${r}/${n}`;await It`git worktree remove ${o}`,t.push(n)}catch(o){s.error({error:o,branch:n},`\u274C Failed to remove worktree for ${n}`)}return t},Dt=e=>{if(e.length>0){s.info("\u274C Removed worktrees:");for(let r of e)s.info(r);s.info("")}else s.info("\u2139\uFE0F No unused worktrees to remove")},ze={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:He.array(He.string()).describe("List of removed worktree branches"),count:He.number().describe("Number of worktrees removed during sync")},handler:Or};var Ke=e=>async r=>{let{toolName:t,handler:n}=e;s.info({msg:`Tool execution started: ${t}`,params:r});try{let o=await n({...r,confirmedCommand:!0});return s.info({msg:`Tool execution successful: ${t}`}),o}catch(o){throw s.error({err:o,params:r,msg:`Tool execution failed: ${t}`}),o}};var Mt=[Ee,ke,Pe,xe,Ie,Ve,Fe,Oe,De,Je,je,We,qe,Ge,ze],_r=async e=>{for(let r of Mt)e.registerTool(r.name,{description:r.description,inputSchema:r.inputSchema,outputSchema:r.outputSchema},Ke({toolName:r.name,handler:r.handler}))};async function Dr(){let e=new Jt({name:"infra-kit",version:"1.0.0"},{capabilities:{resources:{},tools:{},prompts:{}}});return await er(e),await rr(e),await _r(e),e}var M=Ze(),Lt=async()=>{let e;try{e=await Dr(),M.info("MCP Server instance created")}catch(r){M.error({err:r,msg:"Failed to create MCP server"}),M.error("Fatal error during server creation."),Mr.exit(1)}try{let r=new jt;await e.connect(r),M.info({msg:"Server connected to transport. Ready."})}catch(r){M.error({err:r,msg:"Failed to initialize server"}),M.error("Fatal error during server transport init."),Mr.exit(1)}};Qe(M);Lt();
32
+ `);let p={worktrees:o,count:o.length};return{content:[{type:"text",text:JSON.stringify(p,null,2)}],structuredContent:p}},Ue={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:X.array(X.object({version:X.string().describe("Release version"),type:X.enum(["regular","hotfix"]).describe("Release type"),description:X.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:X.number().describe("Number of worktrees")},handler:Nr};import St from"@inquirer/checkbox";import At from"@inquirer/confirm";import Nt from"node:process";import{z as le}from"zod";import{$ as Ge}from"zx";var Or=async e=>{let{confirmedCommand:r,all:t,versions:n}=e;l.start("worktrees-remove");try{let o=await A("release");if(o.length===0)return s.info("\u2139\uFE0F No active worktrees to remove"),l.print(),{content:[{type:"text",text:JSON.stringify({removedWorktrees:[],count:0},null,2)}],structuredContent:{removedWorktrees:[],count:0}};let a=`${await P()}${q}`,p=[];if(t)p=o;else if(n)p=n.split(",").map(h=>`release/v${h.trim()}`);else{l.setInteractive();let[h,d]=await Promise.all([y(),v()]),x=new Map(d.map(I=>[I.branch,g(I.title)]));p=await St({required:!0,message:"\u{1F33F} Select release branches",choices:T({branches:o,descriptions:h,types:x})})}p.length===o.length?l.addOption("--all",!0):l.addOption("--versions",p.map(h=>h.replace("release/v","")));let m=r?!0:await At({message:"Are you sure you want to proceed with these worktree changes?"});r||l.setInteractive(),m||(s.info("Operation cancelled. Exiting..."),Nt.exit(0)),r||l.addOption("--yes",!0);let u=await Ot(p,a);_t(u),l.print();let f={removedWorktrees:u,count:u.length};return{content:[{type:"text",text:JSON.stringify(f,null,2)}],structuredContent:f}}catch(o){throw s.error({error:o},"\u274C Error managing worktrees"),o}},Ot=async(e,r)=>{let t=await Promise.allSettled(e.map(async o=>{let i=`${r}/${o}`;return await Ge`git worktree remove ${i}`,o})),n=[];for(let[o,i]of t.entries())if(i.status==="fulfilled")n.push(i.value);else{let a=e[o];s.error({error:i.reason},`\u274C Failed to remove worktree for ${a}`)}return n.length===e.length&&(await Ge`git worktree prune`,await Ge`rm -rf ${r}`,s.info(`\u{1F5D1}\uFE0F Removed worktree folder: ${r}`),s.info("")),n},_t=e=>{if(e.length>0){s.info("\u274C Removed worktrees:");for(let r of e)s.info(r);s.info("")}else s.info("\u2139\uFE0F No unused worktrees to remove")},Ke={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:le.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:le.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:le.array(le.string()).describe("List of removed git worktree branches"),count:le.number().describe("Number of git worktrees removed")},handler:Or};import Mt from"@inquirer/confirm";import Dt from"node:process";import{z as He}from"zod";import{$ as Jt}from"zx";var jt="release/v",_r=async e=>{let{confirmedCommand:r}=e;l.start("worktrees-sync");try{let t=await A("release"),o=`${await P()}${q}`,i=await ye(),a=r?!0:await Mt({message:"Are you sure you want to proceed with these worktree changes?"});r||l.setInteractive(),a||(s.info("Operation cancelled. Exiting..."),Dt.exit(0)),r||l.addOption("--yes",!0);let{branchesToRemove:p}=Lt({releasePRsList:i,currentWorktrees:t}),c=await Vt(p,o);Ft(c),l.print();let m={removedWorktrees:c,count:c.length};return{content:[{type:"text",text:JSON.stringify(m,null,2)}],structuredContent:m}}catch(t){throw s.error({error:t},"\u274C Error managing worktrees"),t}},Lt=e=>{let{releasePRsList:r,currentWorktrees:t}=e;return{branchesToRemove:t.filter(i=>i.startsWith(jt)).filter(i=>!r.includes(i))}},Vt=async(e,r)=>{let t=[];for(let n of e)try{let o=`${r}/${n}`;await Jt`git worktree remove ${o}`,t.push(n)}catch(o){s.error({error:o,branch:n},`\u274C Failed to remove worktree for ${n}`)}return t},Ft=e=>{if(e.length>0){s.info("\u274C Removed worktrees:");for(let r of e)s.info(r);s.info("")}else s.info("\u2139\uFE0F No unused worktrees to remove")},ze={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:He.array(He.string()).describe("List of removed worktree branches"),count:He.number().describe("Number of worktrees removed during sync")},handler:_r};var Ye=e=>async r=>{let{toolName:t,handler:n}=e;s.info({msg:`Tool execution started: ${t}`,params:r});try{let o=await n({...r,confirmedCommand:!0});return s.info({msg:`Tool execution successful: ${t}`}),o}catch(o){throw s.error({err:o,params:r,msg:`Tool execution failed: ${t}`}),o}};var Bt=[Ie,Ce,$e,xe,Ne,Fe,Be,_e,De,je,Le,qe,Ue,Ke,ze],Mr=async e=>{for(let r of Bt)e.registerTool(r.name,{description:r.description,inputSchema:r.inputSchema,outputSchema:r.outputSchema},Ye({toolName:r.name,handler:r.handler}))};async function Dr(){let e=new Wt({name:"infra-kit",version:"1.0.0"},{capabilities:{resources:{},tools:{},prompts:{}}});return await rr(e),await tr(e),await Mr(e),e}var j=Qe(),Ut=async()=>{let e;try{e=await Dr(),j.info("MCP Server instance created")}catch(r){j.error({err:r,msg:"Failed to create MCP server"}),j.error("Fatal error during server creation."),Jr.exit(1)}try{let r=new qt;await e.connect(r),j.info({msg:"Server connected to transport. Ready."})}catch(r){j.error({err:r,msg:"Failed to initialize server"}),j.error("Fatal error during server transport init."),Jr.exit(1)}};er(j);Ut();
33
33
  //# sourceMappingURL=mcp.js.map