infra-kit 0.1.110 → 0.1.113

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