infra-kit 0.1.107 → 0.1.108

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