infra-kit 0.1.82 → 0.1.87

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.
Files changed (35) hide show
  1. package/.eslintcache +1 -0
  2. package/.turbo/turbo-eslint-check.log +4 -0
  3. package/.turbo/turbo-prettier-check.log +4 -0
  4. package/.turbo/turbo-prettier-fix.log +10 -0
  5. package/.turbo/turbo-test.log +14 -0
  6. package/.turbo/turbo-ts-check.log +4 -0
  7. package/dist/cli.js +27 -25
  8. package/dist/cli.js.map +4 -4
  9. package/dist/mcp.js +24 -22
  10. package/dist/mcp.js.map +4 -4
  11. package/package.json +12 -13
  12. package/src/commands/env-clear/env-clear.ts +2 -1
  13. package/src/commands/env-list/env-list.ts +2 -1
  14. package/src/commands/env-load/env-load.ts +5 -2
  15. package/src/commands/env-status/env-status.ts +2 -1
  16. package/src/commands/gh-merge-dev/gh-merge-dev.ts +10 -4
  17. package/src/commands/gh-release-deliver/gh-release-deliver.ts +3 -2
  18. package/src/commands/gh-release-deploy-all/gh-release-deploy-all.ts +13 -4
  19. package/src/commands/gh-release-deploy-selected/gh-release-deploy-selected.ts +18 -5
  20. package/src/commands/gh-release-list/gh-release-list.ts +2 -1
  21. package/src/commands/release-create/release-create.ts +3 -2
  22. package/src/commands/release-create-batch/release-create-batch.ts +5 -2
  23. package/src/commands/worktrees-add/worktrees-add.ts +26 -5
  24. package/src/commands/worktrees-list/worktrees-list.ts +2 -1
  25. package/src/commands/worktrees-remove/worktrees-remove.ts +14 -3
  26. package/src/commands/worktrees-sync/worktrees-sync.ts +2 -1
  27. package/src/entry/cli.ts +0 -18
  28. package/src/lib/command-echo/command-echo.ts +1 -1
  29. package/src/lib/release-utils/release-utils.ts +2 -1
  30. package/src/mcp/server.ts +1 -1
  31. package/src/mcp/tools/index.ts +0 -2
  32. package/tsconfig.tsbuildinfo +1 -0
  33. package/.env.example +0 -17
  34. package/src/commands/gh-release-deploy-service/gh-release-deploy-service.ts +0 -193
  35. package/src/commands/gh-release-deploy-service/index.ts +0 -1
package/dist/mcp.js CHANGED
@@ -1,31 +1,33 @@
1
- import{StdioServerTransport as Ht}from"@modelcontextprotocol/sdk/server/stdio.js";import Br from"node:process";import O from"node:process";import tr from"node:process";import we from"pino";import Ur from"pino-pretty";var Y="/tmp/mcp-infra-kit.log",or=()=>{let e=tr.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},qr=()=>{let e=tr.argv.includes("--debug")?"debug":"info",r=["time","pid","hostname"];return e==="debug"&&r.push("level"),we({level:e},Ur({destination:2,ignore:r.join(","),colorize:!0}))},s=qr();var sr=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 ${Y}. 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 ${Y}. Shutting down...`),e.flush(),O.exit(1)})};import{McpServer as zt}from"@modelcontextprotocol/sdk/server/mcp.js";var nr=async e=>{};var ir=async e=>{};import pe from"node:fs";import lr from"node:path";import Kr from"node:process";import{z as me}from"zod";import ar from"node:fs";import Gr from"node:path";import zr from"node:process";var k=["dev","arthur","renana","roman","eliran","oriana"],be={"hulyo-monorepo":"hulyo","travelist-monorepo":"travelist"},Hr="./node_modules/.cache/infra-kit",L="env-load.sh",cr="env-clear.sh",xe="INFRA_KIT_SESSION",V="INFRA_KIT_ENV_CONFIG",M="INFRA_KIT_ENV_PROJECT",F="INFRA_KIT_ENV_LOADED_AT",le=e=>ar.existsSync(e)?ar.readFileSync(e,"utf-8").split(`
2
- `).filter(t=>t.includes("=")&&!t.startsWith("set ")).map(t=>t.split("=")[0]):[],B=()=>{let e=zr.env[xe];if(!e)throw new Error("INFRA_KIT_SESSION is not set. Run `source ~/.zshrc` or `infra-kit init` first.");return Gr.join(Hr,e)},W="-worktrees";var pr=async()=>{let e=B(),r=lr.join(e,L);if(!pe.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=le(r),n=[...t.map(a=>`unset ${a}`),`unset ${V}`,`unset ${M}`,`unset ${F}`],o=lr.resolve(e,cr);pe.mkdirSync(e,{recursive:!0}),pe.writeFileSync(o,`${n.join(`
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(`
3
3
  `)}
4
- `),Kr.stdout.write(`${o}
5
- `),pe.unlinkSync(r);let i={variableCount:t.length,unsetStatements:n};return{content:[{type:"text",text:JSON.stringify(i,null,2)}],structuredContent:i}},Te={name:"env-clear",description:"Clear loaded env vars. Returns a file path that must be sourced (source <path>) to apply. The env-clear shell alias does this automatically.",inputSchema:{},outputSchema:{filePath:me.string().describe("Path to the file that must be sourced to apply"),variableCount:me.number().describe("Number of variables cleared"),unsetStatements:me.array(me.string()).describe("Unset statements generated")},handler:pr};import{z as ke}from"zod";import mr from"node:process";import{$ as ur}from"zx";var D=async()=>{try{await ur`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"),mr.exit(1)}try{await ur`doppler me`}catch(e){s.error({error:e},"Error: Doppler CLI is not authenticated."),s.error("Please authenticate by running: doppler login"),mr.exit(1)}};import Zr from"node:path";import{$ as dr}from"zx";var N=async e=>{let t=(await dr`git worktree list`).stdout.split(`
6
- `).filter(Boolean),n={release:Xr,feature:Yr};return t.map(n[e]).filter(o=>o!==null)},Xr=e=>{let r=e.split(" ").filter(Boolean);return r.length<3||!r[0]?.includes("release/v")?null:`release/${r[0]?.split("/").pop()||""}`},Yr=e=>{let r=e.split(" ").filter(Boolean);return r.length<3||!r[0]?.includes("feature/")?null:`feature/${r[0]?.split("/").pop()||""}`},E=async()=>(await dr`git rev-parse --show-toplevel`).stdout.trim();var Z=async()=>{let e=await E(),r=Zr.basename(e),t=be[r];if(!t)throw new Error(`Could not determine Doppler project for directory "${r}". Expected one of: ${Object.keys(be).join(", ")}`);return t};var fr=async()=>{await D();let e=await Z();s.info(`Doppler project: ${e}
7
- `),s.info("Available configs:");for(let t of k)s.info(` - ${t}`);let r={project:e,configs:k};return{content:[{type:"text",text:JSON.stringify(r,null,2)}],structuredContent:r}},$e={name:"env-list",description:"List available Doppler configs for the detected project",inputSchema:{},outputSchema:{project:ke.string().describe("Detected Doppler project name"),configs:ke.array(ke.string()).describe("Available environment configs")},handler:fr};import et from"@inquirer/select";import gr from"node:fs";import rt from"node:path";import hr from"node:process";import{z as Q}from"zod";import{$ as Ee}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:
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:
8
8
  pnpm exec infra-kit ${e} ${n}
9
- `)},reset(){e="",r=[],t=!1}}},c=Qr();var vr=async e=>{await D();let{config:r}=e;c.start("env-load");let t="";r?t=r:(c.setInteractive(),t=await et({message:"Select environment config",choices:k.map(f=>({name:f,value:f}))},{output:hr.stderr})),c.addOption("--config",t);let n=await Z();Ee.quiet=!0;let o=await Ee`doppler secrets download --no-file --format env --project ${n} --config ${t}`;Ee.quiet=!1;let i=o.stdout.trim(),a=new Date().toISOString(),p=["set -a",i,`${V}=${t}`,`${M}=${n}`,`${F}=${a}`,"set +a"],l=B(),m=rt.resolve(l,L);gr.mkdirSync(l,{recursive:!0}),gr.writeFileSync(m,`${p.join(`
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(`
10
10
  `)}
11
- `),hr.stdout.write(`${m}
12
- `);let u={variableCount:i.split(`
13
- `).filter(f=>f.includes("=")).length,project:n,config:t};return{content:[{type:"text",text:JSON.stringify(u,null,2)}],structuredContent:u}},Ce={name:"env-load",description:"Load Doppler env vars for a config. Returns a file path that must be sourced (source <path>) to apply variables. The env-load shell alias does this automatically.",inputSchema:{config:Q.string().describe("Environment config name to load (e.g. dev, arthur, renana)")},outputSchema:{filePath:Q.string().describe("Path to the file that must be sourced to apply variables"),variableCount:Q.number().describe("Number of variables loaded"),project:Q.string().describe("Doppler project name"),config:Q.string().describe("Doppler config name")},handler:vr};import tt from"node:path";import ee from"node:process";import{z as U}from"zod";var yr=async()=>{await D(),s.info("Environment session status:");let e=B(),r=ee.env[xe],t=tt.join(e,L),n=0,o=0,i=ee.env[V]??null,a=ee.env[M]??null,p=ee.env[F]??null;if(i){let m=le(t);m.length>0&&(o=m.length,n=m.filter(u=>u in ee.env).length);let d=p?.replace(/\.\d{3}Z$/,"")??null;s.info(` ${i}: ${n} of ${o} vars loaded (project: ${a}, loadedAt: ${d}, session: ${r})
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})
14
14
  `)}else s.info(` Session ${r}: no env loaded
15
- `);let l={sessionId:r,sessionLoadedCount:n,sessionTotalCount:o,sessionConfig:i,sessionProject:a,sessionLoadedAt:p};return{content:[{type:"text",text:JSON.stringify(l,null,2)}],structuredContent:l}},Se={name:"env-status",description:"Show Doppler authentication status and detected project info",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:yr};import it from"@inquirer/checkbox";import at from"@inquirer/confirm";import ct from"node:process";import{z}from"zod";import{$ as A}from"zx";import{$ as gs}from"zx";import he from"node:process";import{$ as C}from"zx";import{$ as oe}from"zx";import re from"node:process";var Ae=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`,l=btoa(`${o}:${n}`),m=await fetch(p,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${l}`},body:JSON.stringify(a)});if(!m.ok){let u=await m.text();throw s.error({status:m.status,statusText:m.statusText,error:u},"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}},ue=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 ue(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}`),l=await fetch(a,{method:"PUT",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${p}`},body:JSON.stringify(i)});if(!l.ok){let d=await l.text();throw s.error({status:l.status,statusText:l.statusText,error:d},"Failed to update Jira version"),new Error(`HTTP ${l.status}: ${l.statusText}`)}return{success:!0,version:await l.json()}}catch(t){throw s.error({error:t},"Error updating Jira version"),t}},Ie=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}},q=async()=>{let e=re.env.JIRA_BASE_URL,r=re.env.JIRA_TOKEN||re.env.JIRA_API_TOKEN,t=re.env.JIRA_PROJECT_ID,n=re.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}},te=async()=>{try{return await q()}catch(e){return s.warn({error:e},"Jira configuration not available, skipping Jira integration"),null}};var de=e=>e==="hotfix"?"main":"dev",se=async(e="regular")=>{let r=de(e);oe.quiet=!0,await oe`git fetch origin`,await oe`git switch ${r}`,await oe`git pull origin ${r}`,oe.quiet=!1},ne=async e=>{let{version:r,jiraConfig:t,description:n,type:o="regular"}=e,i=`v${r}`,a=await Ae({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`,l=await fe({version:r,jiraVersionUrl:p,type:o});return{version:r,type:o,branchName:l.branchName,prUrl:l.prUrl,jiraVersionUrl:p}},y=async()=>{let e=new Map,r=await te();if(!r)return e;try{let t=await ue(r);for(let n of t)n.description&&e.set(n.name,n.description)}catch{}return e},G=(e,r,t)=>{let n=t?" ".repeat(t-e.length+3):" ";return`${e}${n}[${r}]`},h=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",x=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 l=o[p],m=n?n.get(a)||"regular":void 0,d=t.get(`v${l}`),u=" ".repeat(i-l.length+3),f=m?G(l,m,i):l;return d&&(f=m?`${f} ${d}`:`${l}${u}${d}`),{name:f,value:a}})};var Pe=e=>e.replace("release/","").slice(1).split(".").map(Number),ge=e=>[...e].sort((r,t)=>{let[n,o,i]=Pe(r),[a,p,l]=Pe(t);return n!==a?(n??0)-(a??0):o!==p?(o??0)-(p??0):(i??0)-(l??0)});var Rr=async()=>{let e=await C`gh pr list --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName`,r=await C`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))},ve=async()=>{try{let e=await Rr();return e.length===0&&(s.error("\u274C No release PRs found. Check the project folder for the script. Exiting..."),he.exit(1)),ge(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 Rr();e.length===0&&(s.error("\u274C No release PRs found. Check the project folder for the script. Exiting..."),he.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"),he.exit(1)}},fe=async e=>{let{version:r,jiraVersionUrl:t,type:n}=e,o=n==="hotfix"?"Hotfix":"Release",i=de(n),a=`release/v${r}`;try{C.quiet=!0,await C`git switch ${i}`,await C`git pull origin ${i}`,await C`git checkout -b ${a}`,await C`git push -u origin ${a}`,await C`git commit --allow-empty-message --allow-empty --message ''`,await C`git push origin ${a}`;let l=(await C`gh pr create --title "${o} v${r}" --body "${t} \n" --base ${i} --head ${a}`).stdout.trim();return await C`git switch ${i}`,C.quiet=!1,{branchName:a,prUrl:l}}catch(p){throw s.error({error:p,branchName:a},`Error creating release branch ${a}`),p}};var wr=async e=>{let{all:r,confirmedCommand:t}=e;c.start("merge-dev");let o=(await v()).filter(d=>h(d.title)==="regular").map(d=>d.branch);if(o.length===0)return s.info("\u2139\uFE0F No open release branches found"),c.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{c.setInteractive();let d=await y();i=await it({required:!0,message:"\u{1F33F} Select release branches",choices:x({branches:o,descriptions:d})})}i.length===o.length?c.addOption("--all",!0):c.addOption("--versions",i.map(d=>d.replace("release/v","")));let p=t?!0:await at({message:`Are you sure you want to merge dev into these branches: ${i.join(", ")}?`});t||c.setInteractive(),p||(s.info("Operation cancelled. Exiting..."),ct.exit(0)),t||c.addOption("--yes",!0),A.quiet=!0,await A`git fetch origin`,await A`git switch dev`,await A`git pull origin dev`;let l=[];for(let d of i)await lt(d)||l.push(d);if(A.quiet=!1,l.length>0){s.info(`
17
- \u26A0\uFE0F ${l.length} branch(es) failed to merge automatically.
18
- `),s.info("\u{1F4CB} Manual merge script for failed branches:");for(let d of l)s.info(`# Merge dev into ${d} and resolve conflicts if any
19
- git switch ${d} && git pull origin ${d} && git merge origin/dev
20
- git push origin ${d} && git switch dev
21
- `);s.info(`\u2705 ${i.length-l.length}/${i.length} merges completed successfully.`)}else s.info("\u2705 All merges completed successfully!");c.print();let m={successfulMerges:i.length-l.length,failedMerges:l.length,failedBranches:l,totalBranches:i.length};return{content:[{type:"text",text:JSON.stringify(m,null,2)}],structuredContent:m}},lt=async e=>{try{return await A`git switch ${e}`,await A`git pull origin ${e}`,await A`git merge origin/dev --no-edit`,await A`git push origin ${e}`,await A`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 A`git reset --merge HEAD~1`,!1}},Ne={name:"gh-merge-dev",description:"Merge dev branch into selected release branches",inputSchema:{all:z.boolean().describe("Merge dev into all release branches without prompting")},outputSchema:{successfulMerges:z.number().describe("Number of successful merges"),failedMerges:z.number().describe("Number of failed merges"),failedBranches:z.array(z.string()).describe("List of branches that failed to merge"),totalBranches:z.number().describe("Total number of branches processed")},handler:wr};import pt from"@inquirer/confirm";import mt from"@inquirer/select";import Oe from"node:process";import{z as ie}from"zod";import{$}from"zx";var br=async e=>{let{version:r,confirmedCommand:t}=e;c.start("release-deliver");let n=await v(),o=n.map(u=>u.branch),i=new Map(n.map(u=>[u.branch,h(u.title)])),a="";if(r)a=`release/v${r}`;else{c.setInteractive();let u=await y();a=await mt({message:"\u{1F33F} Select release branch",choices:x({branches:o,descriptions:u,types:i})})}let p=a.replace("release/v","");c.addOption("--version",p);let l=n.find(u=>u.branch===a);l||(s.error(`\u274C Release branch ${a} not found in open PRs. Exiting...`),Oe.exit(1));let m=h(l.title),d=t?!0:await pt({message:`Are you sure you want to deliver version ${a} to production?`});t||c.setInteractive(),d||(s.info("Operation cancelled. Exiting..."),Oe.exit(0)),c.addOption("--yes",!0);try{$.quiet=!0,m==="hotfix"?(await $`gh pr merge ${a} --squash --admin --delete-branch`,$.quiet=!1,await $`gh workflow run deploy-all.yml --ref main -f environment=prod`,$.quiet=!0,await $`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`):(await $`gh pr merge ${a} --squash --admin --delete-branch`,await $`gh pr create --base main --head dev --title "Release v${p} (RC)" --body ""`,await $`gh pr merge dev --squash --admin`,$.quiet=!1,await $`gh workflow run deploy-all.yml --ref main -f environment=prod`,$.quiet=!0,await $`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`),$.quiet=!1;let u=await te();if(u)try{let g=a.replace("release/","");await Ie({versionName:g},u)}catch(g){s.error({error:g},"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!`),c.print();let f={releaseBranch:a,version:a.replace("release/v",""),type:m,success:!0};return{content:[{type:"text",text:JSON.stringify(f,null,2)}],structuredContent:f}}catch(u){s.error({error:u},"\u274C Error merging release branch into dev"),Oe.exit(1)}},_e={name:"gh-release-deliver",description:"Deliver a release branch to production",inputSchema:{version:ie.string().describe('Version to deliver to production (e.g., "1.2.5")')},outputSchema:{releaseBranch:ie.string().describe("The release branch that was delivered"),version:ie.string().describe("The version that was delivered"),type:ie.enum(["regular","hotfix"]).describe("Release type"),success:ie.boolean().describe("Whether the delivery was successful")},handler:br};import xr from"@inquirer/select";import Tr from"node:process";import{z as _}from"zod";import{$ as De}from"zx";var kr=async e=>{let{version:r,env:t,skipTerraform:n}=e;c.start("release-deploy-all");let o="";if(r)o=r==="dev"?"dev":`release/v${r}`;else{c.setInteractive();let l=await v(),m=l.map(f=>f.branch),d=new Map(l.map(f=>[f.branch,h(f.title)])),u=await y();o=await xr({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...x({branches:m,descriptions:u,types:d})]})}let i=o==="dev"?"dev":o.replace("release/v","");c.addOption("--version",i);let a="";t?a=t:(c.setInteractive(),a=await xr({message:"\u{1F9EA} Select environment",choices:k.map(l=>({name:l,value:l}))})),c.addOption("--env",a),k.includes(a)||(s.error(`\u274C Invalid environment: ${a}. Exiting...`),Tr.exit(1));let p=n??!1;p&&c.addOption("--skip-terraform",!0);try{De.quiet=!0,await De`gh workflow run deploy-all.yml --ref ${o} -f environment=${a} ${p?["-f","skip_terraform_deploy=true"]:[]}`,De.quiet=!1,s.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${o} and environment: ${a}`),c.print();let m={releaseBranch:o,version:o.replace("release/v",""),environment:a,skipTerraformDeploy:p,success:!0};return{content:[{type:"text",text:JSON.stringify(m,null,2)}],structuredContent:m}}catch(l){s.error({error:l},"\u274C Error launching workflow"),Tr.exit(1)}},Je={name:"gh-release-deploy-all",description:"Deploy a release branch to a specified environment",inputSchema:{version:_.string().describe('Version to deploy (e.g., "1.2.5")'),env:_.string().describe('Environment to deploy to (e.g., "dev", "renana", "oriana")'),skipTerraform:_.boolean().optional().describe("Skip terraform deployment step")},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:kr};import ut from"@inquirer/checkbox";import $r from"@inquirer/select";import dt from"node:fs/promises";import{resolve as ft}from"node:path";import ae from"node:process";import gt from"yaml";import{z as S}from"zod";import{$ as je}from"zx";var Er=async e=>{let{version:r,env:t,services:n,skipTerraform:o}=e;c.start("release-deploy-selected");let i="";if(r)i=r==="dev"?"dev":`release/v${r}`;else{c.setInteractive();let f=await v(),g=f.map(b=>b.branch),R=new Map(f.map(b=>[b.branch,h(b.title)])),T=await y();i=await $r({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...x({branches:g,descriptions:T,types:R})]})}let a=i==="dev"?"dev":i.replace("release/v","");c.addOption("--version",a);let p="";t?p=t:(c.setInteractive(),p=await $r({message:"\u{1F9EA} Select environment",choices:k.map(f=>({name:f,value:f}))})),c.addOption("--env",p),k.includes(p)||(s.error(`\u274C Invalid environment: ${p}. Exiting...`),ae.exit(1));let l=await ht();l.length===0&&(s.error("\u274C No services found in workflow file. Exiting..."),ae.exit(1));let m=[];n&&n.length>0?m=n:(c.setInteractive(),m=await ut({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:l.map(f=>({name:f,value:f}))})),c.addOption("--services",m),m.length===0&&(s.error("\u274C No services selected. Exiting..."),ae.exit(1));let d=m.filter(f=>!l.includes(f));d.length>0&&(s.error(`\u274C Invalid services: ${d.join(", ")}. Available services: ${l.join(", ")}`),ae.exit(1));let u=o??!1;u&&c.addOption("--skip-terraform",!0);try{je.quiet=!0;let f=m.flatMap(T=>["-f",`${T}=true`]);await je`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${p} ${f} ${u?["-f","skip_terraform_deploy=true"]:[]}`,je.quiet=!1,s.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${p}, services: ${m.join(", ")}`),c.print();let R={releaseBranch:i,version:i.replace("release/v",""),environment:p,services:m,skipTerraformDeploy:u,success:!0};return{content:[{type:"text",text:JSON.stringify(R,null,2)}],structuredContent:R}}catch(f){s.error({error:f},"\u274C Error launching workflow"),ae.exit(1)}},ht=async()=>{let e=await E(),r=ft(e,".github/workflows/deploy-selected-services.yml"),t=await dt.readFile(r,"utf-8"),o=gt.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},Le={name:"gh-release-deploy-selected",description:"Deploy selected services from a release branch to a specified environment",inputSchema:{version:S.string().describe('Version to deploy (e.g., "1.2.5")'),env:S.string().describe('Environment to deploy to (e.g., "dev", "renana", "oriana")'),services:S.array(S.string()).describe('List of services to deploy (e.g., ["client-be", "client-fe"])'),skipTerraform:S.boolean().optional().describe("Skip terraform deployment step")},outputSchema:{releaseBranch:S.string().describe("The release branch that was deployed"),version:S.string().describe("The version that was deployed"),environment:S.string().describe("The environment deployed to"),services:S.array(S.string()).describe("The services that were deployed"),skipTerraformDeploy:S.boolean().describe("Whether terraform deployment was skipped"),success:S.boolean().describe("Whether the deployment was successful")},handler:Er};import Ve from"@inquirer/select";import vt from"node:fs/promises";import{resolve as yt}from"node:path";import Me from"node:process";import Rt from"yaml";import{z as I}from"zod";import{$ as Fe}from"zx";var Cr=async e=>{let{version:r,env:t,service:n,skipTerraform:o}=e;c.start("release-deploy-service");let i="";if(r)i=r==="dev"?"dev":`release/v${r}`;else{c.setInteractive();let u=await v(),f=u.map(T=>T.branch),g=new Map(u.map(T=>[T.branch,h(T.title)])),R=await y();i=await Ve({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...x({branches:f,descriptions:R,types:g})]})}let a=i==="dev"?"dev":i.replace("release/v","");c.addOption("--version",a);let p="";t?p=t:(c.setInteractive(),p=await Ve({message:"\u{1F9EA} Select environment",choices:k.map(u=>({name:u,value:u}))})),c.addOption("--env",p),k.includes(p)||(s.error(`\u274C Invalid environment: ${p}. Exiting...`),Me.exit(1));let l=await wt(),m="";n?m=n:(c.setInteractive(),m=await Ve({message:"\u{1F680} Select service to deploy",choices:l.map(u=>({name:u,value:u}))})),c.addOption("--service",m),l.includes(m)||(s.error(`\u274C Invalid service: ${m}. Available services: ${l.join(", ")}`),Me.exit(1));let d=o??!1;d&&c.addOption("--skip-terraform",!0);try{Fe.quiet=!0,await Fe`gh workflow run deploy-single-service.yml --ref ${i} -f environment=${p} -f service=${m} ${d?["-f","skip_terraform_deploy=true"]:[]}`,Fe.quiet=!1,s.info(`Successfully launched deploy-single-service workflow_dispatch for release branch: ${i}, environment: ${p}, service: ${m}`),c.print();let f={releaseBranch:i,version:i.replace("release/v",""),environment:p,service:m,skipTerraformDeploy:d,success:!0};return{content:[{type:"text",text:JSON.stringify(f,null,2)}],structuredContent:f}}catch(u){s.error({error:u},"\u274C Error launching workflow"),Me.exit(1)}},wt=async()=>{let e=await E(),r=yt(e,".github/workflows/deploy-single-service.yml"),t=await vt.readFile(r,"utf-8");return Rt.parse(t).on.workflow_dispatch.inputs.service.options},Be={name:"gh-release-deploy-service",description:"Deploy a specific service in a release branch to a specified environment",inputSchema:{version:I.string().describe('Version to deploy (e.g., "1.2.5")'),env:I.string().describe('Environment to deploy to (e.g., "dev", "renana", "oriana")'),service:I.string().describe('Service to deploy (e.g., "client-be", "client-fe")'),skipTerraform:I.boolean().optional().describe("Skip terraform deployment step")},outputSchema:{releaseBranch:I.string().describe("The release branch that was deployed"),version:I.string().describe("The version that was deployed"),environment:I.string().describe("The environment deployed to"),service:I.string().describe("The service that was deployed"),skipTerraformDeploy:I.boolean().describe("Whether terraform deployment was skipped"),success:I.boolean().describe("Whether the deployment was successful")},handler:Cr};import{z as H}from"zod";var Sr=async()=>{let r=(await v()).map(a=>({version:a.branch.replace("release/",""),type:h(a.title)})),t=await y(),n=Math.max(...r.map(a=>a.version.length)),o=r.map(a=>{let p=G(a.version,a.type,n),l=t.get(a.version);return l?`${p} ${l}`:p});s.info(`All release branches:
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(`
17
+ \u26A0\uFE0F ${c.length} branch(es) failed to merge automatically.
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
+
20
+ git switch ${u} && git pull origin ${u} && git merge origin/dev
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
24
  `),s.info(`
23
25
  ${o.join(`
24
26
  `)}
25
- `);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}},We={name:"gh-release-list",description:"List all open release branches",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:Sr};import Ar from"@inquirer/confirm";import bt from"@inquirer/select";import Ir from"node:process";import{z as P}from"zod";import{$ as Ue,question as Pr}from"zx";var Nr=async e=>{let{version:r,description:t,type:n,confirmedCommand:o,checkout:i}=e;c.start("release-create");let a=r,p=t,l=n||"regular",m=i,d=await q();a||(c.setInteractive(),a=await Pr("Enter version (e.g. 1.2.5): ")),(!a||a.trim()==="")&&(s.error("No version provided. Exiting..."),Ir.exit(1));let u=a.trim();c.addOption("--version",u),n||(c.setInteractive(),l=await bt({message:"Select release type:",choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"})),c.addOption("--type",l),p===void 0&&(c.setInteractive(),p=await Pr("Enter description (optional, press Enter to skip): "),p.trim()===""&&(p="")),p&&c.addOption("--description",p);let f=o?!0:await Ar({message:`Are you sure you want to create release branch for version ${u}?`});o||c.setInteractive(),f||(s.info("Operation cancelled. Exiting..."),Ir.exit(0)),c.addOption("--yes",!0),await se(l);let g=await ne({version:u,jiraConfig:d,description:p,type:l});s.info(`\u2705 Successfully created release: v${u}`),s.info(`\u{1F517} GitHub PR: ${g.prUrl}`),s.info(`\u{1F517} Jira Version: ${g.jiraVersionUrl}`),m===void 0&&(c.setInteractive(),m=await Ar({message:`Do you want to checkout to the created branch ${g.branchName}?`,default:!0})),m||c.addOption("--no-checkout",!0),m&&(Ue.quiet=!0,await Ue`git switch ${g.branchName}`,Ue.quiet=!1,s.info(`\u{1F504} Switched to branch ${g.branchName}`)),c.print();let R={version:u,type:l,branchName:g.branchName,prUrl:g.prUrl,jiraVersionUrl:g.jiraVersionUrl,isCheckedOut:m};return{content:[{type:"text",text:JSON.stringify(R,null,2)}],structuredContent:R}},qe={name:"release-create",description:"Create a single release branch for specified version with Jira version creation",inputSchema:{version:P.string().describe('Version to create (e.g., "1.2.5")'),description:P.string().optional().describe("Optional description for the Jira version"),type:P.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" or "hotfix" (default: "regular")'),checkout:P.boolean().optional().default(!0).describe("Checkout to the created branch (default: true)")},outputSchema:{version:P.string().describe("Version number"),type:P.enum(["regular","hotfix"]).describe("Release type"),branchName:P.string().describe("Release branch name"),prUrl:P.string().describe("GitHub PR URL"),jiraVersionUrl:P.string().describe("Jira version URL"),isCheckedOut:P.boolean().describe("Whether the branch was checked out")},handler:Nr};import xt from"@inquirer/confirm";import Tt from"@inquirer/select";import Or from"node:process";import{z as w}from"zod";import{question as kt}from"zx";var $t=async e=>{let{versions:r,type:t,confirmedCommand:n}=e,o=r,i=t||"regular";o||(c.setInteractive(),o=await kt("Enter versions by comma (e.g. 1.2.5, 1.2.6): "));let a=o.split(",").map(l=>l.trim()).filter(Boolean);c.addOption("--versions",a.join(", ")),a.length===0&&(s.error("No versions provided. Exiting..."),Or.exit(1)),t||(c.setInteractive(),i=await Tt({message:"Select release type:",choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"})),c.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 xt({message:`Are you sure you want to create release branches for these versions: ${a.join(", ")}?`});return n||c.setInteractive(),p||(s.info("Operation cancelled. Exiting..."),Or.exit(0)),c.addOption("--yes",!0),{versionsList:a,type:i}},_r=async e=>{c.start("release-create-batch");let r=await q(),{versionsList:t,type:n}=await $t(e);await se(n);let o=[],i=[];for(let m of t)try{let d=await ne({version:m,jiraConfig:r,type:n});o.push(d),s.info(`\u2705 Successfully created release: v${m}`),s.info(`\u{1F517} GitHub PR: ${d.prUrl}`),s.info(`\u{1F517} Jira Version: ${d.jiraVersionUrl}
26
- `)}catch(d){let u=d instanceof Error?d.message:String(d);i.push({version:m,error:u}),s.error(`\u274C Failed to create release: v${m}`),s.error(` Error: ${u}
27
- `)}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.`),c.print();let l={createdBranches:o.map(m=>m.branchName),successCount:a,failureCount:p,releases:o,failedReleases:i};return{content:[{type:"text",text:JSON.stringify(l,null,2)}],structuredContent:l}},Ge={name:"release-create-batch",description:"Create multiple release branches for specified versions with Jira version creation (batch operation)",inputSchema:{versions:w.string().describe('Comma-separated list of versions to create (e.g., "1.2.5, 1.2.6")'),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 Et from"@inquirer/checkbox";import ze from"@inquirer/confirm";import Ct from"node:process";import{z as J}from"zod";import{$ as K}from"zx";var St="feature",At="release",It="release/v",Jr=async e=>{let{confirmedCommand:r,all:t,versions:n,cursor:o,githubDesktop:i}=e;c.start("worktrees-add");try{let a=await N("release"),l=`${await E()}${W}`;await Dr(`${l}/${At}`),await Dr(`${l}/${St}`);let m=[];if(n)m=n.split(",").map(b=>`release/v${b.trim()}`);else{let b=await v(),ye=b.map(Re=>Re.branch);if(ye.length===0)return s.info("\u2139\uFE0F No open release branches found"),c.print(),{content:[{type:"text",text:JSON.stringify({createdWorktrees:[],count:0},null,2)}],structuredContent:{createdWorktrees:[],count:0}};if(t)m=ye;else{c.setInteractive();let Re=new Map(b.map(rr=>[rr.branch,h(rr.title)])),Wr=await y();m=await Et({required:!0,message:"\u{1F33F} Select release branches",choices:x({branches:ye,descriptions:Wr,types:Re})})}}t?c.addOption("--all",!0):c.addOption("--versions",m.map(b=>b.replace("release/v","")));let d=r?!0:await ze({message:"Are you sure you want to proceed with these worktree changes?"});r||c.setInteractive(),d||(s.info("Operation cancelled. Exiting..."),Ct.exit(0)),r||c.addOption("--yes",!0);let u=o??await ze({message:"Open created worktrees in Cursor?"});typeof o>"u"&&c.setInteractive(),u?c.addOption("--cursor",!0):c.addOption("--no-cursor",!0);let f=i??await ze({message:"Open created worktrees in GitHub Desktop?"});typeof i>"u"&&c.setInteractive(),f?c.addOption("--github-desktop",!0):c.addOption("--no-github-desktop",!0);let{branchesToCreate:g}=Pt({selectedReleaseBranches:m,currentWorktrees:a}),R=await Nt(g,l);if(Ot(R),u)for(let b of R)await K`cursor ${l}/${b}`;if(f)for(let b of R)await K`github ${l}/${b}`,await K`sleep 5`;c.print();let T={createdWorktrees:R,count:R.length};return{content:[{type:"text",text:JSON.stringify(T,null,2)}],structuredContent:T}}catch(a){throw s.error({error:a},"\u274C Error managing worktrees"),a}},Dr=async e=>{await K`mkdir -p ${e}`},Pt=e=>{let{selectedReleaseBranches:r,currentWorktrees:t}=e,n=t.filter(i=>i.startsWith(It));return{branchesToCreate:r.filter(i=>!n.includes(i))}},Nt=async(e,r)=>{let t=await Promise.allSettled(e.map(async o=>{let i=`${r}/${o}`;return await K`git worktree add ${i} ${o}`,await K({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},Ot=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")},He={name:"worktrees-add",description:"Create git worktrees for selected release branches",inputSchema:{all:J.boolean().describe("Add git worktrees for all release branches without prompting"),versions:J.string().optional().describe("Specify versions by comma, e.g. 1.2.5, 1.2.6"),cursor:J.boolean().optional().describe("Open created git worktrees in Cursor"),githubDesktop:J.boolean().optional().describe("Open created git worktrees in GitHub Desktop")},outputSchema:{createdWorktrees:J.array(J.string()).describe("List of created git worktree branches"),count:J.number().describe("Number of git worktrees created")},handler:Jr};import{z as X}from"zod";var jr=async()=>{let e=await N("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(l=>[l.branch,h(l.title)])),o=e.map(l=>{let m=l.replace("release/",""),d=n.get(l)||"regular",u=t.get(m)||null;return{version:m,type:d,description:u}}),i=Math.max(...o.map(l=>l.version.length)),a=o.map(l=>{let m=G(l.version,l.type,i);return l.description?`${m} ${l.description}`:m});s.info("\u{1F33F} Active worktrees:"),s.info(`
28
- ${a.join(`
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(`
29
31
  `)}
30
- `);let p={worktrees:o,count:o.length};return{content:[{type:"text",text:JSON.stringify(p,null,2)}],structuredContent:p}},Ke={name:"worktrees-list",description:"List all git worktrees with detailed information",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:jr};import _t from"@inquirer/checkbox";import Dt from"@inquirer/confirm";import Jt from"node:process";import{z as ce}from"zod";import{$ as Xe}from"zx";var Lr=async e=>{let{confirmedCommand:r,all:t,versions:n}=e;c.start("worktrees-remove");try{let o=await N("release");if(o.length===0)return s.info("\u2139\uFE0F No active worktrees to remove"),c.print(),{content:[{type:"text",text:JSON.stringify({removedWorktrees:[],count:0},null,2)}],structuredContent:{removedWorktrees:[],count:0}};let a=`${await E()}${W}`,p=[];if(t)p=o;else if(n)p=n.split(",").map(f=>`release/v${f.trim()}`);else{c.setInteractive();let[f,g]=await Promise.all([y(),v()]),R=new Map(g.map(T=>[T.branch,h(T.title)]));p=await _t({required:!0,message:"\u{1F33F} Select release branches",choices:x({branches:o,descriptions:f,types:R})})}p.length===o.length?c.addOption("--all",!0):c.addOption("--versions",p.map(f=>f.replace("release/v","")));let m=r?!0:await Dt({message:"Are you sure you want to proceed with these worktree changes?"});r||c.setInteractive(),m||(s.info("Operation cancelled. Exiting..."),Jt.exit(0)),r||c.addOption("--yes",!0);let d=await jt(p,a);Lt(d),c.print();let u={removedWorktrees:d,count:d.length};return{content:[{type:"text",text:JSON.stringify(u,null,2)}],structuredContent:u}}catch(o){throw s.error({error:o},"\u274C Error managing worktrees"),o}},jt=async(e,r)=>{let t=await Promise.allSettled(e.map(async o=>{let i=`${r}/${o}`;return await Xe`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 Xe`git worktree prune`,await Xe`rm -rf ${r}`,s.info(`\u{1F5D1}\uFE0F Removed worktree folder: ${r}`),s.info("")),n},Lt=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")},Ye={name:"worktrees-remove",description:"Remove selected worktrees",inputSchema:{all:ce.boolean().describe("Remove all git worktrees without prompting"),versions:ce.string().optional().describe("Specify versions by comma, e.g. 1.2.5, 1.2.6")},outputSchema:{removedWorktrees:ce.array(ce.string()).describe("List of removed git worktree branches"),count:ce.number().describe("Number of git worktrees removed")},handler:Lr};import Vt from"@inquirer/confirm";import Mt from"node:process";import{z as Ze}from"zod";import{$ as Ft}from"zx";var Bt="release/v",Vr=async e=>{let{confirmedCommand:r}=e;c.start("worktrees-sync");try{let t=await N("release"),o=`${await E()}${W}`,i=await ve(),a=r?!0:await Vt({message:"Are you sure you want to proceed with these worktree changes?"});r||c.setInteractive(),a||(s.info("Operation cancelled. Exiting..."),Mt.exit(0)),r||c.addOption("--yes",!0);let{branchesToRemove:p}=Wt({releasePRsList:i,currentWorktrees:t}),l=await Ut(p,o);qt(l),c.print();let m={removedWorktrees:l,count:l.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}},Wt=e=>{let{releasePRsList:r,currentWorktrees:t}=e;return{branchesToRemove:t.filter(i=>i.startsWith(Bt)).filter(i=>!r.includes(i))}},Ut=async(e,r)=>{let t=[];for(let n of e)try{let o=`${r}/${n}`;await Ft`git worktree remove ${o}`,t.push(n)}catch(o){s.error({error:o,branch:n},`\u274C Failed to remove worktree for ${n}`)}return t},qt=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")},Qe={name:"worktrees-sync",description:"Synchronize worktrees with active release branches",inputSchema:{},outputSchema:{removedWorktrees:Ze.array(Ze.string()).describe("List of removed worktree branches"),count:Ze.number().describe("Number of worktrees removed during sync")},handler:Vr};var er=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 Gt=[Se,$e,Ce,Te,Ne,qe,Ge,_e,Je,Le,Be,We,He,Ke,Ye,Qe],Mr=async e=>{for(let r of Gt)e.registerTool(r.name,{description:r.description,inputSchema:r.inputSchema,outputSchema:r.outputSchema},er({toolName:r.name,handler:r.handler}))};async function Fr(){let e=new zt({name:"infra-kit",version:"0.1.0"},{capabilities:{resources:{},tools:{},prompts:{}}});return await nr(e),await ir(e),await Mr(e),e}var j=or(),Kt=async()=>{let e;try{e=await Fr(),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."),Br.exit(1)}try{let r=new Ht;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."),Br.exit(1)}};sr(j);Kt();
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();
31
33
  //# sourceMappingURL=mcp.js.map