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