infra-kit 0.1.108 → 0.1.109
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/sessions/3a844fbd-ace8-4af1-8516-33d611839886/pre-tool-advisory-throttle.json +18 -0
- package/.turbo/turbo-build.log +6 -7
- package/.turbo/turbo-eslint-check.log +1 -2
- package/.turbo/turbo-prettier-check.log +1 -2
- package/.turbo/turbo-test.log +70 -72
- package/.turbo/turbo-ts-check.log +1 -2
- package/dist/cli.js +50 -50
- package/dist/cli.js.map +4 -4
- package/dist/mcp.js +36 -36
- package/dist/mcp.js.map +4 -4
- package/package.json +1 -1
- package/src/commands/gh-merge-dev/gh-merge-dev.ts +3 -0
- package/src/commands/gh-release-deliver/gh-release-deliver.ts +5 -0
- package/src/commands/release-create/__tests__/release-create.test.ts +38 -1
- package/src/commands/release-create/release-create.ts +36 -4
- package/src/commands/worktrees-add/worktrees-add.ts +3 -0
- package/src/commands/worktrees-remove/worktrees-remove.ts +3 -0
- package/src/commands/worktrees-sync/worktrees-sync.ts +3 -0
- package/src/lib/git-guard/__tests__/git-guard.test.ts +92 -0
- package/src/lib/git-guard/git-guard.ts +55 -0
- package/src/lib/git-guard/index.ts +2 -0
- package/src/lib/git-utils/__tests__/git-primitives.test.ts +96 -0
- package/src/lib/git-utils/git-utils.ts +41 -0
- package/src/lib/git-utils/index.ts +8 -1
- package/tsconfig.tsbuildinfo +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import
|
|
2
|
-
`).filter(Boolean),o={release:
|
|
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}`)}},
|
|
4
|
-
${o?"\u2705 All valid":"\u274C Audit failed"} (${t.length} checked)`);let n={allPassed:o,packages:t.map(s=>({name:s.packageName,passed:s.passed,checks:s.checks}))};return{content:h(JSON.stringify(n,null,2)),structuredContent:n}},
|
|
1
|
+
import Ua,{Separator as Xe}from"@inquirer/select";import{Command as za}from"commander";import ht from"node:process";import Qe from"node:path";import Vn from"node:process";import{z as W}from"zod";import bo from"node:path";import{$ as _e}from"zx";var vn=/^v?(\d+)\.(\d+)\.(\d+)$/,kn=/^(\d+)\.(\d+)\.(\d+)$/,yn=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Rn="release/",wt="release/v",vt="release/n/",wo="refs/heads/",bn="next";var vo=new Set(["dev","main","next","hotfix","regular","release"]),z=class extends Error{constructor(r){super(r),this.name="InvalidReleaseNameError"}},Ae=class extends Error{constructor(r){super(r),this.name="InvalidReleaseRefError"}},yo=e=>e.startsWith(wo)?e.slice(wo.length):e,Ro=(e,r,t)=>({kind:"version",semver:{major:e,minor:r,patch:t},raw:`${e}.${r}.${t}`}),fe=e=>{if(e.length===0)throw new z('Release name is empty. Provide a kebab-case name like "checkout-redesign".');if(e.length>50)throw new z(`Release name "${e}" is ${e.length} characters; the maximum is 50.`);if(!yn.test(e))throw new z(`Release name "${e}" is not kebab-case. Use lowercase letters, digits, and single hyphens, e.g. "checkout-redesign".`);if(vo.has(e))throw new z(`Release name "${e}" is reserved. Reserved names: ${[...vo].join(", ")}.`)},b=e=>{let r=yo(e.trim());if(r.startsWith(wt)){let t=r.slice(wt.length),o=kn.exec(t);return o?Ro(Number(o[1]),Number(o[2]),Number(o[3])):null}if(r.startsWith(vt)){let t=r.slice(vt.length);try{fe(t)}catch{return null}return{kind:"name",name:t,raw:t}}return null},G=e=>{let r=e.trim();if(yo(r).startsWith(Rn)){let n=b(r);if(!n)throw new Ae(`"${e}" looks like a release branch but is not a valid release/v<semver> or release/n/<name> ref.`);return n}let o=vn.exec(r);if(o)return Ro(Number(o[1]),Number(o[2]),Number(o[3]));if(r.toLowerCase()===bn)throw new Ae('The "next" token must be resolved to a concrete version (via computeNextVersion) before parsing a release ref.');try{fe(r)}catch(n){let s=n instanceof Error?n.message:String(n);throw new Ae(`Cannot parse "${e}" as a release ref: ${s}`)}return{kind:"name",name:r,raw:r}},H=e=>e.kind==="version"?`${wt}${e.raw}`:`${vt}${e.name}`,kt=(e,r)=>{let t=r==="hotfix"?"Hotfix":"Release";return e.kind==="version"?`${t} v${e.raw}`:`${t} ${e.name}`},Ir=e=>e.kind==="version"?`Release v${e.raw} (RC)`:`Release ${e.name} (RC)`,L=e=>e.kind==="version"?`v${e.raw}`:e.name,T=e=>e.raw,ge=e=>e==null?!1:b(e)!==null,ko=e=>{if(e===void 0)return null;let r=e instanceof Date?e.getTime():new Date(e).getTime();return Number.isNaN(r)?null:r},yt=(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=ko(t?.a),n=ko(t?.b);return o!==null&&n!==null&&o!==n?o-n:e.name<r.name?-1:e.name>r.name?1:0};var j=async e=>{let t=(await _e`git worktree list`).stdout.split(`
|
|
2
|
+
`).filter(Boolean),o={release:xn,feature:Cn};return t.map(o[e]).filter(n=>n!==null)},xo=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},xn=e=>{let r=xo(e);return ge(r)?r:null},Cn=e=>{let r=xo(e);return r?.startsWith("feature/")?r:null},R=async()=>(await _e`git rev-parse --show-toplevel`).stdout.trim(),Rt=async()=>(await _e`git rev-parse --abbrev-ref HEAD`).stdout.trim(),bt=async()=>(await _e`git status --porcelain`).stdout.trim().length===0,xt=async()=>{let e=await R(),[r,t]=await Promise.all([_e({cwd:e})`git rev-parse --absolute-git-dir`,_e({cwd:e})`git rev-parse --git-common-dir`]),o=r.stdout.trim(),n=bo.resolve(e,t.stdout.trim());return o!==n},F=async()=>{let e=await R();return bo.basename(e)};import En from"node:process";import Pn from"pino";import Tn from"pino-pretty";var $n=()=>{let e=En.argv.includes("--debug")?"debug":"info",r=["time","pid","hostname"];return e==="debug"&&r.push("level"),Pn({level:e},Tn({destination:2,ignore:r.join(","),colorize:!0}))},a=$n();var re={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},Ct={requiredScripts:["build","dev","test","qa","check","fix"],requiredFiles:["turbo.json","pnpm-workspace.yaml"],turboTasks:["build","test","ts-check","eslint-check","prettier-check","check"]},Et=(e,r=re)=>({requiredScripts:e.requiredScripts??[...r.requiredScripts],requiredFiles:e.requiredFiles??[...r.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...r.turboTasks]});import{z as te}from"zod";var Pt=te.strictObject({requiredScripts:te.array(te.string().min(1)).optional(),requiredFiles:te.array(te.string().min(1)).optional(),turbo:te.strictObject({requiredTasks:te.array(te.string().min(1)).optional()}).optional()});import Sn from"node:fs/promises";var X=async e=>{try{return await Sn.access(e),!0}catch{return!1}};import Bn from"node:path";import Co from"node:fs/promises";import Eo from"node:path";import{pathToFileURL as In}from"node:url";import{z as An}from"zod";var oe="infra-kit.config.ts",Tt=async e=>{try{let r=await Co.readFile(Eo.join(e,"package.json"),"utf-8");return JSON.parse(r)}catch{return{}}},Ye=async(e,r=re)=>{let t=Eo.join(e,oe);if(!await X(t))throw new Error(`${oe} not found at ${t}`);let o=await Co.stat(t),i=(await import(`${In(t).href}?mtime=${Number(o.mtimeMs)}`)).default;if(i===void 0)throw new Error(`${oe} at ${t} has no default export`);let l=typeof i=="function"?await i():i,c=Pt.safeParse(l);if(!c.success)throw new Error(`Invalid ${oe} at ${t}: ${An.prettifyError(c.error)}`);return Et(c.data,r)};import Po from"node:fs/promises";import Ar from"node:path";import _n from"yaml";var Nn="pnpm-workspace.yaml",On=async e=>(await Po.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(t=>t.isDirectory()).map(t=>Ar.join(e,t.name)),jn=async(e,r)=>{let t=[];for(let o of e){if(r==="*"){t.push(...await On(o));continue}let n=Ar.join(o,r);await X(n)&&t.push(n)}return t},Fn=async(e,r)=>{let t=[e];for(let o of r.split("/"))t=await jn(t,o);return t},Ze=async e=>{let r=await Po.readFile(Ar.join(e,Nn),"utf-8"),o=((_n.parse(r)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),n=new Set;for(let s of o){let i=await Fn(e,s);for(let l of i)await X(Ar.join(l,"package.json"))&&n.add(l)}return[...n].sort()};var $t=async(e,r=re)=>{try{let t=await Ye(e,r);return{check:{name:oe,status:"pass",message:"present and valid"},rules:t}}catch(t){return{check:{name:oe,status:"fail",message:t.message},rules:null}}};import Mn from"node:fs/promises";import Dn from"node:path";var St=async(e,r)=>Promise.all(r.map(async t=>{let o=await Mn.stat(Dn.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 It=(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 Ln from"node:fs/promises";import Wn from"node:path";var Ne="turbo.json",At=async(e,r)=>{if(r.length===0)return[];let t;try{let n=await Ln.readFile(Wn.join(e,Ne),"utf-8");t=JSON.parse(n)}catch(n){return[{name:Ne,status:"fail",message:`cannot read/parse ${Ne}: ${n.message}`}]}let o=t.tasks;return o===null||typeof o!="object"?[{name:Ne,status:"fail",message:`no "tasks" object defined in ${Ne}`}]:r.map(n=>{let s=n in o||`//#${n}`in o;return{name:`turbo:${n}`,status:s?"pass":"fail",message:s?"defined":`missing turbo task "${n}" in ${Ne}`}})};var _t=async(e,r=re)=>{let t=await Tt(e),o=t.name??Bn.basename(e),{check:n,rules:s}=await $t(e,r),i=[n];s&&(i.push(...It(t.scripts??{},s.requiredScripts)),i.push(...await St(e,s.requiredFiles)),i.push(...await At(e,s.turboTasks)));let l=i.every(c=>c.status==="pass");return{packageDir:e,packageName:o,checks:i,passed:l}};var h=e=>[{type:"text",text:e}],v=e=>e;var Jn=async e=>{let r=Qe.resolve(e);for(;r!==Qe.dirname(r);){if(await X(Qe.join(r,"package.json")))return r;r=Qe.dirname(r)}if(await X(Qe.join(r,"package.json")))return r;throw new Error(`No package.json found in or above ${e}`)},Kn=async e=>e.root?[{dir:await R(),baseline:Ct}]:e.all?(await Ze(await R())).map(t=>({dir:t})):[{dir:await Jn(e.cwd??Vn.cwd())}],qn=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}`)}},_r=async(e={})=>{let r=await Kn(e),t=[];for(let s of r)t.push(await _t(s.dir,s.baseline));for(let s of t)qn(s);let o=t.every(s=>s.passed);a.info(`
|
|
4
|
+
${o?"\u2705 All valid":"\u274C Audit failed"} (${t.length} checked)`);let n={allPassed:o,packages:t.map(s=>({name:s.packageName,passed:s.passed,checks:s.checks}))};return{content:h(JSON.stringify(n,null,2)),structuredContent:n}},Gn={all:W.boolean().optional().describe("Audit every non-vendor workspace package"),root:W.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},Un={allPassed:W.boolean().describe("Whether every audited package passed all checks"),packages:W.array(W.object({name:W.string(),passed:W.boolean(),checks:W.array(W.object({name:W.string(),status:W.enum(["pass","fail"]),message:W.string()}))})).describe("Per-package check results")},zn=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:Gn,outputSchema:Un,handler:e=>_r({all:e.all,root:e.root})});import Or from"node:fs/promises";import ps from"node:os";import ms from"node:path";import $o from"node:process";import{$ as ds}from"zx";import Ot from"node:fs/promises";import Hn from"node:os";import Nr from"node:path";import{z as k}from"zod";var To="infra-kit.json",Xn=".infra-kit",Yn="config.json",Zn="projects",Qn=k.object({provider:k.literal("doppler"),config:k.object({name:k.string().min(1)})}),es=k.discriminatedUnion("provider",[Qn]),rs=k.object({mode:k.enum(["workspace","windows"]).default("workspace"),workspaceConfigPath:k.string().min(1).optional()}).refine(e=>e.mode!=="workspace"||!!e.workspaceConfigPath,{message:'workspaceConfigPath is required when mode is "workspace"',path:["workspaceConfigPath"]}),ts=k.object({provider:k.literal("cursor"),config:rs}),os=k.discriminatedUnion("provider",[ts]),ns=k.object({provider:k.literal("jira"),config:k.object({baseUrl:k.string().url(),projectId:k.number().int().positive()})}),ss=k.discriminatedUnion("provider",[ns]),is=k.object({openInGithubDesktop:k.boolean().optional(),openInCmux:k.boolean().optional()}),er=k.object({environments:k.array(k.string().min(1)).min(1),envManagement:es,ide:os.optional(),taskManager:ss.optional(),worktrees:is.optional()}),rr=er.partial(),Oe=null,B=async()=>{let e=await R(),r=await F(),t=Nr.join(Hn.homedir(),Xn);return{main:Nr.join(e,To),userGlobal:Nr.join(t,Yn),userProject:Nr.join(t,Zn,r,To),projectName:r}},x=async()=>{let e=await B(),r;try{r=await Ot.stat(e.main)}catch{Oe=null;let c=e.main.replace(/\.json$/,".yml");throw await Nt(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([Nt(e.userGlobal),Nt(e.userProject)]),n={main:Number(r.mtimeMs),userGlobal:t?Number(t.mtimeMs):null,userProject:o?Number(o.mtimeMs):null};if(Oe&&cs(Oe.mtimes,n))return Oe.value;let s=[{label:"infra-kit.json",path:e.main,required:!0},{label:"~/.infra-kit/config.json",path:e.userGlobal,required:!1},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,path:e.userProject,required:!1}],i={};for(let c of s){let p=await ls(c);p!==null&&(i={...i,...p})}let l=er.safeParse(i);if(!l.success)throw new Error(`Invalid merged infra-kit config: ${k.prettifyError(l.error)}`);return Oe={mtimes:n,value:l.data},l.data},he=()=>{Oe=null},Nt=async e=>{try{return await Ot.stat(e)}catch{return null}},as=async e=>{try{return await Ot.readFile(e,"utf-8")}catch{return null}},cs=(e,r)=>{let t=Object.keys(e);return t.length!==Object.keys(r).length?!1:t.every(o=>e[o]===r[o])},ls=async e=>{let r=await as(e.path);if(r===null){if(e.required)throw new Error(`${e.label} not found at ${e.path}`);return null}let t;try{t=r.trim()===""?{}:JSON.parse(r)}catch(n){throw new Error(`Invalid JSON in ${e.label} at ${e.path}: ${n.message}`)}let o=rr.safeParse(t);if(!o.success)throw new Error(`Invalid ${e.label} at ${e.path}: ${k.prettifyError(o.error)}`);return o.data};var So=async e=>{try{return await Or.access(e),!0}catch{return!1}},jr=e=>{let r=ps.homedir();return e.startsWith(r)?`~${e.slice(r.length)}`:e},jt=async()=>{let e=await B(),r=await Promise.all([{label:"project (committed)",path:e.main},{label:"user global",path:e.userGlobal},{label:"user project",path:e.userProject}].map(async o=>({...o,exists:await So(o.path)})));a.info(`Project name: ${e.projectName}
|
|
5
5
|
`),a.info(`Config merge chain (later overrides earlier):
|
|
6
|
-
`);for(let o of r){let n=o.exists?" [\u2713]":" [ ]";a.info(`${n} ${o.label.padEnd(22)} ${
|
|
7
|
-
`,"utf-8"),await
|
|
6
|
+
`);for(let o of r){let n=o.exists?" [\u2713]":" [ ]";a.info(`${n} ${o.label.padEnd(22)} ${jr(o.path)}`)}let t={projectName:e.projectName,layers:r.map(o=>({label:o.label,path:o.path,exists:o.exists}))};return{content:[{type:"text",text:JSON.stringify(t,null,2)}],structuredContent:t}},Ft=async()=>{let e=await B(),r=$o.env.EDITOR||$o.env.VISUAL||"vi";if(await Or.mkdir(ms.dirname(e.userProject),{recursive:!0}),!await So(e.userProject)){let o=us(e.userProject);await Or.writeFile(e.userProject,`{}
|
|
7
|
+
`,"utf-8"),await Or.writeFile(o,fs(e.projectName),"utf-8"),a.info(`Created ${jr(e.userProject)} \u2014 see ${jr(o)} for the annotated reference.`)}a.info(`Opening ${jr(e.userProject)} in ${r}`),await ds({stdio:"inherit"})`${r} ${e.userProject}`,he();let t={path:e.userProject,editor:r};return{content:[{type:"text",text:JSON.stringify(t,null,2)}],structuredContent:t}},us=e=>e.replace(/\.json$/,".example.jsonc"),fs=e=>`// infra-kit user override for ${e} \u2014 ~/.infra-kit/projects/${e}/infra-kit.json
|
|
8
8
|
//
|
|
9
9
|
// Layer 3 (highest precedence) of the config merge chain. Shallow-merged on top
|
|
10
10
|
// of <repo>/infra-kit.json and ~/.infra-kit/config.json \u2014 top-level keys
|
|
@@ -15,17 +15,17 @@ ${o?"\u2705 All valid":"\u274C Audit failed"} (${t.length} checked)`);let n={all
|
|
|
15
15
|
{
|
|
16
16
|
// "worktrees": { "openInGithubDesktop": false, "openInCmux": true }
|
|
17
17
|
}
|
|
18
|
-
`;import
|
|
19
|
-
${i}`:"")};var
|
|
18
|
+
`;import ie from"node:fs";import Mo from"node:os";import ar from"node:path";import{z as De}from"zod";import{$ as Do}from"zx";import J from"node:fs";import ve from"node:path";var je=(e,r,t)=>{let o=e.indexOf(r),n=e.indexOf(t);return o!==-1&&n!==-1&&n>=o},tr=(e,r,t)=>{let o=e.indexOf(r),n=e.indexOf(t);if(o===-1||n===-1||n<o)return null;let s=e.slice(0,o).replace(/\n+$/,""),i=e.slice(n+t.length).replace(/^\n+/,"");return s+(i?`
|
|
19
|
+
${i}`:"")};var Io=(e,r,t)=>`${e}
|
|
20
20
|
${r}
|
|
21
|
-
${t}`,
|
|
21
|
+
${t}`,we=({content:e,body:r,startMarker:t,endMarker:o,placement:n="replace-in-place"})=>{let s=Io(t,r,o),i=je(e,t,o);if(n==="replace-in-place"&&i){let p=e.indexOf(t),m=e.indexOf(o)+o.length;return e.slice(0,p)+s+e.slice(m)}let c=(i?tr(e,t,o)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
|
|
22
22
|
${s}
|
|
23
23
|
`:`${s}
|
|
24
|
-
`};var
|
|
25
|
-
`),
|
|
26
|
-
`),
|
|
27
|
-
`,"utf-8"),await
|
|
28
|
-
`,
|
|
24
|
+
`};var Fr={name:"infra-kit",type:"module",version:"0.1.108",description:"infra-kit",main:"dist/index.js",module:"dist/index.js",types:"dist/entry/index.d.ts",exports:{".":{types:"./dist/entry/index.d.ts",import:"./dist/index.js"}},bin:{"infra-kit":"dist/cli.js"},engines:{node:">=24.x"},scripts:{inspector:"npx @modelcontextprotocol/inspector node ./dist/mcp.js --debug",build:"pnpm run clean-artifacts && node ./scripts/build.js",check:"node ./dist/cli.js check","clean-artifacts":"rm -rf dist","clean-cache":"rm -rf node_modules/.cache .eslintcache tsconfig.tsbuildinfo .turbo .swc","prettier-fix":"pnpm exec prettier **/* --write --no-error-on-unmatched-pattern --log-level silent --ignore-path ../../../.prettierignore","prettier-check":"pnpm exec prettier **/* --check --no-error-on-unmatched-pattern --log-level silent --ignore-path ../../../.prettierignore","eslint-check":"pnpm exec eslint --cache --quiet --report-unused-disable-directives ./src","eslint-fix":"pnpm exec eslint --cache --quiet --report-unused-disable-directives ./src --fix","ts-check":"tsc --noEmit",test:"pnpm exec vitest run --reporter=minimal","test-watch":"pnpm exec vitest --watch --silent passed-only","test-ui":"pnpm exec vitest --ui --silent passed-only","test-report":"pnpm exec vitest run --coverage --silent passed-only",qa:"pnpm run prettier-check && pnpm run eslint-check && pnpm run ts-check && pnpm run test && echo \u2705 Success",fix:"pnpm run prettier-fix && pnpm run eslint-fix && pnpm run qa"},dependencies:{"@inquirer/checkbox":"^5.2.1","@inquirer/confirm":"^6.1.1","@inquirer/select":"^5.2.1","@modelcontextprotocol/sdk":"^1.29.0",commander:"^15.0.0",pino:"^10.3.1","pino-pretty":"^13.1.3",yaml:"^2.9.0",zod:"^4.4.3",zx:"^8.8.5"},devDependencies:{"@wl/eslint-config":"workspace:*","@wl/vitest-config":"workspace:*",esbuild:"^0.28.1",typescript:"^6.0.3"}};var ne="<!-- infra-kit:begin -->",se="<!-- infra-kit:end -->",hs="<!-- infra-kit:version ",or="<!-- infra-kit:import:begin -->",nr="<!-- infra-kit:import:end -->",Ao="AGENTS.md",ws="CLAUDE.md",vs=ve.join(".cursor","rules","infra-kit.mdc"),ks=["---","description: infra-kit CLI usage and conventions","alwaysApply: true","---",""].join(`
|
|
25
|
+
`),ys=e=>`${hs}${e} -->`,Rs=e=>[ys(e),"","# infra-kit","","This repository uses the **infra-kit** CLI for environment, worktree, and release workflows.","This block is generated by `infra-kit init` \u2014 edit text *outside* the markers, never inside.","","## Commands (`ik` = `pnpm exec infra-kit`)","","- `ik env-load -c <config>` / `ik env-clear` / `ik env-status` \u2014 load, clear, or inspect Doppler env vars for a config (e.g. `dev`). Source the returned file to apply.","- `ik worktrees-add` / `worktrees-list` / `worktrees-open` / `worktrees-remove` / `worktrees-sync` \u2014 manage release and feature git worktrees.","- `ik release-create` / `release-list` / `release-deploy-all` / `release-deploy-selected` / `release-deliver` / `release-desc-edit` \u2014 release-branch and deploy flow.","- `ik merge-dev` \u2014 merge the dev branch into every release branch.","- `ik audit` \u2014 audit packages against `infra-kit.config.ts` rules.","- `ik doctor` \u2014 check gh / doppler / aws / rtk install + auth and repo setup.","- `ik init` \u2014 (re)install shell integration and regenerate these agent-instruction files.","","## Conventions","","- Tickets are prefixed by area: `[FE]` frontend, `[BE]` backend, `[DO]` DevOps/infra, `[APP]` mobile app, `[IDEA]` proposal, `[ROOT]` cross-cutting. Pick the single dominant area.","- Environment variables are managed through Doppler via `ik env-load` \u2014 never commit secrets."].join(`
|
|
26
|
+
`),bs=e=>{if(J.existsSync(e)&&J.lstatSync(e).isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},Mt=(e,r)=>{bs(e);let t=J.existsSync(e);if((t?J.readFileSync(e,"utf-8"):null)===r)return"unchanged";if(t){let n=new Date().toISOString().replace(/[:.]/g,"-");J.copyFileSync(e,`${e}.backup.${n}`)}return J.mkdirSync(ve.dirname(e),{recursive:!0}),J.writeFileSync(e,r,"utf-8"),t?"updated":"created"},Dt=(e,r)=>J.existsSync(e)?J.readFileSync(e,"utf-8"):r,Lt=(e,r,t)=>{let o=J.readFileSync(e,"utf-8");if(!je(o,r,t))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},Wt=async()=>{let e;try{e=(await B()).main}catch{return a.info("Skipped agent-instruction files \u2014 not inside an infra-kit repo"),{skipped:!0,root:null,written:[]}}if(!J.existsSync(e))return a.info("Skipped agent-instruction files \u2014 no infra-kit.json at the repo root"),{skipped:!0,root:null,written:[]};let r=ve.dirname(e),t=Fr.version,o=Rs(t),n=ve.join(r,Ao),s=ve.join(r,ws),i=ve.join(r,vs),l=we({content:Dt(n,""),body:o,startMarker:ne,endMarker:se}),c=we({content:Dt(s,""),body:`@${Ao}`,startMarker:or,endMarker:nr}),p=we({content:Dt(i,ks),body:o,startMarker:ne,endMarker:se}),m=[{path:n,action:Mt(n,l)},{path:s,action:Mt(s,c)},{path:i,action:Mt(i,p)}];Lt(n,ne,se),Lt(s,or,nr),Lt(i,ne,se);for(let u of m)a.info(` ${u.action.padEnd(9)} ${ve.relative(r,u.path)}`);return a.info(`Agent-instruction files synced (infra-kit ${t})`),{skipped:!1,root:r,written:m}};import ke from"node:fs";import Oo from"node:os";import Mr from"node:path";import sr from"node:fs/promises";import xs from"node:os";import Cs from"node:path";import Es from"yaml";import{z as Ps}from"zod";var Fe=e=>{let r=xs.homedir();return e.startsWith(r)?`~${e.slice(r.length)}`:e},_o=async e=>{try{return await sr.access(e),!0}catch{return!1}},Bt=e=>e.replace(/\.json$/,".yml"),No=async()=>{let e;try{e=await B()}catch{return}let r=[{label:"infra-kit.json",yml:Bt(e.main),json:e.main,schema:er},{label:"~/.infra-kit/config.json",yml:Bt(e.userGlobal),json:e.userGlobal,schema:rr},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:Bt(e.userProject),json:e.userProject,schema:rr}],t=0;for(let o of r){let[n,s]=await Promise.all([_o(o.yml),_o(o.json)]);if(n){if(s){a.info(`\u26A0 Skipped ${Fe(o.yml)} \u2014 ${Fe(o.json)} already exists (remove the stale .yml manually)`);continue}try{let i=await sr.readFile(o.yml,"utf-8"),l=Es.parse(i)??{},c=o.schema.safeParse(l);if(!c.success){a.info(`\u26A0 Skipped ${Fe(o.yml)} \u2014 invalid config: ${Ps.prettifyError(c.error)}`);continue}await sr.mkdir(Cs.dirname(o.json),{recursive:!0}),await sr.writeFile(o.json,`${JSON.stringify(c.data,null,2)}
|
|
27
|
+
`,"utf-8"),await sr.rm(o.yml,{force:!0}),a.info(`\u2713 Migrated ${Fe(o.yml)} \u2192 ${Fe(o.json)}`),t++}catch(i){a.info(`\u26A0 Skipped ${Fe(o.yml)} \u2014 ${i.message}`)}}}t>0&&he()};var ir="# -- infra-kit:begin --",Me="# -- infra-kit:end --",Ts=[["# region infra-kit","# endregion infra-kit"]],$s="# infra-kit shell functions",Ss=`{}
|
|
28
|
+
`,Is=`// infra-kit user-global config \u2014 ~/.infra-kit/config.json
|
|
29
29
|
//
|
|
30
30
|
// Merge chain (later layers override earlier ones at top-level keys):
|
|
31
31
|
// 1. <repo>/infra-kit.json \u2014 committed project config (required)
|
|
@@ -46,63 +46,63 @@ ${s}
|
|
|
46
46
|
// },
|
|
47
47
|
// "worktrees": { "openInGithubDesktop": false, "openInCmux": true }
|
|
48
48
|
}
|
|
49
|
-
`,
|
|
50
|
-
`),s=0;for(;s<n.length
|
|
49
|
+
`,Vt=async()=>{let e=Mr.join(Oo.homedir(),".zshrc"),r=ke.existsSync(e)?Ns(ke.readFileSync(e,"utf-8")):"",t=we({content:r,body:jo(),startMarker:ir,endMarker:Me,placement:"append-end"});ke.writeFileSync(e,t),a.info(`Added infra-kit shell functions to ${e}`),await No(),As(),await Wt(),a.info("Run `source ~/.zshrc` or open a new terminal to activate.")},As=()=>{let e=Mr.join(Oo.homedir(),".infra-kit"),r=Mr.join(e,"config.json"),t=Mr.join(e,"config.example.jsonc");if(ke.existsSync(r)){a.info(`User-global config already present at ${r}`);return}ke.mkdirSync(e,{recursive:!0}),ke.writeFileSync(r,Ss,"utf-8"),ke.writeFileSync(t,Is,"utf-8"),a.info(`Wrote user-global config to ${r} (see ${t} for the annotated reference)`)},_s=e=>e.startsWith("#")||e.startsWith("alias ")||e.startsWith("env-load")||e.startsWith("env-clear")||e.startsWith("env-status")||e.startsWith("if ")||e.startsWith(" export INFRA_KIT_SESSION")||e.startsWith("export _INFRA_KIT_")||e.startsWith(": ${_INFRA_KIT_")||e.startsWith("fi")||e.startsWith("zmodload ")||e.startsWith("autoload ")||e.startsWith("add-zsh-hook ")||e.startsWith("_infra_kit_autoload"),Ns=e=>{let r=tr(e,ir,Me);if(r!==null)return r;for(let[l,c]of Ts){let p=tr(e,l,c);if(p!==null)return p}let t=e.indexOf($s);if(t===-1)return e;let o=e.slice(0,t).replace(/\n+$/,""),n=e.slice(t).split(`
|
|
50
|
+
`),s=0;for(;s<n.length&&_s(n[s]);)s++;let i=n.slice(s).join(`
|
|
51
51
|
`);return o+(i?`
|
|
52
|
-
${i}`:"")},
|
|
53
|
-
`)},
|
|
54
|
-
${
|
|
55
|
-
${
|
|
56
|
-
`).map(n=>n.trim()).filter(n=>n.startsWith("[ok]")||n.startsWith("[--]")),o=[];for(let n of
|
|
57
|
-
`);for(let o of r){let n=o.status==="pass"?"[PASS]":"[FAIL]";a.info(` ${n} ${o.name}: ${o.message}`)}let t={checks:r.map(o=>({name:o.name,status:o.status,message:o.message})),allPassed:r.every(o=>o.status==="pass")};return{content:h(JSON.stringify(t,null,2)),structuredContent:t}},
|
|
58
|
-
`)){let n=
|
|
52
|
+
${i}`:"")},jo=()=>{let e="pnpm exec infra-kit";return["zmodload zsh/stat 2>/dev/null","zmodload zsh/datetime 2>/dev/null",'if [[ -z "${INFRA_KIT_SESSION}" ]]; then'," export INFRA_KIT_SESSION=$(head -c 4 /dev/urandom | xxd -p)","fi",": ${_INFRA_KIT_LAST_LOAD_MTIME:=0}",": ${_INFRA_KIT_LAST_CLEAR_MTIME:=0}",": ${_INFRA_KIT_SHELL_STARTED:=${EPOCHSECONDS:-0}}","export _INFRA_KIT_LAST_LOAD_MTIME _INFRA_KIT_LAST_CLEAR_MTIME _INFRA_KIT_SHELL_STARTED",`env-load() { local f m; f=$(${e} env-load "$@") || return; m=$(zstat +mtime -- "$f" 2>/dev/null || echo 0); _INFRA_KIT_LAST_LOAD_MTIME=$m; source "$f"; ${e} env-status; }`,`env-clear() { local f m; f=$(${e} env-clear) || return; m=$(zstat +mtime -- "$f" 2>/dev/null || echo 0); _INFRA_KIT_LAST_CLEAR_MTIME=$m; source "$f"; ${e} env-status; }`,`env-status() { ${e} env-status; }`,`alias ik='${e}'`,"_infra_kit_autoload() {",' [[ -z "$INFRA_KIT_SESSION" ]] && return',' local cache_root="${XDG_CACHE_HOME:-$HOME/.cache}/infra-kit"',' local dir="$cache_root/$INFRA_KIT_SESSION"',' local load_file="$dir/env-load.sh"',' local clear_file="$dir/env-clear.sh"'," local mtime",' if [[ -f "$load_file" ]]; then',' mtime=$(zstat +mtime -- "$load_file" 2>/dev/null || echo 0)'," if (( mtime > _INFRA_KIT_LAST_LOAD_MTIME && mtime >= _INFRA_KIT_SHELL_STARTED )); then",' source "$load_file"'," _INFRA_KIT_LAST_LOAD_MTIME=$mtime",' print -u2 "infra-kit: auto-loaded vars for ${INFRA_KIT_ENV_CONFIG:-?}"'," fi"," fi",' if [[ -f "$clear_file" ]]; then',' mtime=$(zstat +mtime -- "$clear_file" 2>/dev/null || echo 0)'," if (( mtime > _INFRA_KIT_LAST_CLEAR_MTIME && mtime >= _INFRA_KIT_SHELL_STARTED )); then",' source "$clear_file"'," _INFRA_KIT_LAST_CLEAR_MTIME=$mtime",' print -u2 "infra-kit: auto-cleared env"'," fi"," fi","}","autoload -Uz add-zsh-hook","if (( _INFRA_KIT_SHELL_STARTED > 0 )); then"," add-zsh-hook precmd _infra_kit_autoload","fi"].join(`
|
|
53
|
+
`)},Fo=()=>`${ir}
|
|
54
|
+
${jo()}
|
|
55
|
+
${Me}`;var Le=async(e,r,t,o)=>{try{return await Do`${r}`,{name:e,status:"pass",message:t}}catch{return{name:e,status:"fail",message:o}}},Os=()=>{let e="zshrc init block",r=ar.join(Mo.homedir(),".zshrc");if(!ie.existsSync(r))return{name:e,status:"fail",message:"~/.zshrc not found. Run: infra-kit init"};let t=ie.readFileSync(r,"utf-8"),o=t.indexOf(ir),n=t.indexOf(Me);if(o===-1||n===-1||n<o)return{name:e,status:"fail",message:"infra-kit shell block missing from ~/.zshrc. Run: infra-kit init"};let s=t.slice(o,n+Me.length).trim(),i=Fo().trim();return s!==i?{name:e,status:"fail",message:"infra-kit shell block in ~/.zshrc is out of date. Run: infra-kit init"}:{name:e,status:"pass",message:"infra-kit shell block in ~/.zshrc is up to date"}},js=async()=>{let e="pnpm enableGlobalVirtualStore";try{let r=await R(),t=ar.join(r,"pnpm-workspace.yaml");if(!ie.existsSync(t))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${t}`};let o=ie.readFileSync(t,"utf-8");return/^\s*enableGlobalVirtualStore\s*:\s*true\s*$/m.test(o)?{name:e,status:"pass",message:"enableGlobalVirtualStore: true is set"}:{name:e,status:"fail",message:"enableGlobalVirtualStore: true is missing in pnpm-workspace.yaml"}}catch(r){return{name:e,status:"fail",message:`Failed to read pnpm-workspace.yaml: ${r.message}`}}},Fs=async()=>{let e="infra-kit config valid";try{return he(),await x(),{name:e,status:"pass",message:"infra-kit.json is valid (user overrides applied if present)"}}catch(r){return{name:e,status:"fail",message:r.message}}},Ms=async()=>{let e="user override path";try{let r=await B(),t=Mo.homedir(),o=r.userProject.startsWith(t)?`~${r.userProject.slice(t.length)}`:r.userProject,s=ie.existsSync(r.userProject)?"(exists)":"(not yet created)";return{name:e,status:"pass",message:`${o} ${s} \u2014 project: ${r.projectName}`}}catch(r){return{name:e,status:"fail",message:r.message}}},Ds=[1,2,3,5,7],Ls=async()=>{let e="rtk configured";try{let t=(await Do`rtk init --show`).stdout.split(`
|
|
56
|
+
`).map(n=>n.trim()).filter(n=>n.startsWith("[ok]")||n.startsWith("[--]")),o=[];for(let n of Ds){let s=t[n-1];(!s||!s.startsWith("[ok]"))&&o.push(n)}return o.length>0?{name:e,status:"fail",message:`rtk setup incomplete (items ${o.join(", ")} not [ok]). Run: rtk init -g --auto-patch`}:{name:e,status:"pass",message:"rtk hook, RTK.md, global CLAUDE.md, settings.json, and Cursor hook are configured"}}catch(r){return{name:e,status:"fail",message:`Failed to run 'rtk init --show': ${r.message}`}}},Ws=async()=>{let e;try{e=(await B()).main}catch{return[]}if(!ie.existsSync(e))return[];let r=ar.dirname(e),t=(n,s,i)=>{let l=ar.join(r,n),c=ie.existsSync(l)?ie.readFileSync(l,"utf-8"):"";return je(c,s,i)};return[{name:"AGENTS.md block",present:t("AGENTS.md",ne,se),okMessage:"AGENTS.md block present",missingMessage:"infra-kit block missing from AGENTS.md. Run: infra-kit init"},{name:"CLAUDE.md import",present:t("CLAUDE.md",or,nr),okMessage:"CLAUDE.md imports @AGENTS.md",missingMessage:"@AGENTS.md import block missing from CLAUDE.md. Run: infra-kit init"},{name:".cursor/rules block",present:t(ar.join(".cursor","rules","infra-kit.mdc"),ne,se),okMessage:".cursor/rules/infra-kit.mdc block present",missingMessage:".cursor/rules/infra-kit.mdc block missing. Run: infra-kit init"}].map(n=>({name:n.name,status:n.present?"pass":"fail",message:n.present?n.okMessage:n.missingMessage}))},Dr=async()=>{let r=[...await Promise.all([Le("gh installed",["gh","--version"],"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/"),Le("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),Le("doppler installed",["doppler","--version"],"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli"),Le("doppler authenticated",["doppler","me"],"Doppler CLI is authenticated","Doppler CLI is not authenticated. Run: doppler login"),Le("aws installed",["aws","--version"],"AWS CLI is installed","AWS CLI is not installed. Install from: https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html"),Le("rtk installed",["rtk","--version"],"RTK is installed","RTK is not installed. Install from: https://github.com/rtk-ai/rtk"),Ls(),Promise.resolve(Os()),js(),Fs(),Ms()]),...await Ws()];a.info(`Doctor check results:
|
|
57
|
+
`);for(let o of r){let n=o.status==="pass"?"[PASS]":"[FAIL]";a.info(` ${n} ${o.name}: ${o.message}`)}let t={checks:r.map(o=>({name:o.name,status:o.status,message:o.message})),allPassed:r.every(o=>o.status==="pass")};return{content:h(JSON.stringify(t,null,2)),structuredContent:t}},Bs=v({name:"doctor",description:"Check installation and authentication status of gh, doppler, aws, and rtk CLIs",inputSchema:{},outputSchema:{checks:De.array(De.object({name:De.string().describe("Name of the check"),status:De.enum(["pass","fail"]).describe("Check result"),message:De.string().describe("Details about the check result")})).describe("List of all check results"),allPassed:De.boolean().describe("Whether all checks passed")},handler:Dr});import Gt from"node:fs";import Wo from"node:path";import Js from"node:process";import{z as Lr}from"zod";import cr from"node:fs";import Vs from"node:os";import Jt from"node:path";import Kt from"node:process";var ye="env-load.sh",qt="env-clear.sh",lr="INFRA_KIT_SESSION",Re="INFRA_KIT_ENV_CONFIG",be="INFRA_KIT_ENV_PROJECT",xe="INFRA_KIT_ENV_LOADED_AT",pr=/^([A-Z_]\w*)=/i,mr=e=>{if(!cr.existsSync(e))return[];let r=cr.readFileSync(e,"utf-8"),t=[];for(let o of r.split(`
|
|
58
|
+
`)){let n=pr.exec(o);n&&t.push(n[1])}return t},Lo=()=>{let e=Kt.env.XDG_CACHE_HOME,r=e&&e.length>0?e:Jt.join(Vs.homedir(),".cache");return Jt.join(r,"infra-kit")},Ce=()=>{let e=Kt.env[lr];if(!e)throw new Error(`${lr} is not set. Run \`infra-kit init\` then \`source ~/.zshrc\`.`);return Jt.join(Lo(),e)},dr=(e,r,t)=>{let o=`${e}.tmp.${Kt.pid}`;cr.writeFileSync(o,r,{mode:t});try{cr.renameSync(o,e)}catch(n){throw cr.rmSync(o,{force:!0}),n}},K="-worktrees";var Wr=async()=>{let e=Ce(),r=Wo.join(e,ye);if(!Gt.existsSync(r))throw new Error("No loaded environment found. Run `env-load` first.");let t=mr(r),o=[...t.map(i=>`unset ${i}`),`unset ${Re}`,`unset ${be}`,`unset ${xe}`],n=Wo.resolve(e,qt);Gt.mkdirSync(e,{recursive:!0,mode:448}),dr(n,`${o.join(`
|
|
59
59
|
`)}
|
|
60
|
-
`,384),
|
|
61
|
-
`),
|
|
62
|
-
`),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}},
|
|
60
|
+
`,384),Js.stdout.write(`${n}
|
|
61
|
+
`),Gt.unlinkSync(r);let s={filePath:n,variableCount:t.length,unsetStatements:o};return{content:h(JSON.stringify(s,null,2)),structuredContent:s}},Ks=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:Lr.string().describe("Path to the file that must be sourced to apply"),variableCount:Lr.number().describe("Number of variables cleared"),unsetStatements:Lr.array(Lr.string()).describe("Unset statements generated")},handler:Wr});import{z as Ut}from"zod";var ur=async()=>{let{envManagement:e}=await x();return e.config.name};var Br=async()=>{let e=await ur(),{environments:r}=await x();a.info(`Doppler project: ${e}
|
|
62
|
+
`),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}},qs=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:Ut.string().describe("Detected Doppler project name"),configs:Ut.array(Ut.string()).describe("Available environment configs")},handler:Br});import Us from"@inquirer/select";import{Buffer as zs}from"node:buffer";import Hs from"node:fs";import Xs from"node:path";import Vo from"node:process";import{z as gr}from"zod";import{$ as Vr}from"zx";import{$ as Bo}from"zx";var fr=async()=>{try{await Bo`doppler --version`}catch(e){throw new Error("Doppler CLI is not installed. Install it from: https://docs.doppler.com/docs/install-cli",{cause:e})}try{await Bo`doppler me`}catch(e){throw new Error("Doppler CLI is not authenticated. Run: doppler login",{cause:e})}};var Gs=()=>{let e="",r=[],t=!1;return{start(o){e=o,r=[],t=!1},setInteractive(){t=!0},addOption(o,n){r.push({flag:o,value:n})},print(){if(!t||r.length===0)return;let o=r.map(n=>typeof n.value=="boolean"?n.value?n.flag:"":Array.isArray(n.value)?`${n.flag} "${n.value.join(", ")}"`:`${n.flag} "${n.value}"`).filter(Boolean).join(" ");a.info(`\u{1F4DF} Equivalent command:
|
|
63
63
|
pnpm exec infra-kit ${e} ${o}
|
|
64
|
-
`)},reset(){e="",r=[],t=!1}}},d=
|
|
64
|
+
`)},reset(){e="",r=[],t=!1}}},d=Gs();var Jr=async e=>{await fr();let{config:r}=e;d.start("env-load");let t="";if(r)t=r;else{let{environments:u}=await x();d.setInteractive(),t=await Us({message:"Select environment config",choices:u.map(g=>({name:g,value:g}))},{output:Vo.stderr})}d.addOption("--config",t);let o=await ur(),n=await Zs(o,t);ti(n);let s=new Date().toISOString(),i=["set -a",n,`${Re}=${zt(t)}`,`${be}=${zt(o)}`,`${xe}=${zt(s)}`,"set +a"],l=Ce(),c=Xs.resolve(l,ye);Hs.mkdirSync(l,{recursive:!0,mode:448}),dr(c,`${i.join(`
|
|
65
65
|
`)}
|
|
66
|
-
`,384),
|
|
67
|
-
`),d.print();let p=
|
|
68
|
-
`).filter(r=>
|
|
69
|
-
`)){let t=r.trim();if(!(t.length===0||
|
|
66
|
+
`,384),Vo.stdout.write(`${c}
|
|
67
|
+
`),d.print();let p=ei(n),m={filePath:c,variableCount:p,project:o,config:t};return{content:h(JSON.stringify(m,null,2)),structuredContent:m}},Jo=1024*1024,Ys=3e4,Zs=async(e,r)=>{let t=Vr.quiet;Vr.quiet=!0;try{let o=await Vr`doppler secrets download --no-file --format env --project ${e} --config ${r}`.timeout(Ys);return Qs(o.stdout),o.stdout.trim()}finally{Vr.quiet=t}},Qs=e=>{let r=zs.byteLength(e,"utf-8");if(r>Jo)throw new Error(`doppler returned unexpectedly large output (${r} bytes > ${Jo}) \u2014 refusing to write to disk`)},ei=e=>e.split(`
|
|
68
|
+
`).filter(r=>pr.test(r)).length,ri=new Set(["set -a","set +a"]),zt=e=>`'${e.replaceAll("'","'\\''")}'`,ti=e=>{if(e.trim().length===0)throw new Error("doppler returned empty output for env-load");for(let r of e.split(`
|
|
69
|
+
`)){let t=r.trim();if(!(t.length===0||ri.has(t))&&!pr.test(t))throw new Error(`doppler returned unexpected output for env-load (expected KEY=value lines, got: ${JSON.stringify(t.slice(0,80))})`)}},oi=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:gr.string().describe('Doppler config / environment name to load (e.g. "dev", "arthur", "renana"). Required for MCP calls.')},outputSchema:{filePath:gr.string().describe("Path to the file that must be sourced to apply variables"),variableCount:gr.number().describe("Number of variables loaded"),project:gr.string().describe("Doppler project name"),config:gr.string().describe("Doppler config name")},handler:Jr});import ni from"node:path";import hr from"node:process";import{z as We}from"zod";var Kr=async()=>{await fr(),a.info("Environment session status:");let e=Ce(),r=hr.env[lr],t=ni.join(e,ye),o=0,n=0,s=hr.env[Re]??null,i=hr.env[be]??null,l=hr.env[xe]??null;if(s){let p=mr(t);p.length>0&&(n=p.length,o=p.filter(u=>u in hr.env).length);let m=l?.replace(/\.\d{3}Z$/,"")??null;if(a.info(` ${s}: ${o} of ${n} vars loaded (project: ${i}, loadedAt: ${m}, session: ${r})
|
|
70
70
|
`),n>0&&o<n){let u=n-o;a.warn(` ${u} cached var(s) are not present in the current process \u2014 env-load needs to be re-sourced, or vars were unset manually.`)}}else a.info(` Session ${r}: no env loaded
|
|
71
|
-
`);let c={sessionId:r,sessionLoadedCount:o,sessionTotalCount:n,sessionConfig:s,sessionProject:i,sessionLoadedAt:l};return{content:h(JSON.stringify(c,null,2)),structuredContent:c}},
|
|
72
|
-
`);throw new Error(i)}let s=Number.parseInt(t,10);if(Number.isNaN(s))throw new TypeError(`Invalid JIRA_PROJECT_ID: "${t}" must be a numeric value (e.g., 10001)`);return{baseUrl:e.replace(/\/$/,""),token:r,projectId:s,email:o}},
|
|
71
|
+
`);let c={sessionId:r,sessionLoadedCount:o,sessionTotalCount:n,sessionConfig:s,sessionProject:i,sessionLoadedAt:l};return{content:h(JSON.stringify(c,null,2)),structuredContent:c}},si=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:We.string().describe("Current terminal session ID"),sessionLoadedCount:We.number().describe("Number of cached vars active in the current session"),sessionTotalCount:We.number().describe("Total number of cached var names"),sessionConfig:We.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:We.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:We.string().nullable().describe("ISO 8601 timestamp of when the env was loaded")},handler:Kr});import li from"@inquirer/checkbox";import pi from"@inquirer/confirm";import mi from"node:process";import{z as qe}from"zod";import{$ as q}from"zx";import{$ as Am}from"zx";import zr from"node:process";import{$ as _}from"zx";import{$ as vr}from"zx";import wr from"node:process";var Ht=async(e,r)=>{try{let{baseUrl:t,token:o,email:n,projectId:s}=r,i={name:e.name,projectId:e.projectId||s,description:e.description||"",released:e.released||!1,archived:e.archived||!1},l=`${t}/rest/api/3/version`,c=btoa(`${n}:${o}`),p=await fetch(l,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${c}`},body:JSON.stringify(i)});if(!p.ok){let u=await p.text();throw a.error({status:p.status,statusText:p.statusText,error:u},"Failed to create Jira version"),new Error(`HTTP ${p.status}: ${p.statusText}`)}return{success:!0,version:await p.json()}}catch(t){throw a.error({error:t},"Error creating Jira version"),t}},Be=async e=>{try{let{baseUrl:r,token:t,email:o,projectId:n}=e,s=`${r}/rest/api/3/project/${n}/versions`,i=btoa(`${o}:${t}`),l=await fetch(s,{method:"GET",headers:{Accept:"application/json",Authorization:`Basic ${i}`}});if(!l.ok){let p=await l.text();throw a.error({status:l.status,statusText:l.statusText,error:p},"Failed to get Jira project versions"),new Error(`HTTP ${l.status}: ${l.statusText}`)}return await l.json()}catch(r){throw a.error({error:r},"Error getting Jira project versions"),r}},qr=async(e,r)=>{try{return(await Be(r)).find(n=>n.name===e)||null}catch(t){throw a.error({error:t,versionName:e},"Error finding Jira version by name"),t}},Gr=async(e,r)=>{try{let{baseUrl:t,token:o,email:n}=r,s={};e.released!==void 0&&(s.released=e.released),e.archived!==void 0&&(s.archived=e.archived),e.releaseDate!==void 0&&(s.releaseDate=e.releaseDate),e.description!==void 0&&(s.description=e.description);let i=`${t}/rest/api/3/version/${e.versionId}`,l=btoa(`${n}:${o}`),c=await fetch(i,{method:"PUT",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${l}`},body:JSON.stringify(s)});if(!c.ok){let m=await c.text();throw a.error({status:c.status,statusText:c.statusText,error:m},"Failed to update Jira version"),new Error(`HTTP ${c.status}: ${c.statusText}`)}return{success:!0,version:await c.json()}}catch(t){throw a.error({error:t},"Error updating Jira version"),t}},Xt=async(e,r)=>{try{let{versionName:t}=e,o=await qr(t,r);if(!o)throw a.error({versionName:t},"Jira version not found"),new Error(`Version "${t}" not found in Jira project`);return await Gr({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}},Ve=async()=>{let e=wr.env.JIRA_BASE_URL,r=wr.env.JIRA_TOKEN||wr.env.JIRA_API_TOKEN,t=wr.env.JIRA_PROJECT_ID,o=wr.env.JIRA_EMAIL,n=[];if(e||n.push("JIRA_BASE_URL (e.g., https://your-domain.atlassian.net)"),r||n.push("JIRA_TOKEN or JIRA_API_TOKEN (your Jira API token)"),t||n.push("JIRA_PROJECT_ID (numeric project ID)"),o||n.push("JIRA_EMAIL (your Jira email address)"),n.length>0){let i=["Jira configuration is required but incomplete.","Please configure the following environment variables:",...n.map(l=>` - ${l}`),"","You can set these in your .env file or as environment variables."].join(`
|
|
72
|
+
`);throw new Error(i)}let s=Number.parseInt(t,10);if(Number.isNaN(s))throw new TypeError(`Invalid JIRA_PROJECT_ID: "${t}" must be a numeric value (e.g., 10001)`);return{baseUrl:e.replace(/\/$/,""),token:r,projectId:s,email:o}},Ee=async()=>{try{return await Ve()}catch(e){return a.warn({error:e},"Jira configuration not available, skipping Jira integration"),null}};var ai=e=>{if(e===null||typeof e!="object")return;let r=e.stderr;return typeof r=="string"&&r.length>0?r:void 0},ci=(e,r)=>{let t=r.stderrExcerpt??ai(e),o=[`failed to ${r.operation}`];return t&&o.push(`stderr: ${t.slice(0,200).trim()}`),r.remediation&&o.push(`try: ${r.remediation}`),o.join(" \u2014 ")},f=class extends Error{operation;remediation;constructor(r,t){super(ci(r,t),{cause:r}),this.name="OperationError",this.operation=t.operation,this.remediation=t.remediation}};var Ko="dev",Je=e=>e==="hotfix"?"main":"dev",Yt=async(e="regular")=>{let r=Je(e);vr.quiet=!0,await vr`git fetch origin`,await vr`git switch ${r}`,await vr`git pull origin ${r}`,vr.quiet=!1},Zt=async e=>{let{id:r,jiraConfig:t,description:o,type:n="regular"}=e,s=L(r),i=await Ht({name:s,projectId:t.projectId,description:o||"",released:!1,archived:!1},t),l=`${t.baseUrl}/projects/${i.version.projectId}/versions/${i.version.id}/tab/release-report-all-issues`,c=await Ur({id:r,jiraVersionUrl:l,type:n,description:o});return{version:T(r),type:n,branchName:c.branchName,prUrl:c.prUrl,jiraVersionUrl:l}},$=async()=>{let e=new Map,r=await Ee();if(!r)return e;try{let t=await Be(r);for(let o of t)o.description&&e.set(o.name,o.description)}catch{}return e},Ke=(e,r,t)=>{let o=t?" ".repeat(t-e.length+3):" ",n=`[${r}]`.padEnd(11);return`${e}${o}${n}`},C=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",qo=e=>e.flatMap(r=>{let t=b(r);return t?[{branch:r,id:t,label:T(t)}]:[]}),Y=e=>{try{return H(G(e))}catch(r){throw new f(r,{operation:`resolve release ref "${e}"`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'})}},kr=e=>{if(e===Ko)return Ko;let r=b(e);return r?T(r):e},Pe=e=>e.flatMap(r=>{let t=b(r);return t?[T(t)]:[]}),A=e=>{let{branches:r,descriptions:t,types:o}=e,n=qo(r),s=Math.max(0,...n.map(i=>i.label.length));return n.map(({branch:i,id:l,label:c})=>{let p=o?o.get(i)||"regular":void 0,m=t.get(L(l)),u=" ".repeat(s-c.length+3),g=p?Ke(c,p,s):c;return m&&(g=p?`${g} ${m}`:`${c}${u}${m}`),{name:g,value:i}})};var Go=e=>e.map(r=>({pr:r,id:b(r.headRefName)})).filter(r=>r.id!==null).sort((r,t)=>yt(r.id,t.id,{a:r.pr.createdAt,b:t.pr.createdAt})).map(r=>r.pr),Uo=async()=>{let e=await _`gh pr list --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,r=await _`gh pr list --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName,createdAt`,t=[...JSON.parse(e.stdout),...JSON.parse(r.stdout)],o=new Set;return t.filter(n=>o.has(n.headRefName)?!1:(o.add(n.headRefName),!0))},Hr=async()=>{try{let e=await Uo();return e.length===0&&(a.error("\u274C No release PRs found. Check the project folder for the script. Exiting..."),zr.exit(1)),Go(e).map(r=>r.headRefName)}catch(e){a.error({error:e},"\u274C Error fetching release PRs"),zr.exit(1)}},E=async()=>{try{let e=await Uo();return e.length===0&&(a.error("\u274C No release PRs found. Check the project folder for the script. Exiting..."),zr.exit(1)),Go(e).map(r=>({branch:r.headRefName,title:r.title,createdAt:r.createdAt}))}catch(e){a.error({error:e},"\u274C Error fetching release PRs"),zr.exit(1)}},Xr=async e=>{let{branch:r,body:t}=e;try{_.quiet=!0,await _`gh pr edit ${r} --body ${t}`,_.quiet=!1}catch(o){throw a.error({error:o,branch:r},`Error updating release PR body for ${r}`),o}},Ur=async e=>{let{id:r,jiraVersionUrl:t,type:o,description:n}=e,s=kt(r,o),i=Je(o),l=H(r),c=n&&n.trim()!==""?`${t}
|
|
73
73
|
|
|
74
74
|
${n}`:`${t}
|
|
75
|
-
`;try{_.quiet=!0,await _`git switch ${i}`,await _`git pull origin ${i}`,await _`git checkout -b ${l}`,await _`git push -u origin ${l}`,await _`git commit --allow-empty-message --allow-empty --message ''`,await _`git push origin ${l}`;let m=(await _`gh pr create --title ${s} --body ${c} --base ${i} --head ${l}`).stdout.trim();return await _`git switch ${i}`,_.quiet=!1,{branchName:l,prUrl:m}}catch(p){throw a.error({error:p,branchName:l},`Error creating release branch ${l}`),p}};var
|
|
75
|
+
`;try{_.quiet=!0,await _`git switch ${i}`,await _`git pull origin ${i}`,await _`git checkout -b ${l}`,await _`git push -u origin ${l}`,await _`git commit --allow-empty-message --allow-empty --message ''`,await _`git push origin ${l}`;let m=(await _`gh pr create --title ${s} --body ${c} --base ${i} --head ${l}`).stdout.trim();return await _`git switch ${i}`,_.quiet=!1,{branchName:l,prUrl:m}}catch(p){throw a.error({error:p,branchName:l},`Error creating release branch ${l}`),p}};var M=async e=>{let{operation:r,requiredBranch:t}=e;if(await xt())throw new f(void 0,{operation:r,remediation:"run this from the main repository checkout, not a linked git worktree",stderrExcerpt:"command run from inside a linked worktree"});if(t){let o=await Rt();if(o!==t)throw new f(void 0,{operation:r,remediation:`switch to ${t} first (git switch ${t})`,stderrExcerpt:`current branch is "${o}", expected "${t}"`})}if(!await bt())throw new f(void 0,{operation:r,remediation:"commit or stash your changes, then retry",stderrExcerpt:"working tree has uncommitted changes"})};var Yr=async e=>{let{all:r,confirmedCommand:t}=e;d.start("merge-dev"),await M({operation:"merge dev into release branches",requiredBranch:"dev"});let n=(await E()).filter(m=>C(m.title)==="regular").map(m=>m.branch);if(n.length===0)return a.info("\u2139\uFE0F No open release branches found"),d.print(),{content:h(JSON.stringify({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0},null,2)),structuredContent:{successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0}};let s=[];if(r)s=n;else{d.setInteractive();let m=await $();s=await li({required:!0,message:"\u{1F33F} Select release branches",choices:A({branches:n,descriptions:m})})}s.length===n.length?d.addOption("--all",!0):d.addOption("--versions",Pe(s));let l=t?!0:await pi({message:`Are you sure you want to merge dev into these branches: ${s.join(", ")}?`});t||d.setInteractive(),l||(a.info("Operation cancelled. Exiting..."),mi.exit(0)),t||d.addOption("--yes",!0),q.quiet=!0,await q`git fetch origin`,await q`git switch dev`,await q`git pull origin dev`;let c=[];for(let m of s)await di(m)||c.push(m);if(q.quiet=!1,c.length>0){a.info(`
|
|
76
76
|
\u26A0\uFE0F ${c.length} branch(es) failed to merge automatically.
|
|
77
77
|
`),a.info("\u{1F4CB} Manual merge script for failed branches:");for(let m of c)a.info(`# Merge dev into ${m} and resolve conflicts if any
|
|
78
78
|
|
|
79
79
|
git switch ${m} && git pull origin ${m} && git merge origin/dev
|
|
80
80
|
git push origin ${m} && git switch dev
|
|
81
81
|
`);a.info(`\u2705 ${s.length-c.length}/${s.length} merges completed successfully.`)}else a.info(`\u2705 All merges completed successfully!
|
|
82
|
-
`);d.print();let p={successfulMerges:s.length-c.length,failedMerges:c.length,failedBranches:c,totalBranches:s.length};return{content:h(JSON.stringify(p,null,2)),structuredContent:p}},
|
|
83
|
-
`)){let n=o.match(/^[* ]\s*(workspace:\d+)\s+(.+?)(?:\s+\[selected\])?\s*$/);if(!n)continue;let s=n[1],i=n[2]?.trim()??"";if(U(i)===t)return s}};import{$ as
|
|
84
|
-
`)){let o=t.match(/^[* ]\s*workspace:\d+\s+(.+?)(?:\s+\[selected\])?\s*$/);if(!o)continue;let n=o[1]?.trim();n&&r.add(U(n))}return r}catch(e){return a.debug({error:e},"cmux: skipped listing workspace titles"),new Set}};import{$ as kr}from"zx";var yr=async e=>{let{cwd:r,title:t}=e,o=(await kr`cmux workspace create --cwd ${r}`).stdout,n=fi(o),s=(await kr`cmux list-pane-surfaces --workspace ${n}`).stdout,i=ui(s);await kr`cmux new-split right --workspace ${n} --surface ${i}`,await kr`cmux new-split down --workspace ${n} --surface ${i}`,t&&await kr`cmux workspace rename --workspace ${n} --title ${t}`},ui=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]},fi=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 Y=e=>{let{repoName:r,branch:t}=e,o=R(t),n=o?T(o):t;return`${r} ${n}`};var Rr=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=Y({repoName:o,branch:l});return await wr(p),await Ht`git worktree remove ${c}`,l})),i=[];for(let[l,c]of s.entries())if(c.status==="fulfilled")i.push(c.value);else{let p=r[l],m=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:m.message})}return n&&i.length===r.length&&(await Ht`git worktree prune`,await Ht`rm -rf ${t}`,a.info(`\u{1F5D1}\uFE0F Removed worktree folder: ${t}`),a.info("")),i};var Be=async(e,r,t)=>{try{return await t()}catch(o){throw a.error({err:zt(o)},`\u274C Failed to ${e}`),new g(o,{operation:e,remediation:r})}},Uo=async e=>{let r=await M`gh pr list --head ${e} --state all --json number,state,title --limit 1`;return JSON.parse(r.stdout)[0]??null},vi=async e=>{let r=Tr(e),t=await M`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},Go=async()=>{let e=await M`gh pr list --head dev --base main --state open --json number,state,title --limit 5`;return JSON.parse(e.stdout)[0]??null},ki=async e=>{let r=X(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}},yi=async()=>{let e=await E(),r=e.map(i=>i.branch),t=new Map(e.map(i=>[i.branch,C(i.title)]));d.setInteractive();let o=await $(),n=await hi({message:"\u{1F33F} Select release branch",choices:A({branches:r,descriptions:o,types:t})}),s=e.find(i=>i.branch===n);if(!s)throw a.error(`\u274C Release branch ${n} not found in open PRs.`),new g(void 0,{operation:`deliver release ${n}`,remediation:`confirm an open PR exists for ${n} ('gh pr list')`});return{selectedReleaseBranch:n,releasePrTitle:s.title}},Ri=async e=>{if(!(await j("release")).includes(e))return;let[t,o]=await Promise.all([b(),F()]),n=`${t}${B}`;if((await Rr({branches:[e],worktreeDir:n,repoName:o})).length===0)throw new g(void 0,{operation:`remove worktree for ${e} before merge`,remediation:`run manually: git worktree remove ${n}/${e} (use --force if uncommitted changes)`})},bi=async e=>{let{selectedReleaseBranch:r,releaseType:t}=e,o=t==="hotfix"?"main":"dev",n=await Uo(r);if(!n)throw new g(void 0,{operation:`look up release PR for ${r}`,remediation:"verify the PR exists in GitHub"});if(n.state==="MERGED"){a.info(`\u2713 Release PR ${r} already merged \u2014 skipping`);return}if(n.state==="CLOSED")throw new 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 Be(`merge release PR ${r} into ${o}`,`check 'gh pr view ${r}' for mergeability and required reviews`,async()=>{await M`gh pr merge ${r} --squash --admin --delete-branch`})},xi=async e=>{let r=T(e),t=Tr(e),o=await Go();if(o){let s=o.number;return o.title!==t&&(a.info(`Adopting open dev \u2192 main PR #${s} ("${o.title}") and retitling for ${r}`),await Be(`retitle dev \u2192 main PR #${s} to "${t}"`,`update manually: gh pr edit ${s} --title "${t}"`,async()=>{await M`gh pr edit ${s} --title ${t}`})),s}await Be(`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 M`gh pr create --base main --head dev --title ${t} --body ""`});let n=await Go();if(!n)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 n.number},Ci=async e=>{let r=T(e);if(await vi(e)){a.info(`\u2713 RC PR for ${r} already merged into main \u2014 skipping`);return}let o=await xi(e);await Be(`merge RC PR #${o} (dev \u2192 main) for ${r}`,`check 'gh pr view ${o}' for mergeability and required reviews`,async()=>{await M`gh pr merge ${o} --squash --admin`})},Ei=async()=>{M.quiet=!1,await Be("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await M`gh workflow run deploy-all.yml --ref main -f environment=prod`}),M.quiet=!0},Pi=async()=>{await Be("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 M`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},Ti=async e=>{let r=await Ce();if(!r){a.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let t=D(e);await Gt({versionName:t},r)}catch(t){a.error({err:zt(t)},"Failed to deliver Jira release (non-blocking)")}},Xr=async e=>{let{version:r,confirmedCommand:t}=e;d.start("release-deliver");let{selectedReleaseBranch:o,releasePrTitle:n}=r?await ki(r):await yi(),s=R(o);if(!s)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=T(s);d.addOption("--version",i),a.info(`Delivering ${s.kind==="name"?"named release":"version"} ${o}`);let l=C(n),c=t?!0:await gi({message:`Are you sure you want to deliver version ${o} to production?`});t||d.setInteractive(),c||(a.info("Operation cancelled. Exiting..."),wi.exit(0)),d.addOption("--yes",!0),M.quiet=!0,await Ri(o),await bi({selectedReleaseBranch:o,releaseType:l}),l!=="hotfix"&&await Ci(s),await Ei(),await Pi(),M.quiet=!1,await Ti(s),a.info(`Successfully delivered ${o} to production!`),d.print();let p={releaseBranch:o,version:i,type:l,success:!0};return{content:h(JSON.stringify(p,null,2)),structuredContent:p}},$i=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:br.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:br.string().describe("The release branch that was delivered"),version:br.string().describe("The version that was delivered"),type:br.enum(["regular","hotfix"]).describe("Release type"),success:br.boolean().describe("Whether the delivery was successful")},handler:Xr});import qo from"@inquirer/select";import{z as ie}from"zod";import{$ as Xt}from"zx";var Yr=async e=>{let{version:r,env:t,skipTerraform:o}=e;d.start("release-deploy-all");let n="";if(r)n=r==="dev"?"dev":X(r);else{d.setInteractive();let p=await E(),m=p.map(w=>w.branch),u=new Map(p.map(w=>[w.branch,C(w.title)])),f=await $();n=await qo({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...A({branches:m,descriptions:f,types:u})]})}let s=hr(n);d.addOption("--version",s);let{environments:i}=await x(),l="";if(t?l=t:(d.setInteractive(),l=await qo({message:"\u{1F9EA} Select environment",choices:i.map(p=>({name:p,value:p}))})),d.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&&d.addOption("--skip-terraform",!0);try{Xt.quiet=!0,await Xt`gh workflow run deploy-all.yml --ref ${n} -f environment=${l} ${c?["-f","skip_terraform_deploy=true"]:[]}`,Xt.quiet=!1,a.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${n} and environment: ${l}`),d.print();let m={releaseBranch:n,version:s,environment:l,skipTerraformDeploy:c,success:!0};return{content:h(JSON.stringify(m,null,2)),structuredContent:m}}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"})}},Si=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:ie.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:ie.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),skipTerraform:ie.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:ie.string().describe("The release branch that was deployed"),version:ie.string().describe("The version that was deployed"),environment:ie.string().describe("The environment deployed to"),skipTerraformDeploy:ie.boolean().describe("Whether terraform deployment was skipped"),success:ie.boolean().describe("Whether the deployment was successful")},handler:Yr});import Ii from"@inquirer/checkbox";import zo from"@inquirer/select";import Ai from"node:fs/promises";import{resolve as _i}from"node:path";import Ni from"yaml";import{z as V}from"zod";import{$ as Yt}from"zx";var Zr=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":X(r);else{d.setInteractive();let w=await E(),S=w.map(Se=>Se.branch),I=new Map(w.map(Se=>[Se.branch,C(Se.title)])),N=await $();s=await zo({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...A({branches:S,descriptions:N,types:I})]})}let i=hr(s);d.addOption("--version",i);let{environments:l}=await x(),c="";if(t?c=t:(d.setInteractive(),c=await zo({message:"\u{1F9EA} Select environment",choices:l.map(w=>({name:w,value:w}))})),d.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 Oi();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 m=[];if(o&&o.length>0?m=o:(d.setInteractive(),m=await Ii({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:p.map(w=>({name:w,value:w}))})),d.addOption("--services",m),m.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=m.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=n??!1;f&&d.addOption("--skip-terraform",!0);try{Yt.quiet=!0;let w=m.flatMap(N=>["-f",`${N}=true`]);await Yt`gh workflow run deploy-selected-services.yml --ref ${s} -f environment=${c} ${w} ${f?["-f","skip_terraform_deploy=true"]:[]}`,Yt.quiet=!1,a.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${s}, environment: ${c}, services: ${m.join(", ")}`),d.print();let I={releaseBranch:s,version:i,environment:c,services:m,skipTerraformDeploy:f,success:!0};return{content:h(JSON.stringify(I,null,2)),structuredContent:I}}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"})}},Oi=async()=>{let e=await b(),r=_i(e,".github/workflows/deploy-selected-services.yml"),t=await Ai.readFile(r,"utf-8"),n=Ni.parse(t).on.workflow_dispatch.inputs,s=[];for(let[i,l]of Object.entries(n))l.type==="boolean"&&i!=="skip_terraform_deploy"&&s.push(i);return s},ji=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:V.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:V.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),services:V.array(V.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:V.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:V.string().describe("The release branch that was deployed"),version:V.string().describe("The version that was deployed"),environment:V.string().describe("The environment deployed to"),services:V.array(V.string()).describe("The services that were deployed"),skipTerraformDeploy:V.boolean().describe("Whether terraform deployment was skipped"),success:V.boolean().describe("Whether the deployment was successful")},handler:Zr});import{z as Ke}from"zod";var Qr=async()=>{let r=(await E()).flatMap(i=>{let l=R(i.branch);return l?[{version:T(l),jiraKey:D(l),type:C(i.title)}]:[]}),t=await $(),o=Math.max(...r.map(i=>i.version.length)),n=r.map(i=>{let l=Ve(i.version,i.type,o),c=t.get(i.jiraKey);return c?`${l} ${c}`:l});a.info(`All release branches:
|
|
82
|
+
`);d.print();let p={successfulMerges:s.length-c.length,failedMerges:c.length,failedBranches:c,totalBranches:s.length};return{content:h(JSON.stringify(p,null,2)),structuredContent:p}},di=async e=>{try{return await q`git switch ${e}`,await q`git pull origin ${e}`,await q`git merge origin/dev --no-edit`,await q`git push origin ${e}`,await q`git switch dev`,a.info(`Successfully merged dev into ${e}`),!0}catch(r){let t=new f(r,{operation:`merge dev into ${e}`,remediation:"resolve conflicts manually or rerun after 'git fetch origin'"});return a.error({error:r,branch:e,msg:t.message}),await q`git reset --merge HEAD~1`,!1}},ui=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:qe.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:qe.number().describe("Number of successful merges"),failedMerges:qe.number().describe("Number of failed merges"),failedBranches:qe.array(qe.string()).describe("List of branches that failed to merge"),totalBranches:qe.number().describe("Total number of branches processed")},handler:Yr});import ki from"@inquirer/confirm";import yi from"@inquirer/select";import Ri from"node:process";import{z as Er}from"zod";import{$ as D}from"zx";var zo=(e,r)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-r).trim()},Qt=e=>{if(e===null||typeof e!="object")return{message:String(e)};let r=e,t={};e instanceof Error?(t.name=e.name,t.message=e.message):typeof r.message=="string"&&(t.message=r.message);let o=r.exitCode;(typeof o=="number"||o===null)&&(t.exitCode=o);let n=zo(r.stderr,500);n&&(t.stderr=n);let s=zo(r.stdout,200);return s&&(t.stdout=s),t};import{$ as eo}from"zx";var fi=/\bv(\d+\.\d+\.\d+)\b/g,U=e=>e.trim().replace(/\s+/g," ").replace(fi,"$1");import{$ as Ho}from"zx";var yr=async e=>{try{let r=(await Ho`cmux list-workspaces`.quiet()).stdout,t=gi(r,e);if(!t)return;await Ho`cmux close-workspace --workspace ${t}`.quiet()}catch(r){a.debug({error:r,title:e},"cmux: skipped closing workspace")}},gi=(e,r)=>{let t=U(r);for(let o of e.split(`
|
|
83
|
+
`)){let n=o.match(/^[* ]\s*(workspace:\d+)\s+(.+?)(?:\s+\[selected\])?\s*$/);if(!n)continue;let s=n[1],i=n[2]?.trim()??"";if(U(i)===t)return s}};import{$ as hi}from"zx";var Rr=async()=>{try{let e=(await hi`cmux list-workspaces`.quiet()).stdout,r=new Set;for(let t of e.split(`
|
|
84
|
+
`)){let o=t.match(/^[* ]\s*workspace:\d+\s+(.+?)(?:\s+\[selected\])?\s*$/);if(!o)continue;let n=o[1]?.trim();n&&r.add(U(n))}return r}catch(e){return a.debug({error:e},"cmux: skipped listing workspace titles"),new Set}};import{$ as br}from"zx";var xr=async e=>{let{cwd:r,title:t}=e,o=(await br`cmux workspace create --cwd ${r}`).stdout,n=vi(o),s=(await br`cmux list-pane-surfaces --workspace ${n}`).stdout,i=wi(s);await br`cmux new-split right --workspace ${n} --surface ${i}`,await br`cmux new-split down --workspace ${n} --surface ${i}`,t&&await br`cmux workspace rename --workspace ${n} --title ${t}`},wi=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]},vi=e=>{let r=e.match(/workspace:\d+/);if(!r)throw new Error("cmux: could not locate workspace ref in workspace create output");return r[0]};var Z=e=>{let{repoName:r,branch:t}=e,o=b(t),n=o?T(o):t;return`${r} ${n}`};var Cr=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=Z({repoName:o,branch:l});return await yr(p),await eo`git worktree remove ${c}`,l})),i=[];for(let[l,c]of s.entries())if(c.status==="fulfilled")i.push(c.value);else{let p=r[l],m=new f(c.reason,{operation:`remove worktree for ${p}`,remediation:"check 'git worktree list' for the path; uncommitted changes block removal"});a.error({error:c.reason,msg:m.message})}return n&&i.length===r.length&&(await eo`git worktree prune`,await eo`rm -rf ${t}`,a.info(`\u{1F5D1}\uFE0F Removed worktree folder: ${t}`),a.info("")),i};var Ge=async(e,r,t)=>{try{return await t()}catch(o){throw a.error({err:Qt(o)},`\u274C Failed to ${e}`),new f(o,{operation:e,remediation:r})}},Yo=async e=>{let r=await D`gh pr list --head ${e} --state all --json number,state,title --limit 1`;return JSON.parse(r.stdout)[0]??null},bi=async e=>{let r=Ir(e),t=await D`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},Xo=async()=>{let e=await D`gh pr list --head dev --base main --state open --json number,state,title --limit 5`;return JSON.parse(e.stdout)[0]??null},xi=async e=>{let r=Y(e),t=await Yo(r);if(!t)throw a.error(`\u274C No PR found for branch ${r}.`),new f(void 0,{operation:`deliver release ${r}`,remediation:`confirm a PR exists ('gh pr list --head ${r} --state all')`});return{selectedReleaseBranch:r,releasePrTitle:t.title}},Ci=async()=>{let e=await E(),r=e.map(i=>i.branch),t=new Map(e.map(i=>[i.branch,C(i.title)]));d.setInteractive();let o=await $(),n=await yi({message:"\u{1F33F} Select release branch",choices:A({branches:r,descriptions:o,types:t})}),s=e.find(i=>i.branch===n);if(!s)throw a.error(`\u274C Release branch ${n} not found in open PRs.`),new f(void 0,{operation:`deliver release ${n}`,remediation:`confirm an open PR exists for ${n} ('gh pr list')`});return{selectedReleaseBranch:n,releasePrTitle:s.title}},Ei=async e=>{if(!(await j("release")).includes(e))return;let[t,o]=await Promise.all([R(),F()]),n=`${t}${K}`;if((await Cr({branches:[e],worktreeDir:n,repoName:o})).length===0)throw new f(void 0,{operation:`remove worktree for ${e} before merge`,remediation:`run manually: git worktree remove ${n}/${e} (use --force if uncommitted changes)`})},Pi=async e=>{let{selectedReleaseBranch:r,releaseType:t}=e,o=t==="hotfix"?"main":"dev",n=await Yo(r);if(!n)throw new f(void 0,{operation:`look up release PR for ${r}`,remediation:"verify the PR exists in GitHub"});if(n.state==="MERGED"){a.info(`\u2713 Release PR ${r} already merged \u2014 skipping`);return}if(n.state==="CLOSED")throw new f(void 0,{operation:`merge release PR ${r} into ${o}`,remediation:"the PR is closed without merge; reopen it or create a new release"});await Ge(`merge release PR ${r} into ${o}`,`check 'gh pr view ${r}' for mergeability and required reviews`,async()=>{await D`gh pr merge ${r} --squash --admin --delete-branch`})},Ti=async e=>{let r=T(e),t=Ir(e),o=await Xo();if(o){let s=o.number;return o.title!==t&&(a.info(`Adopting open dev \u2192 main PR #${s} ("${o.title}") and retitling for ${r}`),await Ge(`retitle dev \u2192 main PR #${s} to "${t}"`,`update manually: gh pr edit ${s} --title "${t}"`,async()=>{await D`gh pr edit ${s} --title ${t}`})),s}await Ge(`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 D`gh pr create --base main --head dev --title ${t} --body ""`});let n=await Xo();if(!n)throw new f(void 0,{operation:`look up RC PR for ${r}`,remediation:"verify the RC PR was created ('gh pr list --head dev --base main')"});return n.number},$i=async e=>{let r=T(e);if(await bi(e)){a.info(`\u2713 RC PR for ${r} already merged into main \u2014 skipping`);return}let o=await Ti(e);await Ge(`merge RC PR #${o} (dev \u2192 main) for ${r}`,`check 'gh pr view ${o}' for mergeability and required reviews`,async()=>{await D`gh pr merge ${o} --squash --admin`})},Si=async()=>{D.quiet=!1,await Ge("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await D`gh workflow run deploy-all.yml --ref main -f environment=prod`}),D.quiet=!0},Ii=async()=>{await Ge("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 D`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},Ai=async e=>{let r=await Ee();if(!r){a.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let t=L(e);await Xt({versionName:t},r)}catch(t){a.error({err:Qt(t)},"Failed to deliver Jira release (non-blocking)")}},Zr=async e=>{let{version:r,confirmedCommand:t}=e;d.start("release-deliver"),await M({operation:"deliver release"});let{selectedReleaseBranch:o,releasePrTitle:n}=r?await xi(r):await Ci(),s=b(o);if(!s)throw new f(void 0,{operation:`deliver release ${o}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let i=T(s);d.addOption("--version",i),a.info(`Delivering ${s.kind==="name"?"named release":"version"} ${o}`);let l=C(n),c=t?!0:await ki({message:`Are you sure you want to deliver version ${o} to production?`});t||d.setInteractive(),c||(a.info("Operation cancelled. Exiting..."),Ri.exit(0)),d.addOption("--yes",!0),D.quiet=!0,await Ei(o),await Pi({selectedReleaseBranch:o,releaseType:l}),l!=="hotfix"&&await $i(s),await Si(),await Ii(),D.quiet=!1,await Ai(s),a.info(`Successfully delivered ${o} to production!`),d.print();let p={releaseBranch:o,version:i,type:l,success:!0};return{content:h(JSON.stringify(p,null,2)),structuredContent:p}},_i=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:Er.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:Er.string().describe("The release branch that was delivered"),version:Er.string().describe("The version that was delivered"),type:Er.enum(["regular","hotfix"]).describe("Release type"),success:Er.boolean().describe("Whether the delivery was successful")},handler:Zr});import Zo from"@inquirer/select";import{z as ae}from"zod";import{$ as ro}from"zx";var Qr=async e=>{let{version:r,env:t,skipTerraform:o}=e;d.start("release-deploy-all");let n="";if(r)n=r==="dev"?"dev":Y(r);else{d.setInteractive();let p=await E(),m=p.map(w=>w.branch),u=new Map(p.map(w=>[w.branch,C(w.title)])),g=await $();n=await Zo({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...A({branches:m,descriptions:g,types:u})]})}let s=kr(n);d.addOption("--version",s);let{environments:i}=await x(),l="";if(t?l=t:(d.setInteractive(),l=await Zo({message:"\u{1F9EA} Select environment",choices:i.map(p=>({name:p,value:p}))})),d.addOption("--env",l),!i.includes(l))throw new f(void 0,{operation:"launch deploy-all workflow",remediation:`pass one of: ${i.join(", ")}`,stderrExcerpt:`invalid environment: ${l}`});let c=o??!1;c&&d.addOption("--skip-terraform",!0);try{ro.quiet=!0,await ro`gh workflow run deploy-all.yml --ref ${n} -f environment=${l} ${c?["-f","skip_terraform_deploy=true"]:[]}`,ro.quiet=!1,a.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${n} and environment: ${l}`),d.print();let m={releaseBranch:n,version:s,environment:l,skipTerraformDeploy:c,success:!0};return{content:h(JSON.stringify(m,null,2)),structuredContent:m}}catch(p){throw a.error({error:p},"\u274C Error launching workflow"),new f(p,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},Ni=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:ae.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:ae.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),skipTerraform:ae.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:ae.string().describe("The release branch that was deployed"),version:ae.string().describe("The version that was deployed"),environment:ae.string().describe("The environment deployed to"),skipTerraformDeploy:ae.boolean().describe("Whether terraform deployment was skipped"),success:ae.boolean().describe("Whether the deployment was successful")},handler:Qr});import Oi from"@inquirer/checkbox";import Qo from"@inquirer/select";import ji from"node:fs/promises";import{resolve as Fi}from"node:path";import Mi from"yaml";import{z as V}from"zod";import{$ as to}from"zx";var et=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":Y(r);else{d.setInteractive();let w=await E(),S=w.map(Ie=>Ie.branch),I=new Map(w.map(Ie=>[Ie.branch,C(Ie.title)])),N=await $();s=await Qo({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...A({branches:S,descriptions:N,types:I})]})}let i=kr(s);d.addOption("--version",i);let{environments:l}=await x(),c="";if(t?c=t:(d.setInteractive(),c=await Qo({message:"\u{1F9EA} Select environment",choices:l.map(w=>({name:w,value:w}))})),d.addOption("--env",c),!l.includes(c))throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass one of: ${l.join(", ")}`,stderrExcerpt:`invalid environment: ${c}`});let p=await Di();if(p.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:"check .github/workflows/deploy-selected-services.yml for boolean service inputs",stderrExcerpt:"no services found in workflow file"});let m=[];if(o&&o.length>0?m=o:(d.setInteractive(),m=await Oi({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:p.map(w=>({name:w,value:w}))})),d.addOption("--services",m),m.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${p.join(", ")}`,stderrExcerpt:"no services selected"});let u=m.filter(w=>!p.includes(w));if(u.length>0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${p.join(", ")}`,stderrExcerpt:`invalid services: ${u.join(", ")}`});let g=n??!1;g&&d.addOption("--skip-terraform",!0);try{to.quiet=!0;let w=m.flatMap(N=>["-f",`${N}=true`]);await to`gh workflow run deploy-selected-services.yml --ref ${s} -f environment=${c} ${w} ${g?["-f","skip_terraform_deploy=true"]:[]}`,to.quiet=!1,a.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${s}, environment: ${c}, services: ${m.join(", ")}`),d.print();let I={releaseBranch:s,version:i,environment:c,services:m,skipTerraformDeploy:g,success:!0};return{content:h(JSON.stringify(I,null,2)),structuredContent:I}}catch(w){throw a.error({error:w},"\u274C Error launching workflow"),new f(w,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},Di=async()=>{let e=await R(),r=Fi(e,".github/workflows/deploy-selected-services.yml"),t=await ji.readFile(r,"utf-8"),n=Mi.parse(t).on.workflow_dispatch.inputs,s=[];for(let[i,l]of Object.entries(n))l.type==="boolean"&&i!=="skip_terraform_deploy"&&s.push(i);return s},Li=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:V.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:V.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),services:V.array(V.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:V.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:V.string().describe("The release branch that was deployed"),version:V.string().describe("The version that was deployed"),environment:V.string().describe("The environment deployed to"),services:V.array(V.string()).describe("The services that were deployed"),skipTerraformDeploy:V.boolean().describe("Whether terraform deployment was skipped"),success:V.boolean().describe("Whether the deployment was successful")},handler:et});import{z as Ue}from"zod";var rt=async()=>{let r=(await E()).flatMap(i=>{let l=b(i.branch);return l?[{version:T(l),jiraKey:L(l),type:C(i.title)}]:[]}),t=await $(),o=Math.max(...r.map(i=>i.version.length)),n=r.map(i=>{let l=Ke(i.version,i.type,o),c=t.get(i.jiraKey);return c?`${l} ${c}`:l});a.info(`All release branches:
|
|
85
85
|
`),a.info(`
|
|
86
86
|
${n.join(`
|
|
87
87
|
`)}
|
|
88
|
-
`);let s={releases:r.map(i=>({version:i.version,type:i.type,description:t.get(i.jiraKey)||null})),count:r.length};return{content:h(JSON.stringify(s,null,2)),structuredContent:s}},
|
|
89
|
-
`).map(r=>{let t=r.indexOf(" ");return t===-1?null:
|
|
90
|
-
- `),o=r?!0:await
|
|
88
|
+
`);let s={releases:r.map(i=>({version:i.version,type:i.type,description:t.get(i.jiraKey)||null})),count:r.length};return{content:h(JSON.stringify(s,null,2)),structuredContent:s}},Wi=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: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 release branches"),count:Ue.number().describe("Number of release branches")},handler:rt});import cn from"@inquirer/confirm";import sn from"@inquirer/select";import nt from"node:process";import{z as P}from"zod";import{question as mo}from"zx";import{$ as ot}from"zx";var ce=e=>e.slice(1).split(".").map(Number),oo=e=>[...e].sort((r,t)=>{let[o,n,s]=ce(r),[i,l,c]=ce(t);return o!==i?(o??0)-(i??0):n!==l?(n??0)-(l??0):(s??0)-(c??0)});var rn="next",Bi=/^v?(\d+)\.(\d+)\.(\d+)$/,Vi=e=>e.replace(/^.*release\//,""),tn=e=>{let r=Vi(e.trim()),t=Bi.exec(r);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null},en=e=>`${e[0]}.${e[1]}.${e[2]}`,so=e=>{let r=[...e.remoteBranches??[],...e.jiraVersions??[]],t=[],o=new Set;for(let n of r){let s=tn(n);if(!s)continue;let i=en(s);o.has(i)||(o.add(i),t.push(s))}return oo(t.map(n=>en(n))).map(n=>ce(`v${n}`))},Te=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},tt=(e,r)=>{if(e.length===0)throw new Te;let t=e[e.length-1];if(r==="hotfix"){let[s,i]=t,l=e.reduce((c,p)=>p[0]===s&&p[1]===i?Math.max(c,p[2]):c,0);return`${s}.${i}.${l+1}`}let[o,n]=t;return`${o}.${n+1}.0`},on=e=>e.trim().toLowerCase()===rn,Ji=e=>e==="regular"||e==="hotfix",nn=e=>"name"in e,io=e=>{let r=e.trim();if(r==="")throw new Error("Release spec is empty");let t=r.indexOf(":");if(t===-1)return{version:r,type:"regular"};let o=r.slice(0,t).trim(),n=r.slice(t+1),s=n.indexOf(":"),i=s===-1?n.trim():n.slice(0,s).trim(),l=s===-1?"":n.slice(s+1).trim(),c=i.toLowerCase();if(!Ji(c))throw new Error(`Invalid release type "${i}". Expected "regular" or "hotfix".`);let p={version:o,type:c};return l!==""&&(p.description=l),p},no=(e,r)=>r!==void 0&&r!==""?{...e,description:r}:e,Ki=e=>{let r=e.name.trim();return fe(r),no({id:{kind:"name",name:r,raw:r},type:e.type},e.description)},ao=(e,r)=>{let t=[...r];return e.map(o=>{if(nn(o))return Ki(o);let n=o.version.trim();if(n==="")throw new Error("Release entry has an empty version");if(on(n)){let l=tt(t,o.type);return t.push(ce(`v${l}`)),no({id:G(l),type:o.type},o.description)}let s=tn(n);if(!s)throw new Error(`Invalid version "${n}". Expected semver like "1.2.5" or the token "next".`);let i=`${s[0]}.${s[1]}.${s[2]}`;return t.push(s),no({id:G(i),type:o.type},o.description)})},co=e=>e.some(r=>!nn(r)&&on(r.version));var qi=e=>e.split(`
|
|
89
|
+
`).map(r=>{let t=r.indexOf(" ");return t===-1?null:b(r.slice(t+1))}).filter(r=>r!==null&&r.kind==="version").map(r=>r.raw),Gi=async()=>{let e=ot.quiet;try{ot.quiet=!0;let r=await ot`git ls-remote --heads origin 'release/v*'`;return qi(r.stdout)}finally{ot.quiet=e}},Ui=async()=>{let e=await Ee();return e?(await Be(e)).map(t=>t.name):[]},lo=async()=>{let[e,r]=await Promise.allSettled([Gi(),Ui()]);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"),so({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:r.status==="fulfilled"?r.value:[]})};var zi='"1.2.5" or "next"',Hi=(e,r)=>{try{return tt(e,r)}catch(t){if(t instanceof Te)return null;throw t}},po=(e,r)=>{try{return ao(e,r)}catch(t){throw t instanceof Te?new f(t,{operation:"resolve release version",remediation:'pass an explicit version (e.g. "1.2.5") instead of "next" when there are no prior versions'}):t instanceof z?new f(t,{operation:"validate release name",remediation:'use a kebab-case name like "checkout-redesign" (lowercase, digits, single hyphens, not a reserved word)'}):t}},Xi=async(e,r)=>{let t=Hi(e,r),o=t?` [${t}]`:"",n=(await mo(` Version (e.g. ${zi})${o}: `)).trim(),s=n===""?t??"":n;return s===""&&(a.error("No version provided. Exiting..."),nt.exit(1)),s},Yi=async()=>{let e=(await mo(' Name (kebab-case, e.g. "checkout-redesign"): ')).trim();e===""&&(a.error("No name provided. Exiting..."),nt.exit(1));try{fe(e)}catch(r){let t=r instanceof Error?r.message:String(r);a.error(`${t} Exiting...`),nt.exit(1)}return e},Zi=async e=>{d.setInteractive();let r=null,t=[],o=async()=>(r===null&&(r=await e(),t.push(...r)),t),n=[],s=!0;for(;s;){let i=n.length+1,l=await sn({message:`Release #${i} \u2014 version or name?`,choices:[{name:"version (semver / next)",value:"version"},{name:"name (free-form)",value:"name"}],default:"version"}),c=await sn({message:`Release #${i} \u2014 select type:`,choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"}),p;if(l==="name"){let u=await Yi();p=po([{name:u,type:c}],[])[0]}else{let u=await Xi(await o(),c);p=po([{version:u,type:c}],t)[0],p.id.kind==="version"&&t.push(ce(`v${p.id.raw}`))}let m=(await mo(" Description (optional, press Enter to skip): ")).trim();n.push({...p,...m!==""?{description:m}:{}}),s=await cn({message:"Add another release?",default:!1})}return n},Qi=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 ")},an=e=>{for(let r of e){if(r.id.kind==="name"){d.addOption("--name",r.id.name);continue}let t=r.description?`${r.id.raw}:${r.type}:${r.description}`:`${r.id.raw}:${r.type}`;d.addOption("--release",t)}},ea=async(e,r)=>{if(e&&e.length>0){let o=co(e)?await r():[],n=po(e,o);return an(n),n}let t=await Zi(r);return an(t),t},ra=e=>{if(new Set(e.map(t=>t.type)).size>1)throw new f(void 0,{operation:"create release",remediation:"create regular and hotfix releases in separate invocations",stderrExcerpt:"mixed regular and hotfix releases in one batch are not supported"})},ta=async(e,r)=>{let t=e.map(Qi).join(`
|
|
90
|
+
- `),o=r?!0:await cn({message:`Create the following ${e.length} release(s)?
|
|
91
91
|
- ${t}
|
|
92
|
-
`});r||d.setInteractive(),o||(a.info("Operation cancelled. Exiting..."),
|
|
93
|
-
`),{result:s}}catch(s){let i=new
|
|
94
|
-
`),{failure:{version:o,error:i.message}}}},
|
|
92
|
+
`});r||d.setInteractive(),o||(a.info("Operation cancelled. Exiting..."),nt.exit(0)),d.addOption("--yes",!0)},oa=async e=>{let{entry:r,jiraConfig:t}=e,o=T(r.id),n=r.id.kind==="version"?`v${r.id.raw}`:r.id.name;try{await Yt(r.type);let s=await Zt({id:r.id,jiraConfig:t,description:r.description,type:r.type});return a.info(`\u2705 Successfully created release: ${n} (${r.type})`),a.info(`\u{1F517} GitHub PR: ${s.prUrl}`),a.info(`\u{1F517} Jira Version: ${s.jiraVersionUrl}
|
|
93
|
+
`),{result:s}}catch(s){let i=new f(s,{operation:`create release ${n} (${r.type})`,remediation:"verify the version or name is unique and the base branch is clean"});return a.error(`\u274C ${i.message}
|
|
94
|
+
`),{failure:{version:o,error:i.message}}}},na=(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.`)},st=async e=>{let{releases:r,confirmedCommand:t}=e;d.start("release-create");let o=await Ve(),n=null,i=await ea(r,async()=>(n===null&&(n=await lo()),n));if(i.length===0)throw new f(void 0,{operation:"create release",remediation:'pass at least one entry in "releases" (e.g. [{ version: "1.2.5", type: "regular" }])',stderrExcerpt:"no releases provided"});ra(i),await M({operation:"create release",requiredBranch:Je(i[0].type)}),await ta(i,!!t);let l=[],c=[];for(let m of i){let{result:u,failure:g}=await oa({entry:m,jiraConfig:o});u&&l.push(u),g&&c.push(g)}na(i.length,l.length,c.length),d.print();let p={createdBranches:l.map(m=>m.branchName),successCount:l.length,failureCount:c.length,releases:l,failedReleases:c};return{content:h(JSON.stringify(p,null,2)),structuredContent:p}},sa=v({name:"release-create",description:'Create one or more releases in a single call. Each entry in "releases" carries EITHER a "version" (semver or the literal token "next") OR a "name" (free-form kebab-case identifier) \u2014 exactly one is required and they are mutually exclusive. Each entry also has its own type (regular|hotfix, default regular) and optional description; all entries in one call must share the same type \u2014 mixed regular+hotfix batches are rejected (create them in separate invocations). For each release this tool switches to the appropriate base branch (dev for regular, main for hotfix), cuts the release branch (release/v<semver> for versions, release/n/<name> for names), opens a GitHub release PR, and creates the matching Jira fix version (v<semver> for versions, <name> for names). The literal token "next" auto-increments from the union of remote release branches and Jira fix versions (regular bumps minor + resets patch; hotfix bumps patch on the highest minor); multiple "next" tokens advance sequentially. Named releases never auto-bump and "next" is version-only. Must be run from the main repository checkout (not a linked worktree) on the matching base branch with a clean working tree. Confirmation is auto-skipped for MCP calls, so the caller is responsible for gating. Continues on per-release failure and reports successes/failures.',inputSchema:{releases:P.array(P.object({version:P.string().optional().describe('Version to create (e.g., "1.2.5") or the literal token "next" for auto-increment. Mutually exclusive with "name".'),name:P.string().optional().describe('Free-form kebab-case release name (e.g., "checkout-redesign"). Mutually exclusive with "version". Named releases never auto-bump.'),type:P.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" (branches off dev) or "hotfix" (branches off main).'),description:P.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:P.array(P.string()).describe("List of created release branch names"),successCount:P.number().describe("Number of releases created successfully"),failureCount:P.number().describe("Number of releases that failed"),releases:P.array(P.object({version:P.string().describe("Version number"),type:P.enum(["regular","hotfix"]).describe("Release type"),branchName:P.string().describe("Release branch name"),prUrl:P.string().describe("GitHub PR URL"),jiraVersionUrl:P.string().describe("Jira version URL")})).describe("Detailed information for each created release with URLs"),failedReleases:P.array(P.object({version:P.string().describe("Version number that failed"),error:P.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:st});import ia from"@inquirer/confirm";import aa from"@inquirer/select";import ca from"node:process";import{z as le}from"zod";import{question as la}from"zx";var ln=(e,r)=>`${e.baseUrl}/projects/${r.projectId}/versions/${r.id}/tab/release-report-all-issues`,pa=(e,r)=>r.trim()!==""?`${e}
|
|
95
95
|
|
|
96
96
|
${r}`:`${e}
|
|
97
|
-
`,
|
|
98
|
-
(press Enter to keep current): `)).replace(/\n$/,"");return o===""?e:o},
|
|
97
|
+
`,ma=async()=>{let e=await E(),r=e.map(s=>s.branch),t=new Map(e.map(s=>[s.branch,C(s.title)])),o=await $(),n=await aa({message:"\u{1F33F} Select release branch",choices:A({branches:r,descriptions:o,types:t})});return{branch:n,type:t.get(n)||"regular"}},da=async e=>{let t=(await E()).find(o=>o.branch===e);if(!t)throw new f(void 0,{operation:`edit description for ${e}`,remediation:`confirm an open PR exists for ${e} ('gh pr list')`});return C(t.title)},ua=async e=>{let r=e===""?"(no current description)":`current: "${e}"`,o=(await la(` New description ${r}
|
|
98
|
+
(press Enter to keep current): `)).replace(/\n$/,"");return o===""?e:o},it=async e=>{let{version:r,description:t,confirmedCommand:o}=e;d.start("release-desc-edit");let n=await Ve(),s;r?(s=Y(r),await da(s)):(d.setInteractive(),s=(await ma()).branch);let i=b(s);if(!i)throw new f(void 0,{operation:`edit description for ${s}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let l=T(i);d.addOption("--version",l);let c=L(i),p=await qr(c,n);if(!p)throw new f(void 0,{operation:`edit description for ${c}`,remediation:`create the Jira fix version "${c}" first or pick a different release`});let m=p.description??"",u;if(t!==void 0?(u=t,d.addOption("--description",u)):(d.setInteractive(),u=await ua(m)),u===m){a.info(`No change \u2014 description for ${c} is already: "${m}"`),d.print();let N={version:l,branch:s,jiraVersionUrl:ln(n,p),previousDescription:m,newDescription:u,changed:!1};return{content:h(JSON.stringify(N,null,2)),structuredContent:N}}let g=o?!0:await ia({message:`Update description for ${c}?
|
|
99
99
|
from: "${m}"
|
|
100
100
|
to: "${u}"
|
|
101
|
-
`});o||d.setInteractive(),
|
|
102
|
-
`),d.print();let I={version:l,branch:s,jiraVersionUrl:w,previousDescription:m,newDescription:u,changed:!0};return{content:h(JSON.stringify(I,null,2)),structuredContent:I}},
|
|
103
|
-
`,"utf-8"),{added:c,skipped:p}};import
|
|
104
|
-
`,"utf-8");let m=[],u=[];for(let
|
|
101
|
+
`});o||d.setInteractive(),g||(a.info("Operation cancelled. Exiting..."),ca.exit(0)),d.addOption("--yes",!0),await Gr({versionId:p.id,description:u},n);let w=ln(n,p),S=pa(w,u);await Xr({branch:s,body:S}),a.info(`\u2705 Updated description for ${c}`),a.info(`\u{1F517} Jira Version: ${w}`),a.info(`\u{1F517} PR branch: ${s}
|
|
102
|
+
`),d.print();let I={version:l,branch:s,jiraVersionUrl:w,previousDescription:m,newDescription:u,changed:!0};return{content:h(JSON.stringify(I,null,2)),structuredContent:I}},fa=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:le.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:le.string().describe("New description. Empty string clears the description.")},outputSchema:{version:le.string().describe("Release version"),branch:le.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/n/checkout-redesign")'),jiraVersionUrl:le.string().describe("Jira fix version URL"),previousDescription:le.string().describe("The description before the update"),newDescription:le.string().describe("The description after the update"),changed:le.boolean().describe("Whether the description actually changed")},handler:it});import{z as ga}from"zod";var at=async()=>{let e=Fr.version;a.info(e);let r={version:e};return{content:h(JSON.stringify(r,null,2)),structuredContent:r}},ha=v({name:"version",description:"Print the installed infra-kit CLI version",inputSchema:{},outputSchema:{version:ga.string().describe("Installed infra-kit CLI version (from package.json)")},handler:at});import va from"@inquirer/checkbox";import fo from"@inquirer/confirm";import ka from"@inquirer/select";import ya from"node:process";import{z as pe}from"zod";import{$ as Se}from"zx";import pn from"node:fs/promises";import ct from"node:path";var Pr=async e=>{let{workspacePath:r,folderPaths:t}=e,o=ct.dirname(r),n;try{n=await pn.readFile(r,"utf-8")}catch(m){throw new Error(`Cursor workspace file not found at ${r}: ${m.message}`)}let s;try{s=JSON.parse(n)}catch(m){throw new Error(`Failed to parse ${r} as JSON. Comments (JSONC) are not supported. ${m.message}`)}let i=s.folders??[],l=new Set(i.map(m=>ct.resolve(o,m.path))),c=[],p=[];for(let m of t){let u=ct.resolve(m);if(l.has(u)){p.push(m);continue}let g=ct.relative(o,u);i.push({path:g}),l.add(u),c.push(m)}return s.folders=i,await pn.writeFile(r,`${JSON.stringify(s,null,2)}
|
|
103
|
+
`,"utf-8"),{added:c,skipped:p}};import wa from"node:fs/promises";import pt from"node:path";import mn from"node:fs/promises";import lt from"node:path";var $e=async e=>{let{workspacePath:r,folderPaths:t}=e,o=lt.dirname(r),n;try{n=await mn.readFile(r,"utf-8")}catch(g){throw new Error(`Cursor workspace file not found at ${r}: ${g.message}`)}let s;try{s=JSON.parse(n)}catch(g){throw new Error(`Failed to parse ${r} as JSON. Comments (JSONC) are not supported. ${g.message}`)}let i=s.folders??[],l=new Set(t.map(g=>lt.resolve(g))),c=new Set,p=i.filter(g=>{let w=lt.resolve(o,g.path);return l.has(w)?(c.add(w),!1):!0});s.folders=p,await mn.writeFile(r,`${JSON.stringify(s,null,2)}
|
|
104
|
+
`,"utf-8");let m=[],u=[];for(let g of t){let w=lt.resolve(g);c.has(w)?m.push(g):u.push(g)}return{removed:m,notFound:u}};var uo=async e=>{let{workspacePath:r,worktreeDir:t,currentBranches:o}=e,n=pt.dirname(r),s=pt.resolve(`${t}/release`),i=await wa.readFile(r,"utf-8"),c=JSON.parse(i).folders??[],p=new Set(o.map(S=>pt.resolve(`${t}/${S}`))),m=[];for(let S of c){let I=pt.resolve(n,S.path);(I===s||I.startsWith(`${s}/`))&&!p.has(I)&&m.push(I)}let u=[];m.length>0&&(u=(await $e({workspacePath:r,folderPaths:m})).removed);let g=o.map(S=>`${t}/${S}`),{added:w}=g.length>0?await Pr({workspacePath:r,folderPaths:g}):{added:[]};return{added:w,removed:u}};import dn from"node:path";var Q=(e,r)=>dn.isAbsolute(e)?e:dn.resolve(r,e);var Ra="feature",ba="release",Tr=["workspace","windows","none"],mt=async e=>{let{confirmedCommand:r,all:t,versions:o,cursor:n,githubDesktop:s,cmux:i}=e;d.start("worktrees-add"),await M({operation:"create worktrees",requiredBranch:"dev"});try{let l=await j("release"),c=await R(),p=`${c}${K}`;await un(`${p}/${ba}`),await un(`${p}/${Ra}`);let m=[];if(o)m=o.split(",").map(O=>H(G(O.trim())));else{let O=await E(),de=O.map(ee=>ee.branch);if(de.length===0)return a.info("\u2139\uFE0F No open release branches found"),d.print(),{content:h(JSON.stringify({createdWorktrees:[],count:0},null,2)),structuredContent:{createdWorktrees:[],count:0}};if(t)m=de;else{d.setInteractive();let ee=new Map(O.map(Sr=>[Sr.branch,C(Sr.title)])),ue=await $();m=await va({required:!0,message:"\u{1F33F} Select release branches",choices:A({branches:de,descriptions:ue,types:ee})})}}t?d.addOption("--all",!0):d.addOption("--versions",Pe(m));let u=r?!0:await fo({message:"Are you sure you want to proceed with these worktree changes?"});r||d.setInteractive(),u||(a.info("Operation cancelled. Exiting..."),ya.exit(0)),r||d.addOption("--yes",!0);let g=await x(),w=g.ide?.provider==="cursor"?g.ide.config:void 0,S=n??w?.mode??await ka({message:"Cursor mode for created worktrees?",default:"workspace",choices:[{name:"Add to workspace file",value:"workspace",description:"Append each worktree as a folder in ide.config.workspaceConfigPath, then open the workspace"},{name:"Open separate windows",value:"windows",description:"Open each created worktree in its own Cursor window"},{name:"Skip",value:"none",description:"Do not open Cursor"}]});typeof n>"u"&&!w?.mode&&d.setInteractive(),d.addOption("--cursor",S);let I=s??g.worktrees?.openInGithubDesktop??await fo({message:"Open created worktrees in GitHub Desktop?"});typeof s>"u"&&g.worktrees?.openInGithubDesktop===void 0&&d.setInteractive(),I?d.addOption("--github-desktop",!0):d.addOption("--no-github-desktop",!0);let N=i??g.worktrees?.openInCmux??await fo({message:"Open created worktrees in cmux?"});typeof i>"u"&&g.worktrees?.openInCmux===void 0&&d.setInteractive(),N?d.addOption("--cmux",!0):d.addOption("--no-cmux",!0);let{branchesToCreate:Ie}=xa({selectedReleaseBranches:m,currentWorktrees:l}),me=await Ca(Ie,p);if(Ea(me),S==="workspace")if(!w?.workspaceConfigPath)a.warn("\u26A0\uFE0F Skipping Cursor: ide.config.workspaceConfigPath is not set in infra-kit config");else{let O=Q(w.workspaceConfigPath,c),de=me.map(wn=>`${p}/${wn}`),{added:ee,skipped:ue}=await Pr({workspacePath:O,folderPaths:de}),Sr=ue.length>0?` (${ue.length} already present)`:"";a.info(`\u2705 Added ${ee.length} folder(s) to ${O}${Sr}`),await Se`cursor ${O}`}else if(S==="windows")for(let O of me)await Se`cursor ${p}/${O}`;if(I)for(let O of me)await Se`github ${p}/${O}`,await Se`sleep 5`;if(N){let O=await F(),de=await Rr();for(let ee of me){let ue=Z({repoName:O,branch:ee});de.has(U(ue))||await xr({cwd:`${p}/${ee}`,title:ue})}}d.print();let ho={createdWorktrees:me,count:me.length};return{content:h(JSON.stringify(ho,null,2)),structuredContent:ho}}catch(l){throw a.error({error:l},"\u274C Error managing worktrees"),new f(l,{operation:"create worktrees",remediation:"verify branches don't already exist as worktrees: 'git worktree list'"})}},un=async e=>{await Se`mkdir -p ${e}`},xa=e=>{let{selectedReleaseBranches:r,currentWorktrees:t}=e,o=t.filter(s=>ge(s));return{branchesToCreate:r.filter(s=>!o.includes(s))}},Ca=async(e,r)=>{let t=await Promise.allSettled(e.map(async n=>{let s=`${r}/${n}`;return await Se`git worktree add ${s} ${n}`,await Se({cwd:s})`pnpm install`,n})),o=[];for(let[n,s]of t.entries())if(s.status==="fulfilled")o.push(s.value);else{let i=e[n],l=new f(s.reason,{operation:`git worktree add for ${i}`,remediation:"check the branch name and that the parent dir is writable"});a.error({error:s.reason,msg:l.message})}return o},Ea=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")},Pa=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:pe.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:pe.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:pe.enum(Tr).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:pe.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:pe.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:pe.array(pe.string()).describe("List of created git worktree branches"),count:pe.number().describe("Number of git worktrees created")},handler:mt});import{z as ze}from"zod";var dt=async()=>{let e=await j("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([E(),$()]),o=new Map(r.map(c=>[c.branch,C(c.title)])),n=e.flatMap(c=>{let p=b(c);if(!p)return[];let m=T(p),u=o.get(c)||"regular",g=t.get(L(p))||null;return[{version:m,type:u,description:g}]}),s=Math.max(...n.map(c=>c.version.length)),i=n.map(c=>{let p=Ke(c.version,c.type,s);return c.description?`${p} ${c.description}`:p});a.info("\u{1F33F} Active worktrees:"),a.info(`
|
|
105
105
|
${i.join(`
|
|
106
106
|
`)}
|
|
107
|
-
`);let l={worktrees:n,count:n.length};return{content:h(JSON.stringify(l,null,2)),structuredContent:l}},ba=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:Ge.array(Ge.object({version:Ge.string().describe("Release version"),type:Ge.enum(["regular","hotfix"]).describe("Release type"),description:Ge.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:Ge.number().describe("Number of worktrees")},handler:pt});import{z as Ue}from"zod";import{$ as xa}from"zx";var mt=async()=>{d.start("worktrees-open");try{let e=await b(),r=`${e}${B}`,t=await j("release"),o=await Ca({projectRoot:e,worktreeDir:r,currentBranches:t}),n=await Ea({worktreeDir:r,currentBranches:t}),s={openedCmux:n.opened,skippedCmux:n.skipped,cursorFoldersAdded:o.added,cursorFoldersRemoved:o.removed};return Pa(s,{cursorRan:o.ran,cmuxRan:n.ran}),d.print(),{content:h(JSON.stringify(s,null,2)),structuredContent:{...s}}}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"})}},Ca=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 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(s.workspaceConfigPath,r);try{let{added:l,removed:c}=await ao({workspacePath:i,worktreeDir:t,currentBranches:o});return await xa`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}}},Ea=async e=>{let{worktreeDir:r,currentBranches:t}=e;if(t.length===0)return{ran:!0,opened:[],skipped:[]};let o=await F(),n=await vr(),s=[],i=[];for(let l of t){let c=Y({repoName:o,branch:l});if(n.has(U(c))){i.push(c);continue}try{await yr({cwd:`${r}/${l}`,title:c}),s.push(c)}catch(p){a.warn({error:p,title:c},`\u26A0\uFE0F Failed to open cmux workspace for ${l}`)}}return{ran:!0,opened:s,skipped:i}},Pa=(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")},Ta=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:Ue.array(Ue.string()).describe("Titles of cmux workspaces opened during this run"),skippedCmux:Ue.array(Ue.string()).describe("Titles of cmux workspaces that were already open"),cursorFoldersAdded:Ue.number().describe("Number of worktree folders added to the Cursor workspace file"),cursorFoldersRemoved:Ue.number().describe("Number of dangling worktree folders removed from the Cursor workspace file")},handler:mt});import $a from"@inquirer/checkbox";import Sa from"@inquirer/confirm";import Ia from"node:process";import{z as Er}from"zod";var dt=async e=>{let{confirmedCommand:r,all:t,versions:o}=e;d.start("worktrees-remove");try{let n=await j("release");if(n.length===0)return a.info("\u2139\uFE0F No active worktrees to remove"),d.print(),{content:h(JSON.stringify({removedWorktrees:[],count:0},null,2)),structuredContent:{removedWorktrees:[],count:0}};let s=await b(),i=`${s}${B}`,l=[];if(t)l=n;else if(o)l=o.split(",").map(w=>z(G(w.trim())));else{d.setInteractive();let[w,S]=await Promise.all([$(),E()]),I=new Map(S.map(N=>[N.branch,C(N.title)]));l=await $a({required:!0,message:"\u{1F33F} Select release branches",choices:A({branches:n,descriptions:w,types:I})})}let c=l.length===n.length;c?d.addOption("--all",!0):d.addOption("--versions",Ee(l));let p=r?!0:await Sa({message:"Are you sure you want to proceed with these worktree changes?"});r||d.setInteractive(),p||(a.info("Operation cancelled. Exiting..."),Ia.exit(0)),r||d.addOption("--yes",!0);let m=await F(),u=await Rr({branches:l,worktreeDir:i,repoName:m,pruneFolder:c});await Aa({removedWorktrees:u,worktreeDir:i,projectRoot:s}),_a(u),d.print();let f={removedWorktrees:u,count:u.length};return{content:h(JSON.stringify(f,null,2)),structuredContent:f}}catch(n){throw a.error({error:n},"\u274C Error managing worktrees"),new g(n,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"})}},Aa=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 i=Z(s.workspaceConfigPath,o),l=r.map(c=>`${t}/${c}`);try{let{removed:c}=await Te({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}`)}},_a=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")},Na=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:dt});import Oa from"@inquirer/confirm";import ja from"node:process";import{z as lo}from"zod";import{$ as Fa}from"zx";var ut=async e=>{let{confirmedCommand:r}=e;d.start("worktrees-sync");try{let t=await j("release"),o=await b(),n=`${o}${B}`,s=await qr(),i=r?!0:await Oa({message:"Are you sure you want to proceed with these worktree changes?"});r||d.setInteractive(),i||(a.info("Operation cancelled. Exiting..."),ja.exit(0)),r||d.addOption("--yes",!0);let{branchesToRemove:l}=Ma({releasePRsList:s,currentWorktrees:t}),c=await F(),p=await Da({branches:l,worktreeDir:n,repoName:c});await La({removedWorktrees:p,worktreeDir:n,projectRoot:o}),Wa(p),d.print();let m={removedWorktrees:p,count:p.length};return{content:h(JSON.stringify(m,null,2)),structuredContent:m}}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"})}},Ma=e=>{let{releasePRsList:r,currentWorktrees:t}=e;return{branchesToRemove:t.filter(s=>fe(s)).filter(s=>!r.includes(s))}},Da=async e=>{let{branches:r,worktreeDir:t,repoName:o}=e,n=[];for(let s of r)try{let i=`${t}/${s}`,l=Y({repoName:o,branch:s});await wr(l),await Fa`git worktree remove ${i}`,n.push(s)}catch(i){let l=new g(i,{operation:`remove stale worktree for ${s}`,remediation:"inspect the worktree dir manually; rerun with the branch checked out elsewhere"});a.error({error:i,branch:s,msg:l.message})}return n},La=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 i=Z(s.workspaceConfigPath,o),l=r.map(c=>`${t}/${c}`);try{let{removed:c}=await Te({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}`)}},Wa=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")},Va=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:lo.array(lo.string()).describe("List of removed worktree branches"),count:lo.number().describe("Number of worktrees removed during sync")},handler:ut});var y=new Ba,ln=(e,r)=>[...r,e],Ka=e=>{if(!(typeof e>"u")){if(e===!0)return"workspace";if(e===!1)return"none";if(typeof e=="string"&&Cr.includes(e))return e;throw new Error(`Invalid --cursor value "${String(e)}". Expected one of: ${Cr.join(", ")}.`)}},pn=async e=>{try{e?await y.parseAsync(e):await y.parseAsync()}catch(r){let t=r instanceof Error?r.message:String(r);a.error(t),ft.exit(1)}};y.command("merge-dev").description("Merge dev branch into every release branch").option("-a, --all","Select all active release branches").option("-y, --yes","Skip confirmation prompt").action(async e=>{await Hr({all:e.all,confirmedCommand:e.yes})});y.command("release-list").description("List all release branches").action(async()=>{await Qr()});y.command("release-create").description("Create one or more release branches (each entry can mix regular/hotfix and its own description)").option("-r, --release <spec>",'Release spec "version[:type[:description]]" (repeatable). Examples: "1.2.5", "1.2.5:hotfix", "next:regular:Holiday backend"',ln,[]).option("-n, --name <name>",'Named release (repeatable). Bare kebab-case name, e.g. "checkout-redesign". Creates a regular release; set a description later via release-desc-edit. Can be combined with --release.',ln,[]).option("-y, --yes","Skip confirmation prompt").action(async e=>{let r=e.release,t=e.name,o=r.map(ro),n=t.map(l=>({name:l,type:"regular"})),s=[...o,...n],i=s.length>0?s:void 0;await ot({releases:i,confirmedCommand:e.yes})});y.command("release-desc-edit").description("Edit a release's description in Jira and in the matching GitHub PR body").option("-v, --version <version>","Release version (e.g. 1.2.5) or release name (e.g. checkout-redesign)").option("-d, --description <description>",'New description (use "" to clear)').option("-y, --yes","Skip confirmation prompt").action(async e=>{await nt({version:e.version,description:e.description,confirmedCommand:e.yes})});y.command("release-deploy-all").description("Deploy any release branch to any environment").option("-v, --version <version>",'Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deploy; "dev" deploys from the dev branch').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("--skip-terraform","Skip terraform deployment step").action(async e=>{await Yr({version:e.version,env:e.env,skipTerraform:e.skipTerraform})});y.command("release-deploy-selected").description("Deploy selected services from release branch to any environment").option("-v, --version <version>",'Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deploy; "dev" deploys from the dev branch').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("-s, --services <services...>","Specify services to deploy, e.g. client-be client-fe").option("--skip-terraform","Skip terraform deployment step").action(async e=>{await Zr({version:e.version,env:e.env,services:e.services,skipTerraform:e.skipTerraform})});y.command("release-deliver").description("Release a new version to production").option("-v, --version <version>","Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deliver").option("-y, --yes","Skip confirmation prompt").action(async e=>{await Xr({version:e.version,confirmedCommand:e.yes})});y.command("worktrees-sync").description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async e=>{await ut({confirmedCommand:e.yes})});y.command("worktrees-add").description("Add git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-c, --cursor [mode]","Cursor mode for created worktrees: workspace (default) | windows | none").option("--no-cursor","Skip Cursor (alias for --cursor none)").option("-g, --github-desktop","Open created worktrees in GitHub Desktop").option("--no-github-desktop","Skip GitHub Desktop prompt").option("-m, --cmux","Open created worktrees in cmux (3-pane layout)").option("--no-cmux","Skip cmux prompt").action(async e=>{await lt({confirmedCommand:e.yes,all:e.all,versions:e.versions,cursor:Ka(e.cursor),githubDesktop:e.githubDesktop,cmux:e.cmux})});y.command("worktrees-list").description("List all git worktrees with detailed information").action(async()=>{await pt()});y.command("worktrees-remove").description("Remove git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").action(async e=>{await dt({confirmedCommand:e.yes,all:e.all,versions:e.versions})});y.command("worktrees-open").description("Open Cursor + cmux for existing release worktrees (cold-start restore)").action(async()=>{await mt()});var mn=y.command("config").description("Manage infra-kit configuration files");mn.command("path").description("Show the resolved config merge chain and file paths").action(async()=>{await It()});mn.command("edit").description("Open the user-scope per-project override file in $EDITOR").action(async()=>{await At()});y.command("audit").description("Audit against infra-kit.config.ts rules (--all for every package, --root for the monorepo root)").option("-a, --all","Audit every non-vendor workspace package").option("-r, --root","Audit the monorepo root (turbo pipeline + root commands)").action(async e=>{(await Sr({all:e.all,root:e.root})).structuredContent.allPassed||(ft.exitCode=1)});y.command("doctor").description("Check installation and authentication status of gh and doppler CLIs").action(async()=>{await jr()});y.command("version").description("Print the installed infra-kit CLI version").action(async()=>{await st()});y.command("env-status").description("Show Doppler authentication status and detected project info").action(async()=>{await Vr()});y.command("env-list").description("List available Doppler configs for the detected project").action(async()=>{await Dr()});y.command("init").description("Inject shell integration into .zshrc and sync repo agent-instruction files").action(async()=>{await Mt()});y.command("env-load").description("Load Doppler env vars for a config. Source the returned file path to apply.").option("-c, --config <config>","Environment config name to load (e.g. dev, arthur)").action(async e=>{await Wr({config:e.config})});y.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{await Mr()});if(ft.argv.length<=2){let e=["merge-dev","release-list","release-create","release-desc-edit","release-deploy-all","release-deploy-selected","release-deliver"],r=["worktrees-add","worktrees-list","worktrees-open","worktrees-remove","worktrees-sync"],t=["audit","doctor","init","version","config","env-status","env-list","env-load","env-clear"],o=new Map(y.commands.map(c=>[c.name(),c])),n=[...e,...r,...t],s=Math.max(...n.map(c=>c.length)),i=c=>c.filter(p=>o.has(p)).map(p=>({name:`${p.padEnd(s)} ${o.get(p).description()}`,value:p})),l=await Ja({message:"Select a command to run",choices:[new qe(" "),new qe("\u2014 Release Management \u2014"),...i(e),new qe(" "),new qe("\u2014 Worktrees \u2014"),...i(r),new qe(" "),new qe("\u2014 Environment \u2014"),...i(t)]},{output:ft.stderr});await pn(["node","infra-kit",l])}else await pn();
|
|
107
|
+
`);let l={worktrees:n,count:n.length};return{content:h(JSON.stringify(l,null,2)),structuredContent:l}},Ta=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:ze.array(ze.object({version:ze.string().describe("Release version"),type:ze.enum(["regular","hotfix"]).describe("Release type"),description:ze.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:ze.number().describe("Number of worktrees")},handler:dt});import{z as He}from"zod";import{$ as $a}from"zx";var ut=async()=>{d.start("worktrees-open");try{let e=await R(),r=`${e}${K}`,t=await j("release"),o=await Sa({projectRoot:e,worktreeDir:r,currentBranches:t}),n=await Ia({worktreeDir:r,currentBranches:t}),s={openedCmux:n.opened,skippedCmux:n.skipped,cursorFoldersAdded:o.added,cursorFoldersRemoved:o.removed};return Aa(s,{cursorRan:o.ran,cmuxRan:n.ran}),d.print(),{content:h(JSON.stringify(s,null,2)),structuredContent:{...s}}}catch(e){throw a.error({error:e},"\u274C Error opening worktrees"),new f(e,{operation:"open worktrees",remediation:"run 'worktrees-list' to confirm the branches exist"})}},Sa=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 a.warn('\u26A0\uFE0F Skipping Cursor: ide.provider must be "cursor", mode "workspace", and workspaceConfigPath set.'),{ran:!1,added:0,removed:0};let i=Q(s.workspaceConfigPath,r);try{let{added:l,removed:c}=await uo({workspacePath:i,worktreeDir:t,currentBranches:o});return await $a`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}}},Ia=async e=>{let{worktreeDir:r,currentBranches:t}=e;if(t.length===0)return{ran:!0,opened:[],skipped:[]};let o=await F(),n=await Rr(),s=[],i=[];for(let l of t){let c=Z({repoName:o,branch:l});if(n.has(U(c))){i.push(c);continue}try{await xr({cwd:`${r}/${l}`,title:c}),s.push(c)}catch(p){a.warn({error:p,title:c},`\u26A0\uFE0F Failed to open cmux workspace for ${l}`)}}return{ran:!0,opened:s,skipped:i}},Aa=(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")},_a=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:He.array(He.string()).describe("Titles of cmux workspaces opened during this run"),skippedCmux:He.array(He.string()).describe("Titles of cmux workspaces that were already open"),cursorFoldersAdded:He.number().describe("Number of worktree folders added to the Cursor workspace file"),cursorFoldersRemoved:He.number().describe("Number of dangling worktree folders removed from the Cursor workspace file")},handler:ut});import Na from"@inquirer/checkbox";import Oa from"@inquirer/confirm";import ja from"node:process";import{z as $r}from"zod";var ft=async e=>{let{confirmedCommand:r,all:t,versions:o}=e;d.start("worktrees-remove"),await M({operation:"remove worktrees",requiredBranch:"dev"});try{let n=await j("release");if(n.length===0)return a.info("\u2139\uFE0F No active worktrees to remove"),d.print(),{content:h(JSON.stringify({removedWorktrees:[],count:0},null,2)),structuredContent:{removedWorktrees:[],count:0}};let s=await R(),i=`${s}${K}`,l=[];if(t)l=n;else if(o)l=o.split(",").map(w=>H(G(w.trim())));else{d.setInteractive();let[w,S]=await Promise.all([$(),E()]),I=new Map(S.map(N=>[N.branch,C(N.title)]));l=await Na({required:!0,message:"\u{1F33F} Select release branches",choices:A({branches:n,descriptions:w,types:I})})}let c=l.length===n.length;c?d.addOption("--all",!0):d.addOption("--versions",Pe(l));let p=r?!0:await Oa({message:"Are you sure you want to proceed with these worktree changes?"});r||d.setInteractive(),p||(a.info("Operation cancelled. Exiting..."),ja.exit(0)),r||d.addOption("--yes",!0);let m=await F(),u=await Cr({branches:l,worktreeDir:i,repoName:m,pruneFolder:c});await Fa({removedWorktrees:u,worktreeDir:i,projectRoot:s}),Ma(u),d.print();let g={removedWorktrees:u,count:u.length};return{content:h(JSON.stringify(g,null,2)),structuredContent:g}}catch(n){throw a.error({error:n},"\u274C Error managing worktrees"),new f(n,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"})}},Fa=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 i=Q(s.workspaceConfigPath,o),l=r.map(c=>`${t}/${c}`);try{let{removed:c}=await $e({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}`)}},Ma=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")},Da=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:$r.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:$r.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:$r.array($r.string()).describe("List of removed git worktree branches"),count:$r.number().describe("Number of git worktrees removed")},handler:ft});import La from"@inquirer/confirm";import Wa from"node:process";import{z as go}from"zod";import{$ as Ba}from"zx";var gt=async e=>{let{confirmedCommand:r}=e;d.start("worktrees-sync"),await M({operation:"sync worktrees",requiredBranch:"dev"});try{let t=await j("release"),o=await R(),n=`${o}${K}`,s=await Hr(),i=r?!0:await La({message:"Are you sure you want to proceed with these worktree changes?"});r||d.setInteractive(),i||(a.info("Operation cancelled. Exiting..."),Wa.exit(0)),r||d.addOption("--yes",!0);let{branchesToRemove:l}=Va({releasePRsList:s,currentWorktrees:t}),c=await F(),p=await Ja({branches:l,worktreeDir:n,repoName:c});await Ka({removedWorktrees:p,worktreeDir:n,projectRoot:o}),qa(p),d.print();let m={removedWorktrees:p,count:p.length};return{content:h(JSON.stringify(m,null,2)),structuredContent:m}}catch(t){throw a.error({error:t},"\u274C Error managing worktrees"),new f(t,{operation:"sync worktrees with remote",remediation:"ensure 'gh auth status' is ok and you can reach origin"})}},Va=e=>{let{releasePRsList:r,currentWorktrees:t}=e;return{branchesToRemove:t.filter(s=>ge(s)).filter(s=>!r.includes(s))}},Ja=async e=>{let{branches:r,worktreeDir:t,repoName:o}=e,n=[];for(let s of r)try{let i=`${t}/${s}`,l=Z({repoName:o,branch:s});await yr(l),await Ba`git worktree remove ${i}`,n.push(s)}catch(i){let l=new f(i,{operation:`remove stale worktree for ${s}`,remediation:"inspect the worktree dir manually; rerun with the branch checked out elsewhere"});a.error({error:i,branch:s,msg:l.message})}return n},Ka=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 i=Q(s.workspaceConfigPath,o),l=r.map(c=>`${t}/${c}`);try{let{removed:c}=await $e({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}`)}},qa=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")},Ga=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:go.array(go.string()).describe("List of removed worktree branches"),count:go.number().describe("Number of worktrees removed during sync")},handler:gt});var y=new za,fn=(e,r)=>[...r,e],Ha=e=>{if(!(typeof e>"u")){if(e===!0)return"workspace";if(e===!1)return"none";if(typeof e=="string"&&Tr.includes(e))return e;throw new Error(`Invalid --cursor value "${String(e)}". Expected one of: ${Tr.join(", ")}.`)}},gn=async e=>{try{e?await y.parseAsync(e):await y.parseAsync()}catch(r){let t=r instanceof Error?r.message:String(r);a.error(t),ht.exit(1)}};y.command("merge-dev").description("Merge dev branch into every release branch").option("-a, --all","Select all active release branches").option("-y, --yes","Skip confirmation prompt").action(async e=>{await Yr({all:e.all,confirmedCommand:e.yes})});y.command("release-list").description("List all release branches").action(async()=>{await rt()});y.command("release-create").description("Create one or more release branches (each entry can mix regular/hotfix and its own description)").option("-r, --release <spec>",'Release spec "version[:type[:description]]" (repeatable). Examples: "1.2.5", "1.2.5:hotfix", "next:regular:Holiday backend"',fn,[]).option("-n, --name <name>",'Named release (repeatable). Bare kebab-case name, e.g. "checkout-redesign". Creates a regular release; set a description later via release-desc-edit. Can be combined with --release.',fn,[]).option("-y, --yes","Skip confirmation prompt").action(async e=>{let r=e.release,t=e.name,o=r.map(io),n=t.map(l=>({name:l,type:"regular"})),s=[...o,...n],i=s.length>0?s:void 0;await st({releases:i,confirmedCommand:e.yes})});y.command("release-desc-edit").description("Edit a release's description in Jira and in the matching GitHub PR body").option("-v, --version <version>","Release version (e.g. 1.2.5) or release name (e.g. checkout-redesign)").option("-d, --description <description>",'New description (use "" to clear)').option("-y, --yes","Skip confirmation prompt").action(async e=>{await it({version:e.version,description:e.description,confirmedCommand:e.yes})});y.command("release-deploy-all").description("Deploy any release branch to any environment").option("-v, --version <version>",'Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deploy; "dev" deploys from the dev branch').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("--skip-terraform","Skip terraform deployment step").action(async e=>{await Qr({version:e.version,env:e.env,skipTerraform:e.skipTerraform})});y.command("release-deploy-selected").description("Deploy selected services from release branch to any environment").option("-v, --version <version>",'Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deploy; "dev" deploys from the dev branch').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("-s, --services <services...>","Specify services to deploy, e.g. client-be client-fe").option("--skip-terraform","Skip terraform deployment step").action(async e=>{await et({version:e.version,env:e.env,services:e.services,skipTerraform:e.skipTerraform})});y.command("release-deliver").description("Release a new version to production").option("-v, --version <version>","Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deliver").option("-y, --yes","Skip confirmation prompt").action(async e=>{await Zr({version:e.version,confirmedCommand:e.yes})});y.command("worktrees-sync").description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async e=>{await gt({confirmedCommand:e.yes})});y.command("worktrees-add").description("Add git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-c, --cursor [mode]","Cursor mode for created worktrees: workspace (default) | windows | none").option("--no-cursor","Skip Cursor (alias for --cursor none)").option("-g, --github-desktop","Open created worktrees in GitHub Desktop").option("--no-github-desktop","Skip GitHub Desktop prompt").option("-m, --cmux","Open created worktrees in cmux (3-pane layout)").option("--no-cmux","Skip cmux prompt").action(async e=>{await mt({confirmedCommand:e.yes,all:e.all,versions:e.versions,cursor:Ha(e.cursor),githubDesktop:e.githubDesktop,cmux:e.cmux})});y.command("worktrees-list").description("List all git worktrees with detailed information").action(async()=>{await dt()});y.command("worktrees-remove").description("Remove git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").action(async e=>{await ft({confirmedCommand:e.yes,all:e.all,versions:e.versions})});y.command("worktrees-open").description("Open Cursor + cmux for existing release worktrees (cold-start restore)").action(async()=>{await ut()});var hn=y.command("config").description("Manage infra-kit configuration files");hn.command("path").description("Show the resolved config merge chain and file paths").action(async()=>{await jt()});hn.command("edit").description("Open the user-scope per-project override file in $EDITOR").action(async()=>{await Ft()});y.command("audit").description("Audit against infra-kit.config.ts rules (--all for every package, --root for the monorepo root)").option("-a, --all","Audit every non-vendor workspace package").option("-r, --root","Audit the monorepo root (turbo pipeline + root commands)").action(async e=>{(await _r({all:e.all,root:e.root})).structuredContent.allPassed||(ht.exitCode=1)});y.command("doctor").description("Check installation and authentication status of gh and doppler CLIs").action(async()=>{await Dr()});y.command("version").description("Print the installed infra-kit CLI version").action(async()=>{await at()});y.command("env-status").description("Show Doppler authentication status and detected project info").action(async()=>{await Kr()});y.command("env-list").description("List available Doppler configs for the detected project").action(async()=>{await Br()});y.command("init").description("Inject shell integration into .zshrc and sync repo agent-instruction files").action(async()=>{await Vt()});y.command("env-load").description("Load Doppler env vars for a config. Source the returned file path to apply.").option("-c, --config <config>","Environment config name to load (e.g. dev, arthur)").action(async e=>{await Jr({config:e.config})});y.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{await Wr()});if(ht.argv.length<=2){let e=["merge-dev","release-list","release-create","release-desc-edit","release-deploy-all","release-deploy-selected","release-deliver"],r=["worktrees-add","worktrees-list","worktrees-open","worktrees-remove","worktrees-sync"],t=["audit","doctor","init","version","config","env-status","env-list","env-load","env-clear"],o=new Map(y.commands.map(c=>[c.name(),c])),n=[...e,...r,...t],s=Math.max(...n.map(c=>c.length)),i=c=>c.filter(p=>o.has(p)).map(p=>({name:`${p.padEnd(s)} ${o.get(p).description()}`,value:p})),l=await Ua({message:"Select a command to run",choices:[new Xe(" "),new Xe("\u2014 Release Management \u2014"),...i(e),new Xe(" "),new Xe("\u2014 Worktrees \u2014"),...i(r),new Xe(" "),new Xe("\u2014 Environment \u2014"),...i(t)]},{output:ht.stderr});await gn(["node","infra-kit",l])}else await gn();
|
|
108
108
|
//# sourceMappingURL=cli.js.map
|