infra-kit 0.1.109 → 0.1.110

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mcp.js CHANGED
@@ -1,55 +1,55 @@
1
- import{StdioServerTransport as Oi}from"@modelcontextprotocol/sdk/server/stdio.js";import Yo from"node:process";import Z from"node:process";import Mt from"node:process";import Pr from"pino";import Qo from"pino-pretty";var Me="/tmp/mcp-infra-kit.log",jt=()=>{let e=Mt.argv.includes("--debug")?"debug":"info",r=Pr({level:e},Pr.destination({dest:Me}));return r.info(`Logger initialized with level: ${e}. Logging to: ${Me}`),r},en=()=>{let e=Mt.argv.includes("--debug")?"debug":"info",r=["time","pid","hostname"];return e==="debug"&&r.push("level"),Pr({level:e},Qo({destination:2,ignore:r.join(","),colorize:!0}))},a=en();var Dt=e=>{Z.on("SIGINT",()=>{e.info({msg:"Received SIGINT. Shutting down..."}),Z.exit(0)}),Z.on("SIGTERM",()=>{e.info({msg:"Received SIGTERM. Shutting down..."}),Z.exit(0)}),Z.on("uncaughtException",r=>{e.fatal({err:r,msg:"Uncaught Exception"}),e.error(`Uncaught Exception! Check ${Me}. Shutting down...`),e.flush(),Z.exit(1)}),Z.on("unhandledRejection",(r,t)=>{e.fatal({reason:r,promise:t,msg:"Unhandled Rejection"}),e.error(`Unhandled Rejection! Check ${Me}. Shutting down...`),e.flush(),Z.exit(1)})};import{McpServer as Ni}from"@modelcontextprotocol/sdk/server/mcp.js";var Lt=async e=>{};var Wt=async e=>{};import Le from"node:path";import bn from"node:process";import{z as L}from"zod";import Kt from"node:path";import{$ as Ce}from"zx";var rn=/^v?(\d+)\.(\d+)\.(\d+)$/,tn=/^(\d+)\.(\d+)\.(\d+)$/,on=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,nn="release/",Tr="release/v",Er="release/n/",Jt="refs/heads/",sn="next";var Vt=new Set(["dev","main","next","hotfix","regular","release"]),U=class extends Error{constructor(r){super(r),this.name="InvalidReleaseNameError"}},xe=class extends Error{constructor(r){super(r),this.name="InvalidReleaseRefError"}},qt=e=>e.startsWith(Jt)?e.slice(Jt.length):e,Ut=(e,r,t)=>({kind:"version",semver:{major:e,minor:r,patch:t},raw:`${e}.${r}.${t}`}),le=e=>{if(e.length===0)throw new U('Release name is empty. Provide a kebab-case name like "checkout-redesign".');if(e.length>50)throw new U(`Release name "${e}" is ${e.length} characters; the maximum is 50.`);if(!on.test(e))throw new U(`Release name "${e}" is not kebab-case. Use lowercase letters, digits, and single hyphens, e.g. "checkout-redesign".`);if(Vt.has(e))throw new U(`Release name "${e}" is reserved. Reserved names: ${[...Vt].join(", ")}.`)},y=e=>{let r=qt(e.trim());if(r.startsWith(Tr)){let t=r.slice(Tr.length),o=tn.exec(t);return o?Ut(Number(o[1]),Number(o[2]),Number(o[3])):null}if(r.startsWith(Er)){let t=r.slice(Er.length);try{le(t)}catch{return null}return{kind:"name",name:t,raw:t}}return null},B=e=>{let r=e.trim();if(qt(r).startsWith(nn)){let n=y(r);if(!n)throw new xe(`"${e}" looks like a release branch but is not a valid release/v<semver> or release/n/<name> ref.`);return n}let o=rn.exec(r);if(o)return Ut(Number(o[1]),Number(o[2]),Number(o[3]));if(r.toLowerCase()===sn)throw new xe('The "next" token must be resolved to a concrete version (via computeNextVersion) before parsing a release ref.');try{le(r)}catch(n){let s=n instanceof Error?n.message:String(n);throw new xe(`Cannot parse "${e}" as a release ref: ${s}`)}return{kind:"name",name:r,raw:r}},K=e=>e.kind==="version"?`${Tr}${e.raw}`:`${Er}${e.name}`,$r=(e,r)=>{let t=r==="hotfix"?"Hotfix":"Release";return e.kind==="version"?`${t} v${e.raw}`:`${t} ${e.name}`},cr=e=>e.kind==="version"?`Release v${e.raw} (RC)`:`Release ${e.name} (RC)`,D=e=>e.kind==="version"?`v${e.raw}`:e.name,C=e=>e.raw,pe=e=>e==null?!1:y(e)!==null,Bt=e=>{if(e===void 0)return null;let r=e instanceof Date?e.getTime():new Date(e).getTime();return Number.isNaN(r)?null:r},Sr=(e,r,t)=>{if(e.kind==="version"&&r.kind==="version")return e.semver.major!==r.semver.major?e.semver.major-r.semver.major:e.semver.minor!==r.semver.minor?e.semver.minor-r.semver.minor:e.semver.patch-r.semver.patch;if(e.kind==="version")return-1;if(r.kind==="version")return 1;let o=Bt(t?.a),n=Bt(t?.b);return o!==null&&n!==null&&o!==n?o-n:e.name<r.name?-1:e.name>r.name?1:0};var _=async e=>{let t=(await Ce`git worktree list`).stdout.split(`
2
- `).filter(Boolean),o={release:an,feature:cn};return t.map(o[e]).filter(n=>n!==null)},Gt=e=>{let r=e.trimEnd();if(!r.endsWith("]"))return null;let t=r.lastIndexOf("[");if(t===-1)return null;let o=r.slice(t+1,-1);return o.length>0?o:null},an=e=>{let r=Gt(e);return pe(r)?r:null},cn=e=>{let r=Gt(e);return r?.startsWith("feature/")?r:null},P=async()=>(await Ce`git rev-parse --show-toplevel`).stdout.trim(),Ir=async()=>(await Ce`git rev-parse --abbrev-ref HEAD`).stdout.trim(),Ar=async()=>(await Ce`git status --porcelain`).stdout.trim().length===0,Nr=async()=>{let e=await P(),[r,t]=await Promise.all([Ce({cwd:e})`git rev-parse --absolute-git-dir`,Ce({cwd:e})`git rev-parse --git-common-dir`]),o=r.stdout.trim(),n=Kt.resolve(e,t.stdout.trim());return o!==n},F=async()=>{let e=await P();return Kt.basename(e)};var Q={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},Or={requiredScripts:["build","dev","test","qa","check","fix"],requiredFiles:["turbo.json","pnpm-workspace.yaml"],turboTasks:["build","test","ts-check","eslint-check","prettier-check","check"]},_r=(e,r=Q)=>({requiredScripts:e.requiredScripts??[...r.requiredScripts],requiredFiles:e.requiredFiles??[...r.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...r.turboTasks]});import{z as ee}from"zod";var Fr=ee.strictObject({requiredScripts:ee.array(ee.string().min(1)).optional(),requiredFiles:ee.array(ee.string().min(1)).optional(),turbo:ee.strictObject({requiredTasks:ee.array(ee.string().min(1)).optional()}).optional()});import ln from"node:fs/promises";var G=async e=>{try{return await ln.access(e),!0}catch{return!1}};import Rn from"node:path";import zt from"node:fs/promises";import Ht from"node:path";import{pathToFileURL as pn}from"node:url";import{z as mn}from"zod";var re="infra-kit.config.ts",Mr=async e=>{try{let r=await zt.readFile(Ht.join(e,"package.json"),"utf-8");return JSON.parse(r)}catch{return{}}},je=async(e,r=Q)=>{let t=Ht.join(e,re);if(!await G(t))throw new Error(`${re} not found at ${t}`);let o=await zt.stat(t),i=(await import(`${pn(t).href}?mtime=${Number(o.mtimeMs)}`)).default;if(i===void 0)throw new Error(`${re} at ${t} has no default export`);let l=typeof i=="function"?await i():i,c=Fr.safeParse(l);if(!c.success)throw new Error(`Invalid ${re} at ${t}: ${mn.prettifyError(c.error)}`);return _r(c.data,r)};import Xt from"node:fs/promises";import lr from"node:path";import dn from"yaml";var un="pnpm-workspace.yaml",fn=async e=>(await Xt.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(t=>t.isDirectory()).map(t=>lr.join(e,t.name)),gn=async(e,r)=>{let t=[];for(let o of e){if(r==="*"){t.push(...await fn(o));continue}let n=lr.join(o,r);await G(n)&&t.push(n)}return t},hn=async(e,r)=>{let t=[e];for(let o of r.split("/"))t=await gn(t,o);return t},De=async e=>{let r=await Xt.readFile(lr.join(e,un),"utf-8"),o=((dn.parse(r)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),n=new Set;for(let s of o){let i=await hn(e,s);for(let l of i)await G(lr.join(l,"package.json"))&&n.add(l)}return[...n].sort()};var jr=async(e,r=Q)=>{try{let t=await je(e,r);return{check:{name:re,status:"pass",message:"present and valid"},rules:t}}catch(t){return{check:{name:re,status:"fail",message:t.message},rules:null}}};import wn from"node:fs/promises";import vn from"node:path";var Dr=async(e,r)=>Promise.all(r.map(async t=>{let o=await wn.stat(vn.join(e,t)).catch(()=>null);return o?o.isFile()?{name:`file:${t}`,status:"pass",message:"exists"}:{name:`file:${t}`,status:"fail",message:`not a file: ${t} (found a directory)`}:{name:`file:${t}`,status:"fail",message:`missing file: ${t}`}}));var Lr=(e,r)=>r.map(t=>{let o=e[t];return typeof o!="string"?{name:`script:${t}`,status:"fail",message:`missing "${t}" in package.json scripts`}:o.trim().length===0?{name:`script:${t}`,status:"fail",message:`"${t}" is empty in package.json scripts`}:{name:`script:${t}`,status:"pass",message:"defined"}});import kn from"node:fs/promises";import yn from"node:path";var Pe="turbo.json",Wr=async(e,r)=>{if(r.length===0)return[];let t;try{let n=await kn.readFile(yn.join(e,Pe),"utf-8");t=JSON.parse(n)}catch(n){return[{name:Pe,status:"fail",message:`cannot read/parse ${Pe}: ${n.message}`}]}let o=t.tasks;return o===null||typeof o!="object"?[{name:Pe,status:"fail",message:`no "tasks" object defined in ${Pe}`}]:r.map(n=>{let s=n in o||`//#${n}`in o;return{name:`turbo:${n}`,status:s?"pass":"fail",message:s?"defined":`missing turbo task "${n}" in ${Pe}`}})};var Jr=async(e,r=Q)=>{let t=await Mr(e),o=t.name??Rn.basename(e),{check:n,rules:s}=await jr(e,r),i=[n];s&&(i.push(...Lr(t.scripts??{},s.requiredScripts)),i.push(...await Dr(e,s.requiredFiles)),i.push(...await Wr(e,s.turboTasks)));let l=i.every(c=>c.status==="pass");return{packageDir:e,packageName:o,checks:i,passed:l}};var h=e=>[{type:"text",text:e}],v=e=>e;var xn=async e=>{let r=Le.resolve(e);for(;r!==Le.dirname(r);){if(await G(Le.join(r,"package.json")))return r;r=Le.dirname(r)}if(await G(Le.join(r,"package.json")))return r;throw new Error(`No package.json found in or above ${e}`)},Cn=async e=>e.root?[{dir:await P(),baseline:Or}]:e.all?(await De(await P())).map(t=>({dir:t})):[{dir:await xn(e.cwd??bn.cwd())}],Pn=e=>{let r=e.passed?"PASS":"FAIL";a.info(`
3
- ${e.packageName} \u2014 ${r}`);for(let t of e.checks){let o=t.status==="pass"?"[PASS]":"[FAIL]";a.info(` ${o} ${t.name}: ${t.message}`)}},Yt=async(e={})=>{let r=await Cn(e),t=[];for(let s of r)t.push(await Jr(s.dir,s.baseline));for(let s of t)Pn(s);let o=t.every(s=>s.passed);a.info(`
4
- ${o?"\u2705 All valid":"\u274C Audit failed"} (${t.length} checked)`);let n={allPassed:o,packages:t.map(s=>({name:s.packageName,passed:s.passed,checks:s.checks}))};return{content:h(JSON.stringify(n,null,2)),structuredContent:n}},Tn={all:L.boolean().optional().describe("Audit every non-vendor workspace package"),root:L.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},En={allPassed:L.boolean().describe("Whether every audited package passed all checks"),packages:L.array(L.object({name:L.string(),passed:L.boolean(),checks:L.array(L.object({name:L.string(),status:L.enum(["pass","fail"]),message:L.string()}))})).describe("Per-package check results")},Vr=v({name:"audit",description:"Audit packages against infra-kit.config.ts rules (config present and valid, required scripts, required files, and turbo tasks for the root). Defaults to the current package; all=true audits every non-vendor workspace package; root=true audits the monorepo root.",inputSchema:Tn,outputSchema:En,handler:e=>Yt({all:e.all,root:e.root})});import Kr from"node:fs";import Qt from"node:path";import Sn from"node:process";import{z as pr}from"zod";import We from"node:fs";import $n from"node:os";import Br from"node:path";import qr from"node:process";var me="env-load.sh",Ur="env-clear.sh",Je="INFRA_KIT_SESSION",de="INFRA_KIT_ENV_CONFIG",ue="INFRA_KIT_ENV_PROJECT",fe="INFRA_KIT_ENV_LOADED_AT",Ve=/^([A-Z_]\w*)=/i,Be=e=>{if(!We.existsSync(e))return[];let r=We.readFileSync(e,"utf-8"),t=[];for(let o of r.split(`
5
- `)){let n=Ve.exec(o);n&&t.push(n[1])}return t},Zt=()=>{let e=qr.env.XDG_CACHE_HOME,r=e&&e.length>0?e:Br.join($n.homedir(),".cache");return Br.join(r,"infra-kit")},ge=()=>{let e=qr.env[Je];if(!e)throw new Error(`${Je} is not set. Run \`infra-kit init\` then \`source ~/.zshrc\`.`);return Br.join(Zt(),e)},qe=(e,r,t)=>{let o=`${e}.tmp.${qr.pid}`;We.writeFileSync(o,r,{mode:t});try{We.renameSync(o,e)}catch(n){throw We.rmSync(o,{force:!0}),n}},J="-worktrees";var eo=async()=>{let e=ge(),r=Qt.join(e,me);if(!Kr.existsSync(r))throw new Error("No loaded environment found. Run `env-load` first.");let t=Be(r),o=[...t.map(i=>`unset ${i}`),`unset ${de}`,`unset ${ue}`,`unset ${fe}`],n=Qt.resolve(e,Ur);Kr.mkdirSync(e,{recursive:!0,mode:448}),qe(n,`${o.join(`
1
+ import{StdioServerTransport as Ni}from"@modelcontextprotocol/sdk/server/stdio.js";import Yo from"node:process";import Z from"node:process";import Mt from"node:process";import Tr from"pino";import Qo from"pino-pretty";var Me="/tmp/mcp-infra-kit.log",jt=()=>{let e=Mt.argv.includes("--debug")?"debug":"info",r=Tr({level:e},Tr.destination({dest:Me}));return r.info(`Logger initialized with level: ${e}. Logging to: ${Me}`),r},en=()=>{let e=Mt.argv.includes("--debug")?"debug":"info",r=["time","pid","hostname"];return e==="debug"&&r.push("level"),Tr({level:e},Qo({destination:2,ignore:r.join(","),colorize:!0}))},a=en();var Dt=e=>{Z.on("SIGINT",()=>{e.info({msg:"Received SIGINT. Shutting down..."}),Z.exit(0)}),Z.on("SIGTERM",()=>{e.info({msg:"Received SIGTERM. Shutting down..."}),Z.exit(0)}),Z.on("uncaughtException",r=>{e.fatal({err:r,msg:"Uncaught Exception"}),e.error(`Uncaught Exception! Check ${Me}. Shutting down...`),e.flush(),Z.exit(1)}),Z.on("unhandledRejection",(r,t)=>{e.fatal({reason:r,promise:t,msg:"Unhandled Rejection"}),e.error(`Unhandled Rejection! Check ${Me}. Shutting down...`),e.flush(),Z.exit(1)})};import{McpServer as Ai}from"@modelcontextprotocol/sdk/server/mcp.js";var Lt=async e=>{};var Wt=async e=>{};import Le from"node:path";import Rn from"node:process";import{z as L}from"zod";import Kt from"node:path";import{$ as Ce}from"zx";var rn=/^v?(\d+)\.(\d+)\.(\d+)$/,tn=/^(\d+)\.(\d+)\.(\d+)$/,on=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,cr="release/",Er="release/v",Jt="refs/heads/",nn="next";var Vt=new Set(["dev","main","next","hotfix","regular","release"]),U=class extends Error{constructor(r){super(r),this.name="InvalidReleaseNameError"}},xe=class extends Error{constructor(r){super(r),this.name="InvalidReleaseRefError"}},qt=e=>e.startsWith(Jt)?e.slice(Jt.length):e,Ut=(e,r,t)=>({kind:"version",semver:{major:e,minor:r,patch:t},raw:`${e}.${r}.${t}`}),le=e=>{if(e.length===0)throw new U('Release name is empty. Provide a kebab-case name like "checkout-redesign".');if(e.length>50)throw new U(`Release name "${e}" is ${e.length} characters; the maximum is 50.`);if(!on.test(e))throw new U(`Release name "${e}" is not kebab-case. Use lowercase letters, digits, and single hyphens, e.g. "checkout-redesign".`);if(Vt.has(e))throw new U(`Release name "${e}" is reserved. Reserved names: ${[...Vt].join(", ")}.`)},y=e=>{let r=qt(e.trim());if(!r.startsWith(cr))return null;if(r.startsWith(Er)){let n=r.slice(Er.length),o=tn.exec(n);if(o)return Ut(Number(o[1]),Number(o[2]),Number(o[3]))}let t=r.slice(cr.length);try{le(t)}catch{return null}return{kind:"name",name:t,raw:t}},B=e=>{let r=e.trim();if(qt(r).startsWith(cr)){let o=y(r);if(!o)throw new xe(`"${e}" looks like a release branch but is not a valid release/v<semver> or release/<name> ref.`);return o}let n=rn.exec(r);if(n)return Ut(Number(n[1]),Number(n[2]),Number(n[3]));if(r.toLowerCase()===nn)throw new xe('The "next" token must be resolved to a concrete version (via computeNextVersion) before parsing a release ref.');try{le(r)}catch(o){let s=o instanceof Error?o.message:String(o);throw new xe(`Cannot parse "${e}" as a release ref: ${s}`)}return{kind:"name",name:r,raw:r}},K=e=>e.kind==="version"?`${Er}${e.raw}`:`${cr}${e.name}`,$r=(e,r)=>{let t=r==="hotfix"?"Hotfix":"Release";return e.kind==="version"?`${t} v${e.raw}`:`${t} ${e.name}`},lr=e=>e.kind==="version"?`Release v${e.raw} (RC)`:`Release ${e.name} (RC)`,D=e=>e.kind==="version"?`v${e.raw}`:e.name,C=e=>e.raw,pe=e=>e==null?!1:y(e)!==null,Bt=e=>{if(e===void 0)return null;let r=e instanceof Date?e.getTime():new Date(e).getTime();return Number.isNaN(r)?null:r},Sr=(e,r,t)=>{if(e.kind==="version"&&r.kind==="version")return e.semver.major!==r.semver.major?e.semver.major-r.semver.major:e.semver.minor!==r.semver.minor?e.semver.minor-r.semver.minor:e.semver.patch-r.semver.patch;if(e.kind==="version")return-1;if(r.kind==="version")return 1;let n=Bt(t?.a),o=Bt(t?.b);return n!==null&&o!==null&&n!==o?n-o:e.name<r.name?-1:e.name>r.name?1:0};var _=async e=>{let t=(await Ce`git worktree list`).stdout.split(`
2
+ `).filter(Boolean),n={release:sn,feature:an};return t.map(n[e]).filter(o=>o!==null)},Gt=e=>{let r=e.trimEnd();if(!r.endsWith("]"))return null;let t=r.lastIndexOf("[");if(t===-1)return null;let n=r.slice(t+1,-1);return n.length>0?n:null},sn=e=>{let r=Gt(e);return pe(r)?r:null},an=e=>{let r=Gt(e);return r?.startsWith("feature/")?r:null},P=async()=>(await Ce`git rev-parse --show-toplevel`).stdout.trim(),Ir=async()=>(await Ce`git rev-parse --abbrev-ref HEAD`).stdout.trim(),Ar=async()=>(await Ce`git status --porcelain`).stdout.trim().length===0,Nr=async()=>{let e=await P(),[r,t]=await Promise.all([Ce({cwd:e})`git rev-parse --absolute-git-dir`,Ce({cwd:e})`git rev-parse --git-common-dir`]),n=r.stdout.trim(),o=Kt.resolve(e,t.stdout.trim());return n!==o},F=async()=>{let e=await P();return Kt.basename(e)};var Q={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},Or={requiredScripts:["build","dev","test","qa","check","fix"],requiredFiles:["turbo.json","pnpm-workspace.yaml"],turboTasks:["build","test","ts-check","eslint-check","prettier-check","check"]},_r=(e,r=Q)=>({requiredScripts:e.requiredScripts??[...r.requiredScripts],requiredFiles:e.requiredFiles??[...r.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...r.turboTasks]});import{z as ee}from"zod";var Fr=ee.strictObject({requiredScripts:ee.array(ee.string().min(1)).optional(),requiredFiles:ee.array(ee.string().min(1)).optional(),turbo:ee.strictObject({requiredTasks:ee.array(ee.string().min(1)).optional()}).optional()});import cn from"node:fs/promises";var G=async e=>{try{return await cn.access(e),!0}catch{return!1}};import yn from"node:path";import zt from"node:fs/promises";import Ht from"node:path";import{pathToFileURL as ln}from"node:url";import{z as pn}from"zod";var re="infra-kit.config.ts",Mr=async e=>{try{let r=await zt.readFile(Ht.join(e,"package.json"),"utf-8");return JSON.parse(r)}catch{return{}}},je=async(e,r=Q)=>{let t=Ht.join(e,re);if(!await G(t))throw new Error(`${re} not found at ${t}`);let n=await zt.stat(t),i=(await import(`${ln(t).href}?mtime=${Number(n.mtimeMs)}`)).default;if(i===void 0)throw new Error(`${re} at ${t} has no default export`);let l=typeof i=="function"?await i():i,c=Fr.safeParse(l);if(!c.success)throw new Error(`Invalid ${re} at ${t}: ${pn.prettifyError(c.error)}`);return _r(c.data,r)};import Xt from"node:fs/promises";import pr from"node:path";import mn from"yaml";var dn="pnpm-workspace.yaml",un=async e=>(await Xt.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(t=>t.isDirectory()).map(t=>pr.join(e,t.name)),fn=async(e,r)=>{let t=[];for(let n of e){if(r==="*"){t.push(...await un(n));continue}let o=pr.join(n,r);await G(o)&&t.push(o)}return t},gn=async(e,r)=>{let t=[e];for(let n of r.split("/"))t=await fn(t,n);return t},De=async e=>{let r=await Xt.readFile(pr.join(e,dn),"utf-8"),n=((mn.parse(r)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),o=new Set;for(let s of n){let i=await gn(e,s);for(let l of i)await G(pr.join(l,"package.json"))&&o.add(l)}return[...o].sort()};var jr=async(e,r=Q)=>{try{let t=await je(e,r);return{check:{name:re,status:"pass",message:"present and valid"},rules:t}}catch(t){return{check:{name:re,status:"fail",message:t.message},rules:null}}};import hn from"node:fs/promises";import wn from"node:path";var Dr=async(e,r)=>Promise.all(r.map(async t=>{let n=await hn.stat(wn.join(e,t)).catch(()=>null);return n?n.isFile()?{name:`file:${t}`,status:"pass",message:"exists"}:{name:`file:${t}`,status:"fail",message:`not a file: ${t} (found a directory)`}:{name:`file:${t}`,status:"fail",message:`missing file: ${t}`}}));var Lr=(e,r)=>r.map(t=>{let n=e[t];return typeof n!="string"?{name:`script:${t}`,status:"fail",message:`missing "${t}" in package.json scripts`}:n.trim().length===0?{name:`script:${t}`,status:"fail",message:`"${t}" is empty in package.json scripts`}:{name:`script:${t}`,status:"pass",message:"defined"}});import vn from"node:fs/promises";import kn from"node:path";var Pe="turbo.json",Wr=async(e,r)=>{if(r.length===0)return[];let t;try{let o=await vn.readFile(kn.join(e,Pe),"utf-8");t=JSON.parse(o)}catch(o){return[{name:Pe,status:"fail",message:`cannot read/parse ${Pe}: ${o.message}`}]}let n=t.tasks;return n===null||typeof n!="object"?[{name:Pe,status:"fail",message:`no "tasks" object defined in ${Pe}`}]:r.map(o=>{let s=o in n||`//#${o}`in n;return{name:`turbo:${o}`,status:s?"pass":"fail",message:s?"defined":`missing turbo task "${o}" in ${Pe}`}})};var Jr=async(e,r=Q)=>{let t=await Mr(e),n=t.name??yn.basename(e),{check:o,rules:s}=await jr(e,r),i=[o];s&&(i.push(...Lr(t.scripts??{},s.requiredScripts)),i.push(...await Dr(e,s.requiredFiles)),i.push(...await Wr(e,s.turboTasks)));let l=i.every(c=>c.status==="pass");return{packageDir:e,packageName:n,checks:i,passed:l}};var h=e=>[{type:"text",text:e}],v=e=>e;var bn=async e=>{let r=Le.resolve(e);for(;r!==Le.dirname(r);){if(await G(Le.join(r,"package.json")))return r;r=Le.dirname(r)}if(await G(Le.join(r,"package.json")))return r;throw new Error(`No package.json found in or above ${e}`)},xn=async e=>e.root?[{dir:await P(),baseline:Or}]:e.all?(await De(await P())).map(t=>({dir:t})):[{dir:await bn(e.cwd??Rn.cwd())}],Cn=e=>{let r=e.passed?"PASS":"FAIL";a.info(`
3
+ ${e.packageName} \u2014 ${r}`);for(let t of e.checks){let n=t.status==="pass"?"[PASS]":"[FAIL]";a.info(` ${n} ${t.name}: ${t.message}`)}},Yt=async(e={})=>{let r=await xn(e),t=[];for(let s of r)t.push(await Jr(s.dir,s.baseline));for(let s of t)Cn(s);let n=t.every(s=>s.passed);a.info(`
4
+ ${n?"\u2705 All valid":"\u274C Audit failed"} (${t.length} checked)`);let o={allPassed:n,packages:t.map(s=>({name:s.packageName,passed:s.passed,checks:s.checks}))};return{content:h(JSON.stringify(o,null,2)),structuredContent:o}},Pn={all:L.boolean().optional().describe("Audit every non-vendor workspace package"),root:L.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},Tn={allPassed:L.boolean().describe("Whether every audited package passed all checks"),packages:L.array(L.object({name:L.string(),passed:L.boolean(),checks:L.array(L.object({name:L.string(),status:L.enum(["pass","fail"]),message:L.string()}))})).describe("Per-package check results")},Vr=v({name:"audit",description:"Audit packages against infra-kit.config.ts rules (config present and valid, required scripts, required files, and turbo tasks for the root). Defaults to the current package; all=true audits every non-vendor workspace package; root=true audits the monorepo root.",inputSchema:Pn,outputSchema:Tn,handler:e=>Yt({all:e.all,root:e.root})});import Kr from"node:fs";import Qt from"node:path";import $n from"node:process";import{z as mr}from"zod";import We from"node:fs";import En from"node:os";import Br from"node:path";import qr from"node:process";var me="env-load.sh",Ur="env-clear.sh",Je="INFRA_KIT_SESSION",de="INFRA_KIT_ENV_CONFIG",ue="INFRA_KIT_ENV_PROJECT",fe="INFRA_KIT_ENV_LOADED_AT",Ve=/^([A-Z_]\w*)=/i,Be=e=>{if(!We.existsSync(e))return[];let r=We.readFileSync(e,"utf-8"),t=[];for(let n of r.split(`
5
+ `)){let o=Ve.exec(n);o&&t.push(o[1])}return t},Zt=()=>{let e=qr.env.XDG_CACHE_HOME,r=e&&e.length>0?e:Br.join(En.homedir(),".cache");return Br.join(r,"infra-kit")},ge=()=>{let e=qr.env[Je];if(!e)throw new Error(`${Je} is not set. Run \`infra-kit init\` then \`source ~/.zshrc\`.`);return Br.join(Zt(),e)},qe=(e,r,t)=>{let n=`${e}.tmp.${qr.pid}`;We.writeFileSync(n,r,{mode:t});try{We.renameSync(n,e)}catch(o){throw We.rmSync(n,{force:!0}),o}},J="-worktrees";var eo=async()=>{let e=ge(),r=Qt.join(e,me);if(!Kr.existsSync(r))throw new Error("No loaded environment found. Run `env-load` first.");let t=Be(r),n=[...t.map(i=>`unset ${i}`),`unset ${de}`,`unset ${ue}`,`unset ${fe}`],o=Qt.resolve(e,Ur);Kr.mkdirSync(e,{recursive:!0,mode:448}),qe(o,`${n.join(`
6
6
  `)}
7
- `,384),Sn.stdout.write(`${n}
8
- `),Kr.unlinkSync(r);let s={filePath:n,variableCount:t.length,unsetStatements:o};return{content:h(JSON.stringify(s,null,2)),structuredContent:s}},Gr=v({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:pr.string().describe("Path to the file that must be sourced to apply"),variableCount:pr.number().describe("Number of variables cleared"),unsetStatements:pr.array(pr.string()).describe("Unset statements generated")},handler:eo});import{z as Yr}from"zod";import Hr from"node:fs/promises";import In from"node:os";import mr from"node:path";import{z as k}from"zod";var ro="infra-kit.json",An=".infra-kit",Nn="config.json",On="projects",_n=k.object({provider:k.literal("doppler"),config:k.object({name:k.string().min(1)})}),Fn=k.discriminatedUnion("provider",[_n]),Mn=k.object({mode:k.enum(["workspace","windows"]).default("workspace"),workspaceConfigPath:k.string().min(1).optional()}).refine(e=>e.mode!=="workspace"||!!e.workspaceConfigPath,{message:'workspaceConfigPath is required when mode is "workspace"',path:["workspaceConfigPath"]}),jn=k.object({provider:k.literal("cursor"),config:Mn}),Dn=k.discriminatedUnion("provider",[jn]),Ln=k.object({provider:k.literal("jira"),config:k.object({baseUrl:k.string().url(),projectId:k.number().int().positive()})}),Wn=k.discriminatedUnion("provider",[Ln]),Jn=k.object({openInGithubDesktop:k.boolean().optional(),openInCmux:k.boolean().optional()}),Xr=k.object({environments:k.array(k.string().min(1)).min(1),envManagement:Fn,ide:Dn.optional(),taskManager:Wn.optional(),worktrees:Jn.optional()}),to=Xr.partial(),Ue=null,oo=async()=>{let e=await P(),r=await F(),t=mr.join(In.homedir(),An);return{main:mr.join(e,ro),userGlobal:mr.join(t,Nn),userProject:mr.join(t,On,r,ro),projectName:r}},T=async()=>{let e=await oo(),r;try{r=await Hr.stat(e.main)}catch{Ue=null;let c=e.main.replace(/\.json$/,".yml");throw await zr(c)?new Error(`infra-kit.json not found at ${e.main}. A legacy infra-kit.yml exists \u2014 run \`infra-kit init\` to convert it.`):new Error(`infra-kit.json not found at ${e.main}`)}let[t,o]=await Promise.all([zr(e.userGlobal),zr(e.userProject)]),n={main:Number(r.mtimeMs),userGlobal:t?Number(t.mtimeMs):null,userProject:o?Number(o.mtimeMs):null};if(Ue&&Bn(Ue.mtimes,n))return Ue.value;let s=[{label:"infra-kit.json",path:e.main,required:!0},{label:"~/.infra-kit/config.json",path:e.userGlobal,required:!1},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,path:e.userProject,required:!1}],i={};for(let c of s){let p=await qn(c);p!==null&&(i={...i,...p})}let l=Xr.safeParse(i);if(!l.success)throw new Error(`Invalid merged infra-kit config: ${k.prettifyError(l.error)}`);return Ue={mtimes:n,value:l.data},l.data};var zr=async e=>{try{return await Hr.stat(e)}catch{return null}},Vn=async e=>{try{return await Hr.readFile(e,"utf-8")}catch{return null}},Bn=(e,r)=>{let t=Object.keys(e);return t.length!==Object.keys(r).length?!1:t.every(o=>e[o]===r[o])},qn=async e=>{let r=await Vn(e.path);if(r===null){if(e.required)throw new Error(`${e.label} not found at ${e.path}`);return null}let t;try{t=r.trim()===""?{}:JSON.parse(r)}catch(n){throw new Error(`Invalid JSON in ${e.label} at ${e.path}: ${n.message}`)}let o=to.safeParse(t);if(!o.success)throw new Error(`Invalid ${e.label} at ${e.path}: ${k.prettifyError(o.error)}`);return o.data};var Ke=async()=>{let{envManagement:e}=await T();return e.config.name};var no=async()=>{let e=await Ke(),{environments:r}=await T();a.info(`Doppler project: ${e}
9
- `),a.info("Available configs:");for(let o of r)a.info(` - ${o}`);let t={project:e,configs:r};return{content:h(JSON.stringify(t,null,2)),structuredContent:t}},Zr=v({name:"env-list",description:"List the environments the project is configured to support. Returns the `environments` list declared in infra-kit.json 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:no});import Kn from"@inquirer/select";import{Buffer as Gn}from"node:buffer";import zn from"node:fs";import Hn from"node:path";import io from"node:process";import{z as ze}from"zod";import{$ as dr}from"zx";import{$ as so}from"zx";var Ge=async()=>{try{await so`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 so`doppler me`}catch(e){throw new Error("Doppler CLI is not authenticated. Run: doppler login",{cause:e})}};var Un=()=>{let e="",r=[],t=!1;return{start(o){e=o,r=[],t=!1},setInteractive(){t=!0},addOption(o,n){r.push({flag:o,value:n})},print(){if(!t||r.length===0)return;let o=r.map(n=>typeof n.value=="boolean"?n.value?n.flag:"":Array.isArray(n.value)?`${n.flag} "${n.value.join(", ")}"`:`${n.flag} "${n.value}"`).filter(Boolean).join(" ");a.info(`\u{1F4DF} Equivalent command:
10
- pnpm exec infra-kit ${e} ${o}
11
- `)},reset(){e="",r=[],t=!1}}},m=Un();var co=async e=>{await Ge();let{config:r}=e;m.start("env-load");let t="";if(r)t=r;else{let{environments:u}=await T();m.setInteractive(),t=await Kn({message:"Select environment config",choices:u.map(g=>({name:g,value:g}))},{output:io.stderr})}m.addOption("--config",t);let o=await Ke(),n=await Yn(o,t);rs(n);let s=new Date().toISOString(),i=["set -a",n,`${de}=${Qr(t)}`,`${ue}=${Qr(o)}`,`${fe}=${Qr(s)}`,"set +a"],l=ge(),c=Hn.resolve(l,me);zn.mkdirSync(l,{recursive:!0,mode:448}),qe(c,`${i.join(`
7
+ `,384),$n.stdout.write(`${o}
8
+ `),Kr.unlinkSync(r);let s={filePath:o,variableCount:t.length,unsetStatements:n};return{content:h(JSON.stringify(s,null,2)),structuredContent:s}},Gr=v({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:mr.string().describe("Path to the file that must be sourced to apply"),variableCount:mr.number().describe("Number of variables cleared"),unsetStatements:mr.array(mr.string()).describe("Unset statements generated")},handler:eo});import{z as Yr}from"zod";import Hr from"node:fs/promises";import Sn from"node:os";import dr from"node:path";import{z as k}from"zod";var ro="infra-kit.json",In=".infra-kit",An="config.json",Nn="projects",On=k.object({provider:k.literal("doppler"),config:k.object({name:k.string().min(1)})}),_n=k.discriminatedUnion("provider",[On]),Fn=k.object({mode:k.enum(["workspace","windows"]).default("workspace"),workspaceConfigPath:k.string().min(1).optional()}).refine(e=>e.mode!=="workspace"||!!e.workspaceConfigPath,{message:'workspaceConfigPath is required when mode is "workspace"',path:["workspaceConfigPath"]}),Mn=k.object({provider:k.literal("cursor"),config:Fn}),jn=k.discriminatedUnion("provider",[Mn]),Dn=k.object({provider:k.literal("jira"),config:k.object({baseUrl:k.string().url(),projectId:k.number().int().positive()})}),Ln=k.discriminatedUnion("provider",[Dn]),Wn=k.object({openInGithubDesktop:k.boolean().optional(),openInCmux:k.boolean().optional()}),Xr=k.object({environments:k.array(k.string().min(1)).min(1),envManagement:_n,ide:jn.optional(),taskManager:Ln.optional(),worktrees:Wn.optional()}),to=Xr.partial(),Ue=null,oo=async()=>{let e=await P(),r=await F(),t=dr.join(Sn.homedir(),In);return{main:dr.join(e,ro),userGlobal:dr.join(t,An),userProject:dr.join(t,Nn,r,ro),projectName:r}},T=async()=>{let e=await oo(),r;try{r=await Hr.stat(e.main)}catch{Ue=null;let c=e.main.replace(/\.json$/,".yml");throw await zr(c)?new Error(`infra-kit.json not found at ${e.main}. A legacy infra-kit.yml exists \u2014 run \`infra-kit init\` to convert it.`):new Error(`infra-kit.json not found at ${e.main}`)}let[t,n]=await Promise.all([zr(e.userGlobal),zr(e.userProject)]),o={main:Number(r.mtimeMs),userGlobal:t?Number(t.mtimeMs):null,userProject:n?Number(n.mtimeMs):null};if(Ue&&Vn(Ue.mtimes,o))return Ue.value;let s=[{label:"infra-kit.json",path:e.main,required:!0},{label:"~/.infra-kit/config.json",path:e.userGlobal,required:!1},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,path:e.userProject,required:!1}],i={};for(let c of s){let p=await Bn(c);p!==null&&(i={...i,...p})}let l=Xr.safeParse(i);if(!l.success)throw new Error(`Invalid merged infra-kit config: ${k.prettifyError(l.error)}`);return Ue={mtimes:o,value:l.data},l.data};var zr=async e=>{try{return await Hr.stat(e)}catch{return null}},Jn=async e=>{try{return await Hr.readFile(e,"utf-8")}catch{return null}},Vn=(e,r)=>{let t=Object.keys(e);return t.length!==Object.keys(r).length?!1:t.every(n=>e[n]===r[n])},Bn=async e=>{let r=await Jn(e.path);if(r===null){if(e.required)throw new Error(`${e.label} not found at ${e.path}`);return null}let t;try{t=r.trim()===""?{}:JSON.parse(r)}catch(o){throw new Error(`Invalid JSON in ${e.label} at ${e.path}: ${o.message}`)}let n=to.safeParse(t);if(!n.success)throw new Error(`Invalid ${e.label} at ${e.path}: ${k.prettifyError(n.error)}`);return n.data};var Ke=async()=>{let{envManagement:e}=await T();return e.config.name};var no=async()=>{let e=await Ke(),{environments:r}=await T();a.info(`Doppler project: ${e}
9
+ `),a.info("Available configs:");for(let n of r)a.info(` - ${n}`);let t={project:e,configs:r};return{content:h(JSON.stringify(t,null,2)),structuredContent:t}},Zr=v({name:"env-list",description:"List the environments the project is configured to support. Returns the `environments` list declared in infra-kit.json 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:no});import Un from"@inquirer/select";import{Buffer as Kn}from"node:buffer";import Gn from"node:fs";import zn from"node:path";import io from"node:process";import{z as ze}from"zod";import{$ as ur}from"zx";import{$ as so}from"zx";var Ge=async()=>{try{await so`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 so`doppler me`}catch(e){throw new Error("Doppler CLI is not authenticated. Run: doppler login",{cause:e})}};var qn=()=>{let e="",r=[],t=!1;return{start(n){e=n,r=[],t=!1},setInteractive(){t=!0},addOption(n,o){r.push({flag:n,value:o})},print(){if(!t||r.length===0)return;let n=r.map(o=>typeof o.value=="boolean"?o.value?o.flag:"":Array.isArray(o.value)?`${o.flag} "${o.value.join(", ")}"`:`${o.flag} "${o.value}"`).filter(Boolean).join(" ");a.info(`\u{1F4DF} Equivalent command:
10
+ pnpm exec infra-kit ${e} ${n}
11
+ `)},reset(){e="",r=[],t=!1}}},m=qn();var co=async e=>{await Ge();let{config:r}=e;m.start("env-load");let t="";if(r)t=r;else{let{environments:u}=await T();m.setInteractive(),t=await Un({message:"Select environment config",choices:u.map(g=>({name:g,value:g}))},{output:io.stderr})}m.addOption("--config",t);let n=await Ke(),o=await Xn(n,t);es(o);let s=new Date().toISOString(),i=["set -a",o,`${de}=${Qr(t)}`,`${ue}=${Qr(n)}`,`${fe}=${Qr(s)}`,"set +a"],l=ge(),c=zn.resolve(l,me);Gn.mkdirSync(l,{recursive:!0,mode:448}),qe(c,`${i.join(`
12
12
  `)}
13
13
  `,384),io.stdout.write(`${c}
14
- `),m.print();let p=Qn(n),d={filePath:c,variableCount:p,project:o,config:t};return{content:h(JSON.stringify(d,null,2)),structuredContent:d}},ao=1024*1024,Xn=3e4,Yn=async(e,r)=>{let t=dr.quiet;dr.quiet=!0;try{let o=await dr`doppler secrets download --no-file --format env --project ${e} --config ${r}`.timeout(Xn);return Zn(o.stdout),o.stdout.trim()}finally{dr.quiet=t}},Zn=e=>{let r=Gn.byteLength(e,"utf-8");if(r>ao)throw new Error(`doppler returned unexpectedly large output (${r} bytes > ${ao}) \u2014 refusing to write to disk`)},Qn=e=>e.split(`
15
- `).filter(r=>Ve.test(r)).length,es=new Set(["set -a","set +a"]),Qr=e=>`'${e.replaceAll("'","'\\''")}'`,rs=e=>{if(e.trim().length===0)throw new Error("doppler returned empty output for env-load");for(let r of e.split(`
16
- `)){let t=r.trim();if(!(t.length===0||es.has(t))&&!Ve.test(t))throw new Error(`doppler returned unexpected output for env-load (expected KEY=value lines, got: ${JSON.stringify(t.slice(0,80))})`)}},et=v({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:ze.string().describe('Doppler config / environment name to load (e.g. "dev", "arthur", "renana"). Required for MCP calls.')},outputSchema:{filePath:ze.string().describe("Path to the file that must be sourced to apply variables"),variableCount:ze.number().describe("Number of variables loaded"),project:ze.string().describe("Doppler project name"),config:ze.string().describe("Doppler config name")},handler:co});import ts from"node:path";import He from"node:process";import{z as Te}from"zod";var lo=async()=>{await Ge(),a.info("Environment session status:");let e=ge(),r=He.env[Je],t=ts.join(e,me),o=0,n=0,s=He.env[de]??null,i=He.env[ue]??null,l=He.env[fe]??null;if(s){let p=Be(t);p.length>0&&(n=p.length,o=p.filter(u=>u in He.env).length);let d=l?.replace(/\.\d{3}Z$/,"")??null;if(a.info(` ${s}: ${o} of ${n} vars loaded (project: ${i}, loadedAt: ${d}, session: ${r})
17
- `),n>0&&o<n){let u=n-o;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
18
- `);let c={sessionId:r,sessionLoadedCount:o,sessionTotalCount:n,sessionConfig:s,sessionProject:i,sessionLoadedAt:l};return{content:h(JSON.stringify(c,null,2)),structuredContent:c}},rt=v({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:Te.string().describe("Current terminal session ID"),sessionLoadedCount:Te.number().describe("Number of cached vars active in the current session"),sessionTotalCount:Te.number().describe("Total number of cached var names"),sessionConfig:Te.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:Te.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:Te.string().nullable().describe("ISO 8601 timestamp of when the env was loaded")},handler:lo});import is from"@inquirer/checkbox";import as from"@inquirer/confirm";import cs from"node:process";import{z as Ae}from"zod";import{$ as V}from"zx";import{$ as xl}from"zx";import hr from"node:process";import{$ as A}from"zx";import{$ as Ye}from"zx";import Xe from"node:process";var tt=async(e,r)=>{try{let{baseUrl:t,token:o,email:n,projectId:s}=r,i={name:e.name,projectId:e.projectId||s,description:e.description||"",released:e.released||!1,archived:e.archived||!1},l=`${t}/rest/api/3/version`,c=btoa(`${n}:${o}`),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}},Ee=async e=>{try{let{baseUrl:r,token:t,email:o,projectId:n}=e,s=`${r}/rest/api/3/project/${n}/versions`,i=btoa(`${o}:${t}`),l=await fetch(s,{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}},ur=async(e,r)=>{try{return(await Ee(r)).find(n=>n.name===e)||null}catch(t){throw a.error({error:t,versionName:e},"Error finding Jira version by name"),t}},fr=async(e,r)=>{try{let{baseUrl:t,token:o,email:n}=r,s={};e.released!==void 0&&(s.released=e.released),e.archived!==void 0&&(s.archived=e.archived),e.releaseDate!==void 0&&(s.releaseDate=e.releaseDate),e.description!==void 0&&(s.description=e.description);let i=`${t}/rest/api/3/version/${e.versionId}`,l=btoa(`${n}:${o}`),c=await fetch(i,{method:"PUT",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${l}`},body:JSON.stringify(s)});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}},ot=async(e,r)=>{try{let{versionName:t}=e,o=await ur(t,r);if(!o)throw a.error({versionName:t},"Jira version not found"),new Error(`Version "${t}" not found in Jira project`);return await fr({versionId:o.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},r)}catch(t){throw a.error({error:t},"Error delivering Jira release"),t}},$e=async()=>{let e=Xe.env.JIRA_BASE_URL,r=Xe.env.JIRA_TOKEN||Xe.env.JIRA_API_TOKEN,t=Xe.env.JIRA_PROJECT_ID,o=Xe.env.JIRA_EMAIL,n=[];if(e||n.push("JIRA_BASE_URL (e.g., https://your-domain.atlassian.net)"),r||n.push("JIRA_TOKEN or JIRA_API_TOKEN (your Jira API token)"),t||n.push("JIRA_PROJECT_ID (numeric project ID)"),o||n.push("JIRA_EMAIL (your Jira email address)"),n.length>0){let i=["Jira configuration is required but incomplete.","Please configure the following environment variables:",...n.map(l=>` - ${l}`),"","You can set these in your .env file or as environment variables."].join(`
19
- `);throw new Error(i)}let s=Number.parseInt(t,10);if(Number.isNaN(s))throw new TypeError(`Invalid JIRA_PROJECT_ID: "${t}" must be a numeric value (e.g., 10001)`);return{baseUrl:e.replace(/\/$/,""),token:r,projectId:s,email:o}},he=async()=>{try{return await $e()}catch(e){return a.warn({error:e},"Jira configuration not available, skipping Jira integration"),null}};var ns=e=>{if(e===null||typeof e!="object")return;let r=e.stderr;return typeof r=="string"&&r.length>0?r:void 0},ss=(e,r)=>{let t=r.stderrExcerpt??ns(e),o=[`failed to ${r.operation}`];return t&&o.push(`stderr: ${t.slice(0,200).trim()}`),r.remediation&&o.push(`try: ${r.remediation}`),o.join(" \u2014 ")},f=class extends Error{operation;remediation;constructor(r,t){super(ss(r,t),{cause:r}),this.name="OperationError",this.operation=t.operation,this.remediation=t.remediation}};var po="dev",Se=e=>e==="hotfix"?"main":"dev",nt=async(e="regular")=>{let r=Se(e);Ye.quiet=!0,await Ye`git fetch origin`,await Ye`git switch ${r}`,await Ye`git pull origin ${r}`,Ye.quiet=!1},st=async e=>{let{id:r,jiraConfig:t,description:o,type:n="regular"}=e,s=D(r),i=await tt({name:s,projectId:t.projectId,description:o||"",released:!1,archived:!1},t),l=`${t.baseUrl}/projects/${i.version.projectId}/versions/${i.version.id}/tab/release-report-all-issues`,c=await gr({id:r,jiraVersionUrl:l,type:n,description:o});return{version:C(r),type:n,branchName:c.branchName,prUrl:c.prUrl,jiraVersionUrl:l}},E=async()=>{let e=new Map,r=await he();if(!r)return e;try{let t=await Ee(r);for(let o of t)o.description&&e.set(o.name,o.description)}catch{}return e},Ie=(e,r,t)=>{let o=t?" ".repeat(t-e.length+3):" ",n=`[${r}]`.padEnd(11);return`${e}${o}${n}`},R=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",mo=e=>e.flatMap(r=>{let t=y(r);return t?[{branch:r,id:t,label:C(t)}]:[]}),z=e=>{try{return K(B(e))}catch(r){throw new f(r,{operation:`resolve release ref "${e}"`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'})}},Ze=e=>{if(e===po)return po;let r=y(e);return r?C(r):e},we=e=>e.flatMap(r=>{let t=y(r);return t?[C(t)]:[]}),I=e=>{let{branches:r,descriptions:t,types:o}=e,n=mo(r),s=Math.max(0,...n.map(i=>i.label.length));return n.map(({branch:i,id:l,label:c})=>{let p=o?o.get(i)||"regular":void 0,d=t.get(D(l)),u=" ".repeat(s-c.length+3),g=p?Ie(c,p,s):c;return d&&(g=p?`${g} ${d}`:`${c}${u}${d}`),{name:g,value:i}})};var uo=e=>e.map(r=>({pr:r,id:y(r.headRefName)})).filter(r=>r.id!==null).sort((r,t)=>Sr(r.id,t.id,{a:r.pr.createdAt,b:t.pr.createdAt})).map(r=>r.pr),fo=async()=>{let e=await A`gh pr list --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,r=await A`gh pr list --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName,createdAt`,t=[...JSON.parse(e.stdout),...JSON.parse(r.stdout)],o=new Set;return t.filter(n=>o.has(n.headRefName)?!1:(o.add(n.headRefName),!0))},wr=async()=>{try{let e=await fo();return e.length===0&&(a.error("\u274C No release PRs found. Check the project folder for the script. Exiting..."),hr.exit(1)),uo(e).map(r=>r.headRefName)}catch(e){a.error({error:e},"\u274C Error fetching release PRs"),hr.exit(1)}},b=async()=>{try{let e=await fo();return e.length===0&&(a.error("\u274C No release PRs found. Check the project folder for the script. Exiting..."),hr.exit(1)),uo(e).map(r=>({branch:r.headRefName,title:r.title,createdAt:r.createdAt}))}catch(e){a.error({error:e},"\u274C Error fetching release PRs"),hr.exit(1)}},vr=async e=>{let{branch:r,body:t}=e;try{A.quiet=!0,await A`gh pr edit ${r} --body ${t}`,A.quiet=!1}catch(o){throw a.error({error:o,branch:r},`Error updating release PR body for ${r}`),o}},gr=async e=>{let{id:r,jiraVersionUrl:t,type:o,description:n}=e,s=$r(r,o),i=Se(o),l=K(r),c=n&&n.trim()!==""?`${t}
14
+ `),m.print();let p=Zn(o),d={filePath:c,variableCount:p,project:n,config:t};return{content:h(JSON.stringify(d,null,2)),structuredContent:d}},ao=1024*1024,Hn=3e4,Xn=async(e,r)=>{let t=ur.quiet;ur.quiet=!0;try{let n=await ur`doppler secrets download --no-file --format env --project ${e} --config ${r}`.timeout(Hn);return Yn(n.stdout),n.stdout.trim()}finally{ur.quiet=t}},Yn=e=>{let r=Kn.byteLength(e,"utf-8");if(r>ao)throw new Error(`doppler returned unexpectedly large output (${r} bytes > ${ao}) \u2014 refusing to write to disk`)},Zn=e=>e.split(`
15
+ `).filter(r=>Ve.test(r)).length,Qn=new Set(["set -a","set +a"]),Qr=e=>`'${e.replaceAll("'","'\\''")}'`,es=e=>{if(e.trim().length===0)throw new Error("doppler returned empty output for env-load");for(let r of e.split(`
16
+ `)){let t=r.trim();if(!(t.length===0||Qn.has(t))&&!Ve.test(t))throw new Error(`doppler returned unexpected output for env-load (expected KEY=value lines, got: ${JSON.stringify(t.slice(0,80))})`)}},et=v({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:ze.string().describe('Doppler config / environment name to load (e.g. "dev", "arthur", "renana"). Required for MCP calls.')},outputSchema:{filePath:ze.string().describe("Path to the file that must be sourced to apply variables"),variableCount:ze.number().describe("Number of variables loaded"),project:ze.string().describe("Doppler project name"),config:ze.string().describe("Doppler config name")},handler:co});import rs from"node:path";import He from"node:process";import{z as Te}from"zod";var lo=async()=>{await Ge(),a.info("Environment session status:");let e=ge(),r=He.env[Je],t=rs.join(e,me),n=0,o=0,s=He.env[de]??null,i=He.env[ue]??null,l=He.env[fe]??null;if(s){let p=Be(t);p.length>0&&(o=p.length,n=p.filter(u=>u in He.env).length);let d=l?.replace(/\.\d{3}Z$/,"")??null;if(a.info(` ${s}: ${n} of ${o} vars loaded (project: ${i}, loadedAt: ${d}, session: ${r})
17
+ `),o>0&&n<o){let u=o-n;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
18
+ `);let c={sessionId:r,sessionLoadedCount:n,sessionTotalCount:o,sessionConfig:s,sessionProject:i,sessionLoadedAt:l};return{content:h(JSON.stringify(c,null,2)),structuredContent:c}},rt=v({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:Te.string().describe("Current terminal session ID"),sessionLoadedCount:Te.number().describe("Number of cached vars active in the current session"),sessionTotalCount:Te.number().describe("Total number of cached var names"),sessionConfig:Te.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:Te.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:Te.string().nullable().describe("ISO 8601 timestamp of when the env was loaded")},handler:lo});import ss from"@inquirer/checkbox";import is from"@inquirer/confirm";import as from"node:process";import{z as Ae}from"zod";import{$ as V}from"zx";import{$ as bl}from"zx";import wr from"node:process";import{$ as A}from"zx";import{$ as Ye}from"zx";import Xe from"node:process";var tt=async(e,r)=>{try{let{baseUrl:t,token:n,email:o,projectId:s}=r,i={name:e.name,projectId:e.projectId||s,description:e.description||"",released:e.released||!1,archived:e.archived||!1},l=`${t}/rest/api/3/version`,c=btoa(`${o}:${n}`),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}},Ee=async e=>{try{let{baseUrl:r,token:t,email:n,projectId:o}=e,s=`${r}/rest/api/3/project/${o}/versions`,i=btoa(`${n}:${t}`),l=await fetch(s,{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}},fr=async(e,r)=>{try{return(await Ee(r)).find(o=>o.name===e)||null}catch(t){throw a.error({error:t,versionName:e},"Error finding Jira version by name"),t}},gr=async(e,r)=>{try{let{baseUrl:t,token:n,email:o}=r,s={};e.released!==void 0&&(s.released=e.released),e.archived!==void 0&&(s.archived=e.archived),e.releaseDate!==void 0&&(s.releaseDate=e.releaseDate),e.description!==void 0&&(s.description=e.description);let i=`${t}/rest/api/3/version/${e.versionId}`,l=btoa(`${o}:${n}`),c=await fetch(i,{method:"PUT",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${l}`},body:JSON.stringify(s)});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}},ot=async(e,r)=>{try{let{versionName:t}=e,n=await fr(t,r);if(!n)throw a.error({versionName:t},"Jira version not found"),new Error(`Version "${t}" not found in Jira project`);return await gr({versionId:n.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},r)}catch(t){throw a.error({error:t},"Error delivering Jira release"),t}},$e=async()=>{let e=Xe.env.JIRA_BASE_URL,r=Xe.env.JIRA_TOKEN||Xe.env.JIRA_API_TOKEN,t=Xe.env.JIRA_PROJECT_ID,n=Xe.env.JIRA_EMAIL,o=[];if(e||o.push("JIRA_BASE_URL (e.g., https://your-domain.atlassian.net)"),r||o.push("JIRA_TOKEN or JIRA_API_TOKEN (your Jira API token)"),t||o.push("JIRA_PROJECT_ID (numeric project ID)"),n||o.push("JIRA_EMAIL (your Jira email address)"),o.length>0){let i=["Jira configuration is required but incomplete.","Please configure the following environment variables:",...o.map(l=>` - ${l}`),"","You can set these in your .env file or as environment variables."].join(`
19
+ `);throw new Error(i)}let s=Number.parseInt(t,10);if(Number.isNaN(s))throw new TypeError(`Invalid JIRA_PROJECT_ID: "${t}" must be a numeric value (e.g., 10001)`);return{baseUrl:e.replace(/\/$/,""),token:r,projectId:s,email:n}},he=async()=>{try{return await $e()}catch(e){return a.warn({error:e},"Jira configuration not available, skipping Jira integration"),null}};var os=e=>{if(e===null||typeof e!="object")return;let r=e.stderr;return typeof r=="string"&&r.length>0?r:void 0},ns=(e,r)=>{let t=r.stderrExcerpt??os(e),n=[`failed to ${r.operation}`];return t&&n.push(`stderr: ${t.slice(0,200).trim()}`),r.remediation&&n.push(`try: ${r.remediation}`),n.join(" \u2014 ")},f=class extends Error{operation;remediation;constructor(r,t){super(ns(r,t),{cause:r}),this.name="OperationError",this.operation=t.operation,this.remediation=t.remediation}};var po="dev",Se=e=>e==="hotfix"?"main":"dev",nt=async(e="regular")=>{let r=Se(e);Ye.quiet=!0,await Ye`git fetch origin`,await Ye`git switch ${r}`,await Ye`git pull origin ${r}`,Ye.quiet=!1},st=async e=>{let{id:r,jiraConfig:t,description:n,type:o="regular"}=e,s=D(r),i=await tt({name:s,projectId:t.projectId,description:n||"",released:!1,archived:!1},t),l=`${t.baseUrl}/projects/${i.version.projectId}/versions/${i.version.id}/tab/release-report-all-issues`,c=await hr({id:r,jiraVersionUrl:l,type:o,description:n});return{version:C(r),type:o,branchName:c.branchName,prUrl:c.prUrl,jiraVersionUrl:l}},E=async()=>{let e=new Map,r=await he();if(!r)return e;try{let t=await Ee(r);for(let n of t)n.description&&e.set(n.name,n.description)}catch{}return e},Ie=(e,r,t)=>{let n=t?" ".repeat(t-e.length+3):" ",o=`[${r}]`.padEnd(11);return`${e}${n}${o}`},R=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",mo=e=>e.flatMap(r=>{let t=y(r);return t?[{branch:r,id:t,label:C(t)}]:[]}),z=e=>{try{return K(B(e))}catch(r){throw new f(r,{operation:`resolve release ref "${e}"`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'})}},Ze=e=>{if(e===po)return po;let r=y(e);return r?C(r):e},we=e=>e.flatMap(r=>{let t=y(r);return t?[C(t)]:[]}),I=e=>{let{branches:r,descriptions:t,types:n}=e,o=mo(r),s=Math.max(0,...o.map(i=>i.label.length));return o.map(({branch:i,id:l,label:c})=>{let p=n?n.get(i)||"regular":void 0,d=t.get(D(l)),u=" ".repeat(s-c.length+3),g=p?Ie(c,p,s):c;return d&&(g=p?`${g} ${d}`:`${c}${u}${d}`),{name:g,value:i}})};var uo=e=>e.map(r=>({pr:r,id:y(r.headRefName)})).filter(r=>r.id!==null).sort((r,t)=>Sr(r.id,t.id,{a:r.pr.createdAt,b:t.pr.createdAt})).map(r=>r.pr),fo=async()=>{let e=await A`gh pr list --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,r=await A`gh pr list --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName,createdAt`,t=[...JSON.parse(e.stdout),...JSON.parse(r.stdout)],n=new Set;return t.filter(o=>n.has(o.headRefName)?!1:(n.add(o.headRefName),!0))},vr=async()=>{try{let e=await fo();return e.length===0&&(a.error("\u274C No release PRs found. Check the project folder for the script. Exiting..."),wr.exit(1)),uo(e).map(r=>r.headRefName)}catch(e){a.error({error:e},"\u274C Error fetching release PRs"),wr.exit(1)}},b=async()=>{try{let e=await fo();return e.length===0&&(a.error("\u274C No release PRs found. Check the project folder for the script. Exiting..."),wr.exit(1)),uo(e).map(r=>({branch:r.headRefName,title:r.title,createdAt:r.createdAt}))}catch(e){a.error({error:e},"\u274C Error fetching release PRs"),wr.exit(1)}},kr=async e=>{let{branch:r,body:t}=e;try{A.quiet=!0,await A`gh pr edit ${r} --body ${t}`,A.quiet=!1}catch(n){throw a.error({error:n,branch:r},`Error updating release PR body for ${r}`),n}},hr=async e=>{let{id:r,jiraVersionUrl:t,type:n,description:o}=e,s=$r(r,n),i=Se(n),l=K(r),c=o&&o.trim()!==""?`${t}
20
20
 
21
- ${n}`:`${t}
22
- `;try{A.quiet=!0,await A`git switch ${i}`,await A`git pull origin ${i}`,await A`git checkout -b ${l}`,await A`git push -u origin ${l}`,await A`git commit --allow-empty-message --allow-empty --message ''`,await A`git push origin ${l}`;let d=(await A`gh pr create --title ${s} --body ${c} --base ${i} --head ${l}`).stdout.trim();return await A`git switch ${i}`,A.quiet=!1,{branchName:l,prUrl:d}}catch(p){throw a.error({error:p,branchName:l},`Error creating release branch ${l}`),p}};var M=async e=>{let{operation:r,requiredBranch:t}=e;if(await Nr())throw new f(void 0,{operation:r,remediation:"run this from the main repository checkout, not a linked git worktree",stderrExcerpt:"command run from inside a linked worktree"});if(t){let o=await Ir();if(o!==t)throw new f(void 0,{operation:r,remediation:`switch to ${t} first (git switch ${t})`,stderrExcerpt:`current branch is "${o}", expected "${t}"`})}if(!await Ar())throw new f(void 0,{operation:r,remediation:"commit or stash your changes, then retry",stderrExcerpt:"working tree has uncommitted changes"})};var go=async e=>{let{all:r,confirmedCommand:t}=e;m.start("merge-dev"),await M({operation:"merge dev into release branches",requiredBranch:"dev"});let n=(await b()).filter(d=>R(d.title)==="regular").map(d=>d.branch);if(n.length===0)return a.info("\u2139\uFE0F No open release branches found"),m.print(),{content:h(JSON.stringify({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0},null,2)),structuredContent:{successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0}};let s=[];if(r)s=n;else{m.setInteractive();let d=await E();s=await is({required:!0,message:"\u{1F33F} Select release branches",choices:I({branches:n,descriptions:d})})}s.length===n.length?m.addOption("--all",!0):m.addOption("--versions",we(s));let l=t?!0:await as({message:`Are you sure you want to merge dev into these branches: ${s.join(", ")}?`});t||m.setInteractive(),l||(a.info("Operation cancelled. Exiting..."),cs.exit(0)),t||m.addOption("--yes",!0),V.quiet=!0,await V`git fetch origin`,await V`git switch dev`,await V`git pull origin dev`;let c=[];for(let d of s)await ls(d)||c.push(d);if(V.quiet=!1,c.length>0){a.info(`
21
+ ${o}`:`${t}
22
+ `;try{A.quiet=!0,await A`git switch ${i}`,await A`git pull origin ${i}`,await A`git checkout -b ${l}`,await A`git push -u origin ${l}`,await A`git commit --allow-empty-message --allow-empty --message ''`,await A`git push origin ${l}`;let d=(await A`gh pr create --title ${s} --body ${c} --base ${i} --head ${l}`).stdout.trim();return await A`git switch ${i}`,A.quiet=!1,{branchName:l,prUrl:d}}catch(p){throw a.error({error:p,branchName:l},`Error creating release branch ${l}`),p}};var M=async e=>{let{operation:r,requiredBranch:t}=e;if(await Nr())throw new f(void 0,{operation:r,remediation:"run this from the main repository checkout, not a linked git worktree",stderrExcerpt:"command run from inside a linked worktree"});if(t){let n=await Ir();if(n!==t)throw new f(void 0,{operation:r,remediation:`switch to ${t} first (git switch ${t})`,stderrExcerpt:`current branch is "${n}", expected "${t}"`})}if(!await Ar())throw new f(void 0,{operation:r,remediation:"commit or stash your changes, then retry",stderrExcerpt:"working tree has uncommitted changes"})};var go=async e=>{let{all:r,confirmedCommand:t}=e;m.start("merge-dev"),await M({operation:"merge dev into release branches",requiredBranch:"dev"});let o=(await b()).filter(d=>R(d.title)==="regular").map(d=>d.branch);if(o.length===0)return a.info("\u2139\uFE0F No open release branches found"),m.print(),{content:h(JSON.stringify({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0},null,2)),structuredContent:{successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0}};let s=[];if(r)s=o;else{m.setInteractive();let d=await E();s=await ss({required:!0,message:"\u{1F33F} Select release branches",choices:I({branches:o,descriptions:d})})}s.length===o.length?m.addOption("--all",!0):m.addOption("--versions",we(s));let l=t?!0:await is({message:`Are you sure you want to merge dev into these branches: ${s.join(", ")}?`});t||m.setInteractive(),l||(a.info("Operation cancelled. Exiting..."),as.exit(0)),t||m.addOption("--yes",!0),V.quiet=!0,await V`git fetch origin`,await V`git switch dev`,await V`git pull origin dev`;let c=[];for(let d of s)await cs(d)||c.push(d);if(V.quiet=!1,c.length>0){a.info(`
23
23
  \u26A0\uFE0F ${c.length} branch(es) failed to merge automatically.
24
24
  `),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
25
25
 
26
26
  git switch ${d} && git pull origin ${d} && git merge origin/dev
27
27
  git push origin ${d} && git switch dev
28
28
  `);a.info(`\u2705 ${s.length-c.length}/${s.length} merges completed successfully.`)}else a.info(`\u2705 All merges completed successfully!
29
- `);m.print();let p={successfulMerges:s.length-c.length,failedMerges:c.length,failedBranches:c,totalBranches:s.length};return{content:h(JSON.stringify(p,null,2)),structuredContent:p}},ls=async e=>{try{return await V`git switch ${e}`,await V`git pull origin ${e}`,await V`git merge origin/dev --no-edit`,await V`git push origin ${e}`,await V`git switch dev`,a.info(`Successfully merged dev into ${e}`),!0}catch(r){let t=new f(r,{operation:`merge dev into ${e}`,remediation:"resolve conflicts manually or rerun after 'git fetch origin'"});return a.error({error:r,branch:e,msg:t.message}),await V`git reset --merge HEAD~1`,!1}},it=v({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:Ae.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:Ae.number().describe("Number of successful merges"),failedMerges:Ae.number().describe("Number of failed merges"),failedBranches:Ae.array(Ae.string()).describe("List of branches that failed to merge"),totalBranches:Ae.number().describe("Total number of branches processed")},handler:go});import gs from"@inquirer/confirm";import hs from"@inquirer/select";import ws from"node:process";import{z as nr}from"zod";import{$ as j}from"zx";var ho=(e,r)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-r).trim()},at=e=>{if(e===null||typeof e!="object")return{message:String(e)};let r=e,t={};e instanceof Error?(t.name=e.name,t.message=e.message):typeof r.message=="string"&&(t.message=r.message);let o=r.exitCode;(typeof o=="number"||o===null)&&(t.exitCode=o);let n=ho(r.stderr,500);n&&(t.stderr=n);let s=ho(r.stdout,200);return s&&(t.stdout=s),t};import{$ as ct}from"zx";var ps=/\bv(\d+\.\d+\.\d+)\b/g,q=e=>e.trim().replace(/\s+/g," ").replace(ps,"$1");import{$ as wo}from"zx";var Qe=async e=>{try{let r=(await wo`cmux list-workspaces`.quiet()).stdout,t=ms(r,e);if(!t)return;await wo`cmux close-workspace --workspace ${t}`.quiet()}catch(r){a.debug({error:r,title:e},"cmux: skipped closing workspace")}},ms=(e,r)=>{let t=q(r);for(let o of e.split(`
30
- `)){let n=o.match(/^[* ]\s*(workspace:\d+)\s+(.+?)(?:\s+\[selected\])?\s*$/);if(!n)continue;let s=n[1],i=n[2]?.trim()??"";if(q(i)===t)return s}};import{$ as ds}from"zx";var er=async()=>{try{let e=(await ds`cmux list-workspaces`.quiet()).stdout,r=new Set;for(let t of e.split(`
31
- `)){let o=t.match(/^[* ]\s*workspace:\d+\s+(.+?)(?:\s+\[selected\])?\s*$/);if(!o)continue;let n=o[1]?.trim();n&&r.add(q(n))}return r}catch(e){return a.debug({error:e},"cmux: skipped listing workspace titles"),new Set}};import{$ as rr}from"zx";var tr=async e=>{let{cwd:r,title:t}=e,o=(await rr`cmux workspace create --cwd ${r}`).stdout,n=fs(o),s=(await rr`cmux list-pane-surfaces --workspace ${n}`).stdout,i=us(s);await rr`cmux new-split right --workspace ${n} --surface ${i}`,await rr`cmux new-split down --workspace ${n} --surface ${i}`,t&&await rr`cmux workspace rename --workspace ${n} --title ${t}`},us=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]},fs=e=>{let r=e.match(/workspace:\d+/);if(!r)throw new Error("cmux: could not locate workspace ref in workspace create output");return r[0]};var H=e=>{let{repoName:r,branch:t}=e,o=y(t),n=o?C(o):t;return`${r} ${n}`};var or=async e=>{let{branches:r,worktreeDir:t,repoName:o,pruneFolder:n=!1}=e,s=await Promise.allSettled(r.map(async l=>{let c=`${t}/${l}`,p=H({repoName:o,branch:l});return await Qe(p),await ct`git worktree remove ${c}`,l})),i=[];for(let[l,c]of s.entries())if(c.status==="fulfilled")i.push(c.value);else{let p=r[l],d=new f(c.reason,{operation:`remove worktree for ${p}`,remediation:"check 'git worktree list' for the path; uncommitted changes block removal"});a.error({error:c.reason,msg:d.message})}return n&&i.length===r.length&&(await ct`git worktree prune`,await ct`rm -rf ${t}`,a.info(`\u{1F5D1}\uFE0F Removed worktree folder: ${t}`),a.info("")),i};var Ne=async(e,r,t)=>{try{return await t()}catch(o){throw a.error({err:at(o)},`\u274C Failed to ${e}`),new f(o,{operation:e,remediation:r})}},ko=async e=>{let r=await j`gh pr list --head ${e} --state all --json number,state,title --limit 1`;return JSON.parse(r.stdout)[0]??null},vs=async e=>{let r=cr(e),t=await j`gh pr list --head dev --base main --state merged --json number,state,title --limit 20`;return JSON.parse(t.stdout).find(s=>s.title===r)??null},vo=async()=>{let e=await j`gh pr list --head dev --base main --state open --json number,state,title --limit 5`;return JSON.parse(e.stdout)[0]??null},ks=async e=>{let r=z(e),t=await ko(r);if(!t)throw a.error(`\u274C No PR found for branch ${r}.`),new f(void 0,{operation:`deliver release ${r}`,remediation:`confirm a PR exists ('gh pr list --head ${r} --state all')`});return{selectedReleaseBranch:r,releasePrTitle:t.title}},ys=async()=>{let e=await b(),r=e.map(i=>i.branch),t=new Map(e.map(i=>[i.branch,R(i.title)]));m.setInteractive();let o=await E(),n=await hs({message:"\u{1F33F} Select release branch",choices:I({branches:r,descriptions:o,types:t})}),s=e.find(i=>i.branch===n);if(!s)throw a.error(`\u274C Release branch ${n} not found in open PRs.`),new f(void 0,{operation:`deliver release ${n}`,remediation:`confirm an open PR exists for ${n} ('gh pr list')`});return{selectedReleaseBranch:n,releasePrTitle:s.title}},Rs=async e=>{if(!(await _("release")).includes(e))return;let[t,o]=await Promise.all([P(),F()]),n=`${t}${J}`;if((await or({branches:[e],worktreeDir:n,repoName:o})).length===0)throw new f(void 0,{operation:`remove worktree for ${e} before merge`,remediation:`run manually: git worktree remove ${n}/${e} (use --force if uncommitted changes)`})},bs=async e=>{let{selectedReleaseBranch:r,releaseType:t}=e,o=t==="hotfix"?"main":"dev",n=await ko(r);if(!n)throw new f(void 0,{operation:`look up release PR for ${r}`,remediation:"verify the PR exists in GitHub"});if(n.state==="MERGED"){a.info(`\u2713 Release PR ${r} already merged \u2014 skipping`);return}if(n.state==="CLOSED")throw new f(void 0,{operation:`merge release PR ${r} into ${o}`,remediation:"the PR is closed without merge; reopen it or create a new release"});await Ne(`merge release PR ${r} into ${o}`,`check 'gh pr view ${r}' for mergeability and required reviews`,async()=>{await j`gh pr merge ${r} --squash --admin --delete-branch`})},xs=async e=>{let r=C(e),t=cr(e),o=await vo();if(o){let s=o.number;return o.title!==t&&(a.info(`Adopting open dev \u2192 main PR #${s} ("${o.title}") and retitling for ${r}`),await Ne(`retitle dev \u2192 main PR #${s} to "${t}"`,`update manually: gh pr edit ${s} --title "${t}"`,async()=>{await j`gh pr edit ${s} --title ${t}`})),s}await Ne(`create RC PR (dev \u2192 main) for ${r}`,"run 'gh pr create --base main --head dev' manually to surface the underlying error (e.g. no commits between dev and main)",async()=>{await j`gh pr create --base main --head dev --title ${t} --body ""`});let n=await vo();if(!n)throw new f(void 0,{operation:`look up RC PR for ${r}`,remediation:"verify the RC PR was created ('gh pr list --head dev --base main')"});return n.number},Cs=async e=>{let r=C(e);if(await vs(e)){a.info(`\u2713 RC PR for ${r} already merged into main \u2014 skipping`);return}let o=await xs(e);await Ne(`merge RC PR #${o} (dev \u2192 main) for ${r}`,`check 'gh pr view ${o}' for mergeability and required reviews`,async()=>{await j`gh pr merge ${o} --squash --admin`})},Ps=async()=>{j.quiet=!1,await Ne("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await j`gh workflow run deploy-all.yml --ref main -f environment=prod`}),j.quiet=!0},Ts=async()=>{await Ne("sync main back into dev","run manually: git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push",async()=>{await j`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},Es=async e=>{let r=await he();if(!r){a.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let t=D(e);await ot({versionName:t},r)}catch(t){a.error({err:at(t)},"Failed to deliver Jira release (non-blocking)")}},yo=async e=>{let{version:r,confirmedCommand:t}=e;m.start("release-deliver"),await M({operation:"deliver release"});let{selectedReleaseBranch:o,releasePrTitle:n}=r?await ks(r):await ys(),s=y(o);if(!s)throw new f(void 0,{operation:`deliver release ${o}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let i=C(s);m.addOption("--version",i),a.info(`Delivering ${s.kind==="name"?"named release":"version"} ${o}`);let l=R(n),c=t?!0:await gs({message:`Are you sure you want to deliver version ${o} to production?`});t||m.setInteractive(),c||(a.info("Operation cancelled. Exiting..."),ws.exit(0)),m.addOption("--yes",!0),j.quiet=!0,await Rs(o),await bs({selectedReleaseBranch:o,releaseType:l}),l!=="hotfix"&&await Cs(s),await Ps(),await Ts(),j.quiet=!1,await Es(s),a.info(`Successfully delivered ${o} to production!`),m.print();let p={releaseBranch:o,version:i,type:l,success:!0};return{content:h(JSON.stringify(p,null,2)),structuredContent:p}},lt=v({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. PR-merge steps are idempotent: re-running after a partial failure skips PRs that are already merged. 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:nr.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign") to deliver to production. Required for MCP calls.')},outputSchema:{releaseBranch:nr.string().describe("The release branch that was delivered"),version:nr.string().describe("The version that was delivered"),type:nr.enum(["regular","hotfix"]).describe("Release type"),success:nr.boolean().describe("Whether the delivery was successful")},handler:yo});import Ro from"@inquirer/select";import{z as te}from"zod";import{$ as pt}from"zx";var bo=async e=>{let{version:r,env:t,skipTerraform:o}=e;m.start("release-deploy-all");let n="";if(r)n=r==="dev"?"dev":z(r);else{m.setInteractive();let p=await b(),d=p.map(w=>w.branch),u=new Map(p.map(w=>[w.branch,R(w.title)])),g=await E();n=await Ro({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...I({branches:d,descriptions:g,types:u})]})}let s=Ze(n);m.addOption("--version",s);let{environments:i}=await T(),l="";if(t?l=t:(m.setInteractive(),l=await Ro({message:"\u{1F9EA} Select environment",choices:i.map(p=>({name:p,value:p}))})),m.addOption("--env",l),!i.includes(l))throw new f(void 0,{operation:"launch deploy-all workflow",remediation:`pass one of: ${i.join(", ")}`,stderrExcerpt:`invalid environment: ${l}`});let c=o??!1;c&&m.addOption("--skip-terraform",!0);try{pt.quiet=!0,await pt`gh workflow run deploy-all.yml --ref ${n} -f environment=${l} ${c?["-f","skip_terraform_deploy=true"]:[]}`,pt.quiet=!1,a.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${n} and environment: ${l}`),m.print();let d={releaseBranch:n,version:s,environment:l,skipTerraformDeploy:c,success:!0};return{content:h(JSON.stringify(d,null,2)),structuredContent:d}}catch(p){throw a.error({error:p},"\u274C Error launching workflow"),new f(p,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},mt=v({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:te.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign") \u2014 resolves to the release/vX.Y.Z or release/n/<name> branch. Pass "dev" to deploy from the dev branch instead. Required for MCP calls.'),env:te.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),skipTerraform:te.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:te.string().describe("The release branch that was deployed"),version:te.string().describe("The version that was deployed"),environment:te.string().describe("The environment deployed to"),skipTerraformDeploy:te.boolean().describe("Whether terraform deployment was skipped"),success:te.boolean().describe("Whether the deployment was successful")},handler:bo});import $s from"@inquirer/checkbox";import xo from"@inquirer/select";import Ss from"node:fs/promises";import{resolve as Is}from"node:path";import As from"yaml";import{z as W}from"zod";import{$ as dt}from"zx";var Co=async e=>{let{version:r,env:t,services:o,skipTerraform:n}=e;m.start("release-deploy-selected");let s="";if(r)s=r==="dev"?"dev":z(r);else{m.setInteractive();let w=await b(),$=w.map(be=>be.branch),S=new Map(w.map(be=>[be.branch,R(be.title)])),N=await E();s=await xo({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...I({branches:$,descriptions:N,types:S})]})}let i=Ze(s);m.addOption("--version",i);let{environments:l}=await T(),c="";if(t?c=t:(m.setInteractive(),c=await xo({message:"\u{1F9EA} Select environment",choices:l.map(w=>({name:w,value:w}))})),m.addOption("--env",c),!l.includes(c))throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass one of: ${l.join(", ")}`,stderrExcerpt:`invalid environment: ${c}`});let p=await Ns();if(p.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:"check .github/workflows/deploy-selected-services.yml for boolean service inputs",stderrExcerpt:"no services found in workflow file"});let d=[];if(o&&o.length>0?d=o:(m.setInteractive(),d=await $s({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:p.map(w=>({name:w,value:w}))})),m.addOption("--services",d),d.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${p.join(", ")}`,stderrExcerpt:"no services selected"});let u=d.filter(w=>!p.includes(w));if(u.length>0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${p.join(", ")}`,stderrExcerpt:`invalid services: ${u.join(", ")}`});let g=n??!1;g&&m.addOption("--skip-terraform",!0);try{dt.quiet=!0;let w=d.flatMap(N=>["-f",`${N}=true`]);await dt`gh workflow run deploy-selected-services.yml --ref ${s} -f environment=${c} ${w} ${g?["-f","skip_terraform_deploy=true"]:[]}`,dt.quiet=!1,a.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${s}, environment: ${c}, services: ${d.join(", ")}`),m.print();let S={releaseBranch:s,version:i,environment:c,services:d,skipTerraformDeploy:g,success:!0};return{content:h(JSON.stringify(S,null,2)),structuredContent:S}}catch(w){throw a.error({error:w},"\u274C Error launching workflow"),new f(w,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},Ns=async()=>{let e=await P(),r=Is(e,".github/workflows/deploy-selected-services.yml"),t=await Ss.readFile(r,"utf-8"),n=As.parse(t).on.workflow_dispatch.inputs,s=[];for(let[i,l]of Object.entries(n))l.type==="boolean"&&i!=="skip_terraform_deploy"&&s.push(i);return s},ut=v({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:W.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign") \u2014 resolves to the release/vX.Y.Z or release/n/<name> branch. Pass "dev" to deploy from the dev branch instead. Required for MCP calls.'),env:W.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),services:W.array(W.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:W.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:W.string().describe("The release branch that was deployed"),version:W.string().describe("The version that was deployed"),environment:W.string().describe("The environment deployed to"),services:W.array(W.string()).describe("The services that were deployed"),skipTerraformDeploy:W.boolean().describe("Whether terraform deployment was skipped"),success:W.boolean().describe("Whether the deployment was successful")},handler:Co});import{z as Oe}from"zod";var Po=async()=>{let r=(await b()).flatMap(i=>{let l=y(i.branch);return l?[{version:C(l),jiraKey:D(l),type:R(i.title)}]:[]}),t=await E(),o=Math.max(...r.map(i=>i.version.length)),n=r.map(i=>{let l=Ie(i.version,i.type,o),c=t.get(i.jiraKey);return c?`${l} ${c}`:l});a.info(`All release branches:
29
+ `);m.print();let p={successfulMerges:s.length-c.length,failedMerges:c.length,failedBranches:c,totalBranches:s.length};return{content:h(JSON.stringify(p,null,2)),structuredContent:p}},cs=async e=>{try{return await V`git switch ${e}`,await V`git pull origin ${e}`,await V`git merge origin/dev --no-edit`,await V`git push origin ${e}`,await V`git switch dev`,a.info(`Successfully merged dev into ${e}`),!0}catch(r){let t=new f(r,{operation:`merge dev into ${e}`,remediation:"resolve conflicts manually or rerun after 'git fetch origin'"});return a.error({error:r,branch:e,msg:t.message}),await V`git reset --merge HEAD~1`,!1}},it=v({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:Ae.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:Ae.number().describe("Number of successful merges"),failedMerges:Ae.number().describe("Number of failed merges"),failedBranches:Ae.array(Ae.string()).describe("List of branches that failed to merge"),totalBranches:Ae.number().describe("Total number of branches processed")},handler:go});import fs from"@inquirer/confirm";import gs from"@inquirer/select";import hs from"node:process";import{z as nr}from"zod";import{$ as j}from"zx";var ho=(e,r)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-r).trim()},at=e=>{if(e===null||typeof e!="object")return{message:String(e)};let r=e,t={};e instanceof Error?(t.name=e.name,t.message=e.message):typeof r.message=="string"&&(t.message=r.message);let n=r.exitCode;(typeof n=="number"||n===null)&&(t.exitCode=n);let o=ho(r.stderr,500);o&&(t.stderr=o);let s=ho(r.stdout,200);return s&&(t.stdout=s),t};import{$ as ct}from"zx";var ls=/\bv(\d+\.\d+\.\d+)\b/g,q=e=>e.trim().replace(/\s+/g," ").replace(ls,"$1");import{$ as wo}from"zx";var Qe=async e=>{try{let r=(await wo`cmux list-workspaces`.quiet()).stdout,t=ps(r,e);if(!t)return;await wo`cmux close-workspace --workspace ${t}`.quiet()}catch(r){a.debug({error:r,title:e},"cmux: skipped closing workspace")}},ps=(e,r)=>{let t=q(r);for(let n of e.split(`
30
+ `)){let o=n.match(/^[* ]\s*(workspace:\d+)\s+(.+?)(?:\s+\[selected\])?\s*$/);if(!o)continue;let s=o[1],i=o[2]?.trim()??"";if(q(i)===t)return s}};import{$ as ms}from"zx";var er=async()=>{try{let e=(await ms`cmux list-workspaces`.quiet()).stdout,r=new Set;for(let t of e.split(`
31
+ `)){let n=t.match(/^[* ]\s*workspace:\d+\s+(.+?)(?:\s+\[selected\])?\s*$/);if(!n)continue;let o=n[1]?.trim();o&&r.add(q(o))}return r}catch(e){return a.debug({error:e},"cmux: skipped listing workspace titles"),new Set}};import{$ as rr}from"zx";var tr=async e=>{let{cwd:r,title:t}=e,n=(await rr`cmux workspace create --cwd ${r}`).stdout,o=us(n),s=(await rr`cmux list-pane-surfaces --workspace ${o}`).stdout,i=ds(s);await rr`cmux new-split right --workspace ${o} --surface ${i}`,await rr`cmux new-split down --workspace ${o} --surface ${i}`,t&&await rr`cmux workspace rename --workspace ${o} --title ${t}`},ds=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]},us=e=>{let r=e.match(/workspace:\d+/);if(!r)throw new Error("cmux: could not locate workspace ref in workspace create output");return r[0]};var H=e=>{let{repoName:r,branch:t}=e,n=y(t),o=n?C(n):t;return`${r} ${o}`};var or=async e=>{let{branches:r,worktreeDir:t,repoName:n,pruneFolder:o=!1}=e,s=await Promise.allSettled(r.map(async l=>{let c=`${t}/${l}`,p=H({repoName:n,branch:l});return await Qe(p),await ct`git worktree remove ${c}`,l})),i=[];for(let[l,c]of s.entries())if(c.status==="fulfilled")i.push(c.value);else{let p=r[l],d=new f(c.reason,{operation:`remove worktree for ${p}`,remediation:"check 'git worktree list' for the path; uncommitted changes block removal"});a.error({error:c.reason,msg:d.message})}return o&&i.length===r.length&&(await ct`git worktree prune`,await ct`rm -rf ${t}`,a.info(`\u{1F5D1}\uFE0F Removed worktree folder: ${t}`),a.info("")),i};var Ne=async(e,r,t)=>{try{return await t()}catch(n){throw a.error({err:at(n)},`\u274C Failed to ${e}`),new f(n,{operation:e,remediation:r})}},ko=async e=>{let r=await j`gh pr list --head ${e} --state all --json number,state,title --limit 1`;return JSON.parse(r.stdout)[0]??null},ws=async e=>{let r=lr(e),t=await j`gh pr list --head dev --base main --state merged --json number,state,title --limit 20`;return JSON.parse(t.stdout).find(s=>s.title===r)??null},vo=async()=>{let e=await j`gh pr list --head dev --base main --state open --json number,state,title --limit 5`;return JSON.parse(e.stdout)[0]??null},vs=async e=>{let r=z(e),t=await ko(r);if(!t)throw a.error(`\u274C No PR found for branch ${r}.`),new f(void 0,{operation:`deliver release ${r}`,remediation:`confirm a PR exists ('gh pr list --head ${r} --state all')`});return{selectedReleaseBranch:r,releasePrTitle:t.title}},ks=async()=>{let e=await b(),r=e.map(i=>i.branch),t=new Map(e.map(i=>[i.branch,R(i.title)]));m.setInteractive();let n=await E(),o=await gs({message:"\u{1F33F} Select release branch",choices:I({branches:r,descriptions:n,types:t})}),s=e.find(i=>i.branch===o);if(!s)throw a.error(`\u274C Release branch ${o} not found in open PRs.`),new f(void 0,{operation:`deliver release ${o}`,remediation:`confirm an open PR exists for ${o} ('gh pr list')`});return{selectedReleaseBranch:o,releasePrTitle:s.title}},ys=async e=>{if(!(await _("release")).includes(e))return;let[t,n]=await Promise.all([P(),F()]),o=`${t}${J}`;if((await or({branches:[e],worktreeDir:o,repoName:n})).length===0)throw new f(void 0,{operation:`remove worktree for ${e} before merge`,remediation:`run manually: git worktree remove ${o}/${e} (use --force if uncommitted changes)`})},Rs=async e=>{let{selectedReleaseBranch:r,releaseType:t}=e,n=t==="hotfix"?"main":"dev",o=await ko(r);if(!o)throw new f(void 0,{operation:`look up release PR for ${r}`,remediation:"verify the PR exists in GitHub"});if(o.state==="MERGED"){a.info(`\u2713 Release PR ${r} already merged \u2014 skipping`);return}if(o.state==="CLOSED")throw new f(void 0,{operation:`merge release PR ${r} into ${n}`,remediation:"the PR is closed without merge; reopen it or create a new release"});await Ne(`merge release PR ${r} into ${n}`,`check 'gh pr view ${r}' for mergeability and required reviews`,async()=>{await j`gh pr merge ${r} --squash --admin --delete-branch`})},bs=async e=>{let r=C(e),t=lr(e),n=await vo();if(n){let s=n.number;return n.title!==t&&(a.info(`Adopting open dev \u2192 main PR #${s} ("${n.title}") and retitling for ${r}`),await Ne(`retitle dev \u2192 main PR #${s} to "${t}"`,`update manually: gh pr edit ${s} --title "${t}"`,async()=>{await j`gh pr edit ${s} --title ${t}`})),s}await Ne(`create RC PR (dev \u2192 main) for ${r}`,"run 'gh pr create --base main --head dev' manually to surface the underlying error (e.g. no commits between dev and main)",async()=>{await j`gh pr create --base main --head dev --title ${t} --body ""`});let o=await vo();if(!o)throw new f(void 0,{operation:`look up RC PR for ${r}`,remediation:"verify the RC PR was created ('gh pr list --head dev --base main')"});return o.number},xs=async e=>{let r=C(e);if(await ws(e)){a.info(`\u2713 RC PR for ${r} already merged into main \u2014 skipping`);return}let n=await bs(e);await Ne(`merge RC PR #${n} (dev \u2192 main) for ${r}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await j`gh pr merge ${n} --squash --admin`})},Cs=async()=>{j.quiet=!1,await Ne("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await j`gh workflow run deploy-all.yml --ref main -f environment=prod`}),j.quiet=!0},Ps=async()=>{await Ne("sync main back into dev","run manually: git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push",async()=>{await j`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},Ts=async e=>{let r=await he();if(!r){a.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let t=D(e);await ot({versionName:t},r)}catch(t){a.error({err:at(t)},"Failed to deliver Jira release (non-blocking)")}},yo=async e=>{let{version:r,confirmedCommand:t}=e;m.start("release-deliver"),await M({operation:"deliver release"});let{selectedReleaseBranch:n,releasePrTitle:o}=r?await vs(r):await ks(),s=y(n);if(!s)throw new f(void 0,{operation:`deliver release ${n}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let i=C(s);m.addOption("--version",i),a.info(`Delivering ${s.kind==="name"?"named release":"version"} ${n}`);let l=R(o),c=t?!0:await fs({message:`Are you sure you want to deliver version ${n} to production?`});t||m.setInteractive(),c||(a.info("Operation cancelled. Exiting..."),hs.exit(0)),m.addOption("--yes",!0),j.quiet=!0,await ys(n),await Rs({selectedReleaseBranch:n,releaseType:l}),l!=="hotfix"&&await xs(s),await Cs(),await Ps(),j.quiet=!1,await Ts(s),a.info(`Successfully delivered ${n} to production!`),m.print();let p={releaseBranch:n,version:i,type:l,success:!0};return{content:h(JSON.stringify(p,null,2)),structuredContent:p}},lt=v({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. PR-merge steps are idempotent: re-running after a partial failure skips PRs that are already merged. 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:nr.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign") to deliver to production. Required for MCP calls.')},outputSchema:{releaseBranch:nr.string().describe("The release branch that was delivered"),version:nr.string().describe("The version that was delivered"),type:nr.enum(["regular","hotfix"]).describe("Release type"),success:nr.boolean().describe("Whether the delivery was successful")},handler:yo});import Ro from"@inquirer/select";import{z as te}from"zod";import{$ as pt}from"zx";var bo=async e=>{let{version:r,env:t,skipTerraform:n}=e;m.start("release-deploy-all");let o="";if(r)o=r==="dev"?"dev":z(r);else{m.setInteractive();let p=await b(),d=p.map(w=>w.branch),u=new Map(p.map(w=>[w.branch,R(w.title)])),g=await E();o=await Ro({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...I({branches:d,descriptions:g,types:u})]})}let s=Ze(o);m.addOption("--version",s);let{environments:i}=await T(),l="";if(t?l=t:(m.setInteractive(),l=await Ro({message:"\u{1F9EA} Select environment",choices:i.map(p=>({name:p,value:p}))})),m.addOption("--env",l),!i.includes(l))throw new f(void 0,{operation:"launch deploy-all workflow",remediation:`pass one of: ${i.join(", ")}`,stderrExcerpt:`invalid environment: ${l}`});let c=n??!1;c&&m.addOption("--skip-terraform",!0);try{pt.quiet=!0,await pt`gh workflow run deploy-all.yml --ref ${o} -f environment=${l} ${c?["-f","skip_terraform_deploy=true"]:[]}`,pt.quiet=!1,a.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${o} and environment: ${l}`),m.print();let d={releaseBranch:o,version:s,environment:l,skipTerraformDeploy:c,success:!0};return{content:h(JSON.stringify(d,null,2)),structuredContent:d}}catch(p){throw a.error({error:p},"\u274C Error launching workflow"),new f(p,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},mt=v({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:te.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign") \u2014 resolves to the release/vX.Y.Z or release/<name> branch. Pass "dev" to deploy from the dev branch instead. Required for MCP calls.'),env:te.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),skipTerraform:te.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:te.string().describe("The release branch that was deployed"),version:te.string().describe("The version that was deployed"),environment:te.string().describe("The environment deployed to"),skipTerraformDeploy:te.boolean().describe("Whether terraform deployment was skipped"),success:te.boolean().describe("Whether the deployment was successful")},handler:bo});import Es from"@inquirer/checkbox";import xo from"@inquirer/select";import $s from"node:fs/promises";import{resolve as Ss}from"node:path";import Is from"yaml";import{z as W}from"zod";import{$ as dt}from"zx";var Co=async e=>{let{version:r,env:t,services:n,skipTerraform:o}=e;m.start("release-deploy-selected");let s="";if(r)s=r==="dev"?"dev":z(r);else{m.setInteractive();let w=await b(),$=w.map(be=>be.branch),S=new Map(w.map(be=>[be.branch,R(be.title)])),N=await E();s=await xo({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...I({branches:$,descriptions:N,types:S})]})}let i=Ze(s);m.addOption("--version",i);let{environments:l}=await T(),c="";if(t?c=t:(m.setInteractive(),c=await xo({message:"\u{1F9EA} Select environment",choices:l.map(w=>({name:w,value:w}))})),m.addOption("--env",c),!l.includes(c))throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass one of: ${l.join(", ")}`,stderrExcerpt:`invalid environment: ${c}`});let p=await As();if(p.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:"check .github/workflows/deploy-selected-services.yml for boolean service inputs",stderrExcerpt:"no services found in workflow file"});let d=[];if(n&&n.length>0?d=n:(m.setInteractive(),d=await Es({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:p.map(w=>({name:w,value:w}))})),m.addOption("--services",d),d.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${p.join(", ")}`,stderrExcerpt:"no services selected"});let u=d.filter(w=>!p.includes(w));if(u.length>0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${p.join(", ")}`,stderrExcerpt:`invalid services: ${u.join(", ")}`});let g=o??!1;g&&m.addOption("--skip-terraform",!0);try{dt.quiet=!0;let w=d.flatMap(N=>["-f",`${N}=true`]);await dt`gh workflow run deploy-selected-services.yml --ref ${s} -f environment=${c} ${w} ${g?["-f","skip_terraform_deploy=true"]:[]}`,dt.quiet=!1,a.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${s}, environment: ${c}, services: ${d.join(", ")}`),m.print();let S={releaseBranch:s,version:i,environment:c,services:d,skipTerraformDeploy:g,success:!0};return{content:h(JSON.stringify(S,null,2)),structuredContent:S}}catch(w){throw a.error({error:w},"\u274C Error launching workflow"),new f(w,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},As=async()=>{let e=await P(),r=Ss(e,".github/workflows/deploy-selected-services.yml"),t=await $s.readFile(r,"utf-8"),o=Is.parse(t).on.workflow_dispatch.inputs,s=[];for(let[i,l]of Object.entries(o))l.type==="boolean"&&i!=="skip_terraform_deploy"&&s.push(i);return s},ut=v({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:W.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign") \u2014 resolves to the release/vX.Y.Z or release/<name> branch. Pass "dev" to deploy from the dev branch instead. Required for MCP calls.'),env:W.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),services:W.array(W.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:W.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:W.string().describe("The release branch that was deployed"),version:W.string().describe("The version that was deployed"),environment:W.string().describe("The environment deployed to"),services:W.array(W.string()).describe("The services that were deployed"),skipTerraformDeploy:W.boolean().describe("Whether terraform deployment was skipped"),success:W.boolean().describe("Whether the deployment was successful")},handler:Co});import{z as Oe}from"zod";var Po=async()=>{let r=(await b()).flatMap(i=>{let l=y(i.branch);return l?[{version:C(l),jiraKey:D(l),type:R(i.title)}]:[]}),t=await E(),n=Math.max(...r.map(i=>i.version.length)),o=r.map(i=>{let l=Ie(i.version,i.type,n),c=t.get(i.jiraKey);return c?`${l} ${c}`:l});a.info(`All release branches:
32
32
  `),a.info(`
33
- ${n.join(`
33
+ ${o.join(`
34
34
  `)}
35
- `);let s={releases:r.map(i=>({version:i.version,type:i.type,description:t.get(i.jiraKey)||null})),count:r.length};return{content:h(JSON.stringify(s,null,2)),structuredContent:s}},ft=v({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:Po});import Oo from"@inquirer/confirm";import Ao from"@inquirer/select";import Rr from"node:process";import{z as x}from"zod";import{question as bt}from"zx";import{$ as yr}from"zx";var oe=e=>e.slice(1).split(".").map(Number),gt=e=>[...e].sort((r,t)=>{let[o,n,s]=oe(r),[i,l,c]=oe(t);return o!==i?(o??0)-(i??0):n!==l?(n??0)-(l??0):(s??0)-(c??0)});var Eo="next",Os=/^v?(\d+)\.(\d+)\.(\d+)$/,_s=e=>e.replace(/^.*release\//,""),$o=e=>{let r=_s(e.trim()),t=Os.exec(r);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null},To=e=>`${e[0]}.${e[1]}.${e[2]}`,wt=e=>{let r=[...e.remoteBranches??[],...e.jiraVersions??[]],t=[],o=new Set;for(let n of r){let s=$o(n);if(!s)continue;let i=To(s);o.has(i)||(o.add(i),t.push(s))}return gt(t.map(n=>To(n))).map(n=>oe(`v${n}`))},ve=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},kr=(e,r)=>{if(e.length===0)throw new ve;let t=e[e.length-1];if(r==="hotfix"){let[s,i]=t,l=e.reduce((c,p)=>p[0]===s&&p[1]===i?Math.max(c,p[2]):c,0);return`${s}.${i}.${l+1}`}let[o,n]=t;return`${o}.${n+1}.0`},So=e=>e.trim().toLowerCase()===Eo;var Io=e=>"name"in e;var ht=(e,r)=>r!==void 0&&r!==""?{...e,description:r}:e,Fs=e=>{let r=e.name.trim();return le(r),ht({id:{kind:"name",name:r,raw:r},type:e.type},e.description)},vt=(e,r)=>{let t=[...r];return e.map(o=>{if(Io(o))return Fs(o);let n=o.version.trim();if(n==="")throw new Error("Release entry has an empty version");if(So(n)){let l=kr(t,o.type);return t.push(oe(`v${l}`)),ht({id:B(l),type:o.type},o.description)}let s=$o(n);if(!s)throw new Error(`Invalid version "${n}". Expected semver like "1.2.5" or the token "next".`);let i=`${s[0]}.${s[1]}.${s[2]}`;return t.push(s),ht({id:B(i),type:o.type},o.description)})},kt=e=>e.some(r=>!Io(r)&&So(r.version));var Ms=e=>e.split(`
36
- `).map(r=>{let t=r.indexOf(" ");return t===-1?null:y(r.slice(t+1))}).filter(r=>r!==null&&r.kind==="version").map(r=>r.raw),js=async()=>{let e=yr.quiet;try{yr.quiet=!0;let r=await yr`git ls-remote --heads origin 'release/v*'`;return Ms(r.stdout)}finally{yr.quiet=e}},Ds=async()=>{let e=await he();return e?(await Ee(e)).map(t=>t.name):[]},yt=async()=>{let[e,r]=await Promise.allSettled([js(),Ds()]);return e.status==="rejected"&&a.warn({error:e.reason},"Failed to list remote release branches; continuing without them"),r.status==="rejected"&&a.warn({error:r.reason},"Failed to fetch Jira versions; continuing without them"),wt({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:r.status==="fulfilled"?r.value:[]})};var Ls='"1.2.5" or "next"',Ws=(e,r)=>{try{return kr(e,r)}catch(t){if(t instanceof ve)return null;throw t}},Rt=(e,r)=>{try{return vt(e,r)}catch(t){throw t instanceof ve?new f(t,{operation:"resolve release version",remediation:'pass an explicit version (e.g. "1.2.5") instead of "next" when there are no prior versions'}):t instanceof U?new f(t,{operation:"validate release name",remediation:'use a kebab-case name like "checkout-redesign" (lowercase, digits, single hyphens, not a reserved word)'}):t}},Js=async(e,r)=>{let t=Ws(e,r),o=t?` [${t}]`:"",n=(await bt(` Version (e.g. ${Ls})${o}: `)).trim(),s=n===""?t??"":n;return s===""&&(a.error("No version provided. Exiting..."),Rr.exit(1)),s},Vs=async()=>{let e=(await bt(' Name (kebab-case, e.g. "checkout-redesign"): ')).trim();e===""&&(a.error("No name provided. Exiting..."),Rr.exit(1));try{le(e)}catch(r){let t=r instanceof Error?r.message:String(r);a.error(`${t} Exiting...`),Rr.exit(1)}return e},Bs=async e=>{m.setInteractive();let r=null,t=[],o=async()=>(r===null&&(r=await e(),t.push(...r)),t),n=[],s=!0;for(;s;){let i=n.length+1,l=await Ao({message:`Release #${i} \u2014 version or name?`,choices:[{name:"version (semver / next)",value:"version"},{name:"name (free-form)",value:"name"}],default:"version"}),c=await Ao({message:`Release #${i} \u2014 select type:`,choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"}),p;if(l==="name"){let u=await Vs();p=Rt([{name:u,type:c}],[])[0]}else{let u=await Js(await o(),c);p=Rt([{version:u,type:c}],t)[0],p.id.kind==="version"&&t.push(oe(`v${p.id.raw}`))}let d=(await bt(" Description (optional, press Enter to skip): ")).trim();n.push({...p,...d!==""?{description:d}:{}}),s=await Oo({message:"Add another release?",default:!1})}return n},qs=e=>{let t=[e.id.kind==="version"?`v${e.id.raw}`:e.id.name,e.type];return e.description&&t.push(e.description),t.join(" \xB7 ")},No=e=>{for(let r of e){if(r.id.kind==="name"){m.addOption("--name",r.id.name);continue}let t=r.description?`${r.id.raw}:${r.type}:${r.description}`:`${r.id.raw}:${r.type}`;m.addOption("--release",t)}},Us=async(e,r)=>{if(e&&e.length>0){let o=kt(e)?await r():[],n=Rt(e,o);return No(n),n}let t=await Bs(r);return No(t),t},Ks=e=>{if(new Set(e.map(t=>t.type)).size>1)throw new f(void 0,{operation:"create release",remediation:"create regular and hotfix releases in separate invocations",stderrExcerpt:"mixed regular and hotfix releases in one batch are not supported"})},Gs=async(e,r)=>{let t=e.map(qs).join(`
37
- - `),o=r?!0:await Oo({message:`Create the following ${e.length} release(s)?
35
+ `);let s={releases:r.map(i=>({version:i.version,type:i.type,description:t.get(i.jiraKey)||null})),count:r.length};return{content:h(JSON.stringify(s,null,2)),structuredContent:s}},ft=v({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:Po});import Oo from"@inquirer/confirm";import Ao from"@inquirer/select";import br from"node:process";import{z as x}from"zod";import{question as bt}from"zx";import{$ as Rr}from"zx";var oe=e=>e.slice(1).split(".").map(Number),gt=e=>[...e].sort((r,t)=>{let[n,o,s]=oe(r),[i,l,c]=oe(t);return n!==i?(n??0)-(i??0):o!==l?(o??0)-(l??0):(s??0)-(c??0)});var Eo="next",Ns=/^v?(\d+)\.(\d+)\.(\d+)$/,Os=e=>e.replace(/^.*release\//,""),$o=e=>{let r=Os(e.trim()),t=Ns.exec(r);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null},To=e=>`${e[0]}.${e[1]}.${e[2]}`,wt=e=>{let r=[...e.remoteBranches??[],...e.jiraVersions??[]],t=[],n=new Set;for(let o of r){let s=$o(o);if(!s)continue;let i=To(s);n.has(i)||(n.add(i),t.push(s))}return gt(t.map(o=>To(o))).map(o=>oe(`v${o}`))},ve=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},yr=(e,r)=>{if(e.length===0)throw new ve;let t=e[e.length-1];if(r==="hotfix"){let[s,i]=t,l=e.reduce((c,p)=>p[0]===s&&p[1]===i?Math.max(c,p[2]):c,0);return`${s}.${i}.${l+1}`}let[n,o]=t;return`${n}.${o+1}.0`},So=e=>e.trim().toLowerCase()===Eo;var Io=e=>"name"in e;var ht=(e,r)=>r!==void 0&&r!==""?{...e,description:r}:e,_s=e=>{let r=e.name.trim();return le(r),ht({id:{kind:"name",name:r,raw:r},type:e.type},e.description)},vt=(e,r)=>{let t=[...r];return e.map(n=>{if(Io(n))return _s(n);let o=n.version.trim();if(o==="")throw new Error("Release entry has an empty version");if(So(o)){let l=yr(t,n.type);return t.push(oe(`v${l}`)),ht({id:B(l),type:n.type},n.description)}let s=$o(o);if(!s)throw new Error(`Invalid version "${o}". Expected semver like "1.2.5" or the token "next".`);let i=`${s[0]}.${s[1]}.${s[2]}`;return t.push(s),ht({id:B(i),type:n.type},n.description)})},kt=e=>e.some(r=>!Io(r)&&So(r.version));var Fs=e=>e.split(`
36
+ `).map(r=>{let t=r.indexOf(" ");return t===-1?null:y(r.slice(t+1))}).filter(r=>r!==null&&r.kind==="version").map(r=>r.raw),Ms=async()=>{let e=Rr.quiet;try{Rr.quiet=!0;let r=await Rr`git ls-remote --heads origin 'release/v*'`;return Fs(r.stdout)}finally{Rr.quiet=e}},js=async()=>{let e=await he();return e?(await Ee(e)).map(t=>t.name):[]},yt=async()=>{let[e,r]=await Promise.allSettled([Ms(),js()]);return e.status==="rejected"&&a.warn({error:e.reason},"Failed to list remote release branches; continuing without them"),r.status==="rejected"&&a.warn({error:r.reason},"Failed to fetch Jira versions; continuing without them"),wt({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:r.status==="fulfilled"?r.value:[]})};var Ds='"1.2.5" or "next"',Ls=(e,r)=>{try{return yr(e,r)}catch(t){if(t instanceof ve)return null;throw t}},Rt=(e,r)=>{try{return vt(e,r)}catch(t){throw t instanceof ve?new f(t,{operation:"resolve release version",remediation:'pass an explicit version (e.g. "1.2.5") instead of "next" when there are no prior versions'}):t instanceof U?new f(t,{operation:"validate release name",remediation:'use a kebab-case name like "checkout-redesign" (lowercase, digits, single hyphens, not a reserved word)'}):t}},Ws=async(e,r)=>{let t=Ls(e,r),n=t?` [${t}]`:"",o=(await bt(` Version (e.g. ${Ds})${n}: `)).trim(),s=o===""?t??"":o;return s===""&&(a.error("No version provided. Exiting..."),br.exit(1)),s},Js=async()=>{let e=(await bt(' Name (kebab-case, e.g. "checkout-redesign"): ')).trim();e===""&&(a.error("No name provided. Exiting..."),br.exit(1));try{le(e)}catch(r){let t=r instanceof Error?r.message:String(r);a.error(`${t} Exiting...`),br.exit(1)}return e},Vs=async e=>{m.setInteractive();let r=null,t=[],n=async()=>(r===null&&(r=await e(),t.push(...r)),t),o=[],s=!0;for(;s;){let i=o.length+1,l=await Ao({message:`Release #${i} \u2014 version or name?`,choices:[{name:"version (semver / next)",value:"version"},{name:"name (free-form)",value:"name"}],default:"version"}),c=await Ao({message:`Release #${i} \u2014 select type:`,choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"}),p;if(l==="name"){let u=await Js();p=Rt([{name:u,type:c}],[])[0]}else{let u=await Ws(await n(),c);p=Rt([{version:u,type:c}],t)[0],p.id.kind==="version"&&t.push(oe(`v${p.id.raw}`))}let d=(await bt(" Description (optional, press Enter to skip): ")).trim();o.push({...p,...d!==""?{description:d}:{}}),s=await Oo({message:"Add another release?",default:!1})}return o},Bs=e=>{let t=[e.id.kind==="version"?`v${e.id.raw}`:e.id.name,e.type];return e.description&&t.push(e.description),t.join(" \xB7 ")},No=e=>{for(let r of e){if(r.id.kind==="name"){m.addOption("--name",r.id.name);continue}let t=r.description?`${r.id.raw}:${r.type}:${r.description}`:`${r.id.raw}:${r.type}`;m.addOption("--release",t)}},qs=async(e,r)=>{if(e&&e.length>0){let n=kt(e)?await r():[],o=Rt(e,n);return No(o),o}let t=await Vs(r);return No(t),t},Us=e=>{if(new Set(e.map(t=>t.type)).size>1)throw new f(void 0,{operation:"create release",remediation:"create regular and hotfix releases in separate invocations",stderrExcerpt:"mixed regular and hotfix releases in one batch are not supported"})},Ks=async(e,r)=>{let t=e.map(Bs).join(`
37
+ - `),n=r?!0:await Oo({message:`Create the following ${e.length} release(s)?
38
38
  - ${t}
39
- `});r||m.setInteractive(),o||(a.info("Operation cancelled. Exiting..."),Rr.exit(0)),m.addOption("--yes",!0)},zs=async e=>{let{entry:r,jiraConfig:t}=e,o=C(r.id),n=r.id.kind==="version"?`v${r.id.raw}`:r.id.name;try{await nt(r.type);let s=await st({id:r.id,jiraConfig:t,description:r.description,type:r.type});return a.info(`\u2705 Successfully created release: ${n} (${r.type})`),a.info(`\u{1F517} GitHub PR: ${s.prUrl}`),a.info(`\u{1F517} Jira Version: ${s.jiraVersionUrl}
40
- `),{result:s}}catch(s){let i=new f(s,{operation:`create release ${n} (${r.type})`,remediation:"verify the version or name is unique and the base branch is clean"});return a.error(`\u274C ${i.message}
41
- `),{failure:{version:o,error:i.message}}}},Hs=(e,r,t)=>{r===e?a.info(`\u2705 All ${e} release branch(es) were created successfully.`):r>0?(a.warn(`\u26A0\uFE0F ${r} of ${e} release branches were created successfully.`),a.warn(`\u274C ${t} release(s) failed.`)):a.error(`\u274C All ${e} release branch(es) failed to create.`)},_o=async e=>{let{releases:r,confirmedCommand:t}=e;m.start("release-create");let o=await $e(),n=null,i=await Us(r,async()=>(n===null&&(n=await yt()),n));if(i.length===0)throw new f(void 0,{operation:"create release",remediation:'pass at least one entry in "releases" (e.g. [{ version: "1.2.5", type: "regular" }])',stderrExcerpt:"no releases provided"});Ks(i),await M({operation:"create release",requiredBranch:Se(i[0].type)}),await Gs(i,!!t);let l=[],c=[];for(let d of i){let{result:u,failure:g}=await zs({entry:d,jiraConfig:o});u&&l.push(u),g&&c.push(g)}Hs(i.length,l.length,c.length),m.print();let p={createdBranches:l.map(d=>d.branchName),successCount:l.length,failureCount:c.length,releases:l,failedReleases:c};return{content:h(JSON.stringify(p,null,2)),structuredContent:p}},xt=v({name:"release-create",description:'Create one or more releases in a single call. Each entry in "releases" carries EITHER a "version" (semver or the literal token "next") OR a "name" (free-form kebab-case identifier) \u2014 exactly one is required and they are mutually exclusive. Each entry also has its own type (regular|hotfix, default regular) and optional description; all entries in one call must share the same type \u2014 mixed regular+hotfix batches are rejected (create them in separate invocations). For each release this tool switches to the appropriate base branch (dev for regular, main for hotfix), cuts the release branch (release/v<semver> for versions, release/n/<name> for names), opens a GitHub release PR, and creates the matching Jira fix version (v<semver> for versions, <name> for names). 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. Named releases never auto-bump and "next" is version-only. Must be run from the main repository checkout (not a linked worktree) on the matching base branch with a clean working tree. 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:x.array(x.object({version:x.string().optional().describe('Version to create (e.g., "1.2.5") or the literal token "next" for auto-increment. Mutually exclusive with "name".'),name:x.string().optional().describe('Free-form kebab-case release name (e.g., "checkout-redesign"). Mutually exclusive with "version". Named releases never auto-bump.'),type:x.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" (branches off dev) or "hotfix" (branches off main).'),description:x.string().optional().describe("Optional description for the Jira version.")}).refine(e=>e.version===void 0!=(e.name===void 0),{message:'Each release entry must have exactly one of "version" or "name" (they are mutually exclusive).'}).transform(e=>e.name!==void 0?{name:e.name,type:e.type,...e.description?{description:e.description}:{}}:{version:e.version,type:e.type,...e.description?{description:e.description}:{}})).min(1).describe('One or more releases to create. Each entry has exactly one of "version" or "name", plus its own type and optional description.')},outputSchema:{createdBranches:x.array(x.string()).describe("List of created release branch names"),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:_o});import Xs from"@inquirer/confirm";import Ys from"@inquirer/select";import Zs from"node:process";import{z as ne}from"zod";import{question as Qs}from"zx";var Fo=(e,r)=>`${e.baseUrl}/projects/${r.projectId}/versions/${r.id}/tab/release-report-all-issues`,ei=(e,r)=>r.trim()!==""?`${e}
39
+ `});r||m.setInteractive(),n||(a.info("Operation cancelled. Exiting..."),br.exit(0)),m.addOption("--yes",!0)},Gs=async e=>{let{entry:r,jiraConfig:t}=e,n=C(r.id),o=r.id.kind==="version"?`v${r.id.raw}`:r.id.name;try{await nt(r.type);let s=await st({id:r.id,jiraConfig:t,description:r.description,type:r.type});return a.info(`\u2705 Successfully created release: ${o} (${r.type})`),a.info(`\u{1F517} GitHub PR: ${s.prUrl}`),a.info(`\u{1F517} Jira Version: ${s.jiraVersionUrl}
40
+ `),{result:s}}catch(s){let i=new f(s,{operation:`create release ${o} (${r.type})`,remediation:"verify the version or name is unique and the base branch is clean"});return a.error(`\u274C ${i.message}
41
+ `),{failure:{version:n,error:i.message}}}},zs=(e,r,t)=>{r===e?a.info(`\u2705 All ${e} release branch(es) were created successfully.`):r>0?(a.warn(`\u26A0\uFE0F ${r} of ${e} release branches were created successfully.`),a.warn(`\u274C ${t} release(s) failed.`)):a.error(`\u274C All ${e} release branch(es) failed to create.`)},_o=async e=>{let{releases:r,confirmedCommand:t}=e;m.start("release-create");let n=await $e(),o=null,i=await qs(r,async()=>(o===null&&(o=await yt()),o));if(i.length===0)throw new f(void 0,{operation:"create release",remediation:'pass at least one entry in "releases" (e.g. [{ version: "1.2.5", type: "regular" }])',stderrExcerpt:"no releases provided"});Us(i),await M({operation:"create release",requiredBranch:Se(i[0].type)}),await Ks(i,!!t);let l=[],c=[];for(let d of i){let{result:u,failure:g}=await Gs({entry:d,jiraConfig:n});u&&l.push(u),g&&c.push(g)}zs(i.length,l.length,c.length),m.print();let p={createdBranches:l.map(d=>d.branchName),successCount:l.length,failureCount:c.length,releases:l,failedReleases:c};return{content:h(JSON.stringify(p,null,2)),structuredContent:p}},xt=v({name:"release-create",description:'Create one or more releases in a single call. Each entry in "releases" carries EITHER a "version" (semver or the literal token "next") OR a "name" (free-form kebab-case identifier) \u2014 exactly one is required and they are mutually exclusive. Each entry also has its own type (regular|hotfix, default regular) and optional description; all entries in one call must share the same type \u2014 mixed regular+hotfix batches are rejected (create them in separate invocations). For each release this tool switches to the appropriate base branch (dev for regular, main for hotfix), cuts the release branch (release/v<semver> for versions, release/<name> for names), opens a GitHub release PR, and creates the matching Jira fix version (v<semver> for versions, <name> for names). 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. Named releases never auto-bump and "next" is version-only. Must be run from the main repository checkout (not a linked worktree) on the matching base branch with a clean working tree. 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:x.array(x.object({version:x.string().optional().describe('Version to create (e.g., "1.2.5") or the literal token "next" for auto-increment. Mutually exclusive with "name".'),name:x.string().optional().describe('Free-form kebab-case release name (e.g., "checkout-redesign"). Mutually exclusive with "version". Named releases never auto-bump.'),type:x.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" (branches off dev) or "hotfix" (branches off main).'),description:x.string().optional().describe("Optional description for the Jira version.")}).refine(e=>e.version===void 0!=(e.name===void 0),{message:'Each release entry must have exactly one of "version" or "name" (they are mutually exclusive).'}).transform(e=>e.name!==void 0?{name:e.name,type:e.type,...e.description?{description:e.description}:{}}:{version:e.version,type:e.type,...e.description?{description:e.description}:{}})).min(1).describe('One or more releases to create. Each entry has exactly one of "version" or "name", plus its own type and optional description.')},outputSchema:{createdBranches:x.array(x.string()).describe("List of created release branch names"),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:_o});import Hs from"@inquirer/confirm";import Xs from"@inquirer/select";import Ys from"node:process";import{z as ne}from"zod";import{question as Zs}from"zx";var Fo=(e,r)=>`${e.baseUrl}/projects/${r.projectId}/versions/${r.id}/tab/release-report-all-issues`,Qs=(e,r)=>r.trim()!==""?`${e}
42
42
 
43
43
  ${r}`:`${e}
44
- `,ri=async()=>{let e=await b(),r=e.map(s=>s.branch),t=new Map(e.map(s=>[s.branch,R(s.title)])),o=await E(),n=await Ys({message:"\u{1F33F} Select release branch",choices:I({branches:r,descriptions:o,types:t})});return{branch:n,type:t.get(n)||"regular"}},ti=async e=>{let t=(await b()).find(o=>o.branch===e);if(!t)throw new f(void 0,{operation:`edit description for ${e}`,remediation:`confirm an open PR exists for ${e} ('gh pr list')`});return R(t.title)},oi=async e=>{let r=e===""?"(no current description)":`current: "${e}"`,o=(await Qs(` New description ${r}
45
- (press Enter to keep current): `)).replace(/\n$/,"");return o===""?e:o},Mo=async e=>{let{version:r,description:t,confirmedCommand:o}=e;m.start("release-desc-edit");let n=await $e(),s;r?(s=z(r),await ti(s)):(m.setInteractive(),s=(await ri()).branch);let i=y(s);if(!i)throw new f(void 0,{operation:`edit description for ${s}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let l=C(i);m.addOption("--version",l);let c=D(i),p=await ur(c,n);if(!p)throw new f(void 0,{operation:`edit description for ${c}`,remediation:`create the Jira fix version "${c}" first or pick a different release`});let d=p.description??"",u;if(t!==void 0?(u=t,m.addOption("--description",u)):(m.setInteractive(),u=await oi(d)),u===d){a.info(`No change \u2014 description for ${c} is already: "${d}"`),m.print();let N={version:l,branch:s,jiraVersionUrl:Fo(n,p),previousDescription:d,newDescription:u,changed:!1};return{content:h(JSON.stringify(N,null,2)),structuredContent:N}}let g=o?!0:await Xs({message:`Update description for ${c}?
44
+ `,ei=async()=>{let e=await b(),r=e.map(s=>s.branch),t=new Map(e.map(s=>[s.branch,R(s.title)])),n=await E(),o=await Xs({message:"\u{1F33F} Select release branch",choices:I({branches:r,descriptions:n,types:t})});return{branch:o,type:t.get(o)||"regular"}},ri=async e=>{let t=(await b()).find(n=>n.branch===e);if(!t)throw new f(void 0,{operation:`edit description for ${e}`,remediation:`confirm an open PR exists for ${e} ('gh pr list')`});return R(t.title)},ti=async e=>{let r=e===""?"(no current description)":`current: "${e}"`,n=(await Zs(` New description ${r}
45
+ (press Enter to keep current): `)).replace(/\n$/,"");return n===""?e:n},Mo=async e=>{let{version:r,description:t,confirmedCommand:n}=e;m.start("release-desc-edit");let o=await $e(),s;r?(s=z(r),await ri(s)):(m.setInteractive(),s=(await ei()).branch);let i=y(s);if(!i)throw new f(void 0,{operation:`edit description for ${s}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let l=C(i);m.addOption("--version",l);let c=D(i),p=await fr(c,o);if(!p)throw new f(void 0,{operation:`edit description for ${c}`,remediation:`create the Jira fix version "${c}" first or pick a different release`});let d=p.description??"",u;if(t!==void 0?(u=t,m.addOption("--description",u)):(m.setInteractive(),u=await ti(d)),u===d){a.info(`No change \u2014 description for ${c} is already: "${d}"`),m.print();let N={version:l,branch:s,jiraVersionUrl:Fo(o,p),previousDescription:d,newDescription:u,changed:!1};return{content:h(JSON.stringify(N,null,2)),structuredContent:N}}let g=n?!0:await Hs({message:`Update description for ${c}?
46
46
  from: "${d}"
47
47
  to: "${u}"
48
- `});o||m.setInteractive(),g||(a.info("Operation cancelled. Exiting..."),Zs.exit(0)),m.addOption("--yes",!0),await fr({versionId:p.id,description:u},n);let w=Fo(n,p),$=ei(w,u);await vr({branch:s,body:$}),a.info(`\u2705 Updated description for ${c}`),a.info(`\u{1F517} Jira Version: ${w}`),a.info(`\u{1F517} PR branch: ${s}
49
- `),m.print();let S={version:l,branch:s,jiraVersionUrl:w,previousDescription:d,newDescription:u,changed:!0};return{content:h(JSON.stringify(S,null,2)),structuredContent:S}},Ct=v({name:"release-desc-edit",description:"Edit a release's description in Jira and in the matching GitHub release PR body. Accepts a release version or a release name: targets the Jira fix version named `v<version>` (versioned) or `<name>` (named) and the open PR on branch `release/v<version>` or `release/n/<name>`. The PR body is rewritten canonically to `<jiraVersionUrl>\\n\\n<description>` \u2014 any prior manual edits to the body are overwritten. Both `version` and `description` are required for MCP calls (the picker/prompt are unreachable without a TTY). Empty `description` clears the description on both sides. Confirmation is auto-skipped for MCP, so the caller is responsible for gating.",inputSchema:{version:ne.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:ne.string().describe("New description. Empty string clears the description.")},outputSchema:{version:ne.string().describe("Release version"),branch:ne.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/n/checkout-redesign")'),jiraVersionUrl:ne.string().describe("Jira fix version URL"),previousDescription:ne.string().describe("The description before the update"),newDescription:ne.string().describe("The description after the update"),changed:ne.boolean().describe("Whether the description actually changed")},handler:Mo});import{z as si}from"zod";var jo={name:"infra-kit",type:"module",version:"0.1.108",description:"infra-kit",main:"dist/index.js",module:"dist/index.js",types:"dist/entry/index.d.ts",exports:{".":{types:"./dist/entry/index.d.ts",import:"./dist/index.js"}},bin:{"infra-kit":"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",check:"node ./dist/cli.js check","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 silent --ignore-path ../../../.prettierignore","prettier-check":"pnpm exec prettier **/* --check --no-error-on-unmatched-pattern --log-level silent --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=minimal","test-watch":"pnpm exec vitest --watch --silent passed-only","test-ui":"pnpm exec vitest --ui --silent passed-only","test-report":"pnpm exec vitest run --coverage --silent passed-only",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.2.1","@inquirer/confirm":"^6.1.1","@inquirer/select":"^5.2.1","@modelcontextprotocol/sdk":"^1.29.0",commander:"^15.0.0",pino:"^10.3.1","pino-pretty":"^13.1.3",yaml:"^2.9.0",zod:"^4.4.3",zx:"^8.8.5"},devDependencies:{"@wl/eslint-config":"workspace:*","@wl/vitest-config":"workspace:*",esbuild:"^0.28.1",typescript:"^6.0.3"}};var Do=async()=>{let e=jo.version;a.info(e);let r={version:e};return{content:h(JSON.stringify(r,null,2)),structuredContent:r}},Pt=v({name:"version",description:"Print the installed infra-kit CLI version",inputSchema:{},outputSchema:{version:si.string().describe("Installed infra-kit CLI version (from package.json)")},handler:Do});import ai from"@inquirer/checkbox";import Et from"@inquirer/confirm";import ci from"@inquirer/select";import li from"node:process";import{z as se}from"zod";import{$ as ye}from"zx";import Lo from"node:fs/promises";import br from"node:path";var sr=async e=>{let{workspacePath:r,folderPaths:t}=e,o=br.dirname(r),n;try{n=await Lo.readFile(r,"utf-8")}catch(d){throw new Error(`Cursor workspace file not found at ${r}: ${d.message}`)}let s;try{s=JSON.parse(n)}catch(d){throw new Error(`Failed to parse ${r} as JSON. Comments (JSONC) are not supported. ${d.message}`)}let i=s.folders??[],l=new Set(i.map(d=>br.resolve(o,d.path))),c=[],p=[];for(let d of t){let u=br.resolve(d);if(l.has(u)){p.push(d);continue}let g=br.relative(o,u);i.push({path:g}),l.add(u),c.push(d)}return s.folders=i,await Lo.writeFile(r,`${JSON.stringify(s,null,2)}
50
- `,"utf-8"),{added:c,skipped:p}};import ii from"node:fs/promises";import Cr from"node:path";import Wo from"node:fs/promises";import xr from"node:path";var ke=async e=>{let{workspacePath:r,folderPaths:t}=e,o=xr.dirname(r),n;try{n=await Wo.readFile(r,"utf-8")}catch(g){throw new Error(`Cursor workspace file not found at ${r}: ${g.message}`)}let s;try{s=JSON.parse(n)}catch(g){throw new Error(`Failed to parse ${r} as JSON. Comments (JSONC) are not supported. ${g.message}`)}let i=s.folders??[],l=new Set(t.map(g=>xr.resolve(g))),c=new Set,p=i.filter(g=>{let w=xr.resolve(o,g.path);return l.has(w)?(c.add(w),!1):!0});s.folders=p,await Wo.writeFile(r,`${JSON.stringify(s,null,2)}
51
- `,"utf-8");let d=[],u=[];for(let g of t){let w=xr.resolve(g);c.has(w)?d.push(g):u.push(g)}return{removed:d,notFound:u}};var Tt=async e=>{let{workspacePath:r,worktreeDir:t,currentBranches:o}=e,n=Cr.dirname(r),s=Cr.resolve(`${t}/release`),i=await ii.readFile(r,"utf-8"),c=JSON.parse(i).folders??[],p=new Set(o.map($=>Cr.resolve(`${t}/${$}`))),d=[];for(let $ of c){let S=Cr.resolve(n,$.path);(S===s||S.startsWith(`${s}/`))&&!p.has(S)&&d.push(S)}let u=[];d.length>0&&(u=(await ke({workspacePath:r,folderPaths:d})).removed);let g=o.map($=>`${t}/${$}`),{added:w}=g.length>0?await sr({workspacePath:r,folderPaths:g}):{added:[]};return{added:w,removed:u}};import Jo from"node:path";var X=(e,r)=>Jo.isAbsolute(e)?e:Jo.resolve(r,e);var pi="feature",mi="release",Bo=["workspace","windows","none"],qo=async e=>{let{confirmedCommand:r,all:t,versions:o,cursor:n,githubDesktop:s,cmux:i}=e;m.start("worktrees-add"),await M({operation:"create worktrees",requiredBranch:"dev"});try{let l=await _("release"),c=await P(),p=`${c}${J}`;await Vo(`${p}/${mi}`),await Vo(`${p}/${pi}`);let d=[];if(o)d=o.split(",").map(O=>K(B(O.trim())));else{let O=await b(),ae=O.map(Y=>Y.branch);if(ae.length===0)return a.info("\u2139\uFE0F No open release branches found"),m.print(),{content:h(JSON.stringify({createdWorktrees:[],count:0},null,2)),structuredContent:{createdWorktrees:[],count:0}};if(t)d=ae;else{m.setInteractive();let Y=new Map(O.map(ar=>[ar.branch,R(ar.title)])),ce=await E();d=await ai({required:!0,message:"\u{1F33F} Select release branches",choices:I({branches:ae,descriptions:ce,types:Y})})}}t?m.addOption("--all",!0):m.addOption("--versions",we(d));let u=r?!0:await Et({message:"Are you sure you want to proceed with these worktree changes?"});r||m.setInteractive(),u||(a.info("Operation cancelled. Exiting..."),li.exit(0)),r||m.addOption("--yes",!0);let g=await T(),w=g.ide?.provider==="cursor"?g.ide.config:void 0,$=n??w?.mode??await ci({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 n>"u"&&!w?.mode&&m.setInteractive(),m.addOption("--cursor",$);let S=s??g.worktrees?.openInGithubDesktop??await Et({message:"Open created worktrees in GitHub Desktop?"});typeof s>"u"&&g.worktrees?.openInGithubDesktop===void 0&&m.setInteractive(),S?m.addOption("--github-desktop",!0):m.addOption("--no-github-desktop",!0);let N=i??g.worktrees?.openInCmux??await Et({message:"Open created worktrees in cmux?"});typeof i>"u"&&g.worktrees?.openInCmux===void 0&&m.setInteractive(),N?m.addOption("--cmux",!0):m.addOption("--no-cmux",!0);let{branchesToCreate:be}=di({selectedReleaseBranches:d,currentWorktrees:l}),ie=await ui(be,p);if(fi(ie),$==="workspace")if(!w?.workspaceConfigPath)a.warn("\u26A0\uFE0F Skipping Cursor: ide.config.workspaceConfigPath is not set in infra-kit config");else{let O=X(w.workspaceConfigPath,c),ae=ie.map(Zo=>`${p}/${Zo}`),{added:Y,skipped:ce}=await sr({workspacePath:O,folderPaths:ae}),ar=ce.length>0?` (${ce.length} already present)`:"";a.info(`\u2705 Added ${Y.length} folder(s) to ${O}${ar}`),await ye`cursor ${O}`}else if($==="windows")for(let O of ie)await ye`cursor ${p}/${O}`;if(S)for(let O of ie)await ye`github ${p}/${O}`,await ye`sleep 5`;if(N){let O=await F(),ae=await er();for(let Y of ie){let ce=H({repoName:O,branch:Y});ae.has(q(ce))||await tr({cwd:`${p}/${Y}`,title:ce})}}m.print();let Ft={createdWorktrees:ie,count:ie.length};return{content:h(JSON.stringify(Ft,null,2)),structuredContent:Ft}}catch(l){throw a.error({error:l},"\u274C Error managing worktrees"),new f(l,{operation:"create worktrees",remediation:"verify branches don't already exist as worktrees: 'git worktree list'"})}},Vo=async e=>{await ye`mkdir -p ${e}`},di=e=>{let{selectedReleaseBranches:r,currentWorktrees:t}=e,o=t.filter(s=>pe(s));return{branchesToCreate:r.filter(s=>!o.includes(s))}},ui=async(e,r)=>{let t=await Promise.allSettled(e.map(async n=>{let s=`${r}/${n}`;return await ye`git worktree add ${s} ${n}`,await ye({cwd:s})`pnpm install`,n})),o=[];for(let[n,s]of t.entries())if(s.status==="fulfilled")o.push(s.value);else{let i=e[n],l=new f(s.reason,{operation:`git worktree add for ${i}`,remediation:"check the branch name and that the parent dir is writable"});a.error({error:s.reason,msg:l.message})}return o},fi=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")},$t=v({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:se.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:se.string().optional().describe('Comma-separated release versions or names to target (e.g. "1.2.5, 1.2.6" or "checkout-redesign, 1.2.5"). Either "versions" or all=true must be provided for MCP calls. Overrides "all" when set.'),cursor:se.enum(Bo).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:se.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:se.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:se.array(se.string()).describe("List of created git worktree branches"),count:se.number().describe("Number of git worktrees created")},handler:qo});import{z as _e}from"zod";var Uo=async()=>{let e=await _("release");if(e.length===0)return a.info("\u2139\uFE0F No active worktrees found"),{content:h(JSON.stringify({worktrees:[],count:0},null,2)),structuredContent:{worktrees:[],count:0}};let[r,t]=await Promise.all([b(),E()]),o=new Map(r.map(c=>[c.branch,R(c.title)])),n=e.flatMap(c=>{let p=y(c);if(!p)return[];let d=C(p),u=o.get(c)||"regular",g=t.get(D(p))||null;return[{version:d,type:u,description:g}]}),s=Math.max(...n.map(c=>c.version.length)),i=n.map(c=>{let p=Ie(c.version,c.type,s);return c.description?`${p} ${c.description}`:p});a.info("\u{1F33F} Active worktrees:"),a.info(`
48
+ `});n||m.setInteractive(),g||(a.info("Operation cancelled. Exiting..."),Ys.exit(0)),m.addOption("--yes",!0),await gr({versionId:p.id,description:u},o);let w=Fo(o,p),$=Qs(w,u);await kr({branch:s,body:$}),a.info(`\u2705 Updated description for ${c}`),a.info(`\u{1F517} Jira Version: ${w}`),a.info(`\u{1F517} PR branch: ${s}
49
+ `),m.print();let S={version:l,branch:s,jiraVersionUrl:w,previousDescription:d,newDescription:u,changed:!0};return{content:h(JSON.stringify(S,null,2)),structuredContent:S}},Ct=v({name:"release-desc-edit",description:"Edit a release's description in Jira and in the matching GitHub release PR body. Accepts a release version or a release name: targets the Jira fix version named `v<version>` (versioned) or `<name>` (named) and the open PR on branch `release/v<version>` or `release/<name>`. The PR body is rewritten canonically to `<jiraVersionUrl>\\n\\n<description>` \u2014 any prior manual edits to the body are overwritten. Both `version` and `description` are required for MCP calls (the picker/prompt are unreachable without a TTY). Empty `description` clears the description on both sides. Confirmation is auto-skipped for MCP, so the caller is responsible for gating.",inputSchema:{version:ne.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:ne.string().describe("New description. Empty string clears the description.")},outputSchema:{version:ne.string().describe("Release version"),branch:ne.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:ne.string().describe("Jira fix version URL"),previousDescription:ne.string().describe("The description before the update"),newDescription:ne.string().describe("The description after the update"),changed:ne.boolean().describe("Whether the description actually changed")},handler:Mo});import{z as ni}from"zod";var jo={name:"infra-kit",type:"module",version:"0.1.110",description:"infra-kit",main:"dist/index.js",module:"dist/index.js",types:"dist/entry/index.d.ts",exports:{".":{types:"./dist/entry/index.d.ts",import:"./dist/index.js"}},bin:{"infra-kit":"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",check:"node ./dist/cli.js check","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 silent --ignore-path ../../../.prettierignore","prettier-check":"pnpm exec prettier **/* --check --no-error-on-unmatched-pattern --log-level silent --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=minimal","test-watch":"pnpm exec vitest --watch --silent passed-only","test-ui":"pnpm exec vitest --ui --silent passed-only","test-report":"pnpm exec vitest run --coverage --silent passed-only",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.2.1","@inquirer/confirm":"^6.1.1","@inquirer/select":"^5.2.1","@modelcontextprotocol/sdk":"^1.29.0",commander:"^15.0.0",pino:"^10.3.1","pino-pretty":"^13.1.3",yaml:"^2.9.0",zod:"^4.4.3",zx:"^8.8.5"},devDependencies:{"@wl/eslint-config":"workspace:*","@wl/vitest-config":"workspace:*",esbuild:"^0.28.1",typescript:"^6.0.3"}};var Do=async()=>{let e=jo.version;a.info(e);let r={version:e};return{content:h(JSON.stringify(r,null,2)),structuredContent:r}},Pt=v({name:"version",description:"Print the installed infra-kit CLI version",inputSchema:{},outputSchema:{version:ni.string().describe("Installed infra-kit CLI version (from package.json)")},handler:Do});import ii from"@inquirer/checkbox";import Et from"@inquirer/confirm";import ai from"@inquirer/select";import ci from"node:process";import{z as se}from"zod";import{$ as ye}from"zx";import Lo from"node:fs/promises";import xr from"node:path";var sr=async e=>{let{workspacePath:r,folderPaths:t}=e,n=xr.dirname(r),o;try{o=await Lo.readFile(r,"utf-8")}catch(d){throw new Error(`Cursor workspace file not found at ${r}: ${d.message}`)}let s;try{s=JSON.parse(o)}catch(d){throw new Error(`Failed to parse ${r} as JSON. Comments (JSONC) are not supported. ${d.message}`)}let i=s.folders??[],l=new Set(i.map(d=>xr.resolve(n,d.path))),c=[],p=[];for(let d of t){let u=xr.resolve(d);if(l.has(u)){p.push(d);continue}let g=xr.relative(n,u);i.push({path:g}),l.add(u),c.push(d)}return s.folders=i,await Lo.writeFile(r,`${JSON.stringify(s,null,2)}
50
+ `,"utf-8"),{added:c,skipped:p}};import si from"node:fs/promises";import Pr from"node:path";import Wo from"node:fs/promises";import Cr from"node:path";var ke=async e=>{let{workspacePath:r,folderPaths:t}=e,n=Cr.dirname(r),o;try{o=await Wo.readFile(r,"utf-8")}catch(g){throw new Error(`Cursor workspace file not found at ${r}: ${g.message}`)}let s;try{s=JSON.parse(o)}catch(g){throw new Error(`Failed to parse ${r} as JSON. Comments (JSONC) are not supported. ${g.message}`)}let i=s.folders??[],l=new Set(t.map(g=>Cr.resolve(g))),c=new Set,p=i.filter(g=>{let w=Cr.resolve(n,g.path);return l.has(w)?(c.add(w),!1):!0});s.folders=p,await Wo.writeFile(r,`${JSON.stringify(s,null,2)}
51
+ `,"utf-8");let d=[],u=[];for(let g of t){let w=Cr.resolve(g);c.has(w)?d.push(g):u.push(g)}return{removed:d,notFound:u}};var Tt=async e=>{let{workspacePath:r,worktreeDir:t,currentBranches:n}=e,o=Pr.dirname(r),s=Pr.resolve(`${t}/release`),i=await si.readFile(r,"utf-8"),c=JSON.parse(i).folders??[],p=new Set(n.map($=>Pr.resolve(`${t}/${$}`))),d=[];for(let $ of c){let S=Pr.resolve(o,$.path);(S===s||S.startsWith(`${s}/`))&&!p.has(S)&&d.push(S)}let u=[];d.length>0&&(u=(await ke({workspacePath:r,folderPaths:d})).removed);let g=n.map($=>`${t}/${$}`),{added:w}=g.length>0?await sr({workspacePath:r,folderPaths:g}):{added:[]};return{added:w,removed:u}};import Jo from"node:path";var X=(e,r)=>Jo.isAbsolute(e)?e:Jo.resolve(r,e);var li="feature",pi="release",Bo=["workspace","windows","none"],qo=async e=>{let{confirmedCommand:r,all:t,versions:n,cursor:o,githubDesktop:s,cmux:i}=e;m.start("worktrees-add"),await M({operation:"create worktrees",requiredBranch:"dev"});try{let l=await _("release"),c=await P(),p=`${c}${J}`;await Vo(`${p}/${pi}`),await Vo(`${p}/${li}`);let d=[];if(n)d=n.split(",").map(O=>K(B(O.trim())));else{let O=await b(),ae=O.map(Y=>Y.branch);if(ae.length===0)return a.info("\u2139\uFE0F No open release branches found"),m.print(),{content:h(JSON.stringify({createdWorktrees:[],count:0},null,2)),structuredContent:{createdWorktrees:[],count:0}};if(t)d=ae;else{m.setInteractive();let Y=new Map(O.map(ar=>[ar.branch,R(ar.title)])),ce=await E();d=await ii({required:!0,message:"\u{1F33F} Select release branches",choices:I({branches:ae,descriptions:ce,types:Y})})}}t?m.addOption("--all",!0):m.addOption("--versions",we(d));let u=r?!0:await Et({message:"Are you sure you want to proceed with these worktree changes?"});r||m.setInteractive(),u||(a.info("Operation cancelled. Exiting..."),ci.exit(0)),r||m.addOption("--yes",!0);let g=await T(),w=g.ide?.provider==="cursor"?g.ide.config:void 0,$=o??w?.mode??await ai({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"&&!w?.mode&&m.setInteractive(),m.addOption("--cursor",$);let S=s??g.worktrees?.openInGithubDesktop??await Et({message:"Open created worktrees in GitHub Desktop?"});typeof s>"u"&&g.worktrees?.openInGithubDesktop===void 0&&m.setInteractive(),S?m.addOption("--github-desktop",!0):m.addOption("--no-github-desktop",!0);let N=i??g.worktrees?.openInCmux??await Et({message:"Open created worktrees in cmux?"});typeof i>"u"&&g.worktrees?.openInCmux===void 0&&m.setInteractive(),N?m.addOption("--cmux",!0):m.addOption("--no-cmux",!0);let{branchesToCreate:be}=mi({selectedReleaseBranches:d,currentWorktrees:l}),ie=await di(be,p);if(ui(ie),$==="workspace")if(!w?.workspaceConfigPath)a.warn("\u26A0\uFE0F Skipping Cursor: ide.config.workspaceConfigPath is not set in infra-kit config");else{let O=X(w.workspaceConfigPath,c),ae=ie.map(Zo=>`${p}/${Zo}`),{added:Y,skipped:ce}=await sr({workspacePath:O,folderPaths:ae}),ar=ce.length>0?` (${ce.length} already present)`:"";a.info(`\u2705 Added ${Y.length} folder(s) to ${O}${ar}`),await ye`cursor ${O}`}else if($==="windows")for(let O of ie)await ye`cursor ${p}/${O}`;if(S)for(let O of ie)await ye`github ${p}/${O}`,await ye`sleep 5`;if(N){let O=await F(),ae=await er();for(let Y of ie){let ce=H({repoName:O,branch:Y});ae.has(q(ce))||await tr({cwd:`${p}/${Y}`,title:ce})}}m.print();let Ft={createdWorktrees:ie,count:ie.length};return{content:h(JSON.stringify(Ft,null,2)),structuredContent:Ft}}catch(l){throw a.error({error:l},"\u274C Error managing worktrees"),new f(l,{operation:"create worktrees",remediation:"verify branches don't already exist as worktrees: 'git worktree list'"})}},Vo=async e=>{await ye`mkdir -p ${e}`},mi=e=>{let{selectedReleaseBranches:r,currentWorktrees:t}=e,n=t.filter(s=>pe(s));return{branchesToCreate:r.filter(s=>!n.includes(s))}},di=async(e,r)=>{let t=await Promise.allSettled(e.map(async o=>{let s=`${r}/${o}`;return await ye`git worktree add ${s} ${o}`,await ye({cwd:s})`pnpm install`,o})),n=[];for(let[o,s]of t.entries())if(s.status==="fulfilled")n.push(s.value);else{let i=e[o],l=new f(s.reason,{operation:`git worktree add for ${i}`,remediation:"check the branch name and that the parent dir is writable"});a.error({error:s.reason,msg:l.message})}return n},ui=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")},$t=v({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:se.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:se.string().optional().describe('Comma-separated release versions or names to target (e.g. "1.2.5, 1.2.6" or "checkout-redesign, 1.2.5"). Either "versions" or all=true must be provided for MCP calls. Overrides "all" when set.'),cursor:se.enum(Bo).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:se.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:se.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:se.array(se.string()).describe("List of created git worktree branches"),count:se.number().describe("Number of git worktrees created")},handler:qo});import{z as _e}from"zod";var Uo=async()=>{let e=await _("release");if(e.length===0)return a.info("\u2139\uFE0F No active worktrees found"),{content:h(JSON.stringify({worktrees:[],count:0},null,2)),structuredContent:{worktrees:[],count:0}};let[r,t]=await Promise.all([b(),E()]),n=new Map(r.map(c=>[c.branch,R(c.title)])),o=e.flatMap(c=>{let p=y(c);if(!p)return[];let d=C(p),u=n.get(c)||"regular",g=t.get(D(p))||null;return[{version:d,type:u,description:g}]}),s=Math.max(...o.map(c=>c.version.length)),i=o.map(c=>{let p=Ie(c.version,c.type,s);return c.description?`${p} ${c.description}`:p});a.info("\u{1F33F} Active worktrees:"),a.info(`
52
52
  ${i.join(`
53
53
  `)}
54
- `);let l={worktrees:n,count:n.length};return{content:h(JSON.stringify(l,null,2)),structuredContent:l}},St=v({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:_e.array(_e.object({version:_e.string().describe("Release version"),type:_e.enum(["regular","hotfix"]).describe("Release type"),description:_e.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:_e.number().describe("Number of worktrees")},handler:Uo});import{z as Fe}from"zod";import{$ as gi}from"zx";var Ko=async()=>{m.start("worktrees-open");try{let e=await P(),r=`${e}${J}`,t=await _("release"),o=await hi({projectRoot:e,worktreeDir:r,currentBranches:t}),n=await wi({worktreeDir:r,currentBranches:t}),s={openedCmux:n.opened,skippedCmux:n.skipped,cursorFoldersAdded:o.added,cursorFoldersRemoved:o.removed};return vi(s,{cursorRan:o.ran,cmuxRan:n.ran}),m.print(),{content:h(JSON.stringify(s,null,2)),structuredContent:{...s}}}catch(e){throw a.error({error:e},"\u274C Error opening worktrees"),new f(e,{operation:"open worktrees",remediation:"run 'worktrees-list' to confirm the branches exist"})}},hi=async e=>{let{projectRoot:r,worktreeDir:t,currentBranches:o}=e,n=await T(),s=n.ide?.provider==="cursor"?n.ide.config:void 0;if(!s||s.mode!=="workspace"||!s.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=X(s.workspaceConfigPath,r);try{let{added:l,removed:c}=await Tt({workspacePath:i,worktreeDir:t,currentBranches:o});return await gi`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}}},wi=async e=>{let{worktreeDir:r,currentBranches:t}=e;if(t.length===0)return{ran:!0,opened:[],skipped:[]};let o=await F(),n=await er(),s=[],i=[];for(let l of t){let c=H({repoName:o,branch:l});if(n.has(q(c))){i.push(c);continue}try{await tr({cwd:`${r}/${l}`,title:c}),s.push(c)}catch(p){a.warn({error:p,title:c},`\u26A0\uFE0F Failed to open cmux workspace for ${l}`)}}return{ran:!0,opened:s,skipped:i}},vi=(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")},It=v({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:Fe.array(Fe.string()).describe("Titles of cmux workspaces opened during this run"),skippedCmux:Fe.array(Fe.string()).describe("Titles of cmux workspaces that were already open"),cursorFoldersAdded:Fe.number().describe("Number of worktree folders added to the Cursor workspace file"),cursorFoldersRemoved:Fe.number().describe("Number of dangling worktree folders removed from the Cursor workspace file")},handler:Ko});import ki from"@inquirer/checkbox";import yi from"@inquirer/confirm";import Ri from"node:process";import{z as ir}from"zod";var Go=async e=>{let{confirmedCommand:r,all:t,versions:o}=e;m.start("worktrees-remove"),await M({operation:"remove worktrees",requiredBranch:"dev"});try{let n=await _("release");if(n.length===0)return a.info("\u2139\uFE0F No active worktrees to remove"),m.print(),{content:h(JSON.stringify({removedWorktrees:[],count:0},null,2)),structuredContent:{removedWorktrees:[],count:0}};let s=await P(),i=`${s}${J}`,l=[];if(t)l=n;else if(o)l=o.split(",").map(w=>K(B(w.trim())));else{m.setInteractive();let[w,$]=await Promise.all([E(),b()]),S=new Map($.map(N=>[N.branch,R(N.title)]));l=await ki({required:!0,message:"\u{1F33F} Select release branches",choices:I({branches:n,descriptions:w,types:S})})}let c=l.length===n.length;c?m.addOption("--all",!0):m.addOption("--versions",we(l));let p=r?!0:await yi({message:"Are you sure you want to proceed with these worktree changes?"});r||m.setInteractive(),p||(a.info("Operation cancelled. Exiting..."),Ri.exit(0)),r||m.addOption("--yes",!0);let d=await F(),u=await or({branches:l,worktreeDir:i,repoName:d,pruneFolder:c});await bi({removedWorktrees:u,worktreeDir:i,projectRoot:s}),xi(u),m.print();let g={removedWorktrees:u,count:u.length};return{content:h(JSON.stringify(g,null,2)),structuredContent:g}}catch(n){throw a.error({error:n},"\u274C Error managing worktrees"),new f(n,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"})}},bi=async e=>{let{removedWorktrees:r,worktreeDir:t,projectRoot:o}=e;if(r.length===0)return;let n=await T(),s=n.ide?.provider==="cursor"?n.ide.config:void 0;if(!s||s.mode!=="workspace"||!s.workspaceConfigPath)return;let i=X(s.workspaceConfigPath,o),l=r.map(c=>`${t}/${c}`);try{let{removed:c}=await ke({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}`)}},xi=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")},At=v({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:ir.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:ir.string().optional().describe('Comma-separated release versions or names to target (e.g. "1.2.5, 1.2.6" or "checkout-redesign, 1.2.5"). Either "versions" or all=true must be provided for MCP calls. Overrides "all" when set.')},outputSchema:{removedWorktrees:ir.array(ir.string()).describe("List of removed git worktree branches"),count:ir.number().describe("Number of git worktrees removed")},handler:Go});import Ci from"@inquirer/confirm";import Pi from"node:process";import{z as Nt}from"zod";import{$ as Ti}from"zx";var zo=async e=>{let{confirmedCommand:r}=e;m.start("worktrees-sync"),await M({operation:"sync worktrees",requiredBranch:"dev"});try{let t=await _("release"),o=await P(),n=`${o}${J}`,s=await wr(),i=r?!0:await Ci({message:"Are you sure you want to proceed with these worktree changes?"});r||m.setInteractive(),i||(a.info("Operation cancelled. Exiting..."),Pi.exit(0)),r||m.addOption("--yes",!0);let{branchesToRemove:l}=Ei({releasePRsList:s,currentWorktrees:t}),c=await F(),p=await $i({branches:l,worktreeDir:n,repoName:c});await Si({removedWorktrees:p,worktreeDir:n,projectRoot:o}),Ii(p),m.print();let d={removedWorktrees:p,count:p.length};return{content:h(JSON.stringify(d,null,2)),structuredContent:d}}catch(t){throw a.error({error:t},"\u274C Error managing worktrees"),new f(t,{operation:"sync worktrees with remote",remediation:"ensure 'gh auth status' is ok and you can reach origin"})}},Ei=e=>{let{releasePRsList:r,currentWorktrees:t}=e;return{branchesToRemove:t.filter(s=>pe(s)).filter(s=>!r.includes(s))}},$i=async e=>{let{branches:r,worktreeDir:t,repoName:o}=e,n=[];for(let s of r)try{let i=`${t}/${s}`,l=H({repoName:o,branch:s});await Qe(l),await Ti`git worktree remove ${i}`,n.push(s)}catch(i){let l=new f(i,{operation:`remove stale worktree for ${s}`,remediation:"inspect the worktree dir manually; rerun with the branch checked out elsewhere"});a.error({error:i,branch:s,msg:l.message})}return n},Si=async e=>{let{removedWorktrees:r,worktreeDir:t,projectRoot:o}=e;if(r.length===0)return;let n=await T(),s=n.ide?.provider==="cursor"?n.ide.config:void 0;if(!s||s.mode!=="workspace"||!s.workspaceConfigPath)return;let i=X(s.workspaceConfigPath,o),l=r.map(c=>`${t}/${c}`);try{let{removed:c}=await ke({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}`)}},Ii=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")},Ot=v({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:Nt.array(Nt.string()).describe("List of removed worktree branches"),count:Nt.number().describe("Number of worktrees removed during sync")},handler:zo});var _t=e=>async r=>{let{toolName:t,handler:o}=e;a.info({msg:`Tool execution started: ${t}`,params:r});try{let n=await o({...r,confirmedCommand:!0});return a.info({msg:`Tool execution successful: ${t}`}),n}catch(n){throw a.error({err:n,params:r,msg:`Tool execution failed: ${t}`}),n}};var Ai=[rt,Zr,et,Gr,it,xt,Ct,lt,mt,ut,ft,Vr,Pt,$t,St,It,At,Ot],Ho=async e=>{for(let r of Ai)e.registerTool(r.name,{description:r.description,inputSchema:r.inputSchema,outputSchema:r.outputSchema},_t({toolName:r.name,handler:r.handler}))};async function Xo(){let e=new Ni({name:"infra-kit",version:"1.0.0"},{capabilities:{resources:{},tools:{},prompts:{}}});return await Lt(e),await Wt(e),await Ho(e),e}var Re=jt(),_i=async()=>{let e;try{e=await Xo(),Re.info("MCP Server instance created")}catch(r){Re.error({err:r,msg:"Failed to create MCP server"}),Re.error("Fatal error during server creation."),Yo.exit(1)}try{let r=new Oi;await e.connect(r),Re.info({msg:"Server connected to transport. Ready."})}catch(r){Re.error({err:r,msg:"Failed to initialize server"}),Re.error("Fatal error during server transport init."),Yo.exit(1)}};Dt(Re);_i();
54
+ `);let l={worktrees:o,count:o.length};return{content:h(JSON.stringify(l,null,2)),structuredContent:l}},St=v({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:_e.array(_e.object({version:_e.string().describe("Release version"),type:_e.enum(["regular","hotfix"]).describe("Release type"),description:_e.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:_e.number().describe("Number of worktrees")},handler:Uo});import{z as Fe}from"zod";import{$ as fi}from"zx";var Ko=async()=>{m.start("worktrees-open");try{let e=await P(),r=`${e}${J}`,t=await _("release"),n=await gi({projectRoot:e,worktreeDir:r,currentBranches:t}),o=await hi({worktreeDir:r,currentBranches:t}),s={openedCmux:o.opened,skippedCmux:o.skipped,cursorFoldersAdded:n.added,cursorFoldersRemoved:n.removed};return wi(s,{cursorRan:n.ran,cmuxRan:o.ran}),m.print(),{content:h(JSON.stringify(s,null,2)),structuredContent:{...s}}}catch(e){throw a.error({error:e},"\u274C Error opening worktrees"),new f(e,{operation:"open worktrees",remediation:"run 'worktrees-list' to confirm the branches exist"})}},gi=async e=>{let{projectRoot:r,worktreeDir:t,currentBranches:n}=e,o=await T(),s=o.ide?.provider==="cursor"?o.ide.config:void 0;if(!s||s.mode!=="workspace"||!s.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=X(s.workspaceConfigPath,r);try{let{added:l,removed:c}=await Tt({workspacePath:i,worktreeDir:t,currentBranches:n});return await fi`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}}},hi=async e=>{let{worktreeDir:r,currentBranches:t}=e;if(t.length===0)return{ran:!0,opened:[],skipped:[]};let n=await F(),o=await er(),s=[],i=[];for(let l of t){let c=H({repoName:n,branch:l});if(o.has(q(c))){i.push(c);continue}try{await tr({cwd:`${r}/${l}`,title:c}),s.push(c)}catch(p){a.warn({error:p,title:c},`\u26A0\uFE0F Failed to open cmux workspace for ${l}`)}}return{ran:!0,opened:s,skipped:i}},wi=(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")},It=v({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:Fe.array(Fe.string()).describe("Titles of cmux workspaces opened during this run"),skippedCmux:Fe.array(Fe.string()).describe("Titles of cmux workspaces that were already open"),cursorFoldersAdded:Fe.number().describe("Number of worktree folders added to the Cursor workspace file"),cursorFoldersRemoved:Fe.number().describe("Number of dangling worktree folders removed from the Cursor workspace file")},handler:Ko});import vi from"@inquirer/checkbox";import ki from"@inquirer/confirm";import yi from"node:process";import{z as ir}from"zod";var Go=async e=>{let{confirmedCommand:r,all:t,versions:n}=e;m.start("worktrees-remove"),await M({operation:"remove worktrees",requiredBranch:"dev"});try{let o=await _("release");if(o.length===0)return a.info("\u2139\uFE0F No active worktrees to remove"),m.print(),{content:h(JSON.stringify({removedWorktrees:[],count:0},null,2)),structuredContent:{removedWorktrees:[],count:0}};let s=await P(),i=`${s}${J}`,l=[];if(t)l=o;else if(n)l=n.split(",").map(w=>K(B(w.trim())));else{m.setInteractive();let[w,$]=await Promise.all([E(),b()]),S=new Map($.map(N=>[N.branch,R(N.title)]));l=await vi({required:!0,message:"\u{1F33F} Select release branches",choices:I({branches:o,descriptions:w,types:S})})}let c=l.length===o.length;c?m.addOption("--all",!0):m.addOption("--versions",we(l));let p=r?!0:await ki({message:"Are you sure you want to proceed with these worktree changes?"});r||m.setInteractive(),p||(a.info("Operation cancelled. Exiting..."),yi.exit(0)),r||m.addOption("--yes",!0);let d=await F(),u=await or({branches:l,worktreeDir:i,repoName:d,pruneFolder:c});await Ri({removedWorktrees:u,worktreeDir:i,projectRoot:s}),bi(u),m.print();let g={removedWorktrees:u,count:u.length};return{content:h(JSON.stringify(g,null,2)),structuredContent:g}}catch(o){throw a.error({error:o},"\u274C Error managing worktrees"),new f(o,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"})}},Ri=async e=>{let{removedWorktrees:r,worktreeDir:t,projectRoot:n}=e;if(r.length===0)return;let o=await T(),s=o.ide?.provider==="cursor"?o.ide.config:void 0;if(!s||s.mode!=="workspace"||!s.workspaceConfigPath)return;let i=X(s.workspaceConfigPath,n),l=r.map(c=>`${t}/${c}`);try{let{removed:c}=await ke({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}`)}},bi=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")},At=v({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:ir.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:ir.string().optional().describe('Comma-separated release versions or names to target (e.g. "1.2.5, 1.2.6" or "checkout-redesign, 1.2.5"). Either "versions" or all=true must be provided for MCP calls. Overrides "all" when set.')},outputSchema:{removedWorktrees:ir.array(ir.string()).describe("List of removed git worktree branches"),count:ir.number().describe("Number of git worktrees removed")},handler:Go});import xi from"@inquirer/confirm";import Ci from"node:process";import{z as Nt}from"zod";import{$ as Pi}from"zx";var zo=async e=>{let{confirmedCommand:r}=e;m.start("worktrees-sync"),await M({operation:"sync worktrees",requiredBranch:"dev"});try{let t=await _("release"),n=await P(),o=`${n}${J}`,s=await vr(),i=r?!0:await xi({message:"Are you sure you want to proceed with these worktree changes?"});r||m.setInteractive(),i||(a.info("Operation cancelled. Exiting..."),Ci.exit(0)),r||m.addOption("--yes",!0);let{branchesToRemove:l}=Ti({releasePRsList:s,currentWorktrees:t}),c=await F(),p=await Ei({branches:l,worktreeDir:o,repoName:c});await $i({removedWorktrees:p,worktreeDir:o,projectRoot:n}),Si(p),m.print();let d={removedWorktrees:p,count:p.length};return{content:h(JSON.stringify(d,null,2)),structuredContent:d}}catch(t){throw a.error({error:t},"\u274C Error managing worktrees"),new f(t,{operation:"sync worktrees with remote",remediation:"ensure 'gh auth status' is ok and you can reach origin"})}},Ti=e=>{let{releasePRsList:r,currentWorktrees:t}=e;return{branchesToRemove:t.filter(s=>pe(s)).filter(s=>!r.includes(s))}},Ei=async e=>{let{branches:r,worktreeDir:t,repoName:n}=e,o=[];for(let s of r)try{let i=`${t}/${s}`,l=H({repoName:n,branch:s});await Qe(l),await Pi`git worktree remove ${i}`,o.push(s)}catch(i){let l=new f(i,{operation:`remove stale worktree for ${s}`,remediation:"inspect the worktree dir manually; rerun with the branch checked out elsewhere"});a.error({error:i,branch:s,msg:l.message})}return o},$i=async e=>{let{removedWorktrees:r,worktreeDir:t,projectRoot:n}=e;if(r.length===0)return;let o=await T(),s=o.ide?.provider==="cursor"?o.ide.config:void 0;if(!s||s.mode!=="workspace"||!s.workspaceConfigPath)return;let i=X(s.workspaceConfigPath,n),l=r.map(c=>`${t}/${c}`);try{let{removed:c}=await ke({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}`)}},Si=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")},Ot=v({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:Nt.array(Nt.string()).describe("List of removed worktree branches"),count:Nt.number().describe("Number of worktrees removed during sync")},handler:zo});var _t=e=>async r=>{let{toolName:t,handler:n}=e;a.info({msg:`Tool execution started: ${t}`,params:r});try{let o=await n({...r,confirmedCommand:!0});return a.info({msg:`Tool execution successful: ${t}`}),o}catch(o){throw a.error({err:o,params:r,msg:`Tool execution failed: ${t}`}),o}};var Ii=[rt,Zr,et,Gr,it,xt,Ct,lt,mt,ut,ft,Vr,Pt,$t,St,It,At,Ot],Ho=async e=>{for(let r of Ii)e.registerTool(r.name,{description:r.description,inputSchema:r.inputSchema,outputSchema:r.outputSchema},_t({toolName:r.name,handler:r.handler}))};async function Xo(){let e=new Ai({name:"infra-kit",version:"1.0.0"},{capabilities:{resources:{},tools:{},prompts:{}}});return await Lt(e),await Wt(e),await Ho(e),e}var Re=jt(),Oi=async()=>{let e;try{e=await Xo(),Re.info("MCP Server instance created")}catch(r){Re.error({err:r,msg:"Failed to create MCP server"}),Re.error("Fatal error during server creation."),Yo.exit(1)}try{let r=new Ni;await e.connect(r),Re.info({msg:"Server connected to transport. Ready."})}catch(r){Re.error({err:r,msg:"Failed to initialize server"}),Re.error("Fatal error during server transport init."),Yo.exit(1)}};Dt(Re);Oi();
55
55
  //# sourceMappingURL=mcp.js.map