infra-kit 0.1.95 → 0.1.97

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,48 +1,49 @@
1
- import as,{Separator as se}from"@inquirer/select";import{Command as cs,Option as ot}from"commander";import Sr from"node:process";import Ee from"node:fs";import At from"node:os";import Dr from"node:path";import{z as q}from"zod/v4";import{$ as Lr}from"zx";import Te from"node:fs";import pt from"node:os";import mt from"node:path";import it from"node:process";import at from"pino";import ct from"pino-pretty";var lt=()=>{let e=it.argv.includes("--debug")?"debug":"info",r=["time","pid","hostname"];return e==="debug"&&r.push("level"),at({level:e},ct({destination:2,ignore:r.join(","),colorize:!0}))},a=lt();var $e="# -- infra-kit:begin --",ne="# -- infra-kit:end --",dt=[["# region infra-kit","# endregion infra-kit"]],ut="# infra-kit shell functions",cr=async()=>{let e=mt.join(pt.homedir(),".zshrc"),r=lr();if(Te.existsSync(e)){let t=Te.readFileSync(e,"utf-8"),s=ht(t);Te.writeFileSync(e,s)}Te.appendFileSync(e,`
1
+ import ks,{Separator as ie}from"@inquirer/select";import{Command as Rs,Option as lt}from"commander";import Or from"node:process";import _e from"node:fs";import Dt from"node:os";import Jr from"node:path";import{z as U}from"zod/v4";import{$ as Vr}from"zx";import Ie from"node:fs";import gt from"node:os";import vt from"node:path";import dt from"node:process";import ut from"pino";import ft from"pino-pretty";var ht=()=>{let e=dt.argv.includes("--debug")?"debug":"info",r=["time","pid","hostname"];return e==="debug"&&r.push("level"),ut({level:e},ft({destination:2,ignore:r.join(","),colorize:!0}))},a=ht();var Ee="# -- infra-kit:begin --",ae="# -- infra-kit:end --",wt=[["# region infra-kit","# endregion infra-kit"]],yt="# infra-kit shell functions",ur=async()=>{let e=vt.join(gt.homedir(),".zshrc"),r=fr();if(Ie.existsSync(e)){let t=Ie.readFileSync(e,"utf-8"),s=Rt(t);Ie.writeFileSync(e,s)}Ie.appendFileSync(e,`
2
2
  ${r}
3
- `),a.info(`Added infra-kit shell functions to ${e}`),a.info("Run `source ~/.zshrc` or open a new terminal to activate.")},ft=e=>e.startsWith("#")||e.startsWith("alias ")||e.startsWith("env-load")||e.startsWith("env-clear")||e.startsWith("env-status")||e.startsWith("if ")||e.startsWith(" export INFRA_KIT_SESSION")||e.startsWith("export _INFRA_KIT_")||e.startsWith(": ${_INFRA_KIT_")||e.startsWith("fi")||e.startsWith("zmodload ")||e.startsWith("autoload ")||e.startsWith("add-zsh-hook ")||e.startsWith("_infra_kit_autoload"),Ar=(e,r,t)=>{let s=e.indexOf(r),o=e.indexOf(t);if(s===-1||o===-1)return null;let n=e.slice(0,s).replace(/\n+$/,""),i=e.slice(o+t.length).replace(/^\n+/,"");return n+(i?`
4
- ${i}`:"")},ht=e=>{let r=Ar(e,$e,ne);if(r!==null)return r;for(let[l,c]of dt){let p=Ar(e,l,c);if(p!==null)return p}let t=e.indexOf(ut);if(t===-1)return e;let s=e.slice(0,t).replace(/\n+$/,""),o=e.slice(t).split(`
5
- `),n=0;for(;n<o.length&&ft(o[n]);)n++;let i=o.slice(n).join(`
3
+ `),a.info(`Added infra-kit shell functions to ${e}`),a.info("Run `source ~/.zshrc` or open a new terminal to activate.")},kt=e=>e.startsWith("#")||e.startsWith("alias ")||e.startsWith("env-load")||e.startsWith("env-clear")||e.startsWith("env-status")||e.startsWith("if ")||e.startsWith(" export INFRA_KIT_SESSION")||e.startsWith("export _INFRA_KIT_")||e.startsWith(": ${_INFRA_KIT_")||e.startsWith("fi")||e.startsWith("zmodload ")||e.startsWith("autoload ")||e.startsWith("add-zsh-hook ")||e.startsWith("_infra_kit_autoload"),Fr=(e,r,t)=>{let s=e.indexOf(r),o=e.indexOf(t);if(s===-1||o===-1)return null;let n=e.slice(0,s).replace(/\n+$/,""),i=e.slice(o+t.length).replace(/^\n+/,"");return n+(i?`
4
+ ${i}`:"")},Rt=e=>{let r=Fr(e,Ee,ae);if(r!==null)return r;for(let[l,c]of wt){let p=Fr(e,l,c);if(p!==null)return p}let t=e.indexOf(yt);if(t===-1)return e;let s=e.slice(0,t).replace(/\n+$/,""),o=e.slice(t).split(`
5
+ `),n=0;for(;n<o.length&&kt(o[n]);)n++;let i=o.slice(n).join(`
6
6
  `);return s+(i?`
7
- ${i}`:"")},lr=()=>{let e="pnpm exec infra-kit";return[$e,"zmodload zsh/stat 2>/dev/null","zmodload zsh/datetime 2>/dev/null",'if [[ -z "${INFRA_KIT_SESSION}" ]]; then'," export INFRA_KIT_SESSION=$(head -c 4 /dev/urandom | xxd -p)","fi",": ${_INFRA_KIT_LAST_LOAD_MTIME:=0}",": ${_INFRA_KIT_LAST_CLEAR_MTIME:=0}",": ${_INFRA_KIT_SHELL_STARTED:=${EPOCHSECONDS:-0}}","export _INFRA_KIT_LAST_LOAD_MTIME _INFRA_KIT_LAST_CLEAR_MTIME _INFRA_KIT_SHELL_STARTED",`env-load() { local f m; f=$(${e} env-load "$@") || return; m=$(zstat +mtime -- "$f" 2>/dev/null || echo 0); _INFRA_KIT_LAST_LOAD_MTIME=$m; source "$f"; ${e} env-status; }`,`env-clear() { local f m; f=$(${e} env-clear) || return; m=$(zstat +mtime -- "$f" 2>/dev/null || echo 0); _INFRA_KIT_LAST_CLEAR_MTIME=$m; source "$f"; ${e} env-status; }`,`env-status() { ${e} env-status; }`,`alias ik='${e}'`,"_infra_kit_autoload() {",' [[ -z "$INFRA_KIT_SESSION" ]] && return',' local cache_root="${XDG_CACHE_HOME:-$HOME/.cache}/infra-kit"',' local dir="$cache_root/$INFRA_KIT_SESSION"',' local load_file="$dir/env-load.sh"',' local clear_file="$dir/env-clear.sh"'," local mtime",' if [[ -f "$load_file" ]]; then',' mtime=$(zstat +mtime -- "$load_file" 2>/dev/null || echo 0)'," if (( mtime > _INFRA_KIT_LAST_LOAD_MTIME && mtime >= _INFRA_KIT_SHELL_STARTED )); then",' source "$load_file"'," _INFRA_KIT_LAST_LOAD_MTIME=$mtime",' print -u2 "infra-kit: auto-loaded vars for ${INFRA_KIT_ENV_CONFIG:-?}"'," fi"," fi",' if [[ -f "$clear_file" ]]; then',' mtime=$(zstat +mtime -- "$clear_file" 2>/dev/null || echo 0)'," if (( mtime > _INFRA_KIT_LAST_CLEAR_MTIME && mtime >= _INFRA_KIT_SHELL_STARTED )); then",' source "$clear_file"'," _INFRA_KIT_LAST_CLEAR_MTIME=$mtime",' print -u2 "infra-kit: auto-cleared env"'," fi"," fi","}","autoload -Uz add-zsh-hook","if (( _INFRA_KIT_SHELL_STARTED > 0 )); then"," add-zsh-hook precmd _infra_kit_autoload","fi",ne].join(`
8
- `)};import gt from"node:path";import{$ as Pr}from"zx";var D=async e=>{let t=(await Pr`git worktree list`).stdout.split(`
9
- `).filter(Boolean),s={release:vt,feature:wt};return t.map(s[e]).filter(o=>o!==null)},vt=e=>{let r=e.split(" ").filter(Boolean);return r.length<3||!r[0]?.includes("release/v")?null:`release/${r[0]?.split("/").pop()||""}`},wt=e=>{let r=e.split(" ").filter(Boolean);return r.length<3||!r[0]?.includes("feature/")?null:`feature/${r[0]?.split("/").pop()||""}`},C=async()=>(await Pr`git rev-parse --show-toplevel`).stdout.trim(),j=async()=>{let e=await C();return gt.basename(e)};import Ie from"node:fs/promises";import _r from"node:path";import Nr from"yaml";import{z as g}from"zod/v4";var yt="infra-kit.yml",kt="infra-kit.local.yml",Rt=g.object({provider:g.literal("doppler"),config:g.object({name:g.string().min(1)})}),bt=g.discriminatedUnion("provider",[Rt]),xt=g.object({mode:g.enum(["workspace","windows"]).default("workspace"),workspaceConfigPath:g.string().min(1).optional()}).refine(e=>e.mode!=="workspace"||!!e.workspaceConfigPath,{message:'workspaceConfigPath is required when mode is "workspace"',path:["workspaceConfigPath"]}),Ct=g.object({provider:g.literal("cursor"),config:xt}),Tt=g.discriminatedUnion("provider",[Ct]),$t=g.object({provider:g.literal("jira"),config:g.object({baseUrl:g.string().url(),projectId:g.number().int().positive()})}),It=g.discriminatedUnion("provider",[$t]),Or=g.object({environments:g.array(g.string().min(1)).min(1),envManagement:bt,ide:Tt.optional(),taskManager:It.optional()}),St=Or.partial(),J=null,w=async()=>{let e=await C(),r=_r.join(e,yt),t=_r.join(e,kt),s;try{s=await Ie.stat(r)}catch{throw J=null,new Error(`infra-kit.yml not found at ${r}`)}let o=await Et(t),n=Number(s.mtimeMs),i=o?Number(o.mtimeMs):null;if(J&&J.mainMtimeMs===n&&J.localMtimeMs===i)return J.value;let l=await Ie.readFile(r,"utf-8"),c=Nr.parse(l),p=c;if(o){let u=await Ie.readFile(t,"utf-8"),h=Nr.parse(u)??{},f=St.safeParse(h);if(!f.success)throw new Error(`Invalid infra-kit.local.yml at ${t}: ${g.prettifyError(f.error)}`);p={...c,...f.data}}let d=Or.safeParse(p);if(!d.success)throw new Error(`Invalid infra-kit.yml at ${r}: ${g.prettifyError(d.error)}`);return J={mainMtimeMs:n,localMtimeMs:i,value:d.data},d.data},pr=()=>{J=null},Et=async e=>{try{return await Ie.stat(e)}catch{return null}};var Se="infra-kit.local.yml",ie=async(e,r,t,s)=>{try{return await Lr`${r}`,{name:e,status:"pass",message:t}}catch{return{name:e,status:"fail",message:s}}},Pt=()=>{let e="zshrc init block",r=Dr.join(At.homedir(),".zshrc");if(!Ee.existsSync(r))return{name:e,status:"fail",message:"~/.zshrc not found. Run: infra-kit init"};let t=Ee.readFileSync(r,"utf-8"),s=t.indexOf($e),o=t.indexOf(ne);if(s===-1||o===-1||o<s)return{name:e,status:"fail",message:"infra-kit shell block missing from ~/.zshrc. Run: infra-kit init"};let n=t.slice(s,o+ne.length).trim(),i=lr().trim();return n!==i?{name:e,status:"fail",message:"infra-kit shell block in ~/.zshrc is out of date. Run: infra-kit init"}:{name:e,status:"pass",message:"infra-kit shell block in ~/.zshrc is up to date"}},_t=async()=>{let e="pnpm enableGlobalVirtualStore";try{let r=await C(),t=Dr.join(r,"pnpm-workspace.yaml");if(!Ee.existsSync(t))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${t}`};let s=Ee.readFileSync(t,"utf-8");return/^\s*enableGlobalVirtualStore\s*:\s*true\s*$/m.test(s)?{name:e,status:"pass",message:"enableGlobalVirtualStore: true is set"}:{name:e,status:"fail",message:"enableGlobalVirtualStore: true is missing in pnpm-workspace.yaml"}}catch(r){return{name:e,status:"fail",message:`Failed to read pnpm-workspace.yaml: ${r.message}`}}},Nt=async()=>{let e="infra-kit config valid";try{return pr(),await w(),{name:e,status:"pass",message:"infra-kit.yml is valid (infra-kit.local.yml overrides applied if present)"}}catch(r){return{name:e,status:"fail",message:r.message}}},Ot=async()=>{let e="infra-kit.local.yml gitignored";try{let r=await C();return await Lr({cwd:r,nothrow:!0})`git check-ignore -q ${Se}`.then(t=>{if(t.exitCode!==0)throw new Error("not ignored")}),{name:e,status:"pass",message:`${Se} is covered by .gitignore`}}catch{return{name:e,status:"fail",message:`${Se} is not gitignored. Add "${Se}" to .gitignore.`}}},Ae=async()=>{let e=await Promise.all([ie("gh installed",["gh","--version"],"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/"),ie("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),ie("doppler installed",["doppler","--version"],"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli"),ie("doppler authenticated",["doppler","me"],"Doppler CLI is authenticated","Doppler CLI is not authenticated. Run: doppler login"),ie("aws installed",["aws","--version"],"AWS CLI is installed","AWS CLI is not installed. Install from: https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html"),Promise.resolve(Pt()),_t(),Nt(),Ot()]);a.info(`Doctor check results:
10
- `);for(let t of e){let s=t.status==="pass"?"[PASS]":"[FAIL]";a.info(` ${s} ${t.name}: ${t.message}`)}let r={checks:e.map(t=>({name:t.name,status:t.status,message:t.message})),allPassed:e.every(t=>t.status==="pass")};return{content:[{type:"text",text:JSON.stringify(r,null,2)}],structuredContent:r}},Dt={name:"doctor",description:"Check installation and authentication status of gh, doppler, and aws CLIs",inputSchema:{},outputSchema:{checks:q.array(q.object({name:q.string().describe("Name of the check"),status:q.enum(["pass","fail"]).describe("Check result"),message:q.string().describe("Details about the check result")})).describe("List of all check results"),allPassed:q.boolean().describe("Whether all checks passed")},handler:Ae};import ur from"node:fs";import Fr from"node:path";import Ft from"node:process";import{z as De}from"zod/v4";import ae from"node:fs";import Lt from"node:os";import mr from"node:path";import dr from"node:process";var z="env-load.sh",Mr="env-clear.sh",Pe="INFRA_KIT_SESSION",G="INFRA_KIT_ENV_CONFIG",U="INFRA_KIT_ENV_PROJECT",H="INFRA_KIT_ENV_LOADED_AT",_e=/^([A-Z_]\w*)=/i,Ne=e=>{if(!ae.existsSync(e))return[];let r=ae.readFileSync(e,"utf-8"),t=[];for(let s of r.split(`
11
- `)){let o=_e.exec(s);o&&t.push(o[1])}return t},Mt=()=>{let e=dr.env.XDG_CACHE_HOME,r=e&&e.length>0?e:mr.join(Lt.homedir(),".cache");return mr.join(r,"infra-kit")},Y=()=>{let e=dr.env[Pe];if(!e)throw new Error(`${Pe} is not set. Run \`infra-kit init\` then \`source ~/.zshrc\`.`);return mr.join(Mt(),e)},Oe=(e,r,t)=>{let s=`${e}.tmp.${dr.pid}`;ae.writeFileSync(s,r,{mode:t});try{ae.renameSync(s,e)}catch(o){throw ae.rmSync(s,{force:!0}),o}},X="-worktrees";var Le=async()=>{let e=Y(),r=Fr.join(e,z);if(!ur.existsSync(r))throw new Error("No loaded environment found. Run `env-load` first.");let t=Ne(r),s=[...t.map(i=>`unset ${i}`),`unset ${G}`,`unset ${U}`,`unset ${H}`],o=Fr.resolve(e,Mr);ur.mkdirSync(e,{recursive:!0,mode:448}),Oe(o,`${s.join(`
7
+ ${i}`:"")},fr=()=>{let e="pnpm exec infra-kit";return[Ee,"zmodload zsh/stat 2>/dev/null","zmodload zsh/datetime 2>/dev/null",'if [[ -z "${INFRA_KIT_SESSION}" ]]; then'," export INFRA_KIT_SESSION=$(head -c 4 /dev/urandom | xxd -p)","fi",": ${_INFRA_KIT_LAST_LOAD_MTIME:=0}",": ${_INFRA_KIT_LAST_CLEAR_MTIME:=0}",": ${_INFRA_KIT_SHELL_STARTED:=${EPOCHSECONDS:-0}}","export _INFRA_KIT_LAST_LOAD_MTIME _INFRA_KIT_LAST_CLEAR_MTIME _INFRA_KIT_SHELL_STARTED",`env-load() { local f m; f=$(${e} env-load "$@") || return; m=$(zstat +mtime -- "$f" 2>/dev/null || echo 0); _INFRA_KIT_LAST_LOAD_MTIME=$m; source "$f"; ${e} env-status; }`,`env-clear() { local f m; f=$(${e} env-clear) || return; m=$(zstat +mtime -- "$f" 2>/dev/null || echo 0); _INFRA_KIT_LAST_CLEAR_MTIME=$m; source "$f"; ${e} env-status; }`,`env-status() { ${e} env-status; }`,`alias ik='${e}'`,"_infra_kit_autoload() {",' [[ -z "$INFRA_KIT_SESSION" ]] && return',' local cache_root="${XDG_CACHE_HOME:-$HOME/.cache}/infra-kit"',' local dir="$cache_root/$INFRA_KIT_SESSION"',' local load_file="$dir/env-load.sh"',' local clear_file="$dir/env-clear.sh"'," local mtime",' if [[ -f "$load_file" ]]; then',' mtime=$(zstat +mtime -- "$load_file" 2>/dev/null || echo 0)'," if (( mtime > _INFRA_KIT_LAST_LOAD_MTIME && mtime >= _INFRA_KIT_SHELL_STARTED )); then",' source "$load_file"'," _INFRA_KIT_LAST_LOAD_MTIME=$mtime",' print -u2 "infra-kit: auto-loaded vars for ${INFRA_KIT_ENV_CONFIG:-?}"'," fi"," fi",' if [[ -f "$clear_file" ]]; then',' mtime=$(zstat +mtime -- "$clear_file" 2>/dev/null || echo 0)'," if (( mtime > _INFRA_KIT_LAST_CLEAR_MTIME && mtime >= _INFRA_KIT_SHELL_STARTED )); then",' source "$clear_file"'," _INFRA_KIT_LAST_CLEAR_MTIME=$mtime",' print -u2 "infra-kit: auto-cleared env"'," fi"," fi","}","autoload -Uz add-zsh-hook","if (( _INFRA_KIT_SHELL_STARTED > 0 )); then"," add-zsh-hook precmd _infra_kit_autoload","fi",ae].join(`
8
+ `)};import bt from"node:path";import{$ as Dr}from"zx";var _=async e=>{let t=(await Dr`git worktree list`).stdout.split(`
9
+ `).filter(Boolean),s={release:Ct,feature:xt};return t.map(s[e]).filter(o=>o!==null)},Wr=e=>{let r=e.trimEnd();if(!r.endsWith("]"))return null;let t=r.lastIndexOf("[");if(t===-1)return null;let s=r.slice(t+1,-1);return s.length>0?s:null},Ct=e=>{let r=Wr(e);return r?.startsWith("release/v")?r:null},xt=e=>{let r=Wr(e);return r?.startsWith("feature/")?r:null},b=async()=>(await Dr`git rev-parse --show-toplevel`).stdout.trim(),W=async()=>{let e=await b();return bt.basename(e)};import Pe from"node:fs/promises";import Lr from"node:path";import Mr from"yaml";import{z as g}from"zod/v4";var Tt="infra-kit.yml",$t="infra-kit.local.yml",St=g.object({provider:g.literal("doppler"),config:g.object({name:g.string().min(1)})}),It=g.discriminatedUnion("provider",[St]),Et=g.object({mode:g.enum(["workspace","windows"]).default("workspace"),workspaceConfigPath:g.string().min(1).optional()}).refine(e=>e.mode!=="workspace"||!!e.workspaceConfigPath,{message:'workspaceConfigPath is required when mode is "workspace"',path:["workspaceConfigPath"]}),Pt=g.object({provider:g.literal("cursor"),config:Et}),At=g.discriminatedUnion("provider",[Pt]),_t=g.object({provider:g.literal("jira"),config:g.object({baseUrl:g.string().url(),projectId:g.number().int().positive()})}),Ot=g.discriminatedUnion("provider",[_t]),jr=g.object({environments:g.array(g.string().min(1)).min(1),envManagement:It,ide:At.optional(),taskManager:Ot.optional()}),Nt=jr.partial(),K=null,w=async()=>{let e=await b(),r=Lr.join(e,Tt),t=Lr.join(e,$t),s;try{s=await Pe.stat(r)}catch{throw K=null,new Error(`infra-kit.yml not found at ${r}`)}let o=await Ft(t),n=Number(s.mtimeMs),i=o?Number(o.mtimeMs):null;if(K&&K.mainMtimeMs===n&&K.localMtimeMs===i)return K.value;let l=await Pe.readFile(r,"utf-8"),c=Mr.parse(l),p=c;if(o){let u=await Pe.readFile(t,"utf-8"),h=Mr.parse(u)??{},f=Nt.safeParse(h);if(!f.success)throw new Error(`Invalid infra-kit.local.yml at ${t}: ${g.prettifyError(f.error)}`);p={...c,...f.data}}let d=jr.safeParse(p);if(!d.success)throw new Error(`Invalid infra-kit.yml at ${r}: ${g.prettifyError(d.error)}`);return K={mainMtimeMs:n,localMtimeMs:i,value:d.data},d.data},hr=()=>{K=null},Ft=async e=>{try{return await Pe.stat(e)}catch{return null}};var Ae="infra-kit.local.yml",ce=async(e,r,t,s)=>{try{return await Vr`${r}`,{name:e,status:"pass",message:t}}catch{return{name:e,status:"fail",message:s}}},Wt=()=>{let e="zshrc init block",r=Jr.join(Dt.homedir(),".zshrc");if(!_e.existsSync(r))return{name:e,status:"fail",message:"~/.zshrc not found. Run: infra-kit init"};let t=_e.readFileSync(r,"utf-8"),s=t.indexOf(Ee),o=t.indexOf(ae);if(s===-1||o===-1||o<s)return{name:e,status:"fail",message:"infra-kit shell block missing from ~/.zshrc. Run: infra-kit init"};let n=t.slice(s,o+ae.length).trim(),i=fr().trim();return n!==i?{name:e,status:"fail",message:"infra-kit shell block in ~/.zshrc is out of date. Run: infra-kit init"}:{name:e,status:"pass",message:"infra-kit shell block in ~/.zshrc is up to date"}},Lt=async()=>{let e="pnpm enableGlobalVirtualStore";try{let r=await b(),t=Jr.join(r,"pnpm-workspace.yaml");if(!_e.existsSync(t))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${t}`};let s=_e.readFileSync(t,"utf-8");return/^\s*enableGlobalVirtualStore\s*:\s*true\s*$/m.test(s)?{name:e,status:"pass",message:"enableGlobalVirtualStore: true is set"}:{name:e,status:"fail",message:"enableGlobalVirtualStore: true is missing in pnpm-workspace.yaml"}}catch(r){return{name:e,status:"fail",message:`Failed to read pnpm-workspace.yaml: ${r.message}`}}},Mt=async()=>{let e="infra-kit config valid";try{return hr(),await w(),{name:e,status:"pass",message:"infra-kit.yml is valid (infra-kit.local.yml overrides applied if present)"}}catch(r){return{name:e,status:"fail",message:r.message}}},jt=async()=>{let e="infra-kit.local.yml gitignored";try{let r=await b();return await Vr({cwd:r,nothrow:!0})`git check-ignore -q ${Ae}`.then(t=>{if(t.exitCode!==0)throw new Error("not ignored")}),{name:e,status:"pass",message:`${Ae} is covered by .gitignore`}}catch{return{name:e,status:"fail",message:`${Ae} is not gitignored. Add "${Ae}" to .gitignore.`}}},Oe=async()=>{let e=await Promise.all([ce("gh installed",["gh","--version"],"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/"),ce("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),ce("doppler installed",["doppler","--version"],"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli"),ce("doppler authenticated",["doppler","me"],"Doppler CLI is authenticated","Doppler CLI is not authenticated. Run: doppler login"),ce("aws installed",["aws","--version"],"AWS CLI is installed","AWS CLI is not installed. Install from: https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html"),Promise.resolve(Wt()),Lt(),Mt(),jt()]);a.info(`Doctor check results:
10
+ `);for(let t of e){let s=t.status==="pass"?"[PASS]":"[FAIL]";a.info(` ${s} ${t.name}: ${t.message}`)}let r={checks:e.map(t=>({name:t.name,status:t.status,message:t.message})),allPassed:e.every(t=>t.status==="pass")};return{content:[{type:"text",text:JSON.stringify(r,null,2)}],structuredContent:r}},Jt={name:"doctor",description:"Check installation and authentication status of gh, doppler, and aws CLIs",inputSchema:{},outputSchema:{checks:U.array(U.object({name:U.string().describe("Name of the check"),status:U.enum(["pass","fail"]).describe("Check result"),message:U.string().describe("Details about the check result")})).describe("List of all check results"),allPassed:U.boolean().describe("Whether all checks passed")},handler:Oe};import wr from"node:fs";import Kr from"node:path";import Kt from"node:process";import{z as Le}from"zod/v4";import le from"node:fs";import Vt from"node:os";import gr from"node:path";import vr from"node:process";var G="env-load.sh",Br="env-clear.sh",Ne="INFRA_KIT_SESSION",H="INFRA_KIT_ENV_CONFIG",Y="INFRA_KIT_ENV_PROJECT",X="INFRA_KIT_ENV_LOADED_AT",Fe=/^([A-Z_]\w*)=/i,De=e=>{if(!le.existsSync(e))return[];let r=le.readFileSync(e,"utf-8"),t=[];for(let s of r.split(`
11
+ `)){let o=Fe.exec(s);o&&t.push(o[1])}return t},Bt=()=>{let e=vr.env.XDG_CACHE_HOME,r=e&&e.length>0?e:gr.join(Vt.homedir(),".cache");return gr.join(r,"infra-kit")},Z=()=>{let e=vr.env[Ne];if(!e)throw new Error(`${Ne} is not set. Run \`infra-kit init\` then \`source ~/.zshrc\`.`);return gr.join(Bt(),e)},We=(e,r,t)=>{let s=`${e}.tmp.${vr.pid}`;le.writeFileSync(s,r,{mode:t});try{le.renameSync(s,e)}catch(o){throw le.rmSync(s,{force:!0}),o}},j="-worktrees";var Me=async()=>{let e=Z(),r=Kr.join(e,G);if(!wr.existsSync(r))throw new Error("No loaded environment found. Run `env-load` first.");let t=De(r),s=[...t.map(i=>`unset ${i}`),`unset ${H}`,`unset ${Y}`,`unset ${X}`],o=Kr.resolve(e,Br);wr.mkdirSync(e,{recursive:!0,mode:448}),We(o,`${s.join(`
12
12
  `)}
13
- `,384),Ft.stdout.write(`${o}
14
- `),ur.unlinkSync(r);let n={filePath:o,variableCount:t.length,unsetStatements:s};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}},Wt={name:"env-clear",description:'Generate a shell script that unsets every env var previously loaded by env-load for this session, plus the infra-kit session metadata vars. Does NOT mutate the calling process. When `infra-kit init` has installed the zsh shell integration, the user\'s terminal auto-sources the unset script on its next prompt (precmd hook) \u2014 so calling this via MCP will clear the vars in the shell that launched Claude Code automatically. Other callers must source "<filePath>" themselves or surface it to the user. Errors if no env is currently loaded.',inputSchema:{},outputSchema:{filePath:De.string().describe("Path to the file that must be sourced to apply"),variableCount:De.number().describe("Number of variables cleared"),unsetStatements:De.array(De.string()).describe("Unset statements generated")},handler:Le};import{z as fr}from"zod/v4";var ce=async()=>{let{envManagement:e}=await w();return e.config.name};var Me=async()=>{let e=await ce(),{environments:r}=await w();a.info(`Doppler project: ${e}
15
- `),a.info("Available configs:");for(let s of r)a.info(` - ${s}`);let t={project:e,configs:r};return{content:[{type:"text",text:JSON.stringify(t,null,2)}],structuredContent:t}},jt={name:"env-list",description:"List the environments the project is configured to support. Returns the `environments` list declared in infra-kit.yml at the project root (not a live fetch from Doppler) plus the Doppler project name resolved from the same file. Read-only.",inputSchema:{},outputSchema:{project:fr.string().describe("Detected Doppler project name"),configs:fr.array(fr.string()).describe("Available environment configs")},handler:Me};import Vt from"@inquirer/select";import{Buffer as Bt}from"node:buffer";import Kt from"node:fs";import qt from"node:path";import jr from"node:process";import{z as pe}from"zod/v4";import{$ as Fe}from"zx";import{$ as Wr}from"zx";var le=async()=>{try{await Wr`doppler --version`}catch(e){throw new Error("Doppler CLI is not installed. Install it from: https://docs.doppler.com/docs/install-cli",{cause:e})}try{await Wr`doppler me`}catch(e){throw new Error("Doppler CLI is not authenticated. Run: doppler login",{cause:e})}};var Jt=()=>{let e="",r=[],t=!1;return{start(s){e=s,r=[],t=!1},setInteractive(){t=!0},addOption(s,o){r.push({flag:s,value:o})},print(){if(!t||r.length===0)return;let s=r.map(o=>typeof o.value=="boolean"?o.value?o.flag:"":Array.isArray(o.value)?`${o.flag} "${o.value.join(", ")}"`:`${o.flag} "${o.value}"`).filter(Boolean).join(" ");a.info(`\u{1F4DF} Equivalent command:
13
+ `,384),Kt.stdout.write(`${o}
14
+ `),wr.unlinkSync(r);let n={filePath:o,variableCount:t.length,unsetStatements:s};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}},qt={name:"env-clear",description:'Generate a shell script that unsets every env var previously loaded by env-load for this session, plus the infra-kit session metadata vars. Does NOT mutate the calling process. When `infra-kit init` has installed the zsh shell integration, the user\'s terminal auto-sources the unset script on its next prompt (precmd hook) \u2014 so calling this via MCP will clear the vars in the shell that launched Claude Code automatically. Other callers must source "<filePath>" themselves or surface it to the user. Errors if no env is currently loaded.',inputSchema:{},outputSchema:{filePath:Le.string().describe("Path to the file that must be sourced to apply"),variableCount:Le.number().describe("Number of variables cleared"),unsetStatements:Le.array(Le.string()).describe("Unset statements generated")},handler:Me};import{z as yr}from"zod/v4";var pe=async()=>{let{envManagement:e}=await w();return e.config.name};var je=async()=>{let e=await pe(),{environments:r}=await w();a.info(`Doppler project: ${e}
15
+ `),a.info("Available configs:");for(let s of r)a.info(` - ${s}`);let t={project:e,configs:r};return{content:[{type:"text",text:JSON.stringify(t,null,2)}],structuredContent:t}},zt={name:"env-list",description:"List the environments the project is configured to support. Returns the `environments` list declared in infra-kit.yml at the project root (not a live fetch from Doppler) plus the Doppler project name resolved from the same file. Read-only.",inputSchema:{},outputSchema:{project:yr.string().describe("Detected Doppler project name"),configs:yr.array(yr.string()).describe("Available environment configs")},handler:je};import Gt from"@inquirer/select";import{Buffer as Ht}from"node:buffer";import Yt from"node:fs";import Xt from"node:path";import zr from"node:process";import{z as de}from"zod/v4";import{$ as Je}from"zx";import{$ as qr}from"zx";var me=async()=>{try{await qr`doppler --version`}catch(e){throw new Error("Doppler CLI is not installed. Install it from: https://docs.doppler.com/docs/install-cli",{cause:e})}try{await qr`doppler me`}catch(e){throw new Error("Doppler CLI is not authenticated. Run: doppler login",{cause:e})}};var Ut=()=>{let e="",r=[],t=!1;return{start(s){e=s,r=[],t=!1},setInteractive(){t=!0},addOption(s,o){r.push({flag:s,value:o})},print(){if(!t||r.length===0)return;let s=r.map(o=>typeof o.value=="boolean"?o.value?o.flag:"":Array.isArray(o.value)?`${o.flag} "${o.value.join(", ")}"`:`${o.flag} "${o.value}"`).filter(Boolean).join(" ");a.info(`\u{1F4DF} Equivalent command:
16
16
  pnpm exec infra-kit ${e} ${s}
17
- `)},reset(){e="",r=[],t=!1}}},m=Jt();var We=async e=>{await le();let{config:r}=e;m.start("env-load");let t="";if(r)t=r;else{let{environments:u}=await w();m.setInteractive(),t=await Vt({message:"Select environment config",choices:u.map(h=>({name:h,value:h}))},{output:jr.stderr})}m.addOption("--config",t);let s=await ce(),o=await Gt(s,t);Xt(o);let n=new Date().toISOString(),i=["set -a",o,`${G}=${hr(t)}`,`${U}=${hr(s)}`,`${H}=${hr(n)}`,"set +a"],l=Y(),c=qt.resolve(l,z);Kt.mkdirSync(l,{recursive:!0,mode:448}),Oe(c,`${i.join(`
17
+ `)},reset(){e="",r=[],t=!1}}},m=Ut();var Ve=async e=>{await me();let{config:r}=e;m.start("env-load");let t="";if(r)t=r;else{let{environments:u}=await w();m.setInteractive(),t=await Gt({message:"Select environment config",choices:u.map(h=>({name:h,value:h}))},{output:zr.stderr})}m.addOption("--config",t);let s=await pe(),o=await Qt(s,t);oo(o);let n=new Date().toISOString(),i=["set -a",o,`${H}=${kr(t)}`,`${Y}=${kr(s)}`,`${X}=${kr(n)}`,"set +a"],l=Z(),c=Xt.resolve(l,G);Yt.mkdirSync(l,{recursive:!0,mode:448}),We(c,`${i.join(`
18
18
  `)}
19
- `,384),jr.stdout.write(`${c}
20
- `),m.print();let p=Ht(o),d={filePath:c,variableCount:p,project:s,config:t};return{content:[{type:"text",text:JSON.stringify(d,null,2)}],structuredContent:d}},Jr=1024*1024,zt=3e4,Gt=async(e,r)=>{let t=Fe.quiet;Fe.quiet=!0;try{let s=await Fe`doppler secrets download --no-file --format env --project ${e} --config ${r}`.timeout(zt);return Ut(s.stdout),s.stdout.trim()}finally{Fe.quiet=t}},Ut=e=>{let r=Bt.byteLength(e,"utf-8");if(r>Jr)throw new Error(`doppler returned unexpectedly large output (${r} bytes > ${Jr}) \u2014 refusing to write to disk`)},Ht=e=>e.split(`
21
- `).filter(r=>_e.test(r)).length,Yt=new Set(["set -a","set +a"]),hr=e=>`'${e.replaceAll("'","'\\''")}'`,Xt=e=>{if(e.trim().length===0)throw new Error("doppler returned empty output for env-load");for(let r of e.split(`
22
- `)){let t=r.trim();if(!(t.length===0||Yt.has(t))&&!_e.test(t))throw new Error(`doppler returned unexpected output for env-load (expected KEY=value lines, got: ${JSON.stringify(t.slice(0,80))})`)}},Zt={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:pe.string().describe('Doppler config / environment name to load (e.g. "dev", "arthur", "renana"). Required for MCP calls.')},outputSchema:{filePath:pe.string().describe("Path to the file that must be sourced to apply variables"),variableCount:pe.number().describe("Number of variables loaded"),project:pe.string().describe("Doppler project name"),config:pe.string().describe("Doppler config name")},handler:We};import Qt from"node:path";import me from"node:process";import{z as Z}from"zod/v4";var je=async()=>{await le(),a.info("Environment session status:");let e=Y(),r=me.env[Pe],t=Qt.join(e,z),s=0,o=0,n=me.env[G]??null,i=me.env[U]??null,l=me.env[H]??null;if(n){let p=Ne(t);p.length>0&&(o=p.length,s=p.filter(u=>u in me.env).length);let d=l?.replace(/\.\d{3}Z$/,"")??null;if(a.info(` ${n}: ${s} of ${o} vars loaded (project: ${i}, loadedAt: ${d}, session: ${r})
19
+ `,384),zr.stdout.write(`${c}
20
+ `),m.print();let p=ro(o),d={filePath:c,variableCount:p,project:s,config:t};return{content:[{type:"text",text:JSON.stringify(d,null,2)}],structuredContent:d}},Ur=1024*1024,Zt=3e4,Qt=async(e,r)=>{let t=Je.quiet;Je.quiet=!0;try{let s=await Je`doppler secrets download --no-file --format env --project ${e} --config ${r}`.timeout(Zt);return eo(s.stdout),s.stdout.trim()}finally{Je.quiet=t}},eo=e=>{let r=Ht.byteLength(e,"utf-8");if(r>Ur)throw new Error(`doppler returned unexpectedly large output (${r} bytes > ${Ur}) \u2014 refusing to write to disk`)},ro=e=>e.split(`
21
+ `).filter(r=>Fe.test(r)).length,to=new Set(["set -a","set +a"]),kr=e=>`'${e.replaceAll("'","'\\''")}'`,oo=e=>{if(e.trim().length===0)throw new Error("doppler returned empty output for env-load");for(let r of e.split(`
22
+ `)){let t=r.trim();if(!(t.length===0||to.has(t))&&!Fe.test(t))throw new Error(`doppler returned unexpected output for env-load (expected KEY=value lines, got: ${JSON.stringify(t.slice(0,80))})`)}},so={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:de.string().describe('Doppler config / environment name to load (e.g. "dev", "arthur", "renana"). Required for MCP calls.')},outputSchema:{filePath:de.string().describe("Path to the file that must be sourced to apply variables"),variableCount:de.number().describe("Number of variables loaded"),project:de.string().describe("Doppler project name"),config:de.string().describe("Doppler config name")},handler:Ve};import no from"node:path";import ue from"node:process";import{z as Q}from"zod/v4";var Be=async()=>{await me(),a.info("Environment session status:");let e=Z(),r=ue.env[Ne],t=no.join(e,G),s=0,o=0,n=ue.env[H]??null,i=ue.env[Y]??null,l=ue.env[X]??null;if(n){let p=De(t);p.length>0&&(o=p.length,s=p.filter(u=>u in ue.env).length);let d=l?.replace(/\.\d{3}Z$/,"")??null;if(a.info(` ${n}: ${s} of ${o} vars loaded (project: ${i}, loadedAt: ${d}, session: ${r})
23
23
  `),o>0&&s<o){let u=o-s;a.warn(` ${u} cached var(s) are not present in the current process \u2014 env-load needs to be re-sourced, or vars were unset manually.`)}}else a.info(` Session ${r}: no env loaded
24
- `);let c={sessionId:r,sessionLoadedCount:s,sessionTotalCount:o,sessionConfig:n,sessionProject:i,sessionLoadedAt:l};return{content:[{type:"text",text:JSON.stringify(c,null,2)}],structuredContent:c}},eo={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:Z.string().describe("Current terminal session ID"),sessionLoadedCount:Z.number().describe("Number of cached vars active in the current session"),sessionTotalCount:Z.number().describe("Total number of cached var names"),sessionConfig:Z.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:Z.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:Z.string().nullable().describe("ISO 8601 timestamp of when the env was loaded")},handler:je};import so from"@inquirer/checkbox";import no from"@inquirer/confirm";import io from"node:process";import{z as re}from"zod/v4";import{$ as A}from"zx";import{$ as Gn}from"zx";import qe from"node:process";import{$ as S}from"zx";import{$ as fe}from"zx";import de from"node:process";var gr=async(e,r)=>{try{let{baseUrl:t,token:s,email:o,projectId:n}=r,i={name:e.name,projectId:e.projectId||n,description:e.description||"",released:e.released||!1,archived:e.archived||!1},l=`${t}/rest/api/3/version`,c=btoa(`${o}:${s}`),p=await fetch(l,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${c}`},body:JSON.stringify(i)});if(!p.ok){let u=await p.text();throw a.error({status:p.status,statusText:p.statusText,error:u},"Failed to create Jira version"),new Error(`HTTP ${p.status}: ${p.statusText}`)}return{success:!0,version:await p.json()}}catch(t){throw a.error({error:t},"Error creating Jira version"),t}},Je=async e=>{try{let{baseUrl:r,token:t,email:s,projectId:o}=e,n=`${r}/rest/api/3/project/${o}/versions`,i=btoa(`${s}:${t}`),l=await fetch(n,{method:"GET",headers:{Accept:"application/json",Authorization:`Basic ${i}`}});if(!l.ok){let p=await l.text();throw a.error({status:l.status,statusText:l.statusText,error:p},"Failed to get Jira project versions"),new Error(`HTTP ${l.status}: ${l.statusText}`)}return await l.json()}catch(r){throw a.error({error:r},"Error getting Jira project versions"),r}},to=async(e,r)=>{try{return(await Je(r)).find(o=>o.name===e)||null}catch(t){throw a.error({error:t,versionName:e},"Error finding Jira version by name"),t}},oo=async(e,r)=>{try{let{baseUrl:t,token:s,email:o}=r,n={released:e.released??!0,archived:e.archived??!1};e.releaseDate?n.releaseDate=e.releaseDate:e.released!==!1&&(n.releaseDate=new Date().toISOString().split("T")[0]),e.description!==void 0&&(n.description=e.description);let i=`${t}/rest/api/3/version/${e.versionId}`,l=btoa(`${o}:${s}`),c=await fetch(i,{method:"PUT",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${l}`},body:JSON.stringify(n)});if(!c.ok){let d=await c.text();throw a.error({status:c.status,statusText:c.statusText,error:d},"Failed to update Jira version"),new Error(`HTTP ${c.status}: ${c.statusText}`)}return{success:!0,version:await c.json()}}catch(t){throw a.error({error:t},"Error updating Jira version"),t}},vr=async(e,r)=>{try{let{versionName:t}=e,s=await to(t,r);if(!s)throw a.error({versionName:t},"Jira version not found"),new Error(`Version "${t}" not found in Jira project`);return await oo({versionId:s.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},r)}catch(t){throw a.error({error:t},"Error delivering Jira release"),t}},Q=async()=>{let e=de.env.JIRA_BASE_URL,r=de.env.JIRA_TOKEN||de.env.JIRA_API_TOKEN,t=de.env.JIRA_PROJECT_ID,s=de.env.JIRA_EMAIL,o=[];if(e||o.push("JIRA_BASE_URL (e.g., https://your-domain.atlassian.net)"),r||o.push("JIRA_TOKEN or JIRA_API_TOKEN (your Jira API token)"),t||o.push("JIRA_PROJECT_ID (numeric project ID)"),s||o.push("JIRA_EMAIL (your Jira email address)"),o.length>0){let i=["Jira configuration is required but incomplete.","Please configure the following environment variables:",...o.map(l=>` - ${l}`),"","You can set these in your .env file or as environment variables."].join(`
25
- `);throw new Error(i)}let n=Number.parseInt(t,10);if(Number.isNaN(n))throw new TypeError(`Invalid JIRA_PROJECT_ID: "${t}" must be a numeric value (e.g., 10001)`);return{baseUrl:e.replace(/\/$/,""),token:r,projectId:n,email:s}},ue=async()=>{try{return await Q()}catch(e){return a.warn({error:e},"Jira configuration not available, skipping Jira integration"),null}};var Ve=e=>e==="hotfix"?"main":"dev",he=async(e="regular")=>{let r=Ve(e);fe.quiet=!0,await fe`git fetch origin`,await fe`git switch ${r}`,await fe`git pull origin ${r}`,fe.quiet=!1},ge=async e=>{let{version:r,jiraConfig:t,description:s,type:o="regular"}=e,n=`v${r}`,i=await gr({name:n,projectId:t.projectId,description:s||"",released:!1,archived:!1},t),l=`${t.baseUrl}/projects/${i.version.projectId}/versions/${i.version.id}/tab/release-report-all-issues`,c=await Be({version:r,jiraVersionUrl:l,type:o,description:s});return{version:r,type:o,branchName:c.branchName,prUrl:c.prUrl,jiraVersionUrl:l}},R=async()=>{let e=new Map,r=await ue();if(!r)return e;try{let t=await Je(r);for(let s of t)s.description&&e.set(s.name,s.description)}catch{}return e},ee=(e,r,t)=>{let s=t?" ".repeat(t-e.length+3):" ",o=`[${r}]`.padEnd(11);return`${e}${s}${o}`},y=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",I=e=>{let{branches:r,descriptions:t,types:s}=e,o=r.map(i=>i.replace("release/v","")),n=Math.max(...o.map(i=>i.length));return r.map((i,l)=>{let c=o[l],p=s?s.get(i)||"regular":void 0,d=t.get(`v${c}`),u=" ".repeat(n-c.length+3),h=p?ee(c,p,n):c;return d&&(h=p?`${h} ${d}`:`${c}${u}${d}`),{name:h,value:i}})};var wr=e=>e.replace("release/","").slice(1).split(".").map(Number),Ke=e=>[...e].sort((r,t)=>{let[s,o,n]=wr(r),[i,l,c]=wr(t);return s!==i?(s??0)-(i??0):o!==l?(o??0)-(l??0):(n??0)-(c??0)});var Vr=async()=>{let e=await S`gh pr list --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName`,r=await S`gh pr list --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName`,t=[...JSON.parse(e.stdout),...JSON.parse(r.stdout)],s=new Set;return t.filter(o=>s.has(o.headRefName)?!1:(s.add(o.headRefName),!0))},ze=async()=>{try{let e=await Vr();return e.length===0&&(a.error("\u274C No release PRs found. Check the project folder for the script. Exiting..."),qe.exit(1)),Ke(e.map(r=>r.headRefName))}catch(e){a.error({error:e},"\u274C Error fetching release PRs"),qe.exit(1)}},k=async()=>{try{let e=await Vr();e.length===0&&(a.error("\u274C No release PRs found. Check the project folder for the script. Exiting..."),qe.exit(1));let r=Ke(e.map(s=>s.headRefName)),t=new Map(e.map(s=>[s.headRefName,s]));return r.map(s=>({branch:s,title:t.get(s).title}))}catch(e){a.error({error:e},"\u274C Error fetching release PRs"),qe.exit(1)}},Be=async e=>{let{version:r,jiraVersionUrl:t,type:s,description:o}=e,n=s==="hotfix"?"Hotfix":"Release",i=Ve(s),l=`release/v${r}`,c=o&&o.trim()!==""?`${t}
24
+ `);let c={sessionId:r,sessionLoadedCount:s,sessionTotalCount:o,sessionConfig:n,sessionProject:i,sessionLoadedAt:l};return{content:[{type:"text",text:JSON.stringify(c,null,2)}],structuredContent:c}},io={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:Q.string().describe("Current terminal session ID"),sessionLoadedCount:Q.number().describe("Number of cached vars active in the current session"),sessionTotalCount:Q.number().describe("Total number of cached var names"),sessionConfig:Q.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:Q.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:Q.string().nullable().describe("ISO 8601 timestamp of when the env was loaded")},handler:Be};import po from"@inquirer/checkbox";import mo from"@inquirer/confirm";import uo from"node:process";import{z as te}from"zod/v4";import{$ as O}from"zx";import{$ as ii}from"zx";import Ge from"node:process";import{$ as P}from"zx";import{$ as ge}from"zx";import fe from"node:process";var Rr=async(e,r)=>{try{let{baseUrl:t,token:s,email:o,projectId:n}=r,i={name:e.name,projectId:e.projectId||n,description:e.description||"",released:e.released||!1,archived:e.archived||!1},l=`${t}/rest/api/3/version`,c=btoa(`${o}:${s}`),p=await fetch(l,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${c}`},body:JSON.stringify(i)});if(!p.ok){let u=await p.text();throw a.error({status:p.status,statusText:p.statusText,error:u},"Failed to create Jira version"),new Error(`HTTP ${p.status}: ${p.statusText}`)}return{success:!0,version:await p.json()}}catch(t){throw a.error({error:t},"Error creating Jira version"),t}},Ke=async e=>{try{let{baseUrl:r,token:t,email:s,projectId:o}=e,n=`${r}/rest/api/3/project/${o}/versions`,i=btoa(`${s}:${t}`),l=await fetch(n,{method:"GET",headers:{Accept:"application/json",Authorization:`Basic ${i}`}});if(!l.ok){let p=await l.text();throw a.error({status:l.status,statusText:l.statusText,error:p},"Failed to get Jira project versions"),new Error(`HTTP ${l.status}: ${l.statusText}`)}return await l.json()}catch(r){throw a.error({error:r},"Error getting Jira project versions"),r}},co=async(e,r)=>{try{return(await Ke(r)).find(o=>o.name===e)||null}catch(t){throw a.error({error:t,versionName:e},"Error finding Jira version by name"),t}},lo=async(e,r)=>{try{let{baseUrl:t,token:s,email:o}=r,n={released:e.released??!0,archived:e.archived??!1};e.releaseDate?n.releaseDate=e.releaseDate:e.released!==!1&&(n.releaseDate=new Date().toISOString().split("T")[0]),e.description!==void 0&&(n.description=e.description);let i=`${t}/rest/api/3/version/${e.versionId}`,l=btoa(`${o}:${s}`),c=await fetch(i,{method:"PUT",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${l}`},body:JSON.stringify(n)});if(!c.ok){let d=await c.text();throw a.error({status:c.status,statusText:c.statusText,error:d},"Failed to update Jira version"),new Error(`HTTP ${c.status}: ${c.statusText}`)}return{success:!0,version:await c.json()}}catch(t){throw a.error({error:t},"Error updating Jira version"),t}},br=async(e,r)=>{try{let{versionName:t}=e,s=await co(t,r);if(!s)throw a.error({versionName:t},"Jira version not found"),new Error(`Version "${t}" not found in Jira project`);return await lo({versionId:s.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},r)}catch(t){throw a.error({error:t},"Error delivering Jira release"),t}},ee=async()=>{let e=fe.env.JIRA_BASE_URL,r=fe.env.JIRA_TOKEN||fe.env.JIRA_API_TOKEN,t=fe.env.JIRA_PROJECT_ID,s=fe.env.JIRA_EMAIL,o=[];if(e||o.push("JIRA_BASE_URL (e.g., https://your-domain.atlassian.net)"),r||o.push("JIRA_TOKEN or JIRA_API_TOKEN (your Jira API token)"),t||o.push("JIRA_PROJECT_ID (numeric project ID)"),s||o.push("JIRA_EMAIL (your Jira email address)"),o.length>0){let i=["Jira configuration is required but incomplete.","Please configure the following environment variables:",...o.map(l=>` - ${l}`),"","You can set these in your .env file or as environment variables."].join(`
25
+ `);throw new Error(i)}let n=Number.parseInt(t,10);if(Number.isNaN(n))throw new TypeError(`Invalid JIRA_PROJECT_ID: "${t}" must be a numeric value (e.g., 10001)`);return{baseUrl:e.replace(/\/$/,""),token:r,projectId:n,email:s}},he=async()=>{try{return await ee()}catch(e){return a.warn({error:e},"Jira configuration not available, skipping Jira integration"),null}};var qe=e=>e==="hotfix"?"main":"dev",ve=async(e="regular")=>{let r=qe(e);ge.quiet=!0,await ge`git fetch origin`,await ge`git switch ${r}`,await ge`git pull origin ${r}`,ge.quiet=!1},we=async e=>{let{version:r,jiraConfig:t,description:s,type:o="regular"}=e,n=`v${r}`,i=await Rr({name:n,projectId:t.projectId,description:s||"",released:!1,archived:!1},t),l=`${t.baseUrl}/projects/${i.version.projectId}/versions/${i.version.id}/tab/release-report-all-issues`,c=await ze({version:r,jiraVersionUrl:l,type:o,description:s});return{version:r,type:o,branchName:c.branchName,prUrl:c.prUrl,jiraVersionUrl:l}},C=async()=>{let e=new Map,r=await he();if(!r)return e;try{let t=await Ke(r);for(let s of t)s.description&&e.set(s.name,s.description)}catch{}return e},re=(e,r,t)=>{let s=t?" ".repeat(t-e.length+3):" ",o=`[${r}]`.padEnd(11);return`${e}${s}${o}`},y=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",E=e=>{let{branches:r,descriptions:t,types:s}=e,o=r.map(i=>i.replace("release/v","")),n=Math.max(...o.map(i=>i.length));return r.map((i,l)=>{let c=o[l],p=s?s.get(i)||"regular":void 0,d=t.get(`v${c}`),u=" ".repeat(n-c.length+3),h=p?re(c,p,n):c;return d&&(h=p?`${h} ${d}`:`${c}${u}${d}`),{name:h,value:i}})};var Cr=e=>e.replace("release/","").slice(1).split(".").map(Number),Ue=e=>[...e].sort((r,t)=>{let[s,o,n]=Cr(r),[i,l,c]=Cr(t);return s!==i?(s??0)-(i??0):o!==l?(o??0)-(l??0):(n??0)-(c??0)});var Gr=async()=>{let e=await P`gh pr list --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName`,r=await P`gh pr list --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName`,t=[...JSON.parse(e.stdout),...JSON.parse(r.stdout)],s=new Set;return t.filter(o=>s.has(o.headRefName)?!1:(s.add(o.headRefName),!0))},He=async()=>{try{let e=await Gr();return e.length===0&&(a.error("\u274C No release PRs found. Check the project folder for the script. Exiting..."),Ge.exit(1)),Ue(e.map(r=>r.headRefName))}catch(e){a.error({error:e},"\u274C Error fetching release PRs"),Ge.exit(1)}},k=async()=>{try{let e=await Gr();e.length===0&&(a.error("\u274C No release PRs found. Check the project folder for the script. Exiting..."),Ge.exit(1));let r=Ue(e.map(s=>s.headRefName)),t=new Map(e.map(s=>[s.headRefName,s]));return r.map(s=>({branch:s,title:t.get(s).title}))}catch(e){a.error({error:e},"\u274C Error fetching release PRs"),Ge.exit(1)}},ze=async e=>{let{version:r,jiraVersionUrl:t,type:s,description:o}=e,n=s==="hotfix"?"Hotfix":"Release",i=qe(s),l=`release/v${r}`,c=o&&o.trim()!==""?`${t}
26
26
 
27
27
  ${o}`:`${t}
28
- `;try{S.quiet=!0,await S`git switch ${i}`,await S`git pull origin ${i}`,await S`git checkout -b ${l}`,await S`git push -u origin ${l}`,await S`git commit --allow-empty-message --allow-empty --message ''`,await S`git push origin ${l}`;let d=(await S`gh pr create --title "${n} v${r}" --body ${c} --base ${i} --head ${l}`).stdout.trim();return await S`git switch ${i}`,S.quiet=!1,{branchName:l,prUrl:d}}catch(p){throw a.error({error:p,branchName:l},`Error creating release branch ${l}`),p}};var Ge=async e=>{let{all:r,confirmedCommand:t}=e;m.start("merge-dev");let o=(await k()).filter(d=>y(d.title)==="regular").map(d=>d.branch);if(o.length===0)return a.info("\u2139\uFE0F No open release branches found"),m.print(),{content:[{type:"text",text:JSON.stringify({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0},null,2)}],structuredContent:{successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0}};let n=[];if(r)n=o;else{m.setInteractive();let d=await R();n=await so({required:!0,message:"\u{1F33F} Select release branches",choices:I({branches:o,descriptions:d})})}n.length===o.length?m.addOption("--all",!0):m.addOption("--versions",n.map(d=>d.replace("release/v","")));let l=t?!0:await no({message:`Are you sure you want to merge dev into these branches: ${n.join(", ")}?`});t||m.setInteractive(),l||(a.info("Operation cancelled. Exiting..."),io.exit(0)),t||m.addOption("--yes",!0),A.quiet=!0,await A`git fetch origin`,await A`git switch dev`,await A`git pull origin dev`;let c=[];for(let d of n)await ao(d)||c.push(d);if(A.quiet=!1,c.length>0){a.info(`
28
+ `;try{P.quiet=!0,await P`git switch ${i}`,await P`git pull origin ${i}`,await P`git checkout -b ${l}`,await P`git push -u origin ${l}`,await P`git commit --allow-empty-message --allow-empty --message ''`,await P`git push origin ${l}`;let d=(await P`gh pr create --title "${n} v${r}" --body ${c} --base ${i} --head ${l}`).stdout.trim();return await P`git switch ${i}`,P.quiet=!1,{branchName:l,prUrl:d}}catch(p){throw a.error({error:p,branchName:l},`Error creating release branch ${l}`),p}};var Ye=async e=>{let{all:r,confirmedCommand:t}=e;m.start("merge-dev");let o=(await k()).filter(d=>y(d.title)==="regular").map(d=>d.branch);if(o.length===0)return a.info("\u2139\uFE0F No open release branches found"),m.print(),{content:[{type:"text",text:JSON.stringify({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0},null,2)}],structuredContent:{successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0}};let n=[];if(r)n=o;else{m.setInteractive();let d=await C();n=await po({required:!0,message:"\u{1F33F} Select release branches",choices:E({branches:o,descriptions:d})})}n.length===o.length?m.addOption("--all",!0):m.addOption("--versions",n.map(d=>d.replace("release/v","")));let l=t?!0:await mo({message:`Are you sure you want to merge dev into these branches: ${n.join(", ")}?`});t||m.setInteractive(),l||(a.info("Operation cancelled. Exiting..."),uo.exit(0)),t||m.addOption("--yes",!0),O.quiet=!0,await O`git fetch origin`,await O`git switch dev`,await O`git pull origin dev`;let c=[];for(let d of n)await fo(d)||c.push(d);if(O.quiet=!1,c.length>0){a.info(`
29
29
  \u26A0\uFE0F ${c.length} branch(es) failed to merge automatically.
30
30
  `),a.info("\u{1F4CB} Manual merge script for failed branches:");for(let d of c)a.info(`# Merge dev into ${d} and resolve conflicts if any
31
31
 
32
32
  git switch ${d} && git pull origin ${d} && git merge origin/dev
33
33
  git push origin ${d} && git switch dev
34
34
  `);a.info(`\u2705 ${n.length-c.length}/${n.length} merges completed successfully.`)}else a.info(`\u2705 All merges completed successfully!
35
- `);m.print();let p={successfulMerges:n.length-c.length,failedMerges:c.length,failedBranches:c,totalBranches:n.length};return{content:[{type:"text",text:JSON.stringify(p,null,2)}],structuredContent:p}},ao=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`,a.info(`Successfully merged dev into ${e}`),!0}catch(r){return a.error({error:r,branch:e},`Error merging dev into ${e}`),await A`git reset --merge HEAD~1`,!1}},co={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:re.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:re.number().describe("Number of successful merges"),failedMerges:re.number().describe("Number of failed merges"),failedBranches:re.array(re.string()).describe("List of branches that failed to merge"),totalBranches:re.number().describe("Total number of branches processed")},handler:Ge};import lo from"@inquirer/confirm";import po from"@inquirer/select";import yr from"node:process";import{z as ve}from"zod/v4";import{$}from"zx";var Ue=async e=>{let{version:r,confirmedCommand:t}=e;m.start("release-deliver");let s=await k(),o=s.map(u=>u.branch),n=new Map(s.map(u=>[u.branch,y(u.title)])),i="";if(r)i=`release/v${r}`;else{m.setInteractive();let u=await R();i=await po({message:"\u{1F33F} Select release branch",choices:I({branches:o,descriptions:u,types:n})})}let l=i.replace("release/v","");m.addOption("--version",l);let c=s.find(u=>u.branch===i);c||(a.error(`\u274C Release branch ${i} not found in open PRs. Exiting...`),yr.exit(1));let p=y(c.title),d=t?!0:await lo({message:`Are you sure you want to deliver version ${i} to production?`});t||m.setInteractive(),d||(a.info("Operation cancelled. Exiting..."),yr.exit(0)),m.addOption("--yes",!0);try{$.quiet=!0,p==="hotfix"?(await $`gh pr merge ${i} --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 ${i} --squash --admin --delete-branch`,await $`gh pr create --base main --head dev --title "Release v${l} (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 ue();if(u)try{let f=i.replace("release/","");await vr({versionName:f},u)}catch(f){a.error({error:f},"Failed to deliver Jira release (non-blocking)")}else a.info("\u{1F514} Jira is not configured, skipping Jira release delivery");a.info(`Successfully delivered ${i} to production!`),m.print();let h={releaseBranch:i,version:i.replace("release/v",""),type:p,success:!0};return{content:[{type:"text",text:JSON.stringify(h,null,2)}],structuredContent:h}}catch(u){a.error({error:u},"\u274C Error merging release branch into dev"),yr.exit(1)}},mo={name:"gh-release-deliver",description:'Deliver a release to production. For hotfixes: squash-merges the release branch to main and dispatches the deploy-all workflow. For regular releases: squash-merges to dev, opens an RC PR, merges dev into main, dispatches the deploy-all workflow, then syncs main back to dev. Also releases the matching Jira fix version if Jira is configured. Dispatches the deploy workflow fire-and-forget \u2014 the tool returns once the workflow is accepted by GitHub, not when the deployment finishes. Irreversible production operation: the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. "version" is required when invoked via MCP (the picker is unreachable without a TTY).',inputSchema:{version:ve.string().describe('Release version to deliver to production (e.g., "1.2.5"). Required for MCP calls.')},outputSchema:{releaseBranch:ve.string().describe("The release branch that was delivered"),version:ve.string().describe("The version that was delivered"),type:ve.enum(["regular","hotfix"]).describe("Release type"),success:ve.boolean().describe("Whether the delivery was successful")},handler:Ue};import Br from"@inquirer/select";import Kr from"node:process";import{z as M}from"zod/v4";import{$ as kr}from"zx";var He=async e=>{let{version:r,env:t,skipTerraform:s}=e;m.start("release-deploy-all");let o="";if(r)o=r==="dev"?"dev":`release/v${r}`;else{m.setInteractive();let p=await k(),d=p.map(f=>f.branch),u=new Map(p.map(f=>[f.branch,y(f.title)])),h=await R();o=await Br({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...I({branches:d,descriptions:h,types:u})]})}let n=o==="dev"?"dev":o.replace("release/v","");m.addOption("--version",n);let{environments:i}=await w(),l="";t?l=t:(m.setInteractive(),l=await Br({message:"\u{1F9EA} Select environment",choices:i.map(p=>({name:p,value:p}))})),m.addOption("--env",l),i.includes(l)||(a.error(`\u274C Invalid environment: ${l}. Exiting...`),Kr.exit(1));let c=s??!1;c&&m.addOption("--skip-terraform",!0);try{kr.quiet=!0,await kr`gh workflow run deploy-all.yml --ref ${o} -f environment=${l} ${c?["-f","skip_terraform_deploy=true"]:[]}`,kr.quiet=!1,a.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${o} and environment: ${l}`),m.print();let d={releaseBranch:o,version:o.replace("release/v",""),environment:l,skipTerraformDeploy:c,success:!0};return{content:[{type:"text",text:JSON.stringify(d,null,2)}],structuredContent:d}}catch(p){a.error({error:p},"\u274C Error launching workflow"),Kr.exit(1)}},uo={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:M.string().describe('Release version to deploy from (e.g. "1.2.5") \u2014 resolves to the release/vX.Y.Z branch. Pass "dev" to deploy from the dev branch instead. Required for MCP calls.'),env:M.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),skipTerraform:M.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:M.string().describe("The release branch that was deployed"),version:M.string().describe("The version that was deployed"),environment:M.string().describe("The environment deployed to"),skipTerraformDeploy:M.boolean().describe("Whether terraform deployment was skipped"),success:M.boolean().describe("Whether the deployment was successful")},handler:He};import fo from"@inquirer/checkbox";import qr from"@inquirer/select";import ho from"node:fs/promises";import{resolve as go}from"node:path";import we from"node:process";import vo from"yaml";import{z as E}from"zod/v4";import{$ as Rr}from"zx";var Ye=async e=>{let{version:r,env:t,services:s,skipTerraform:o}=e;m.start("release-deploy-selected");let n="";if(r)n=r==="dev"?"dev":`release/v${r}`;else{m.setInteractive();let f=await k(),P=f.map(W=>W.branch),L=new Map(f.map(W=>[W.branch,y(W.title)])),T=await R();n=await qr({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...I({branches:P,descriptions:T,types:L})]})}let i=n==="dev"?"dev":n.replace("release/v","");m.addOption("--version",i);let{environments:l}=await w(),c="";t?c=t:(m.setInteractive(),c=await qr({message:"\u{1F9EA} Select environment",choices:l.map(f=>({name:f,value:f}))})),m.addOption("--env",c),l.includes(c)||(a.error(`\u274C Invalid environment: ${c}. Exiting...`),we.exit(1));let p=await wo();p.length===0&&(a.error("\u274C No services found in workflow file. Exiting..."),we.exit(1));let d=[];s&&s.length>0?d=s:(m.setInteractive(),d=await fo({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:p.map(f=>({name:f,value:f}))})),m.addOption("--services",d),d.length===0&&(a.error("\u274C No services selected. Exiting..."),we.exit(1));let u=d.filter(f=>!p.includes(f));u.length>0&&(a.error(`\u274C Invalid services: ${u.join(", ")}. Available services: ${p.join(", ")}`),we.exit(1));let h=o??!1;h&&m.addOption("--skip-terraform",!0);try{Rr.quiet=!0;let f=d.flatMap(T=>["-f",`${T}=true`]);await Rr`gh workflow run deploy-selected-services.yml --ref ${n} -f environment=${c} ${f} ${h?["-f","skip_terraform_deploy=true"]:[]}`,Rr.quiet=!1,a.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${n}, environment: ${c}, services: ${d.join(", ")}`),m.print();let L={releaseBranch:n,version:n.replace("release/v",""),environment:c,services:d,skipTerraformDeploy:h,success:!0};return{content:[{type:"text",text:JSON.stringify(L,null,2)}],structuredContent:L}}catch(f){a.error({error:f},"\u274C Error launching workflow"),we.exit(1)}},wo=async()=>{let e=await C(),r=go(e,".github/workflows/deploy-selected-services.yml"),t=await ho.readFile(r,"utf-8"),o=vo.parse(t).on.workflow_dispatch.inputs,n=[];for(let[i,l]of Object.entries(o))l.type==="boolean"&&i!=="skip_terraform_deploy"&&n.push(i);return n},yo={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:E.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:E.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),services:E.array(E.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:E.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:E.string().describe("The release branch that was deployed"),version:E.string().describe("The version that was deployed"),environment:E.string().describe("The environment deployed to"),services:E.array(E.string()).describe("The services that were deployed"),skipTerraformDeploy:E.boolean().describe("Whether terraform deployment was skipped"),success:E.boolean().describe("Whether the deployment was successful")},handler:Ye};import{z as te}from"zod/v4";var Xe=async()=>{let r=(await k()).map(i=>({version:i.branch.replace("release/",""),type:y(i.title)})),t=await R(),s=Math.max(...r.map(i=>i.version.length)),o=r.map(i=>{let l=ee(i.version,i.type,s),c=t.get(i.version);return c?`${l} ${c}`:l});a.info(`All release branches:
35
+ `);m.print();let p={successfulMerges:n.length-c.length,failedMerges:c.length,failedBranches:c,totalBranches:n.length};return{content:[{type:"text",text:JSON.stringify(p,null,2)}],structuredContent:p}},fo=async e=>{try{return await O`git switch ${e}`,await O`git pull origin ${e}`,await O`git merge origin/dev --no-edit`,await O`git push origin ${e}`,await O`git switch dev`,a.info(`Successfully merged dev into ${e}`),!0}catch(r){return a.error({error:r,branch:e},`Error merging dev into ${e}`),await O`git reset --merge HEAD~1`,!1}},ho={name:"gh-merge-dev",description:"Merge origin/dev into every open regular (non-hotfix) release branch and push the result. Mutates local git state and the remote release branches. When invoked via MCP, pass all=true \u2014 the branch picker is unreachable without a TTY, and the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. Irreversible once pushed.",inputSchema:{all:te.boolean().optional().describe("Target every open regular release branch. Must be true for MCP calls (the interactive picker is unavailable without a TTY).")},outputSchema:{successfulMerges:te.number().describe("Number of successful merges"),failedMerges:te.number().describe("Number of failed merges"),failedBranches:te.array(te.string()).describe("List of branches that failed to merge"),totalBranches:te.number().describe("Total number of branches processed")},handler:Ye};import go from"@inquirer/confirm";import vo from"@inquirer/select";import xr from"node:process";import{z as ye}from"zod/v4";import{$ as S}from"zx";var Xe=async e=>{let{version:r,confirmedCommand:t}=e;m.start("release-deliver");let s=await k(),o=s.map(u=>u.branch),n=new Map(s.map(u=>[u.branch,y(u.title)])),i="";if(r)i=`release/v${r}`;else{m.setInteractive();let u=await C();i=await vo({message:"\u{1F33F} Select release branch",choices:E({branches:o,descriptions:u,types:n})})}let l=i.replace("release/v","");m.addOption("--version",l);let c=s.find(u=>u.branch===i);c||(a.error(`\u274C Release branch ${i} not found in open PRs. Exiting...`),xr.exit(1));let p=y(c.title),d=t?!0:await go({message:`Are you sure you want to deliver version ${i} to production?`});t||m.setInteractive(),d||(a.info("Operation cancelled. Exiting..."),xr.exit(0)),m.addOption("--yes",!0);try{S.quiet=!0,p==="hotfix"?(await S`gh pr merge ${i} --squash --admin --delete-branch`,S.quiet=!1,await S`gh workflow run deploy-all.yml --ref main -f environment=prod`,S.quiet=!0,await S`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`):(await S`gh pr merge ${i} --squash --admin --delete-branch`,await S`gh pr create --base main --head dev --title "Release v${l} (RC)" --body ""`,await S`gh pr merge dev --squash --admin`,S.quiet=!1,await S`gh workflow run deploy-all.yml --ref main -f environment=prod`,S.quiet=!0,await S`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`),S.quiet=!1;let u=await he();if(u)try{let f=i.replace("release/","");await br({versionName:f},u)}catch(f){a.error({error:f},"Failed to deliver Jira release (non-blocking)")}else a.info("\u{1F514} Jira is not configured, skipping Jira release delivery");a.info(`Successfully delivered ${i} to production!`),m.print();let h={releaseBranch:i,version:i.replace("release/v",""),type:p,success:!0};return{content:[{type:"text",text:JSON.stringify(h,null,2)}],structuredContent:h}}catch(u){a.error({error:u},"\u274C Error merging release branch into dev"),xr.exit(1)}},wo={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:ye.string().describe('Release version to deliver to production (e.g., "1.2.5"). Required for MCP calls.')},outputSchema:{releaseBranch:ye.string().describe("The release branch that was delivered"),version:ye.string().describe("The version that was delivered"),type:ye.enum(["regular","hotfix"]).describe("Release type"),success:ye.boolean().describe("Whether the delivery was successful")},handler:Xe};import Hr from"@inquirer/select";import Yr from"node:process";import{z as J}from"zod/v4";import{$ as Tr}from"zx";var Ze=async e=>{let{version:r,env:t,skipTerraform:s}=e;m.start("release-deploy-all");let o="";if(r)o=r==="dev"?"dev":`release/v${r}`;else{m.setInteractive();let p=await k(),d=p.map(f=>f.branch),u=new Map(p.map(f=>[f.branch,y(f.title)])),h=await C();o=await Hr({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...E({branches:d,descriptions:h,types:u})]})}let n=o==="dev"?"dev":o.replace("release/v","");m.addOption("--version",n);let{environments:i}=await w(),l="";t?l=t:(m.setInteractive(),l=await Hr({message:"\u{1F9EA} Select environment",choices:i.map(p=>({name:p,value:p}))})),m.addOption("--env",l),i.includes(l)||(a.error(`\u274C Invalid environment: ${l}. Exiting...`),Yr.exit(1));let c=s??!1;c&&m.addOption("--skip-terraform",!0);try{Tr.quiet=!0,await Tr`gh workflow run deploy-all.yml --ref ${o} -f environment=${l} ${c?["-f","skip_terraform_deploy=true"]:[]}`,Tr.quiet=!1,a.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${o} and environment: ${l}`),m.print();let d={releaseBranch:o,version:o.replace("release/v",""),environment:l,skipTerraformDeploy:c,success:!0};return{content:[{type:"text",text:JSON.stringify(d,null,2)}],structuredContent:d}}catch(p){a.error({error:p},"\u274C Error launching workflow"),Yr.exit(1)}},yo={name:"gh-release-deploy-all",description:'Dispatch the deploy-all.yml GitHub Actions workflow to deploy every service from a release branch to the given environment. Fire-and-forget \u2014 returns once GitHub accepts the workflow_dispatch, NOT when the deployment finishes; watch the workflow run for completion status. Use gh-release-deploy-selected for a subset of services. Pass version="dev" to deploy from the dev branch instead of a release branch. Both "version" and "env" are required when invoked via MCP (interactive pickers are unavailable without a TTY).',inputSchema:{version:J.string().describe('Release version to deploy from (e.g. "1.2.5") \u2014 resolves to the release/vX.Y.Z branch. Pass "dev" to deploy from the dev branch instead. Required for MCP calls.'),env:J.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),skipTerraform:J.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:J.string().describe("The release branch that was deployed"),version:J.string().describe("The version that was deployed"),environment:J.string().describe("The environment deployed to"),skipTerraformDeploy:J.boolean().describe("Whether terraform deployment was skipped"),success:J.boolean().describe("Whether the deployment was successful")},handler:Ze};import ko from"@inquirer/checkbox";import Xr from"@inquirer/select";import Ro from"node:fs/promises";import{resolve as bo}from"node:path";import ke from"node:process";import Co from"yaml";import{z as A}from"zod/v4";import{$ as $r}from"zx";var Qe=async e=>{let{version:r,env:t,services:s,skipTerraform:o}=e;m.start("release-deploy-selected");let n="";if(r)n=r==="dev"?"dev":`release/v${r}`;else{m.setInteractive();let f=await k(),R=f.map(B=>B.branch),I=new Map(f.map(B=>[B.branch,y(B.title)])),T=await C();n=await Xr({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...E({branches:R,descriptions:T,types:I})]})}let i=n==="dev"?"dev":n.replace("release/v","");m.addOption("--version",i);let{environments:l}=await w(),c="";t?c=t:(m.setInteractive(),c=await Xr({message:"\u{1F9EA} Select environment",choices:l.map(f=>({name:f,value:f}))})),m.addOption("--env",c),l.includes(c)||(a.error(`\u274C Invalid environment: ${c}. Exiting...`),ke.exit(1));let p=await xo();p.length===0&&(a.error("\u274C No services found in workflow file. Exiting..."),ke.exit(1));let d=[];s&&s.length>0?d=s:(m.setInteractive(),d=await ko({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:p.map(f=>({name:f,value:f}))})),m.addOption("--services",d),d.length===0&&(a.error("\u274C No services selected. Exiting..."),ke.exit(1));let u=d.filter(f=>!p.includes(f));u.length>0&&(a.error(`\u274C Invalid services: ${u.join(", ")}. Available services: ${p.join(", ")}`),ke.exit(1));let h=o??!1;h&&m.addOption("--skip-terraform",!0);try{$r.quiet=!0;let f=d.flatMap(T=>["-f",`${T}=true`]);await $r`gh workflow run deploy-selected-services.yml --ref ${n} -f environment=${c} ${f} ${h?["-f","skip_terraform_deploy=true"]:[]}`,$r.quiet=!1,a.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${n}, environment: ${c}, services: ${d.join(", ")}`),m.print();let I={releaseBranch:n,version:n.replace("release/v",""),environment:c,services:d,skipTerraformDeploy:h,success:!0};return{content:[{type:"text",text:JSON.stringify(I,null,2)}],structuredContent:I}}catch(f){a.error({error:f},"\u274C Error launching workflow"),ke.exit(1)}},xo=async()=>{let e=await b(),r=bo(e,".github/workflows/deploy-selected-services.yml"),t=await Ro.readFile(r,"utf-8"),o=Co.parse(t).on.workflow_dispatch.inputs,n=[];for(let[i,l]of Object.entries(o))l.type==="boolean"&&i!=="skip_terraform_deploy"&&n.push(i);return n},To={name:"gh-release-deploy-selected",description:'Dispatch the deploy-selected-services.yml GitHub Actions workflow to deploy a chosen subset of services from a release branch to the given environment. Fire-and-forget \u2014 returns once GitHub accepts the workflow_dispatch, NOT when the deployment finishes; watch the workflow run for completion status. Service names are validated against the boolean inputs declared in the workflow. Use gh-release-deploy-all for every service. "version", "env", and "services" are all required when invoked via MCP (interactive pickers are unavailable without a TTY).',inputSchema:{version:A.string().describe('Release version to deploy from (e.g. "1.2.5") \u2014 resolves to the release/vX.Y.Z branch. Pass "dev" to deploy from the dev branch instead. Required for MCP calls.'),env:A.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),services:A.array(A.string()).describe('Service names to deploy. Each must match a boolean input declared in .github/workflows/deploy-selected-services.yml (e.g. "client-be", "client-fe"). Required for MCP calls.'),skipTerraform:A.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:A.string().describe("The release branch that was deployed"),version:A.string().describe("The version that was deployed"),environment:A.string().describe("The environment deployed to"),services:A.array(A.string()).describe("The services that were deployed"),skipTerraformDeploy:A.boolean().describe("Whether terraform deployment was skipped"),success:A.boolean().describe("Whether the deployment was successful")},handler:Qe};import{z as oe}from"zod/v4";var er=async()=>{let r=(await k()).map(i=>({version:i.branch.replace("release/",""),type:y(i.title)})),t=await C(),s=Math.max(...r.map(i=>i.version.length)),o=r.map(i=>{let l=re(i.version,i.type,s),c=t.get(i.version);return c?`${l} ${c}`:l});a.info(`All release branches:
36
36
  `),a.info(`
37
37
  ${o.join(`
38
38
  `)}
39
- `);let n={releases:r.map(i=>({version:i.version,type:i.type,description:t.get(i.version)||null})),count:r.length};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}},ko={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:te.array(te.object({version:te.string().describe("Release version"),type:te.enum(["regular","hotfix"]).describe("Release type"),description:te.string().nullable().describe("Jira version description")})).describe("List of all release branches"),count:te.number().describe("Number of release branches")},handler:Xe};import zr from"@inquirer/confirm";import Ro from"@inquirer/select";import Gr from"node:process";import{z as _}from"zod/v4";import{$ as br,question as Ur}from"zx";var Ze=async e=>{let{version:r,description:t,type:s,confirmedCommand:o,checkout:n}=e;m.start("release-create");let i=r,l=t,c=s||"regular",p=n,d=await Q();i||(m.setInteractive(),i=await Ur("Enter version (e.g. 1.2.5): ")),(!i||i.trim()==="")&&(a.error("No version provided. Exiting..."),Gr.exit(1));let u=i.trim();m.addOption("--version",u),s||(m.setInteractive(),c=await Ro({message:"Select release type:",choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"})),m.addOption("--type",c),l===void 0&&(m.setInteractive(),l=await Ur("Enter description (optional, press Enter to skip): "),l.trim()===""&&(l="")),l&&m.addOption("--description",l);let h=o?!0:await zr({message:`Are you sure you want to create release branch for version ${u}?`});o||m.setInteractive(),h||(a.info("Operation cancelled. Exiting..."),Gr.exit(0)),m.addOption("--yes",!0),await he(c);let f=await ge({version:u,jiraConfig:d,description:l,type:c});a.info(`\u2705 Successfully created release: v${u}`),a.info(`\u{1F517} GitHub PR: ${f.prUrl}`),a.info(`\u{1F517} Jira Version: ${f.jiraVersionUrl}`),p===void 0&&(m.setInteractive(),p=await zr({message:`Do you want to checkout to the created branch ${f.branchName}?`,default:!0})),p||m.addOption("--no-checkout",!0),p&&(br.quiet=!0,await br`git switch ${f.branchName}`,br.quiet=!1,a.info(`\u{1F504} Switched to branch ${f.branchName}`)),m.print();let P={version:u,type:c,branchName:f.branchName,prUrl:f.prUrl,jiraVersionUrl:f.jiraVersionUrl,isCheckedOut:p};return{content:[{type:"text",text:JSON.stringify(P,null,2)}],structuredContent:P}},bo={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:_.string().describe('Version to create (e.g., "1.2.5"). Required for MCP calls.'),description:_.string().optional().describe("Optional description for the Jira version"),type:_.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" or "hotfix" (default: "regular")'),checkout:_.boolean().optional().default(!0).describe("Checkout to the created branch (default: true)")},outputSchema:{version:_.string().describe("Version number"),type:_.enum(["regular","hotfix"]).describe("Release type"),branchName:_.string().describe("Release branch name"),prUrl:_.string().describe("GitHub PR URL"),jiraVersionUrl:_.string().describe("Jira version URL"),isCheckedOut:_.boolean().describe("Whether the branch was checked out")},handler:Ze};import xo from"@inquirer/confirm";import Co from"@inquirer/select";import Hr from"node:process";import{z as b}from"zod/v4";import{question as To}from"zx";var $o=async e=>{let{versions:r,type:t,confirmedCommand:s}=e,o=r,n=t||"regular";o||(m.setInteractive(),o=await To("Enter versions by comma (e.g. 1.2.5, 1.2.6): "));let i=o.split(",").map(c=>c.trim()).filter(Boolean);m.addOption("--versions",i.join(", ")),i.length===0&&(a.error("No versions provided. Exiting..."),Hr.exit(1)),t||(m.setInteractive(),n=await Co({message:"Select release type:",choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"})),m.addOption("--type",n),i.length===1&&a.warn('\u{1F4A1} You are creating only one release. Consider using "create-release" command for single releases.');let l=s?!0:await xo({message:`Are you sure you want to create release branches for these versions: ${i.join(", ")}?`});return s||m.setInteractive(),l||(a.info("Operation cancelled. Exiting..."),Hr.exit(0)),m.addOption("--yes",!0),{versionsList:i,type:n}},Qe=async e=>{m.start("release-create-batch");let r=await Q(),{versionsList:t,type:s}=await $o(e);await he(s);let o=[],n=[];for(let p of t)try{let d=await ge({version:p,jiraConfig:r,type:s});o.push(d),a.info(`\u2705 Successfully created release: v${p}`),a.info(`\u{1F517} GitHub PR: ${d.prUrl}`),a.info(`\u{1F517} Jira Version: ${d.jiraVersionUrl}
39
+ `);let n={releases:r.map(i=>({version:i.version,type:i.type,description:t.get(i.version)||null})),count:r.length};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}},$o={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:oe.array(oe.object({version:oe.string().describe("Release version"),type:oe.enum(["regular","hotfix"]).describe("Release type"),description:oe.string().nullable().describe("Jira version description")})).describe("List of all release branches"),count:oe.number().describe("Number of release branches")},handler:er};import Zr from"@inquirer/confirm";import So from"@inquirer/select";import Qr from"node:process";import{z as N}from"zod/v4";import{$ as Sr,question as et}from"zx";var rr=async e=>{let{version:r,description:t,type:s,confirmedCommand:o,checkout:n}=e;m.start("release-create");let i=r,l=t,c=s||"regular",p=n,d=await ee();i||(m.setInteractive(),i=await et("Enter version (e.g. 1.2.5): ")),(!i||i.trim()==="")&&(a.error("No version provided. Exiting..."),Qr.exit(1));let u=i.trim();m.addOption("--version",u),s||(m.setInteractive(),c=await So({message:"Select release type:",choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"})),m.addOption("--type",c),l===void 0&&(m.setInteractive(),l=await et("Enter description (optional, press Enter to skip): "),l.trim()===""&&(l="")),l&&m.addOption("--description",l);let h=o?!0:await Zr({message:`Are you sure you want to create release branch for version ${u}?`});o||m.setInteractive(),h||(a.info("Operation cancelled. Exiting..."),Qr.exit(0)),m.addOption("--yes",!0),await ve(c);let f=await we({version:u,jiraConfig:d,description:l,type:c});a.info(`\u2705 Successfully created release: v${u}`),a.info(`\u{1F517} GitHub PR: ${f.prUrl}`),a.info(`\u{1F517} Jira Version: ${f.jiraVersionUrl}`),p===void 0&&(m.setInteractive(),p=await Zr({message:`Do you want to checkout to the created branch ${f.branchName}?`,default:!0})),p||m.addOption("--no-checkout",!0),p&&(Sr.quiet=!0,await Sr`git switch ${f.branchName}`,Sr.quiet=!1,a.info(`\u{1F504} Switched to branch ${f.branchName}`)),m.print();let R={version:u,type:c,branchName:f.branchName,prUrl:f.prUrl,jiraVersionUrl:f.jiraVersionUrl,isCheckedOut:p};return{content:[{type:"text",text:JSON.stringify(R,null,2)}],structuredContent:R}},Io={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:N.string().describe('Version to create (e.g., "1.2.5"). Required for MCP calls.'),description:N.string().optional().describe("Optional description for the Jira version"),type:N.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" or "hotfix" (default: "regular")'),checkout:N.boolean().optional().default(!0).describe("Checkout to the created branch (default: true)")},outputSchema:{version:N.string().describe("Version number"),type:N.enum(["regular","hotfix"]).describe("Release type"),branchName:N.string().describe("Release branch name"),prUrl:N.string().describe("GitHub PR URL"),jiraVersionUrl:N.string().describe("Jira version URL"),isCheckedOut:N.boolean().describe("Whether the branch was checked out")},handler:rr};import Eo from"@inquirer/confirm";import Po from"@inquirer/select";import rt from"node:process";import{z as x}from"zod/v4";import{question as Ao}from"zx";var _o=async e=>{let{versions:r,type:t,confirmedCommand:s}=e,o=r,n=t||"regular";o||(m.setInteractive(),o=await Ao("Enter versions by comma (e.g. 1.2.5, 1.2.6): "));let i=o.split(",").map(c=>c.trim()).filter(Boolean);m.addOption("--versions",i.join(", ")),i.length===0&&(a.error("No versions provided. Exiting..."),rt.exit(1)),t||(m.setInteractive(),n=await Po({message:"Select release type:",choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"})),m.addOption("--type",n),i.length===1&&a.warn('\u{1F4A1} You are creating only one release. Consider using "create-release" command for single releases.');let l=s?!0:await Eo({message:`Are you sure you want to create release branches for these versions: ${i.join(", ")}?`});return s||m.setInteractive(),l||(a.info("Operation cancelled. Exiting..."),rt.exit(0)),m.addOption("--yes",!0),{versionsList:i,type:n}},tr=async e=>{m.start("release-create-batch");let r=await ee(),{versionsList:t,type:s}=await _o(e);await ve(s);let o=[],n=[];for(let p of t)try{let d=await we({version:p,jiraConfig:r,type:s});o.push(d),a.info(`\u2705 Successfully created release: v${p}`),a.info(`\u{1F517} GitHub PR: ${d.prUrl}`),a.info(`\u{1F517} Jira Version: ${d.jiraVersionUrl}
40
40
  `)}catch(d){let u=d instanceof Error?d.message:String(d);n.push({version:p,error:u}),a.error(`\u274C Failed to create release: v${p}`),a.error(` Error: ${u}
41
- `)}let i=o.length,l=n.length;i===t.length?a.info(`\u2705 All ${t.length} release branches were created successfully.`):i>0?(a.warn(`\u26A0\uFE0F ${i} of ${t.length} release branches were created successfully.`),a.warn(`\u274C ${l} release(s) failed.`)):a.error(`\u274C All ${t.length} release branches failed to create.`),m.print();let c={createdBranches:o.map(p=>p.branchName),successCount:i,failureCount:l,releases:o,failedReleases:n};return{content:[{type:"text",text:JSON.stringify(c,null,2)}],structuredContent:c}},Io={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:b.string().describe('Comma-separated list of versions to create (e.g., "1.2.5, 1.2.6"). Required for MCP calls.'),type:b.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" or "hotfix" (default: "regular")')},outputSchema:{createdBranches:b.array(b.string()).describe("List of created release branches"),successCount:b.number().describe("Number of releases created successfully"),failureCount:b.number().describe("Number of releases that failed"),releases:b.array(b.object({version:b.string().describe("Version number"),type:b.enum(["regular","hotfix"]).describe("Release type"),branchName:b.string().describe("Release branch name"),prUrl:b.string().describe("GitHub PR URL"),jiraVersionUrl:b.string().describe("Jira version URL")})).describe("Detailed information for each created release with URLs"),failedReleases:b.array(b.object({version:b.string().describe("Version number that failed"),error:b.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:Qe};import{z as Eo}from"zod/v4";var Yr={name:"infra-kit",type:"module",version:"0.1.95",description:"infra-kit",main:"dist/cli.js",module:"dist/cli.js",bin:{"infra-kit":"dist/cli.js",ik:"dist/cli.js"},engines:{node:">=24.x"},scripts:{inspector:"npx @modelcontextprotocol/inspector node ./dist/mcp.js --debug",build:"pnpm run clean-artifacts && node ./scripts/build.js","clean-artifacts":"rm -rf dist","clean-cache":"rm -rf node_modules/.cache .eslintcache tsconfig.tsbuildinfo .turbo .swc","prettier-fix":"pnpm exec prettier **/* --write --no-error-on-unmatched-pattern --log-level warn --ignore-path ../../../.prettierignore","prettier-check":"pnpm exec prettier **/* --check --no-error-on-unmatched-pattern --log-level warn --ignore-path ../../../.prettierignore","eslint-check":"pnpm exec eslint --cache --quiet --report-unused-disable-directives ./src","eslint-fix":"pnpm exec eslint --cache --quiet --report-unused-disable-directives ./src --fix","ts-check":"tsc --noEmit",test:"pnpm exec vitest run --reporter=dot","test-watch":"pnpm exec vitest --watch","test-ui":"pnpm exec vitest --ui","test-report":"pnpm exec vitest run --coverage",qa:"pnpm run prettier-check && pnpm run eslint-check && pnpm run ts-check && pnpm run test && echo \u2705 Success",fix:"pnpm run prettier-fix && pnpm run eslint-fix && pnpm run qa"},dependencies:{"@inquirer/checkbox":"^5.1.4","@inquirer/confirm":"^6.0.12","@inquirer/select":"^5.1.4","@modelcontextprotocol/sdk":"^1.29.0",commander:"^14.0.3",pino:"^10.3.1","pino-pretty":"^13.1.3",yaml:"^2.8.3",zod:"^3.25.76",zx:"^8.8.5"},devDependencies:{"@pkg/eslint-config":"workspace:*","@pkg/vitest-config":"workspace:*",esbuild:"^0.28.0",typescript:"catalog:"}};var er=async()=>{let e=Yr.version;a.info(e);let r={version:e};return{content:[{type:"text",text:JSON.stringify(r,null,2)}],structuredContent:r}},Ao={name:"version",description:"Print the installed infra-kit CLI version",inputSchema:{},outputSchema:{version:Eo.string().describe("Installed infra-kit CLI version (from package.json)")},handler:er};import Oo from"@inquirer/checkbox";import Tr from"@inquirer/confirm";import Do from"@inquirer/select";import Lo from"node:process";import{z as F}from"zod/v4";import{$ as K}from"zx";import{$ as Xr}from"zx";var ye=async e=>{try{let r=(await Xr`cmux list-workspaces`.quiet()).stdout,t=Po(r,e);if(!t)return;await Xr`cmux close-workspace --workspace ${t}`.quiet()}catch(r){a.debug({error:r,title:e},"cmux: skipped closing workspace")}},Po=(e,r)=>{for(let t of e.split(`
42
- `)){let s=t.match(/^[* ]\s*(workspace:\d+)\s+(.+?)(?:\s+\[selected\])?\s*$/);if(!s)continue;let o=s[1];if((s[2]?.trim()??"")===r)return o}};import{$ as ke}from"zx";var xr=async e=>{let{cwd:r,title:t}=e,s=(await ke`cmux new-workspace --cwd ${r}`).stdout,o=No(s),n=(await ke`cmux list-pane-surfaces --workspace ${o}`).stdout,i=_o(n);await ke`cmux new-split right --workspace ${o} --surface ${i}`,await ke`cmux new-split down --workspace ${o} --surface ${i}`,t&&await ke`cmux rename-workspace --workspace ${o} ${t}`},_o=e=>{let r=e.match(/surface:\d+/);if(!r)throw new Error("cmux: could not locate initial surface in list-pane-surfaces output");return r[0]},No=e=>{let r=e.match(/workspace:\d+/);if(!r)throw new Error("cmux: could not locate workspace ref in new-workspace output");return r[0]};var V=e=>{let{repoName:r,branch:t}=e,s=t.replace("release/","");return`${r} ${s}`};import Zr from"node:fs/promises";import rr from"node:path";var Cr=async e=>{let{workspacePath:r,folderPaths:t}=e,s=rr.dirname(r),o;try{o=await Zr.readFile(r,"utf-8")}catch(d){throw new Error(`Cursor workspace file not found at ${r}: ${d.message}`)}let n;try{n=JSON.parse(o)}catch(d){throw new Error(`Failed to parse ${r} as JSON. Comments (JSONC) are not supported. ${d.message}`)}let i=n.folders??[],l=new Set(i.map(d=>rr.resolve(s,d.path))),c=[],p=[];for(let d of t){let u=rr.resolve(d);if(l.has(u)){p.push(d);continue}let h=rr.relative(s,u);i.push({path:h}),l.add(u),c.push(d)}return n.folders=i,await Zr.writeFile(r,`${JSON.stringify(n,null,2)}
43
- `,"utf-8"),{added:c,skipped:p}};import Qr from"node:fs/promises";import tr from"node:path";var Re=async e=>{let{workspacePath:r,folderPaths:t}=e,s=tr.dirname(r),o;try{o=await Qr.readFile(r,"utf-8")}catch(h){throw new Error(`Cursor workspace file not found at ${r}: ${h.message}`)}let n;try{n=JSON.parse(o)}catch(h){throw new Error(`Failed to parse ${r} as JSON. Comments (JSONC) are not supported. ${h.message}`)}let i=n.folders??[],l=new Set(t.map(h=>tr.resolve(h))),c=new Set,p=i.filter(h=>{let f=tr.resolve(s,h.path);return l.has(f)?(c.add(f),!1):!0});n.folders=p,await Qr.writeFile(r,`${JSON.stringify(n,null,2)}
44
- `,"utf-8");let d=[],u=[];for(let h of t){let f=tr.resolve(h);c.has(f)?d.push(h):u.push(h)}return{removed:d,notFound:u}};import et from"node:path";var B=(e,r)=>et.isAbsolute(e)?e:et.resolve(r,e);var Mo="feature",Fo="release",Wo="release/v",be=["workspace","windows","none"],or=async e=>{let{confirmedCommand:r,all:t,versions:s,cursor:o,githubDesktop:n,cmux:i}=e;m.start("worktrees-add");try{let l=await D("release"),c=await C(),p=`${c}${X}`;await rt(`${p}/${Fo}`),await rt(`${p}/${Mo}`);let d=[];if(s)d=s.split(",").map(x=>`release/v${x.trim()}`);else{let x=await k(),N=x.map(O=>O.branch);if(N.length===0)return a.info("\u2139\uFE0F No open release branches found"),m.print(),{content:[{type:"text",text:JSON.stringify({createdWorktrees:[],count:0},null,2)}],structuredContent:{createdWorktrees:[],count:0}};if(t)d=N;else{m.setInteractive();let O=new Map(x.map(Ce=>[Ce.branch,y(Ce.title)])),ar=await R();d=await Oo({required:!0,message:"\u{1F33F} Select release branches",choices:I({branches:N,descriptions:ar,types:O})})}}t?m.addOption("--all",!0):m.addOption("--versions",d.map(x=>x.replace("release/v","")));let u=r?!0:await Tr({message:"Are you sure you want to proceed with these worktree changes?"});r||m.setInteractive(),u||(a.info("Operation cancelled. Exiting..."),Lo.exit(0)),r||m.addOption("--yes",!0);let h=o??await Do({message:"Cursor mode for created worktrees?",default:"workspace",choices:[{name:"Add to workspace file",value:"workspace",description:"Append each worktree as a folder in ide.config.workspaceConfigPath, then open the workspace"},{name:"Open separate windows",value:"windows",description:"Open each created worktree in its own Cursor window"},{name:"Skip",value:"none",description:"Do not open Cursor"}]});typeof o>"u"&&m.setInteractive(),m.addOption("--cursor",h);let f=n??await Tr({message:"Open created worktrees in GitHub Desktop?"});typeof n>"u"&&m.setInteractive(),f?m.addOption("--github-desktop",!0):m.addOption("--no-github-desktop",!0);let P=i??await Tr({message:"Open created worktrees in cmux?"});typeof i>"u"&&m.setInteractive(),P?m.addOption("--cmux",!0):m.addOption("--no-cmux",!0);let{branchesToCreate:L}=jo({selectedReleaseBranches:d,currentWorktrees:l}),T=await Jo(L,p);if(Vo(T),h==="workspace"){let x=await w(),N=x.ide?.provider==="cursor"?x.ide.config:void 0;if(!N?.workspaceConfigPath)a.warn("\u26A0\uFE0F Skipping Cursor: ide.config.workspaceConfigPath is not set in infra-kit.yml");else{let O=B(N.workspaceConfigPath,c),ar=T.map(nt=>`${p}/${nt}`),{added:Ce,skipped:Er}=await Cr({workspacePath:O,folderPaths:ar}),st=Er.length>0?` (${Er.length} already present)`:"";a.info(`\u2705 Added ${Ce.length} folder(s) to ${O}${st}`),await K`cursor ${O}`}}else if(h==="windows")for(let x of T)await K`cursor ${p}/${x}`;if(f)for(let x of T)await K`github ${p}/${x}`,await K`sleep 5`;if(P){let x=await j();for(let N of T){let O=V({repoName:x,branch:N});await xr({cwd:`${p}/${N}`,title:O})}}m.print();let W={createdWorktrees:T,count:T.length};return{content:[{type:"text",text:JSON.stringify(W,null,2)}],structuredContent:W}}catch(l){throw a.error({error:l},"\u274C Error managing worktrees"),l}},rt=async e=>{await K`mkdir -p ${e}`},jo=e=>{let{selectedReleaseBranches:r,currentWorktrees:t}=e,s=t.filter(n=>n.startsWith(Wo));return{branchesToCreate:r.filter(n=>!s.includes(n))}},Jo=async(e,r)=>{let t=await Promise.allSettled(e.map(async o=>{let n=`${r}/${o}`;return await K`git worktree add ${n} ${o}`,await K({cwd:n})`pnpm install`,o})),s=[];for(let[o,n]of t.entries())if(n.status==="fulfilled")s.push(n.value);else{let i=e[o];a.error({error:n.reason},`\u274C Failed to create worktree for ${i}`)}return s},Vo=e=>{if(e.length>0){a.info("\u2705 Created git worktrees:");for(let r of e)a.info(r);a.info("")}else a.info("\u2139\uFE0F No new git worktrees to create")},Bo={name:"worktrees-add",description:'Create local git worktrees for release branches under the worktrees directory and run "pnpm install" in each. Mutates the local filesystem. When invoked via MCP, pass either "versions" (comma-separated) or all=true \u2014 the branch picker and "open in Cursor / GitHub Desktop / cmux" follow-up prompts are unreachable without a TTY, and the CLI confirmation is auto-skipped for MCP calls.',inputSchema:{all:F.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:F.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:F.enum(be).optional().describe('Cursor open mode for created worktrees. "workspace" (default behavior when set interactively) appends each worktree as a folder to "ide.config.workspaceConfigPath" in infra-kit.yml and opens the workspace. "windows" opens each worktree in its own Cursor window. "none" skips Cursor. Defaults to "none" in MCP mode (the follow-up prompt is not shown).'),githubDesktop:F.boolean().optional().describe("Open each created worktree in GitHub Desktop. Defaults to false in MCP mode (the follow-up prompt is not shown)."),cmux:F.boolean().optional().describe("Open each created worktree in a new cmux workspace with a 3-pane layout (left-top, left-bottom, full-height right), all rooted at the worktree directory. Defaults to false in MCP mode (the follow-up prompt is not shown).")},outputSchema:{createdWorktrees:F.array(F.string()).describe("List of created git worktree branches"),count:F.number().describe("Number of git worktrees created")},handler:or};import{z as oe}from"zod/v4";var sr=async()=>{let e=await D("release");if(e.length===0)return a.info("\u2139\uFE0F No active worktrees found"),{content:[{type:"text",text:JSON.stringify({worktrees:[],count:0},null,2)}],structuredContent:{worktrees:[],count:0}};let[r,t]=await Promise.all([k(),R()]),s=new Map(r.map(c=>[c.branch,y(c.title)])),o=e.map(c=>{let p=c.replace("release/",""),d=s.get(c)||"regular",u=t.get(p)||null;return{version:p,type:d,description:u}}),n=Math.max(...o.map(c=>c.version.length)),i=o.map(c=>{let p=ee(c.version,c.type,n);return c.description?`${p} ${c.description}`:p});a.info("\u{1F33F} Active worktrees:"),a.info(`
41
+ `)}let i=o.length,l=n.length;i===t.length?a.info(`\u2705 All ${t.length} release branches were created successfully.`):i>0?(a.warn(`\u26A0\uFE0F ${i} of ${t.length} release branches were created successfully.`),a.warn(`\u274C ${l} release(s) failed.`)):a.error(`\u274C All ${t.length} release branches failed to create.`),m.print();let c={createdBranches:o.map(p=>p.branchName),successCount:i,failureCount:l,releases:o,failedReleases:n};return{content:[{type:"text",text:JSON.stringify(c,null,2)}],structuredContent:c}},Oo={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:x.string().describe('Comma-separated list of versions to create (e.g., "1.2.5, 1.2.6"). Required for MCP calls.'),type:x.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" or "hotfix" (default: "regular")')},outputSchema:{createdBranches:x.array(x.string()).describe("List of created release branches"),successCount:x.number().describe("Number of releases created successfully"),failureCount:x.number().describe("Number of releases that failed"),releases:x.array(x.object({version:x.string().describe("Version number"),type:x.enum(["regular","hotfix"]).describe("Release type"),branchName:x.string().describe("Release branch name"),prUrl:x.string().describe("GitHub PR URL"),jiraVersionUrl:x.string().describe("Jira version URL")})).describe("Detailed information for each created release with URLs"),failedReleases:x.array(x.object({version:x.string().describe("Version number that failed"),error:x.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:tr};import{z as Fo}from"zod/v4";var tt={name:"infra-kit",type:"module",version:"0.1.97",description:"infra-kit",main:"dist/cli.js",module:"dist/cli.js",bin:{"infra-kit":"dist/cli.js",ik:"dist/cli.js"},engines:{node:">=24.x"},scripts:{inspector:"npx @modelcontextprotocol/inspector node ./dist/mcp.js --debug",build:"pnpm run clean-artifacts && node ./scripts/build.js","clean-artifacts":"rm -rf dist","clean-cache":"rm -rf node_modules/.cache .eslintcache tsconfig.tsbuildinfo .turbo .swc","prettier-fix":"pnpm exec prettier **/* --write --no-error-on-unmatched-pattern --log-level warn --ignore-path ../../../.prettierignore","prettier-check":"pnpm exec prettier **/* --check --no-error-on-unmatched-pattern --log-level warn --ignore-path ../../../.prettierignore","eslint-check":"pnpm exec eslint --cache --quiet --report-unused-disable-directives ./src","eslint-fix":"pnpm exec eslint --cache --quiet --report-unused-disable-directives ./src --fix","ts-check":"tsc --noEmit",test:"pnpm exec vitest run --reporter=dot","test-watch":"pnpm exec vitest --watch","test-ui":"pnpm exec vitest --ui","test-report":"pnpm exec vitest run --coverage",qa:"pnpm run prettier-check && pnpm run eslint-check && pnpm run ts-check && pnpm run test && echo \u2705 Success",fix:"pnpm run prettier-fix && pnpm run eslint-fix && pnpm run qa"},dependencies:{"@inquirer/checkbox":"^5.1.4","@inquirer/confirm":"^6.0.12","@inquirer/select":"^5.1.4","@modelcontextprotocol/sdk":"^1.29.0",commander:"^14.0.3",pino:"^10.3.1","pino-pretty":"^13.1.3",yaml:"^2.8.4",zod:"^3.25.76",zx:"^8.8.5"},devDependencies:{"@pkg/eslint-config":"workspace:*","@pkg/vitest-config":"workspace:*",esbuild:"^0.28.0",typescript:"catalog:"}};var or=async()=>{let e=tt.version;a.info(e);let r={version:e};return{content:[{type:"text",text:JSON.stringify(r,null,2)}],structuredContent:r}},Do={name:"version",description:"Print the installed infra-kit CLI version",inputSchema:{},outputSchema:{version:Fo.string().describe("Installed infra-kit CLI version (from package.json)")},handler:or};import Vo from"@inquirer/checkbox";import Pr from"@inquirer/confirm";import Bo from"@inquirer/select";import Ko from"node:process";import{z as V}from"zod/v4";import{$ as z}from"zx";import{$ as ot}from"zx";var Re=async e=>{try{let r=(await ot`cmux list-workspaces`.quiet()).stdout,t=Wo(r,e);if(!t)return;await ot`cmux close-workspace --workspace ${t}`.quiet()}catch(r){a.debug({error:r,title:e},"cmux: skipped closing workspace")}},Wo=(e,r)=>{for(let t of e.split(`
42
+ `)){let s=t.match(/^[* ]\s*(workspace:\d+)\s+(.+?)(?:\s+\[selected\])?\s*$/);if(!s)continue;let o=s[1];if((s[2]?.trim()??"")===r)return o}};import{$ as Lo}from"zx";var Ir=async()=>{try{let e=(await Lo`cmux list-workspaces`.quiet()).stdout,r=new Set;for(let t of e.split(`
43
+ `)){let s=t.match(/^[* ]\s*workspace:\d+\s+(.+?)(?:\s+\[selected\])?\s*$/);if(!s)continue;let o=s[1]?.trim();o&&r.add(o)}return r}catch(e){return a.debug({error:e},"cmux: skipped listing workspace titles"),new Set}};import{$ as be}from"zx";var Ce=async e=>{let{cwd:r,title:t}=e,s=(await be`cmux new-workspace --cwd ${r}`).stdout,o=jo(s),n=(await be`cmux list-pane-surfaces --workspace ${o}`).stdout,i=Mo(n);await be`cmux new-split right --workspace ${o} --surface ${i}`,await be`cmux new-split down --workspace ${o} --surface ${i}`,t&&await be`cmux rename-workspace --workspace ${o} ${t}`},Mo=e=>{let r=e.match(/surface:\d+/);if(!r)throw new Error("cmux: could not locate initial surface in list-pane-surfaces output");return r[0]},jo=e=>{let r=e.match(/workspace:\d+/);if(!r)throw new Error("cmux: could not locate workspace ref in new-workspace output");return r[0]};var L=e=>{let{repoName:r,branch:t}=e,s=t.replace("release/","");return`${r} ${s}`};import st from"node:fs/promises";import sr from"node:path";var xe=async e=>{let{workspacePath:r,folderPaths:t}=e,s=sr.dirname(r),o;try{o=await st.readFile(r,"utf-8")}catch(d){throw new Error(`Cursor workspace file not found at ${r}: ${d.message}`)}let n;try{n=JSON.parse(o)}catch(d){throw new Error(`Failed to parse ${r} as JSON. Comments (JSONC) are not supported. ${d.message}`)}let i=n.folders??[],l=new Set(i.map(d=>sr.resolve(s,d.path))),c=[],p=[];for(let d of t){let u=sr.resolve(d);if(l.has(u)){p.push(d);continue}let h=sr.relative(s,u);i.push({path:h}),l.add(u),c.push(d)}return n.folders=i,await st.writeFile(r,`${JSON.stringify(n,null,2)}
44
+ `,"utf-8"),{added:c,skipped:p}};import Jo from"node:fs/promises";import ir from"node:path";import nt from"node:fs/promises";import nr from"node:path";var q=async e=>{let{workspacePath:r,folderPaths:t}=e,s=nr.dirname(r),o;try{o=await nt.readFile(r,"utf-8")}catch(h){throw new Error(`Cursor workspace file not found at ${r}: ${h.message}`)}let n;try{n=JSON.parse(o)}catch(h){throw new Error(`Failed to parse ${r} as JSON. Comments (JSONC) are not supported. ${h.message}`)}let i=n.folders??[],l=new Set(t.map(h=>nr.resolve(h))),c=new Set,p=i.filter(h=>{let f=nr.resolve(s,h.path);return l.has(f)?(c.add(f),!1):!0});n.folders=p,await nt.writeFile(r,`${JSON.stringify(n,null,2)}
45
+ `,"utf-8");let d=[],u=[];for(let h of t){let f=nr.resolve(h);c.has(f)?d.push(h):u.push(h)}return{removed:d,notFound:u}};var Er=async e=>{let{workspacePath:r,worktreeDir:t,currentBranches:s}=e,o=ir.dirname(r),n=ir.resolve(`${t}/release`),i=await Jo.readFile(r,"utf-8"),c=JSON.parse(i).folders??[],p=new Set(s.map(R=>ir.resolve(`${t}/${R}`))),d=[];for(let R of c){let I=ir.resolve(o,R.path);(I===n||I.startsWith(`${n}/`))&&!p.has(I)&&d.push(I)}let u=[];d.length>0&&(u=(await q({workspacePath:r,folderPaths:d})).removed);let h=s.map(R=>`${t}/${R}`),{added:f}=h.length>0?await xe({workspacePath:r,folderPaths:h}):{added:[]};return{added:f,removed:u}};import it from"node:path";var M=(e,r)=>it.isAbsolute(e)?e:it.resolve(r,e);var qo="feature",zo="release",Uo="release/v",Te=["workspace","windows","none"],ar=async e=>{let{confirmedCommand:r,all:t,versions:s,cursor:o,githubDesktop:n,cmux:i}=e;m.start("worktrees-add");try{let l=await _("release"),c=await b(),p=`${c}${j}`;await at(`${p}/${zo}`),await at(`${p}/${qo}`);let d=[];if(s)d=s.split(",").map($=>`release/v${$.trim()}`);else{let $=await k(),F=$.map(D=>D.branch);if(F.length===0)return a.info("\u2139\uFE0F No open release branches found"),m.print(),{content:[{type:"text",text:JSON.stringify({createdWorktrees:[],count:0},null,2)}],structuredContent:{createdWorktrees:[],count:0}};if(t)d=F;else{m.setInteractive();let D=new Map($.map(Se=>[Se.branch,y(Se.title)])),dr=await C();d=await Vo({required:!0,message:"\u{1F33F} Select release branches",choices:E({branches:F,descriptions:dr,types:D})})}}t?m.addOption("--all",!0):m.addOption("--versions",d.map($=>$.replace("release/v","")));let u=r?!0:await Pr({message:"Are you sure you want to proceed with these worktree changes?"});r||m.setInteractive(),u||(a.info("Operation cancelled. Exiting..."),Ko.exit(0)),r||m.addOption("--yes",!0);let h=o??await Bo({message:"Cursor mode for created worktrees?",default:"workspace",choices:[{name:"Add to workspace file",value:"workspace",description:"Append each worktree as a folder in ide.config.workspaceConfigPath, then open the workspace"},{name:"Open separate windows",value:"windows",description:"Open each created worktree in its own Cursor window"},{name:"Skip",value:"none",description:"Do not open Cursor"}]});typeof o>"u"&&m.setInteractive(),m.addOption("--cursor",h);let f=n??await Pr({message:"Open created worktrees in GitHub Desktop?"});typeof n>"u"&&m.setInteractive(),f?m.addOption("--github-desktop",!0):m.addOption("--no-github-desktop",!0);let R=i??await Pr({message:"Open created worktrees in cmux?"});typeof i>"u"&&m.setInteractive(),R?m.addOption("--cmux",!0):m.addOption("--no-cmux",!0);let{branchesToCreate:I}=Go({selectedReleaseBranches:d,currentWorktrees:l}),T=await Ho(I,p);if(Yo(T),h==="workspace"){let $=await w(),F=$.ide?.provider==="cursor"?$.ide.config:void 0;if(!F?.workspaceConfigPath)a.warn("\u26A0\uFE0F Skipping Cursor: ide.config.workspaceConfigPath is not set in infra-kit.yml");else{let D=M(F.workspaceConfigPath,c),dr=T.map(mt=>`${p}/${mt}`),{added:Se,skipped:Nr}=await xe({workspacePath:D,folderPaths:dr}),pt=Nr.length>0?` (${Nr.length} already present)`:"";a.info(`\u2705 Added ${Se.length} folder(s) to ${D}${pt}`),await z`cursor ${D}`}}else if(h==="windows")for(let $ of T)await z`cursor ${p}/${$}`;if(f)for(let $ of T)await z`github ${p}/${$}`,await z`sleep 5`;if(R){let $=await W();for(let F of T){let D=L({repoName:$,branch:F});await Ce({cwd:`${p}/${F}`,title:D})}}m.print();let B={createdWorktrees:T,count:T.length};return{content:[{type:"text",text:JSON.stringify(B,null,2)}],structuredContent:B}}catch(l){throw a.error({error:l},"\u274C Error managing worktrees"),l}},at=async e=>{await z`mkdir -p ${e}`},Go=e=>{let{selectedReleaseBranches:r,currentWorktrees:t}=e,s=t.filter(n=>n.startsWith(Uo));return{branchesToCreate:r.filter(n=>!s.includes(n))}},Ho=async(e,r)=>{let t=await Promise.allSettled(e.map(async o=>{let n=`${r}/${o}`;return await z`git worktree add ${n} ${o}`,await z({cwd:n})`pnpm install`,o})),s=[];for(let[o,n]of t.entries())if(n.status==="fulfilled")s.push(n.value);else{let i=e[o];a.error({error:n.reason},`\u274C Failed to create worktree for ${i}`)}return s},Yo=e=>{if(e.length>0){a.info("\u2705 Created git worktrees:");for(let r of e)a.info(r);a.info("")}else a.info("\u2139\uFE0F No new git worktrees to create")},Xo={name:"worktrees-add",description:'Create local git worktrees for release branches under the worktrees directory and run "pnpm install" in each. Mutates the local filesystem. When invoked via MCP, pass either "versions" (comma-separated) or all=true \u2014 the branch picker and "open in Cursor / GitHub Desktop / cmux" follow-up prompts are unreachable without a TTY, and the CLI confirmation is auto-skipped for MCP calls.',inputSchema:{all:V.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:V.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:V.enum(Te).optional().describe('Cursor open mode for created worktrees. "workspace" (default behavior when set interactively) appends each worktree as a folder to "ide.config.workspaceConfigPath" in infra-kit.yml and opens the workspace. "windows" opens each worktree in its own Cursor window. "none" skips Cursor. Defaults to "none" in MCP mode (the follow-up prompt is not shown).'),githubDesktop:V.boolean().optional().describe("Open each created worktree in GitHub Desktop. Defaults to false in MCP mode (the follow-up prompt is not shown)."),cmux:V.boolean().optional().describe("Open each created worktree in a new cmux workspace with a 3-pane layout (left-top, left-bottom, full-height right), all rooted at the worktree directory. Defaults to false in MCP mode (the follow-up prompt is not shown).")},outputSchema:{createdWorktrees:V.array(V.string()).describe("List of created git worktree branches"),count:V.number().describe("Number of git worktrees created")},handler:ar};import{z as se}from"zod/v4";var cr=async()=>{let e=await _("release");if(e.length===0)return a.info("\u2139\uFE0F No active worktrees found"),{content:[{type:"text",text:JSON.stringify({worktrees:[],count:0},null,2)}],structuredContent:{worktrees:[],count:0}};let[r,t]=await Promise.all([k(),C()]),s=new Map(r.map(c=>[c.branch,y(c.title)])),o=e.map(c=>{let p=c.replace("release/",""),d=s.get(c)||"regular",u=t.get(p)||null;return{version:p,type:d,description:u}}),n=Math.max(...o.map(c=>c.version.length)),i=o.map(c=>{let p=re(c.version,c.type,n);return c.description?`${p} ${c.description}`:p});a.info("\u{1F33F} Active worktrees:"),a.info(`
45
46
  ${i.join(`
46
47
  `)}
47
- `);let l={worktrees:o,count:o.length};return{content:[{type:"text",text:JSON.stringify(l,null,2)}],structuredContent:l}},Ko={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:oe.array(oe.object({version:oe.string().describe("Release version"),type:oe.enum(["regular","hotfix"]).describe("Release type"),description:oe.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:oe.number().describe("Number of worktrees")},handler:sr};import qo from"@inquirer/checkbox";import zo from"@inquirer/confirm";import Go from"node:process";import{z as xe}from"zod/v4";import{$ as $r}from"zx";var nr=async e=>{let{confirmedCommand:r,all:t,versions:s}=e;m.start("worktrees-remove");try{let o=await D("release");if(o.length===0)return a.info("\u2139\uFE0F No active worktrees to remove"),m.print(),{content:[{type:"text",text:JSON.stringify({removedWorktrees:[],count:0},null,2)}],structuredContent:{removedWorktrees:[],count:0}};let n=await C(),i=`${n}${X}`,l=[];if(t)l=o;else if(s)l=s.split(",").map(f=>`release/v${f.trim()}`);else{m.setInteractive();let[f,P]=await Promise.all([R(),k()]),L=new Map(P.map(T=>[T.branch,y(T.title)]));l=await qo({required:!0,message:"\u{1F33F} Select release branches",choices:I({branches:o,descriptions:f,types:L})})}l.length===o.length?m.addOption("--all",!0):m.addOption("--versions",l.map(f=>f.replace("release/v","")));let p=r?!0:await zo({message:"Are you sure you want to proceed with these worktree changes?"});r||m.setInteractive(),p||(a.info("Operation cancelled. Exiting..."),Go.exit(0)),r||m.addOption("--yes",!0);let d=await j(),u=await Uo({branches:l,worktreeDir:i,repoName:d});await Ho({removedWorktrees:u,worktreeDir:i,projectRoot:n}),Yo(u),m.print();let h={removedWorktrees:u,count:u.length};return{content:[{type:"text",text:JSON.stringify(h,null,2)}],structuredContent:h}}catch(o){throw a.error({error:o},"\u274C Error managing worktrees"),o}},Uo=async e=>{let{branches:r,worktreeDir:t,repoName:s}=e,o=await Promise.allSettled(r.map(async i=>{let l=`${t}/${i}`,c=V({repoName:s,branch:i});return await ye(c),await $r`git worktree remove ${l}`,i})),n=[];for(let[i,l]of o.entries())if(l.status==="fulfilled")n.push(l.value);else{let c=r[i];a.error({error:l.reason},`\u274C Failed to remove worktree for ${c}`)}return n.length===r.length&&(await $r`git worktree prune`,await $r`rm -rf ${t}`,a.info(`\u{1F5D1}\uFE0F Removed worktree folder: ${t}`),a.info("")),n},Ho=async e=>{let{removedWorktrees:r,worktreeDir:t,projectRoot:s}=e;if(r.length===0)return;let o=await w(),n=o.ide?.provider==="cursor"?o.ide.config:void 0;if(!n||n.mode!=="workspace"||!n.workspaceConfigPath)return;let i=B(n.workspaceConfigPath,s),l=r.map(c=>`${t}/${c}`);try{let{removed:c}=await Re({workspacePath:i,folderPaths:l});c.length>0&&a.info(`\u2705 Removed ${c.length} folder(s) from ${i}`)}catch(c){a.warn({error:c},`\u26A0\uFE0F Failed to update Cursor workspace at ${i}`)}},Yo=e=>{if(e.length>0){a.info("\u274C Removed worktrees:");for(let r of e)a.info(r);a.info("")}else a.info("\u2139\uFE0F No unused worktrees to remove")},Xo={name:"worktrees-remove",description:'Remove local git worktrees for release branches. When everything is removed, also runs "git worktree prune" and deletes the worktrees directory. When invoked via MCP, pass either "versions" (comma-separated) or all=true \u2014 the branch picker is unreachable without a TTY, and the CLI confirmation is auto-skipped for MCP calls, so the caller is responsible for gating.',inputSchema:{all:xe.boolean().optional().describe('Remove every existing worktree. Either "all" or "versions" must be provided for MCP calls (the interactive picker is unavailable without a TTY). Ignored if "versions" is provided.'),versions:xe.string().optional().describe('Comma-separated release versions to target (e.g. "1.2.5, 1.2.6"). Either "versions" or all=true must be provided for MCP calls. Overrides "all" when set.')},outputSchema:{removedWorktrees:xe.array(xe.string()).describe("List of removed git worktree branches"),count:xe.number().describe("Number of git worktrees removed")},handler:nr};import Zo from"@inquirer/confirm";import Qo from"node:process";import{z as Ir}from"zod/v4";import{$ as es}from"zx";var rs="release/v",ir=async e=>{let{confirmedCommand:r}=e;m.start("worktrees-sync");try{let t=await D("release"),s=await C(),o=`${s}${X}`,n=await ze(),i=r?!0:await Zo({message:"Are you sure you want to proceed with these worktree changes?"});r||m.setInteractive(),i||(a.info("Operation cancelled. Exiting..."),Qo.exit(0)),r||m.addOption("--yes",!0);let{branchesToRemove:l}=ts({releasePRsList:n,currentWorktrees:t}),c=await j(),p=await os({branches:l,worktreeDir:o,repoName:c});await ss({removedWorktrees:p,worktreeDir:o,projectRoot:s}),ns(p),m.print();let d={removedWorktrees:p,count:p.length};return{content:[{type:"text",text:JSON.stringify(d,null,2)}],structuredContent:d}}catch(t){throw a.error({error:t},"\u274C Error managing worktrees"),t}},ts=e=>{let{releasePRsList:r,currentWorktrees:t}=e;return{branchesToRemove:t.filter(n=>n.startsWith(rs)).filter(n=>!r.includes(n))}},os=async e=>{let{branches:r,worktreeDir:t,repoName:s}=e,o=[];for(let n of r)try{let i=`${t}/${n}`,l=V({repoName:s,branch:n});await ye(l),await es`git worktree remove ${i}`,o.push(n)}catch(i){a.error({error:i,branch:n},`\u274C Failed to remove worktree for ${n}`)}return o},ss=async e=>{let{removedWorktrees:r,worktreeDir:t,projectRoot:s}=e;if(r.length===0)return;let o=await w(),n=o.ide?.provider==="cursor"?o.ide.config:void 0;if(!n||n.mode!=="workspace"||!n.workspaceConfigPath)return;let i=B(n.workspaceConfigPath,s),l=r.map(c=>`${t}/${c}`);try{let{removed:c}=await Re({workspacePath:i,folderPaths:l});c.length>0&&a.info(`\u2705 Removed ${c.length} folder(s) from ${i}`)}catch(c){a.warn({error:c},`\u26A0\uFE0F Failed to update Cursor workspace at ${i}`)}},ns=e=>{if(e.length>0){a.info("\u274C Removed worktrees:");for(let r of e)a.info(r);a.info("")}else a.info("\u2139\uFE0F No unused worktrees to remove")},is={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:Ir.array(Ir.string()).describe("List of removed worktree branches"),count:Ir.number().describe("Number of worktrees removed during sync")},handler:ir};var v=new cs,ls=e=>{if(!(typeof e>"u")){if(e===!0)return"workspace";if(e===!1)return"none";if(typeof e=="string"&&be.includes(e))return e;throw new Error(`Invalid --cursor value "${String(e)}". Expected one of: ${be.join(", ")}.`)}},tt=async e=>{try{e?await v.parseAsync(e):await v.parseAsync()}catch(r){let t=r instanceof Error?r.message:String(r);a.error(t),Sr.exit(1)}};v.command("merge-dev").description("Merge dev branch into every release branch").option("-a, --all","Select all active release branches").option("-y, --yes","Skip confirmation prompt").action(async e=>{await Ge({all:e.all,confirmedCommand:e.yes})});v.command("release-list").description("List all release branches").action(async()=>{await Xe()});v.command("release-create").description("Create a single release branch").option("-v, --version <version>","Specify the version to create, e.g. 1.2.5").option("-d, --description <description>","Optional description for the Jira version").addOption(new ot("-t, --type <type>","Release type (default: regular)").choices(["regular","hotfix"])).option("-y, --yes","Skip confirmation prompt").option("--no-checkout","Do not checkout the created branch after creation (checkout is default)").action(async e=>{await Ze({version:e.version,description:e.description,type:e.type,confirmedCommand:e.yes,checkout:e.checkout})});v.command("release-create-batch").description("Create multiple release branches (batch operation)").option("-v, --versions <versions>","Specify the versions to create by comma, e.g. 1.2.5, 1.2.6").addOption(new ot("-t, --type <type>","Release type (default: regular)").choices(["regular","hotfix"])).option("-y, --yes","Skip confirmation prompt").action(async e=>{await Qe({versions:e.versions,type:e.type,confirmedCommand:e.yes})});v.command("release-deploy-all").description("Deploy any release branch to any environment").option("-v, --version <version>","Specify the version to deploy, e.g. 1.2.5").option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("--skip-terraform","Skip terraform deployment step").action(async e=>{await He({version:e.version,env:e.env,skipTerraform:e.skipTerraform})});v.command("release-deploy-selected").description("Deploy selected services from release branch to any environment").option("-v, --version <version>","Specify the version to deploy, e.g. 1.2.5").option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("-s, --services <services...>","Specify services to deploy, e.g. client-be client-fe").option("--skip-terraform","Skip terraform deployment step").action(async e=>{await Ye({version:e.version,env:e.env,services:e.services,skipTerraform:e.skipTerraform})});v.command("release-deliver").description("Release a new version to production").option("-v, --version <version>","Specify the version to release, e.g. 1.2.5").option("-y, --yes","Skip confirmation prompt").action(async e=>{await Ue({version:e.version,confirmedCommand:e.yes})});v.command("worktrees-sync").description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async e=>{await ir({confirmedCommand:e.yes})});v.command("worktrees-add").description("Add git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-c, --cursor [mode]","Cursor mode for created worktrees: workspace (default) | windows | none").option("--no-cursor","Skip Cursor (alias for --cursor none)").option("-g, --github-desktop","Open created worktrees in GitHub Desktop").option("--no-github-desktop","Skip GitHub Desktop prompt").option("-m, --cmux","Open created worktrees in cmux (3-pane layout)").option("--no-cmux","Skip cmux prompt").action(async e=>{await or({confirmedCommand:e.yes,all:e.all,versions:e.versions,cursor:ls(e.cursor),githubDesktop:e.githubDesktop,cmux:e.cmux})});v.command("worktrees-list").description("List all git worktrees with detailed information").action(async()=>{await sr()});v.command("worktrees-remove").description("Remove git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").action(async e=>{await nr({confirmedCommand:e.yes,all:e.all,versions:e.versions})});v.command("doctor").description("Check installation and authentication status of gh and doppler CLIs").action(async()=>{await Ae()});v.command("version").description("Print the installed infra-kit CLI version").action(async()=>{await er()});v.command("env-status").description("Show Doppler authentication status and detected project info").action(async()=>{await je()});v.command("env-list").description("List available Doppler configs for the detected project").action(async()=>{await Me()});v.command("init").description("Inject shell integration into your profile .zshrc").action(async()=>{await cr()});v.command("env-load").description("Load Doppler env vars for a config. Source the returned file path to apply.").option("-c, --config <config>","Environment config name to load (e.g. dev, arthur)").action(async e=>{await We({config:e.config})});v.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{await Le()});if(Sr.argv.length<=2){let e=["merge-dev","release-list","release-create","release-create-batch","release-deploy-all","release-deploy-selected","release-deliver"],r=["worktrees-add","worktrees-list","worktrees-remove","worktrees-sync"],t=["doctor","init","version","env-status","env-list","env-load","env-clear"],s=new Map(v.commands.map(c=>[c.name(),c])),o=[...e,...r,...t],n=Math.max(...o.map(c=>c.length)),i=c=>c.filter(p=>s.has(p)).map(p=>({name:`${p.padEnd(n)} ${s.get(p).description()}`,value:p})),l=await as({message:"Select a command to run",choices:[new se(" "),new se("\u2014 Release Management \u2014"),...i(e),new se(" "),new se("\u2014 Worktrees \u2014"),...i(r),new se(" "),new se("\u2014 Environment \u2014"),...i(t)]},{output:Sr.stderr});await tt(["node","infra-kit",l])}else await tt();
48
+ `);let l={worktrees:o,count:o.length};return{content:[{type:"text",text:JSON.stringify(l,null,2)}],structuredContent:l}},Zo={name:"worktrees-list",description:"List existing release-branch worktrees with version, release type (regular / hotfix), and Jira fix-version description. Read-only.",inputSchema:{},outputSchema:{worktrees:se.array(se.object({version:se.string().describe("Release version"),type:se.enum(["regular","hotfix"]).describe("Release type"),description:se.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:se.number().describe("Number of worktrees")},handler:cr};import{z as ne}from"zod/v4";import{$ as Qo}from"zx";var lr=async()=>{m.start("worktrees-open");try{let e=await b(),r=`${e}${j}`,t=await _("release"),s=await es({projectRoot:e,worktreeDir:r,currentBranches:t}),o=await rs({worktreeDir:r,currentBranches:t}),n={openedCmux:o.opened,skippedCmux:o.skipped,cursorFoldersAdded:s.added,cursorFoldersRemoved:s.removed};return ts(n,{cursorRan:s.ran,cmuxRan:o.ran}),m.print(),{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:{...n}}}catch(e){throw a.error({error:e},"\u274C Error opening worktrees"),e}},es=async e=>{let{projectRoot:r,worktreeDir:t,currentBranches:s}=e,o=await w(),n=o.ide?.provider==="cursor"?o.ide.config:void 0;if(!n||n.mode!=="workspace"||!n.workspaceConfigPath)return a.warn('\u26A0\uFE0F Skipping Cursor: ide.provider must be "cursor", mode "workspace", and workspaceConfigPath set.'),{ran:!1,added:0,removed:0};let i=M(n.workspaceConfigPath,r);try{let{added:l,removed:c}=await Er({workspacePath:i,worktreeDir:t,currentBranches:s});return await Qo`cursor ${i}`,{ran:!0,added:l.length,removed:c.length}}catch(l){return a.warn({error:l},`\u26A0\uFE0F Failed to reconcile/open Cursor workspace at ${i}`),{ran:!1,added:0,removed:0}}},rs=async e=>{let{worktreeDir:r,currentBranches:t}=e;if(t.length===0)return{ran:!0,opened:[],skipped:[]};let s=await W(),o=await Ir(),n=[],i=[];for(let l of t){let c=L({repoName:s,branch:l});if(o.has(c)){i.push(c);continue}try{await Ce({cwd:`${r}/${l}`,title:c}),n.push(c)}catch(p){a.warn({error:p,title:c},`\u26A0\uFE0F Failed to open cmux workspace for ${l}`)}}return{ran:!0,opened:n,skipped:i}},ts=(e,r)=>{if(r.cursorRan&&(e.cursorFoldersAdded>0&&a.info(`\u2705 Added ${e.cursorFoldersAdded} folder(s) to Cursor workspace`),e.cursorFoldersRemoved>0&&a.info(`\u{1F9F9} Removed ${e.cursorFoldersRemoved} dangling folder(s) from Cursor workspace`)),e.openedCmux.length>0){a.info("\u2705 Opened cmux workspaces:");for(let t of e.openedCmux)a.info(t)}e.skippedCmux.length>0&&a.info(`\u2139\uFE0F Skipped ${e.skippedCmux.length} cmux workspace(s) already open`),!r.cursorRan&&e.openedCmux.length===0&&e.skippedCmux.length===0&&e.cursorFoldersAdded===0&&e.cursorFoldersRemoved===0&&a.info("\u2139\uFE0F Nothing to open")},os={name:"worktrees-open",description:"Open Cursor against the configured workspace file and ensure a cmux workspace exists for each existing release worktree. Idempotent and additive \u2014 never removes worktrees, never recreates running cmux workspaces. Use after a cold start (Cursor + cmux closed). For stale-worktree cleanup, use worktrees-sync.",inputSchema:{},outputSchema:{openedCmux:ne.array(ne.string()).describe("Titles of cmux workspaces opened during this run"),skippedCmux:ne.array(ne.string()).describe("Titles of cmux workspaces that were already open"),cursorFoldersAdded:ne.number().describe("Number of worktree folders added to the Cursor workspace file"),cursorFoldersRemoved:ne.number().describe("Number of dangling worktree folders removed from the Cursor workspace file")},handler:lr};import ss from"@inquirer/checkbox";import ns from"@inquirer/confirm";import is from"node:process";import{z as $e}from"zod/v4";import{$ as Ar}from"zx";var pr=async e=>{let{confirmedCommand:r,all:t,versions:s}=e;m.start("worktrees-remove");try{let o=await _("release");if(o.length===0)return a.info("\u2139\uFE0F No active worktrees to remove"),m.print(),{content:[{type:"text",text:JSON.stringify({removedWorktrees:[],count:0},null,2)}],structuredContent:{removedWorktrees:[],count:0}};let n=await b(),i=`${n}${j}`,l=[];if(t)l=o;else if(s)l=s.split(",").map(f=>`release/v${f.trim()}`);else{m.setInteractive();let[f,R]=await Promise.all([C(),k()]),I=new Map(R.map(T=>[T.branch,y(T.title)]));l=await ss({required:!0,message:"\u{1F33F} Select release branches",choices:E({branches:o,descriptions:f,types:I})})}let c=l.length===o.length;c?m.addOption("--all",!0):m.addOption("--versions",l.map(f=>f.replace("release/v","")));let p=r?!0:await ns({message:"Are you sure you want to proceed with these worktree changes?"});r||m.setInteractive(),p||(a.info("Operation cancelled. Exiting..."),is.exit(0)),r||m.addOption("--yes",!0);let d=await W(),u=await as({branches:l,worktreeDir:i,repoName:d,allSelected:c});await cs({removedWorktrees:u,worktreeDir:i,projectRoot:n}),ls(u),m.print();let h={removedWorktrees:u,count:u.length};return{content:[{type:"text",text:JSON.stringify(h,null,2)}],structuredContent:h}}catch(o){throw a.error({error:o},"\u274C Error managing worktrees"),o}},as=async e=>{let{branches:r,worktreeDir:t,repoName:s,allSelected:o}=e,n=await Promise.allSettled(r.map(async l=>{let c=`${t}/${l}`,p=L({repoName:s,branch:l});return await Re(p),await Ar`git worktree remove ${c}`,l})),i=[];for(let[l,c]of n.entries())if(c.status==="fulfilled")i.push(c.value);else{let p=r[l];a.error({error:c.reason},`\u274C Failed to remove worktree for ${p}`)}return o&&i.length===r.length&&(await Ar`git worktree prune`,await Ar`rm -rf ${t}`,a.info(`\u{1F5D1}\uFE0F Removed worktree folder: ${t}`),a.info("")),i},cs=async e=>{let{removedWorktrees:r,worktreeDir:t,projectRoot:s}=e;if(r.length===0)return;let o=await w(),n=o.ide?.provider==="cursor"?o.ide.config:void 0;if(!n||n.mode!=="workspace"||!n.workspaceConfigPath)return;let i=M(n.workspaceConfigPath,s),l=r.map(c=>`${t}/${c}`);try{let{removed:c}=await q({workspacePath:i,folderPaths:l});c.length>0&&a.info(`\u2705 Removed ${c.length} folder(s) from ${i}`)}catch(c){a.warn({error:c},`\u26A0\uFE0F Failed to update Cursor workspace at ${i}`)}},ls=e=>{if(e.length>0){a.info("\u274C Removed worktrees:");for(let r of e)a.info(r);a.info("")}else a.info("\u2139\uFE0F No unused worktrees to remove")},ps={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:$e.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:$e.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:$e.array($e.string()).describe("List of removed git worktree branches"),count:$e.number().describe("Number of git worktrees removed")},handler:pr};import ms from"@inquirer/confirm";import ds from"node:process";import{z as _r}from"zod/v4";import{$ as us}from"zx";var fs="release/v",mr=async e=>{let{confirmedCommand:r}=e;m.start("worktrees-sync");try{let t=await _("release"),s=await b(),o=`${s}${j}`,n=await He(),i=r?!0:await ms({message:"Are you sure you want to proceed with these worktree changes?"});r||m.setInteractive(),i||(a.info("Operation cancelled. Exiting..."),ds.exit(0)),r||m.addOption("--yes",!0);let{branchesToRemove:l}=hs({releasePRsList:n,currentWorktrees:t}),c=await W(),p=await gs({branches:l,worktreeDir:o,repoName:c});await vs({removedWorktrees:p,worktreeDir:o,projectRoot:s}),ws(p),m.print();let d={removedWorktrees:p,count:p.length};return{content:[{type:"text",text:JSON.stringify(d,null,2)}],structuredContent:d}}catch(t){throw a.error({error:t},"\u274C Error managing worktrees"),t}},hs=e=>{let{releasePRsList:r,currentWorktrees:t}=e;return{branchesToRemove:t.filter(n=>n.startsWith(fs)).filter(n=>!r.includes(n))}},gs=async e=>{let{branches:r,worktreeDir:t,repoName:s}=e,o=[];for(let n of r)try{let i=`${t}/${n}`,l=L({repoName:s,branch:n});await Re(l),await us`git worktree remove ${i}`,o.push(n)}catch(i){a.error({error:i,branch:n},`\u274C Failed to remove worktree for ${n}`)}return o},vs=async e=>{let{removedWorktrees:r,worktreeDir:t,projectRoot:s}=e;if(r.length===0)return;let o=await w(),n=o.ide?.provider==="cursor"?o.ide.config:void 0;if(!n||n.mode!=="workspace"||!n.workspaceConfigPath)return;let i=M(n.workspaceConfigPath,s),l=r.map(c=>`${t}/${c}`);try{let{removed:c}=await q({workspacePath:i,folderPaths:l});c.length>0&&a.info(`\u2705 Removed ${c.length} folder(s) from ${i}`)}catch(c){a.warn({error:c},`\u26A0\uFE0F Failed to update Cursor workspace at ${i}`)}},ws=e=>{if(e.length>0){a.info("\u274C Removed worktrees:");for(let r of e)a.info(r);a.info("")}else a.info("\u2139\uFE0F No unused worktrees to remove")},ys={name:"worktrees-sync",description:"Remove worktrees whose release PR is no longer open (stale cleanup). Only removes \u2014 never creates; use worktrees-add to create worktrees for new releases. The CLI confirmation is auto-skipped for MCP calls, so the caller is responsible for gating.",inputSchema:{},outputSchema:{removedWorktrees:_r.array(_r.string()).describe("List of removed worktree branches"),count:_r.number().describe("Number of worktrees removed during sync")},handler:mr};var v=new Rs,bs=e=>{if(!(typeof e>"u")){if(e===!0)return"workspace";if(e===!1)return"none";if(typeof e=="string"&&Te.includes(e))return e;throw new Error(`Invalid --cursor value "${String(e)}". Expected one of: ${Te.join(", ")}.`)}},ct=async e=>{try{e?await v.parseAsync(e):await v.parseAsync()}catch(r){let t=r instanceof Error?r.message:String(r);a.error(t),Or.exit(1)}};v.command("merge-dev").description("Merge dev branch into every release branch").option("-a, --all","Select all active release branches").option("-y, --yes","Skip confirmation prompt").action(async e=>{await Ye({all:e.all,confirmedCommand:e.yes})});v.command("release-list").description("List all release branches").action(async()=>{await er()});v.command("release-create").description("Create a single release branch").option("-v, --version <version>","Specify the version to create, e.g. 1.2.5").option("-d, --description <description>","Optional description for the Jira version").addOption(new lt("-t, --type <type>","Release type (default: regular)").choices(["regular","hotfix"])).option("-y, --yes","Skip confirmation prompt").option("--no-checkout","Do not checkout the created branch after creation (checkout is default)").action(async e=>{await rr({version:e.version,description:e.description,type:e.type,confirmedCommand:e.yes,checkout:e.checkout})});v.command("release-create-batch").description("Create multiple release branches (batch operation)").option("-v, --versions <versions>","Specify the versions to create by comma, e.g. 1.2.5, 1.2.6").addOption(new lt("-t, --type <type>","Release type (default: regular)").choices(["regular","hotfix"])).option("-y, --yes","Skip confirmation prompt").action(async e=>{await tr({versions:e.versions,type:e.type,confirmedCommand:e.yes})});v.command("release-deploy-all").description("Deploy any release branch to any environment").option("-v, --version <version>","Specify the version to deploy, e.g. 1.2.5").option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("--skip-terraform","Skip terraform deployment step").action(async e=>{await Ze({version:e.version,env:e.env,skipTerraform:e.skipTerraform})});v.command("release-deploy-selected").description("Deploy selected services from release branch to any environment").option("-v, --version <version>","Specify the version to deploy, e.g. 1.2.5").option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("-s, --services <services...>","Specify services to deploy, e.g. client-be client-fe").option("--skip-terraform","Skip terraform deployment step").action(async e=>{await Qe({version:e.version,env:e.env,services:e.services,skipTerraform:e.skipTerraform})});v.command("release-deliver").description("Release a new version to production").option("-v, --version <version>","Specify the version to release, e.g. 1.2.5").option("-y, --yes","Skip confirmation prompt").action(async e=>{await Xe({version:e.version,confirmedCommand:e.yes})});v.command("worktrees-sync").description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async e=>{await mr({confirmedCommand:e.yes})});v.command("worktrees-add").description("Add git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-c, --cursor [mode]","Cursor mode for created worktrees: workspace (default) | windows | none").option("--no-cursor","Skip Cursor (alias for --cursor none)").option("-g, --github-desktop","Open created worktrees in GitHub Desktop").option("--no-github-desktop","Skip GitHub Desktop prompt").option("-m, --cmux","Open created worktrees in cmux (3-pane layout)").option("--no-cmux","Skip cmux prompt").action(async e=>{await ar({confirmedCommand:e.yes,all:e.all,versions:e.versions,cursor:bs(e.cursor),githubDesktop:e.githubDesktop,cmux:e.cmux})});v.command("worktrees-list").description("List all git worktrees with detailed information").action(async()=>{await cr()});v.command("worktrees-remove").description("Remove git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").action(async e=>{await pr({confirmedCommand:e.yes,all:e.all,versions:e.versions})});v.command("worktrees-open").description("Open Cursor + cmux for existing release worktrees (cold-start restore)").action(async()=>{await lr()});v.command("doctor").description("Check installation and authentication status of gh and doppler CLIs").action(async()=>{await Oe()});v.command("version").description("Print the installed infra-kit CLI version").action(async()=>{await or()});v.command("env-status").description("Show Doppler authentication status and detected project info").action(async()=>{await Be()});v.command("env-list").description("List available Doppler configs for the detected project").action(async()=>{await je()});v.command("init").description("Inject shell integration into your profile .zshrc").action(async()=>{await ur()});v.command("env-load").description("Load Doppler env vars for a config. Source the returned file path to apply.").option("-c, --config <config>","Environment config name to load (e.g. dev, arthur)").action(async e=>{await Ve({config:e.config})});v.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{await Me()});if(Or.argv.length<=2){let e=["merge-dev","release-list","release-create","release-create-batch","release-deploy-all","release-deploy-selected","release-deliver"],r=["worktrees-add","worktrees-list","worktrees-open","worktrees-remove","worktrees-sync"],t=["doctor","init","version","env-status","env-list","env-load","env-clear"],s=new Map(v.commands.map(c=>[c.name(),c])),o=[...e,...r,...t],n=Math.max(...o.map(c=>c.length)),i=c=>c.filter(p=>s.has(p)).map(p=>({name:`${p.padEnd(n)} ${s.get(p).description()}`,value:p})),l=await ks({message:"Select a command to run",choices:[new ie(" "),new ie("\u2014 Release Management \u2014"),...i(e),new ie(" "),new ie("\u2014 Worktrees \u2014"),...i(r),new ie(" "),new ie("\u2014 Environment \u2014"),...i(t)]},{output:Or.stderr});await ct(["node","infra-kit",l])}else await ct();
48
49
  //# sourceMappingURL=cli.js.map