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