infra-kit 0.1.105 → 0.1.108
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.eslintcache +1 -1
- package/.omc/state/agent-replay-36d91435-50b4-442f-9f4e-3cc68d776236.jsonl +2 -0
- package/.omc/state/agent-replay-afc6290b-40d3-4bef-b3b6-14484c034ab9.jsonl +14 -0
- package/.omc/state/agent-replay-e947a3c6-989d-4a60-91dd-6b0ddd827b2d.jsonl +3 -0
- package/.omc/state/idle-notif-cooldown.json +1 -1
- package/.omc/state/sessions/36d91435-50b4-442f-9f4e-3cc68d776236/pre-tool-advisory-throttle.json +18 -0
- package/.omc/state/sessions/36d91435-50b4-442f-9f4e-3cc68d776236/subagent-tracking-state.json +17 -0
- package/.omc/state/sessions/afc6290b-40d3-4bef-b3b6-14484c034ab9/last-tool-error-state.json +7 -0
- package/.omc/state/sessions/afc6290b-40d3-4bef-b3b6-14484c034ab9/mission-state.json +89 -0
- package/.omc/state/sessions/afc6290b-40d3-4bef-b3b6-14484c034ab9/pre-tool-advisory-throttle.json +34 -0
- package/.omc/state/sessions/afc6290b-40d3-4bef-b3b6-14484c034ab9/ralph-state.json +13 -0
- package/.omc/state/sessions/afc6290b-40d3-4bef-b3b6-14484c034ab9/skill-active-state.json +15 -0
- package/.omc/state/sessions/afc6290b-40d3-4bef-b3b6-14484c034ab9/subagent-tracking-state.json +35 -0
- package/.omc/state/sessions/afc6290b-40d3-4bef-b3b6-14484c034ab9/ultrawork-state.json +11 -0
- package/.omc/state/sessions/e947a3c6-989d-4a60-91dd-6b0ddd827b2d/last-tool-error-state.json +7 -0
- package/.omc/state/sessions/e947a3c6-989d-4a60-91dd-6b0ddd827b2d/pre-tool-advisory-throttle.json +10 -0
- package/.omc/state/sessions/e947a3c6-989d-4a60-91dd-6b0ddd827b2d/subagent-tracking-state.json +26 -0
- package/.turbo/turbo-build.log +2 -2
- package/.turbo/turbo-test.log +43 -6
- package/dist/cli.js +61 -54
- package/dist/cli.js.map +4 -4
- package/dist/mcp.js +31 -31
- package/dist/mcp.js.map +4 -4
- package/package.json +1 -1
- package/src/commands/.omc/state/sessions/afc6290b-40d3-4bef-b3b6-14484c034ab9/pre-tool-advisory-throttle.json +14 -0
- package/src/commands/doctor/__tests__/agent-files.test.ts +110 -0
- package/src/commands/doctor/doctor.ts +66 -1
- package/src/commands/init/__tests__/agent-files.test.ts +147 -0
- package/src/commands/init/agent-files.ts +199 -0
- package/src/commands/init/index.ts +7 -0
- package/src/commands/init/init.ts +34 -25
- package/src/commands/worktrees-add/worktrees-add.ts +13 -1
- package/src/commands/worktrees-open/__tests__/open-cmux.test.ts +96 -0
- package/src/commands/worktrees-open/worktrees-open.ts +10 -3
- package/src/entry/cli.ts +1 -1
- package/src/integrations/cmux/__tests__/canonicalize-cmux-title.test.ts +56 -0
- package/src/integrations/cmux/__tests__/close-workspace-by-title.test.ts +63 -0
- package/src/integrations/cmux/__tests__/list-workspace-titles.test.ts +65 -0
- package/src/integrations/cmux/canonicalize-cmux-title.ts +31 -0
- package/src/integrations/cmux/close-workspace-by-title.ts +12 -4
- package/src/integrations/cmux/index.ts +1 -0
- package/src/integrations/cmux/list-workspace-titles.ts +11 -6
- package/src/integrations/cmux/open-workspace-with-layout.ts +1 -1
- package/src/integrations/gh/gh-release-prs/.omc/state/sessions/c6ed6186-1aac-48e0-aa2a-edc6da8e0410/pre-tool-advisory-throttle.json +10 -0
- package/src/integrations/gh/gh-release-prs/__tests__/gh-release-prs.test.ts +89 -6
- package/src/integrations/gh/gh-release-prs/gh-release-prs.ts +1 -1
- package/src/lib/managed-block/__tests__/managed-block.test.ts +121 -0
- package/src/lib/managed-block/index.ts +8 -0
- package/src/lib/managed-block/managed-block.ts +145 -0
- 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
|
|
1
|
+
import Ja,{Separator as qe}from"@inquirer/select";import{Command as Ba}from"commander";import ft from"node:process";import Xe from"node:path";import Dn from"node:process";import{z as L}from"zod";import vn from"node:path";import{$ as wo}from"zx";var un=/^v?(\d+)\.(\d+)\.(\d+)$/,fn=/^(\d+)\.(\d+)\.(\d+)$/,gn=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,hn="release/",gt="release/v",ht="release/n/",mo="refs/heads/",wn="next";var uo=new Set(["dev","main","next","hotfix","regular","release"]),q=class extends Error{constructor(r){super(r),this.name="InvalidReleaseNameError"}},Ie=class extends Error{constructor(r){super(r),this.name="InvalidReleaseRefError"}},go=e=>e.startsWith(mo)?e.slice(mo.length):e,ho=(e,r,t)=>({kind:"version",semver:{major:e,minor:r,patch:t},raw:`${e}.${r}.${t}`}),ue=e=>{if(e.length===0)throw new q('Release name is empty. Provide a kebab-case name like "checkout-redesign".');if(e.length>50)throw new q(`Release name "${e}" is ${e.length} characters; the maximum is 50.`);if(!gn.test(e))throw new q(`Release name "${e}" is not kebab-case. Use lowercase letters, digits, and single hyphens, e.g. "checkout-redesign".`);if(uo.has(e))throw new q(`Release name "${e}" is reserved. Reserved names: ${[...uo].join(", ")}.`)},R=e=>{let r=go(e.trim());if(r.startsWith(gt)){let t=r.slice(gt.length),o=fn.exec(t);return o?ho(Number(o[1]),Number(o[2]),Number(o[3])):null}if(r.startsWith(ht)){let t=r.slice(ht.length);try{ue(t)}catch{return null}return{kind:"name",name:t,raw:t}}return null},G=e=>{let r=e.trim();if(go(r).startsWith(hn)){let n=R(r);if(!n)throw new Ie(`"${e}" looks like a release branch but is not a valid release/v<semver> or release/n/<name> ref.`);return n}let o=un.exec(r);if(o)return ho(Number(o[1]),Number(o[2]),Number(o[3]));if(r.toLowerCase()===wn)throw new Ie('The "next" token must be resolved to a concrete version (via computeNextVersion) before parsing a release ref.');try{ue(r)}catch(n){let s=n instanceof Error?n.message:String(n);throw new Ie(`Cannot parse "${e}" as a release ref: ${s}`)}return{kind:"name",name:r,raw:r}},z=e=>e.kind==="version"?`${gt}${e.raw}`:`${ht}${e.name}`,wt=(e,r)=>{let t=r==="hotfix"?"Hotfix":"Release";return e.kind==="version"?`${t} v${e.raw}`:`${t} ${e.name}`},Tr=e=>e.kind==="version"?`Release v${e.raw} (RC)`:`Release ${e.name} (RC)`,D=e=>e.kind==="version"?`v${e.raw}`:e.name,T=e=>e.raw,fe=e=>e==null?!1:R(e)!==null,fo=e=>{if(e===void 0)return null;let r=e instanceof Date?e.getTime():new Date(e).getTime();return Number.isNaN(r)?null:r},vt=(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=fo(t?.a),n=fo(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 wo`git worktree list`).stdout.split(`
|
|
2
|
+
`).filter(Boolean),o={release:kn,feature:yn};return t.map(o[e]).filter(n=>n!==null)},vo=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},kn=e=>{let r=vo(e);return fe(r)?r:null},yn=e=>{let r=vo(e);return r?.startsWith("feature/")?r:null},b=async()=>(await wo`git rev-parse --show-toplevel`).stdout.trim(),F=async()=>{let e=await b();return vn.basename(e)};import Rn from"node:process";import bn from"pino";import xn from"pino-pretty";var Cn=()=>{let e=Rn.argv.includes("--debug")?"debug":"info",r=["time","pid","hostname"];return e==="debug"&&r.push("level"),bn({level:e},xn({destination:2,ignore:r.join(","),colorize:!0}))},a=Cn();var ee={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},kt={requiredScripts:["build","dev","test","qa","check","fix"],requiredFiles:["turbo.json","pnpm-workspace.yaml"],turboTasks:["build","test","ts-check","eslint-check","prettier-check","check"]},yt=(e,r=ee)=>({requiredScripts:e.requiredScripts??[...r.requiredScripts],requiredFiles:e.requiredFiles??[...r.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...r.turboTasks]});import{z as re}from"zod";var Rt=re.strictObject({requiredScripts:re.array(re.string().min(1)).optional(),requiredFiles:re.array(re.string().min(1)).optional(),turbo:re.strictObject({requiredTasks:re.array(re.string().min(1)).optional()}).optional()});import En from"node:fs/promises";var H=async e=>{try{return await En.access(e),!0}catch{return!1}};import Mn from"node:path";import ko from"node:fs/promises";import yo from"node:path";import{pathToFileURL as Pn}from"node:url";import{z as Tn}from"zod";var te="infra-kit.config.ts",bt=async e=>{try{let r=await ko.readFile(yo.join(e,"package.json"),"utf-8");return JSON.parse(r)}catch{return{}}},ze=async(e,r=ee)=>{let t=yo.join(e,te);if(!await H(t))throw new Error(`${te} not found at ${t}`);let o=await ko.stat(t),i=(await import(`${Pn(t).href}?mtime=${Number(o.mtimeMs)}`)).default;if(i===void 0)throw new Error(`${te} at ${t} has no default export`);let l=typeof i=="function"?await i():i,c=Rt.safeParse(l);if(!c.success)throw new Error(`Invalid ${te} at ${t}: ${Tn.prettifyError(c.error)}`);return yt(c.data,r)};import Ro from"node:fs/promises";import $r from"node:path";import $n from"yaml";var Sn="pnpm-workspace.yaml",In=async e=>(await Ro.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(t=>t.isDirectory()).map(t=>$r.join(e,t.name)),An=async(e,r)=>{let t=[];for(let o of e){if(r==="*"){t.push(...await In(o));continue}let n=$r.join(o,r);await H(n)&&t.push(n)}return t},_n=async(e,r)=>{let t=[e];for(let o of r.split("/"))t=await An(t,o);return t},He=async e=>{let r=await Ro.readFile($r.join(e,Sn),"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 _n(e,s);for(let l of i)await H($r.join(l,"package.json"))&&n.add(l)}return[...n].sort()};var xt=async(e,r=ee)=>{try{let t=await ze(e,r);return{check:{name:te,status:"pass",message:"present and valid"},rules:t}}catch(t){return{check:{name:te,status:"fail",message:t.message},rules:null}}};import Nn from"node:fs/promises";import On from"node:path";var Ct=async(e,r)=>Promise.all(r.map(async t=>{let o=await Nn.stat(On.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 Et=(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 jn from"node:fs/promises";import Fn from"node:path";var Ae="turbo.json",Pt=async(e,r)=>{if(r.length===0)return[];let t;try{let n=await jn.readFile(Fn.join(e,Ae),"utf-8");t=JSON.parse(n)}catch(n){return[{name:Ae,status:"fail",message:`cannot read/parse ${Ae}: ${n.message}`}]}let o=t.tasks;return o===null||typeof o!="object"?[{name:Ae,status:"fail",message:`no "tasks" object defined in ${Ae}`}]: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 ${Ae}`}})};var Tt=async(e,r=ee)=>{let t=await bt(e),o=t.name??Mn.basename(e),{check:n,rules:s}=await xt(e,r),i=[n];s&&(i.push(...Et(t.scripts??{},s.requiredScripts)),i.push(...await Ct(e,s.requiredFiles)),i.push(...await Pt(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 Ln=async e=>{let r=Xe.resolve(e);for(;r!==Xe.dirname(r);){if(await H(Xe.join(r,"package.json")))return r;r=Xe.dirname(r)}if(await H(Xe.join(r,"package.json")))return r;throw new Error(`No package.json found in or above ${e}`)},Wn=async e=>e.root?[{dir:await b(),baseline:kt}]:e.all?(await He(await b())).map(t=>({dir:t})):[{dir:await Ln(e.cwd??Dn.cwd())}],Vn=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}`)}},Sr=async(e={})=>{let r=await Wn(e),t=[];for(let s of r)t.push(await Tt(s.dir,s.baseline));for(let s of t)Vn(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}},Jn={all:L.boolean().optional().describe("Audit every non-vendor workspace package"),root:L.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},Bn={allPassed:L.boolean().describe("Whether every audited package passed all checks"),packages:L.array(L.object({name:L.string(),passed:L.boolean(),checks:L.array(L.object({name:L.string(),status:L.enum(["pass","fail"]),message:L.string()}))})).describe("Per-package check results")},Kn=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:Jn,outputSchema:Bn,handler:e=>Sr({all:e.all,root:e.root})});import Ar from"node:fs/promises";import is from"node:os";import as from"node:path";import xo from"node:process";import{$ as cs}from"zx";import St from"node:fs/promises";import Gn from"node:os";import Ir from"node:path";import{z as k}from"zod";var bo="infra-kit.json",Un=".infra-kit",qn="config.json",zn="projects",Hn=k.object({provider:k.literal("doppler"),config:k.object({name:k.string().min(1)})}),Xn=k.discriminatedUnion("provider",[Hn]),Yn=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"]}),Zn=k.object({provider:k.literal("cursor"),config:Yn}),Qn=k.discriminatedUnion("provider",[Zn]),es=k.object({provider:k.literal("jira"),config:k.object({baseUrl:k.string().url(),projectId:k.number().int().positive()})}),rs=k.discriminatedUnion("provider",[es]),ts=k.object({openInGithubDesktop:k.boolean().optional(),openInCmux:k.boolean().optional()}),Ye=k.object({environments:k.array(k.string().min(1)).min(1),envManagement:Xn,ide:Qn.optional(),taskManager:rs.optional(),worktrees:ts.optional()}),Ze=Ye.partial(),_e=null,W=async()=>{let e=await b(),r=await F(),t=Ir.join(Gn.homedir(),Un);return{main:Ir.join(e,bo),userGlobal:Ir.join(t,qn),userProject:Ir.join(t,zn,r,bo),projectName:r}},x=async()=>{let e=await W(),r;try{r=await St.stat(e.main)}catch{_e=null;let c=e.main.replace(/\.json$/,".yml");throw await $t(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([$t(e.userGlobal),$t(e.userProject)]),n={main:Number(r.mtimeMs),userGlobal:t?Number(t.mtimeMs):null,userProject:o?Number(o.mtimeMs):null};if(_e&&ns(_e.mtimes,n))return _e.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 ss(c);p!==null&&(i={...i,...p})}let l=Ye.safeParse(i);if(!l.success)throw new Error(`Invalid merged infra-kit config: ${k.prettifyError(l.error)}`);return _e={mtimes:n,value:l.data},l.data},ge=()=>{_e=null},$t=async e=>{try{return await St.stat(e)}catch{return null}},os=async e=>{try{return await St.readFile(e,"utf-8")}catch{return null}},ns=(e,r)=>{let t=Object.keys(e);return t.length!==Object.keys(r).length?!1:t.every(o=>e[o]===r[o])},ss=async e=>{let r=await os(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=Ze.safeParse(t);if(!o.success)throw new Error(`Invalid ${e.label} at ${e.path}: ${k.prettifyError(o.error)}`);return o.data};var Co=async e=>{try{return await Ar.access(e),!0}catch{return!1}},_r=e=>{let r=is.homedir();return e.startsWith(r)?`~${e.slice(r.length)}`:e},It=async()=>{let e=await W(),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 Co(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
|
|
7
|
-
`,"utf-8"),await
|
|
6
|
+
`);for(let o of r){let n=o.exists?" [\u2713]":" [ ]";a.info(`${n} ${o.label.padEnd(22)} ${_r(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}},At=async()=>{let e=await W(),r=xo.env.EDITOR||xo.env.VISUAL||"vi";if(await Ar.mkdir(as.dirname(e.userProject),{recursive:!0}),!await Co(e.userProject)){let o=ls(e.userProject);await Ar.writeFile(e.userProject,`{}
|
|
7
|
+
`,"utf-8"),await Ar.writeFile(o,ps(e.projectName),"utf-8"),a.info(`Created ${_r(e.userProject)} \u2014 see ${_r(o)} for the annotated reference.`)}a.info(`Opening ${_r(e.userProject)} in ${r}`),await cs({stdio:"inherit"})`${r} ${e.userProject}`,ge();let t={path:e.userProject,editor:r};return{content:[{type:"text",text:JSON.stringify(t,null,2)}],structuredContent:t}},ls=e=>e.replace(/\.json$/,".example.jsonc"),ps=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,9 +15,17 @@ ${o?"\u2705 All valid":"\u274C Audit failed"} (${t.length} checked)`);let s={all
|
|
|
15
15
|
{
|
|
16
16
|
// "worktrees": { "openInGithubDesktop": false, "openInCmux": true }
|
|
17
17
|
}
|
|
18
|
-
`;import
|
|
19
|
-
|
|
20
|
-
|
|
18
|
+
`;import se from"node:fs";import _o from"node:os";import nr from"node:path";import{z as Fe}from"zod";import{$ as No}from"zx";import J from"node:fs";import we from"node:path";var Ne=(e,r,t)=>{let o=e.indexOf(r),n=e.indexOf(t);return o!==-1&&n!==-1&&n>=o},Qe=(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 Eo=(e,r,t)=>`${e}
|
|
20
|
+
${r}
|
|
21
|
+
${t}`,he=({content:e,body:r,startMarker:t,endMarker:o,placement:n="replace-in-place"})=>{let s=Eo(t,r,o),i=Ne(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?Qe(e,t,o)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
|
|
22
|
+
${s}
|
|
23
|
+
`:`${s}
|
|
24
|
+
`};var Nr={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 oe="<!-- infra-kit:begin -->",ne="<!-- infra-kit:end -->",ds="<!-- infra-kit:version ",er="<!-- infra-kit:import:begin -->",rr="<!-- infra-kit:import:end -->",Po="AGENTS.md",us="CLAUDE.md",fs=we.join(".cursor","rules","infra-kit.mdc"),gs=["---","description: infra-kit CLI usage and conventions","alwaysApply: true","---",""].join(`
|
|
25
|
+
`),hs=e=>`${ds}${e} -->`,ws=e=>[hs(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
|
+
`),vs=e=>{if(J.existsSync(e)&&J.lstatSync(e).isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},_t=(e,r)=>{vs(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(we.dirname(e),{recursive:!0}),J.writeFileSync(e,r,"utf-8"),t?"updated":"created"},Nt=(e,r)=>J.existsSync(e)?J.readFileSync(e,"utf-8"):r,Ot=(e,r,t)=>{let o=J.readFileSync(e,"utf-8");if(!Ne(o,r,t))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},jt=async()=>{let e;try{e=(await W()).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=we.dirname(e),t=Nr.version,o=ws(t),n=we.join(r,Po),s=we.join(r,us),i=we.join(r,fs),l=he({content:Nt(n,""),body:o,startMarker:oe,endMarker:ne}),c=he({content:Nt(s,""),body:`@${Po}`,startMarker:er,endMarker:rr}),p=he({content:Nt(i,gs),body:o,startMarker:oe,endMarker:ne}),m=[{path:n,action:_t(n,l)},{path:s,action:_t(s,c)},{path:i,action:_t(i,p)}];Ot(n,oe,ne),Ot(s,er,rr),Ot(i,oe,ne);for(let u of m)a.info(` ${u.action.padEnd(9)} ${we.relative(r,u.path)}`);return a.info(`Agent-instruction files synced (infra-kit ${t})`),{skipped:!1,root:r,written:m}};import ve from"node:fs";import So from"node:os";import Or from"node:path";import tr from"node:fs/promises";import ks from"node:os";import ys from"node:path";import Rs from"yaml";import{z as bs}from"zod";var Oe=e=>{let r=ks.homedir();return e.startsWith(r)?`~${e.slice(r.length)}`:e},To=async e=>{try{return await tr.access(e),!0}catch{return!1}},Ft=e=>e.replace(/\.json$/,".yml"),$o=async()=>{let e;try{e=await W()}catch{return}let r=[{label:"infra-kit.json",yml:Ft(e.main),json:e.main,schema:Ye},{label:"~/.infra-kit/config.json",yml:Ft(e.userGlobal),json:e.userGlobal,schema:Ze},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:Ft(e.userProject),json:e.userProject,schema:Ze}],t=0;for(let o of r){let[n,s]=await Promise.all([To(o.yml),To(o.json)]);if(n){if(s){a.info(`\u26A0 Skipped ${Oe(o.yml)} \u2014 ${Oe(o.json)} already exists (remove the stale .yml manually)`);continue}try{let i=await tr.readFile(o.yml,"utf-8"),l=Rs.parse(i)??{},c=o.schema.safeParse(l);if(!c.success){a.info(`\u26A0 Skipped ${Oe(o.yml)} \u2014 invalid config: ${bs.prettifyError(c.error)}`);continue}await tr.mkdir(ys.dirname(o.json),{recursive:!0}),await tr.writeFile(o.json,`${JSON.stringify(c.data,null,2)}
|
|
27
|
+
`,"utf-8"),await tr.rm(o.yml,{force:!0}),a.info(`\u2713 Migrated ${Oe(o.yml)} \u2192 ${Oe(o.json)}`),t++}catch(i){a.info(`\u26A0 Skipped ${Oe(o.yml)} \u2014 ${i.message}`)}}}t>0&&ge()};var or="# -- infra-kit:begin --",je="# -- infra-kit:end --",xs=[["# region infra-kit","# endregion infra-kit"]],Cs="# infra-kit shell functions",Es=`{}
|
|
28
|
+
`,Ps=`// infra-kit user-global config \u2014 ~/.infra-kit/config.json
|
|
21
29
|
//
|
|
22
30
|
// Merge chain (later layers override earlier ones at top-level keys):
|
|
23
31
|
// 1. <repo>/infra-kit.json \u2014 committed project config (required)
|
|
@@ -38,64 +46,63 @@ ${o?"\u2705 All valid":"\u274C Audit failed"} (${t.length} checked)`);let s={all
|
|
|
38
46
|
// },
|
|
39
47
|
// "worktrees": { "openInGithubDesktop": false, "openInCmux": true }
|
|
40
48
|
}
|
|
41
|
-
`,
|
|
42
|
-
|
|
43
|
-
`),a.info(`Added infra-kit shell functions to ${e}`),await po(),tn(),a.info("Run `source ~/.zshrc` or open a new terminal to activate.")},tn=()=>{let e=yr.join(uo.homedir(),".infra-kit"),r=yr.join(e,"config.json"),t=yr.join(e,"config.example.jsonc");if(re.existsSync(r)){a.info(`User-global config already present at ${r}`);return}re.mkdirSync(e,{recursive:!0}),re.writeFileSync(r,en,"utf-8"),re.writeFileSync(t,rn,"utf-8"),a.info(`Wrote user-global config to ${r} (see ${t} for the annotated reference)`)},on=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"),mo=(e,r,t)=>{let o=e.indexOf(r),s=e.indexOf(t);if(o===-1||s===-1)return null;let n=e.slice(0,o).replace(/\n+$/,""),i=e.slice(s+t.length).replace(/^\n+/,"");return n+(i?`
|
|
44
|
-
${i}`:"")},sn=e=>{let r=mo(e,Rr,Ke);if(r!==null)return r;for(let[l,c]of Zs){let p=mo(e,l,c);if(p!==null)return p}let t=e.indexOf(Qs);if(t===-1)return e;let o=e.slice(0,t).replace(/\n+$/,""),s=e.slice(t).split(`
|
|
45
|
-
`),n=0;for(;n<s.length&&on(s[n]);)n++;let i=s.slice(n).join(`
|
|
49
|
+
`,Mt=async()=>{let e=Or.join(So.homedir(),".zshrc"),r=ve.existsSync(e)?Ss(ve.readFileSync(e,"utf-8")):"",t=he({content:r,body:Io(),startMarker:or,endMarker:je,placement:"append-end"});ve.writeFileSync(e,t),a.info(`Added infra-kit shell functions to ${e}`),await $o(),Ts(),await jt(),a.info("Run `source ~/.zshrc` or open a new terminal to activate.")},Ts=()=>{let e=Or.join(So.homedir(),".infra-kit"),r=Or.join(e,"config.json"),t=Or.join(e,"config.example.jsonc");if(ve.existsSync(r)){a.info(`User-global config already present at ${r}`);return}ve.mkdirSync(e,{recursive:!0}),ve.writeFileSync(r,Es,"utf-8"),ve.writeFileSync(t,Ps,"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"),Ss=e=>{let r=Qe(e,or,je);if(r!==null)return r;for(let[l,c]of xs){let p=Qe(e,l,c);if(p!==null)return p}let t=e.indexOf(Cs);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(`
|
|
46
51
|
`);return o+(i?`
|
|
47
|
-
${i}`:"")},
|
|
48
|
-
`)}
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
`))
|
|
52
|
+
${i}`:"")},Io=()=>{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
|
+
`)},Ao=()=>`${or}
|
|
54
|
+
${Io()}
|
|
55
|
+
${je}`;var Me=async(e,r,t,o)=>{try{return await No`${r}`,{name:e,status:"pass",message:t}}catch{return{name:e,status:"fail",message:o}}},Is=()=>{let e="zshrc init block",r=nr.join(_o.homedir(),".zshrc");if(!se.existsSync(r))return{name:e,status:"fail",message:"~/.zshrc not found. Run: infra-kit init"};let t=se.readFileSync(r,"utf-8"),o=t.indexOf(or),n=t.indexOf(je);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+je.length).trim(),i=Ao().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"}},As=async()=>{let e="pnpm enableGlobalVirtualStore";try{let r=await b(),t=nr.join(r,"pnpm-workspace.yaml");if(!se.existsSync(t))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${t}`};let o=se.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}`}}},_s=async()=>{let e="infra-kit config valid";try{return ge(),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}}},Ns=async()=>{let e="user override path";try{let r=await W(),t=_o.homedir(),o=r.userProject.startsWith(t)?`~${r.userProject.slice(t.length)}`:r.userProject,s=se.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}}},Os=[1,2,3,5,7],js=async()=>{let e="rtk configured";try{let t=(await No`rtk init --show`).stdout.split(`
|
|
56
|
+
`).map(n=>n.trim()).filter(n=>n.startsWith("[ok]")||n.startsWith("[--]")),o=[];for(let n of Os){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}`}}},Fs=async()=>{let e;try{e=(await W()).main}catch{return[]}if(!se.existsSync(e))return[];let r=nr.dirname(e),t=(n,s,i)=>{let l=nr.join(r,n),c=se.existsSync(l)?se.readFileSync(l,"utf-8"):"";return Ne(c,s,i)};return[{name:"AGENTS.md block",present:t("AGENTS.md",oe,ne),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",er,rr),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(nr.join(".cursor","rules","infra-kit.mdc"),oe,ne),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}))},jr=async()=>{let r=[...await Promise.all([Me("gh installed",["gh","--version"],"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/"),Me("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),Me("doppler installed",["doppler","--version"],"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli"),Me("doppler authenticated",["doppler","me"],"Doppler CLI is authenticated","Doppler CLI is not authenticated. Run: doppler login"),Me("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"),Me("rtk installed",["rtk","--version"],"RTK is installed","RTK is not installed. Install from: https://github.com/rtk-ai/rtk"),js(),Promise.resolve(Is()),As(),_s(),Ns()]),...await Fs()];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}},Ms=v({name:"doctor",description:"Check installation and authentication status of gh, doppler, aws, and rtk CLIs",inputSchema:{},outputSchema:{checks:Fe.array(Fe.object({name:Fe.string().describe("Name of the check"),status:Fe.enum(["pass","fail"]).describe("Check result"),message:Fe.string().describe("Details about the check result")})).describe("List of all check results"),allPassed:Fe.boolean().describe("Whether all checks passed")},handler:jr});import Vt from"node:fs";import jo from"node:path";import Ls from"node:process";import{z as Fr}from"zod";import sr from"node:fs";import Ds from"node:os";import Dt from"node:path";import Lt from"node:process";var ke="env-load.sh",Wt="env-clear.sh",ir="INFRA_KIT_SESSION",ye="INFRA_KIT_ENV_CONFIG",Re="INFRA_KIT_ENV_PROJECT",be="INFRA_KIT_ENV_LOADED_AT",ar=/^([A-Z_]\w*)=/i,cr=e=>{if(!sr.existsSync(e))return[];let r=sr.readFileSync(e,"utf-8"),t=[];for(let o of r.split(`
|
|
58
|
+
`)){let n=ar.exec(o);n&&t.push(n[1])}return t},Oo=()=>{let e=Lt.env.XDG_CACHE_HOME,r=e&&e.length>0?e:Dt.join(Ds.homedir(),".cache");return Dt.join(r,"infra-kit")},xe=()=>{let e=Lt.env[ir];if(!e)throw new Error(`${ir} is not set. Run \`infra-kit init\` then \`source ~/.zshrc\`.`);return Dt.join(Oo(),e)},lr=(e,r,t)=>{let o=`${e}.tmp.${Lt.pid}`;sr.writeFileSync(o,r,{mode:t});try{sr.renameSync(o,e)}catch(n){throw sr.rmSync(o,{force:!0}),n}},B="-worktrees";var Mr=async()=>{let e=xe(),r=jo.join(e,ke);if(!Vt.existsSync(r))throw new Error("No loaded environment found. Run `env-load` first.");let t=cr(r),o=[...t.map(i=>`unset ${i}`),`unset ${ye}`,`unset ${Re}`,`unset ${be}`],n=jo.resolve(e,Wt);Vt.mkdirSync(e,{recursive:!0,mode:448}),lr(n,`${o.join(`
|
|
52
59
|
`)}
|
|
53
|
-
`,384),
|
|
54
|
-
`),
|
|
55
|
-
`),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),Ls.stdout.write(`${n}
|
|
61
|
+
`),Vt.unlinkSync(r);let s={filePath:n,variableCount:t.length,unsetStatements:o};return{content:h(JSON.stringify(s,null,2)),structuredContent:s}},Ws=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:Fr.string().describe("Path to the file that must be sourced to apply"),variableCount:Fr.number().describe("Number of variables cleared"),unsetStatements:Fr.array(Fr.string()).describe("Unset statements generated")},handler:Mr});import{z as Jt}from"zod";var pr=async()=>{let{envManagement:e}=await x();return e.config.name};var Dr=async()=>{let e=await pr(),{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}},Vs=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:Jt.string().describe("Detected Doppler project name"),configs:Jt.array(Jt.string()).describe("Available environment configs")},handler:Dr});import Bs from"@inquirer/select";import{Buffer as Ks}from"node:buffer";import Gs from"node:fs";import Us from"node:path";import Mo from"node:process";import{z as dr}from"zod";import{$ as Lr}from"zx";import{$ as Fo}from"zx";var mr=async()=>{try{await Fo`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 Fo`doppler me`}catch(e){throw new Error("Doppler CLI is not authenticated. Run: doppler login",{cause:e})}};var Js=()=>{let e="",r=[],t=!1;return{start(o){e=o,r=[],t=!1},setInteractive(){t=!0},addOption(o,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:
|
|
56
63
|
pnpm exec infra-kit ${e} ${o}
|
|
57
|
-
`)},reset(){e="",r=[],t=!1}}},
|
|
64
|
+
`)},reset(){e="",r=[],t=!1}}},d=Js();var Wr=async e=>{await mr();let{config:r}=e;d.start("env-load");let t="";if(r)t=r;else{let{environments:u}=await x();d.setInteractive(),t=await Bs({message:"Select environment config",choices:u.map(f=>({name:f,value:f}))},{output:Mo.stderr})}d.addOption("--config",t);let o=await pr(),n=await zs(o,t);Zs(n);let s=new Date().toISOString(),i=["set -a",n,`${ye}=${Bt(t)}`,`${Re}=${Bt(o)}`,`${be}=${Bt(s)}`,"set +a"],l=xe(),c=Us.resolve(l,ke);Gs.mkdirSync(l,{recursive:!0,mode:448}),lr(c,`${i.join(`
|
|
58
65
|
`)}
|
|
59
|
-
`,384),
|
|
60
|
-
`),
|
|
61
|
-
`).filter(r=>
|
|
62
|
-
`)){let t=r.trim();if(!(t.length===0
|
|
63
|
-
`),
|
|
64
|
-
`);let c={sessionId:r,sessionLoadedCount:o,sessionTotalCount:
|
|
65
|
-
`);throw new Error(i)}let
|
|
66
|
+
`,384),Mo.stdout.write(`${c}
|
|
67
|
+
`),d.print();let p=Xs(n),m={filePath:c,variableCount:p,project:o,config:t};return{content:h(JSON.stringify(m,null,2)),structuredContent:m}},Do=1024*1024,qs=3e4,zs=async(e,r)=>{let t=Lr.quiet;Lr.quiet=!0;try{let o=await Lr`doppler secrets download --no-file --format env --project ${e} --config ${r}`.timeout(qs);return Hs(o.stdout),o.stdout.trim()}finally{Lr.quiet=t}},Hs=e=>{let r=Ks.byteLength(e,"utf-8");if(r>Do)throw new Error(`doppler returned unexpectedly large output (${r} bytes > ${Do}) \u2014 refusing to write to disk`)},Xs=e=>e.split(`
|
|
68
|
+
`).filter(r=>ar.test(r)).length,Ys=new Set(["set -a","set +a"]),Bt=e=>`'${e.replaceAll("'","'\\''")}'`,Zs=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||Ys.has(t))&&!ar.test(t))throw new Error(`doppler returned unexpected output for env-load (expected KEY=value lines, got: ${JSON.stringify(t.slice(0,80))})`)}},Qs=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:dr.string().describe('Doppler config / environment name to load (e.g. "dev", "arthur", "renana"). Required for MCP calls.')},outputSchema:{filePath:dr.string().describe("Path to the file that must be sourced to apply variables"),variableCount:dr.number().describe("Number of variables loaded"),project:dr.string().describe("Doppler project name"),config:dr.string().describe("Doppler config name")},handler:Wr});import ei from"node:path";import ur from"node:process";import{z as De}from"zod";var Vr=async()=>{await mr(),a.info("Environment session status:");let e=xe(),r=ur.env[ir],t=ei.join(e,ke),o=0,n=0,s=ur.env[ye]??null,i=ur.env[Re]??null,l=ur.env[be]??null;if(s){let p=cr(t);p.length>0&&(n=p.length,o=p.filter(u=>u in ur.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
|
+
`),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}},ri=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:De.string().describe("Current terminal session ID"),sessionLoadedCount:De.number().describe("Number of cached vars active in the current session"),sessionTotalCount:De.number().describe("Total number of cached var names"),sessionConfig:De.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:De.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:De.string().nullable().describe("ISO 8601 timestamp of when the env was loaded")},handler:Vr});import si from"@inquirer/checkbox";import ii from"@inquirer/confirm";import ai from"node:process";import{z as Je}from"zod";import{$ as K}from"zx";import{$ as Pm}from"zx";import Ur from"node:process";import{$ as _}from"zx";import{$ as gr}from"zx";import fr from"node:process";var Kt=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}},Le=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}},Jr=async(e,r)=>{try{return(await Le(r)).find(n=>n.name===e)||null}catch(t){throw a.error({error:t,versionName:e},"Error finding Jira version by name"),t}},Br=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}},Gt=async(e,r)=>{try{let{versionName:t}=e,o=await Jr(t,r);if(!o)throw a.error({versionName:t},"Jira version not found"),new Error(`Version "${t}" not found in Jira project`);return await Br({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}},We=async()=>{let e=fr.env.JIRA_BASE_URL,r=fr.env.JIRA_TOKEN||fr.env.JIRA_API_TOKEN,t=fr.env.JIRA_PROJECT_ID,o=fr.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}},Ce=async()=>{try{return await We()}catch(e){return a.warn({error:e},"Jira configuration not available, skipping Jira integration"),null}};var oi=e=>{if(e===null||typeof e!="object")return;let r=e.stderr;return typeof r=="string"&&r.length>0?r:void 0},ni=(e,r)=>{let t=r.stderrExcerpt??oi(e),o=[`failed to ${r.operation}`];return t&&o.push(`stderr: ${t.slice(0,200).trim()}`),r.remediation&&o.push(`try: ${r.remediation}`),o.join(" \u2014 ")},g=class extends Error{operation;remediation;constructor(r,t){super(ni(r,t),{cause:r}),this.name="OperationError",this.operation=t.operation,this.remediation=t.remediation}};var Lo="dev",Kr=e=>e==="hotfix"?"main":"dev",Ut=async(e="regular")=>{let r=Kr(e);gr.quiet=!0,await gr`git fetch origin`,await gr`git switch ${r}`,await gr`git pull origin ${r}`,gr.quiet=!1},qt=async e=>{let{id:r,jiraConfig:t,description:o,type:n="regular"}=e,s=D(r),i=await Kt({name:s,projectId:t.projectId,description:o||"",released:!1,archived:!1},t),l=`${t.baseUrl}/projects/${i.version.projectId}/versions/${i.version.id}/tab/release-report-all-issues`,c=await Gr({id:r,jiraVersionUrl:l,type:n,description:o});return{version:T(r),type:n,branchName:c.branchName,prUrl:c.prUrl,jiraVersionUrl:l}},$=async()=>{let e=new Map,r=await Ce();if(!r)return e;try{let t=await Le(r);for(let o of t)o.description&&e.set(o.name,o.description)}catch{}return e},Ve=(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",Wo=e=>e.flatMap(r=>{let t=R(r);return t?[{branch:r,id:t,label:T(t)}]:[]}),X=e=>{try{return z(G(e))}catch(r){throw new g(r,{operation:`resolve release ref "${e}"`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'})}},hr=e=>{if(e===Lo)return Lo;let r=R(e);return r?T(r):e},Ee=e=>e.flatMap(r=>{let t=R(r);return t?[T(t)]:[]}),A=e=>{let{branches:r,descriptions:t,types:o}=e,n=Wo(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(D(l)),u=" ".repeat(s-c.length+3),f=p?Ve(c,p,s):c;return m&&(f=p?`${f} ${m}`:`${c}${u}${m}`),{name:f,value:i}})};var Vo=e=>e.map(r=>({pr:r,id:R(r.headRefName)})).filter(r=>r.id!==null).sort((r,t)=>vt(r.id,t.id,{a:r.pr.createdAt,b:t.pr.createdAt})).map(r=>r.pr),Jo=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))},qr=async()=>{try{let e=await Jo();return e.length===0&&(a.error("\u274C No release PRs found. Check the project folder for the script. Exiting..."),Ur.exit(1)),Vo(e).map(r=>r.headRefName)}catch(e){a.error({error:e},"\u274C Error fetching release PRs"),Ur.exit(1)}},E=async()=>{try{let e=await Jo();return e.length===0&&(a.error("\u274C No release PRs found. Check the project folder for the script. Exiting..."),Ur.exit(1)),Vo(e).map(r=>({branch:r.headRefName,title:r.title,createdAt:r.createdAt}))}catch(e){a.error({error:e},"\u274C Error fetching release PRs"),Ur.exit(1)}},zr=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}},Gr=async e=>{let{id:r,jiraVersionUrl:t,type:o,description:n}=e,s=wt(r,o),i=Kr(o),l=z(r),c=n&&n.trim()!==""?`${t}
|
|
66
73
|
|
|
67
|
-
${
|
|
68
|
-
`;try{
|
|
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 Hr=async e=>{let{all:r,confirmedCommand:t}=e;d.start("merge-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 si({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",Ee(s));let l=t?!0:await ii({message:`Are you sure you want to merge dev into these branches: ${s.join(", ")}?`});t||d.setInteractive(),l||(a.info("Operation cancelled. Exiting..."),ai.exit(0)),t||d.addOption("--yes",!0),K.quiet=!0,await K`git fetch origin`,await K`git switch dev`,await K`git pull origin dev`;let c=[];for(let m of s)await ci(m)||c.push(m);if(K.quiet=!1,c.length>0){a.info(`
|
|
69
76
|
\u26A0\uFE0F ${c.length} branch(es) failed to merge automatically.
|
|
70
|
-
`),a.info("\u{1F4CB} Manual merge script for failed branches:");for(let
|
|
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
|
|
71
78
|
|
|
72
|
-
git switch ${
|
|
73
|
-
git push origin ${
|
|
74
|
-
`);a.info(`\u2705 ${
|
|
75
|
-
`);
|
|
76
|
-
`)){let o
|
|
77
|
-
`)){let o=t.match(/^[* ]\s*workspace:\d+\s+(.+?)(?:\s+\[selected\])?\s*$/);if(!o)continue;let s=o[1]?.trim();s&&r.add(s)}return r}catch(e){return a.debug({error:e},"cmux: skipped listing workspace titles"),new Set}};import{$ as nr}from"zx";var ir=async e=>{let{cwd:r,title:t}=e,o=(await nr`cmux workspace create --cwd ${r}`).stdout,s=Vn(o),n=(await nr`cmux list-pane-surfaces --workspace ${s}`).stdout,i=Jn(n);await nr`cmux new-split right --workspace ${s} --surface ${i}`,await nr`cmux new-split down --workspace ${s} --surface ${i}`,t&&await nr`cmux workspace rename --workspace ${s} ${t}`},Jn=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]},Vn=e=>{let r=e.match(/workspace:\d+/);if(!r)throw new Error("cmux: could not locate workspace ref in workspace create output");return r[0]};var H=e=>{let{repoName:r,branch:t}=e,o=R(t),s=o?E(o):t;return`${r} ${s}`};var ar=async e=>{let{branches:r,worktreeDir:t,repoName:o,pruneFolder:s=!1}=e,n=await Promise.allSettled(r.map(async l=>{let c=`${t}/${l}`,p=H({repoName:o,branch:l});return await sr(p),await Ot`git worktree remove ${c}`,l})),i=[];for(let[l,c]of n.entries())if(c.status==="fulfilled")i.push(c.value);else{let p=r[l],d=new g(c.reason,{operation:`remove worktree for ${p}`,remediation:"check 'git worktree list' for the path; uncommitted changes block removal"});a.error({error:c.reason,msg:d.message})}return s&&i.length===r.length&&(await Ot`git worktree prune`,await Ot`rm -rf ${t}`,a.info(`\u{1F5D1}\uFE0F Removed worktree folder: ${t}`),a.info("")),i};var _e=async(e,r,t)=>{try{return await t()}catch(o){throw a.error({err:Nt(o)},`\u274C Failed to ${e}`),new g(o,{operation:e,remediation:r})}},So=async e=>{let r=await L`gh pr list --head ${e} --state all --json number,state,title --limit 1`;return JSON.parse(r.stdout)[0]??null},Un=async e=>{let r=fr(e),t=await L`gh pr list --head dev --base main --state merged --json number,state,title --limit 20`;return JSON.parse(t.stdout).find(n=>n.title===r)??null},To=async()=>{let e=await L`gh pr list --head dev --base main --state open --json number,state,title --limit 5`;return JSON.parse(e.stdout)[0]??null},Gn=async e=>{let r=z(e),t=await So(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}},zn=async()=>{let e=await P(),r=e.map(i=>i.branch),t=new Map(e.map(i=>[i.branch,C(i.title)]));m.setInteractive();let o=await T(),s=await Kn({message:"\u{1F33F} Select release branch",choices:A({branches:r,descriptions:o,types:t})}),n=e.find(i=>i.branch===s);if(!n)throw a.error(`\u274C Release branch ${s} not found in open PRs.`),new g(void 0,{operation:`deliver release ${s}`,remediation:`confirm an open PR exists for ${s} ('gh pr list')`});return{selectedReleaseBranch:s,releasePrTitle:n.title}},Hn=async e=>{if(!(await j("release")).includes(e))return;let[t,o]=await Promise.all([b(),F()]),s=`${t}${J}`;if((await ar({branches:[e],worktreeDir:s,repoName:o})).length===0)throw new g(void 0,{operation:`remove worktree for ${e} before merge`,remediation:`run manually: git worktree remove ${s}/${e} (use --force if uncommitted changes)`})},Xn=async e=>{let{selectedReleaseBranch:r,releaseType:t}=e,o=t==="hotfix"?"main":"dev",s=await So(r);if(!s)throw new g(void 0,{operation:`look up release PR for ${r}`,remediation:"verify the PR exists in GitHub"});if(s.state==="MERGED"){a.info(`\u2713 Release PR ${r} already merged \u2014 skipping`);return}if(s.state==="CLOSED")throw new g(void 0,{operation:`merge release PR ${r} into ${o}`,remediation:"the PR is closed without merge; reopen it or create a new release"});await _e(`merge release PR ${r} into ${o}`,`check 'gh pr view ${r}' for mergeability and required reviews`,async()=>{await L`gh pr merge ${r} --squash --admin --delete-branch`})},Yn=async e=>{let r=E(e),t=fr(e),o=await To();if(o){let n=o.number;return o.title!==t&&(a.info(`Adopting open dev \u2192 main PR #${n} ("${o.title}") and retitling for ${r}`),await _e(`retitle dev \u2192 main PR #${n} to "${t}"`,`update manually: gh pr edit ${n} --title "${t}"`,async()=>{await L`gh pr edit ${n} --title ${t}`})),n}await _e(`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 L`gh pr create --base main --head dev --title ${t} --body ""`});let s=await To();if(!s)throw new g(void 0,{operation:`look up RC PR for ${r}`,remediation:"verify the RC PR was created ('gh pr list --head dev --base main')"});return s.number},Zn=async e=>{let r=E(e);if(await Un(e)){a.info(`\u2713 RC PR for ${r} already merged into main \u2014 skipping`);return}let o=await Yn(e);await _e(`merge RC PR #${o} (dev \u2192 main) for ${r}`,`check 'gh pr view ${o}' for mergeability and required reviews`,async()=>{await L`gh pr merge ${o} --squash --admin`})},Qn=async()=>{L.quiet=!1,await _e("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await L`gh workflow run deploy-all.yml --ref main -f environment=prod`}),L.quiet=!0},ei=async()=>{await _e("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 L`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},ri=async e=>{let r=await he();if(!r){a.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let t=D(e);await St({versionName:t},r)}catch(t){a.error({err:Nt(t)},"Failed to deliver Jira release (non-blocking)")}},Lr=async e=>{let{version:r,confirmedCommand:t}=e;m.start("release-deliver");let{selectedReleaseBranch:o,releasePrTitle:s}=r?await Gn(r):await zn(),n=R(o);if(!n)throw new g(void 0,{operation:`deliver release ${o}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let i=E(n);m.addOption("--version",i),a.info(`Delivering ${n.kind==="name"?"named release":"version"} ${o}`);let l=C(s),c=t?!0:await Bn({message:`Are you sure you want to deliver version ${o} to production?`});t||m.setInteractive(),c||(a.info("Operation cancelled. Exiting..."),qn.exit(0)),m.addOption("--yes",!0),L.quiet=!0,await Hn(o),await Xn({selectedReleaseBranch:o,releaseType:l}),l!=="hotfix"&&await Zn(n),await Qn(),await ei(),L.quiet=!1,await ri(n),a.info(`Successfully delivered ${o} to production!`),m.print();let p={releaseBranch:o,version:i,type:l,success:!0};return{content:h(JSON.stringify(p,null,2)),structuredContent:p}},ti=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:cr.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:cr.string().describe("The release branch that was delivered"),version:cr.string().describe("The version that was delivered"),type:cr.enum(["regular","hotfix"]).describe("Release type"),success:cr.boolean().describe("Whether the delivery was successful")},handler:Lr});import Io from"@inquirer/select";import{z as te}from"zod";import{$ as jt}from"zx";var Dr=async e=>{let{version:r,env:t,skipTerraform:o}=e;m.start("release-deploy-all");let s="";if(r)s=r==="dev"?"dev":z(r);else{m.setInteractive();let p=await P(),d=p.map(w=>w.branch),u=new Map(p.map(w=>[w.branch,C(w.title)])),f=await T();s=await Io({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...A({branches:d,descriptions:f,types:u})]})}let n=or(s);m.addOption("--version",n);let{environments:i}=await x(),l="";if(t?l=t:(m.setInteractive(),l=await Io({message:"\u{1F9EA} Select environment",choices:i.map(p=>({name:p,value:p}))})),m.addOption("--env",l),!i.includes(l))throw new g(void 0,{operation:"launch deploy-all workflow",remediation:`pass one of: ${i.join(", ")}`,stderrExcerpt:`invalid environment: ${l}`});let c=o??!1;c&&m.addOption("--skip-terraform",!0);try{jt.quiet=!0,await jt`gh workflow run deploy-all.yml --ref ${s} -f environment=${l} ${c?["-f","skip_terraform_deploy=true"]:[]}`,jt.quiet=!1,a.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${s} and environment: ${l}`),m.print();let d={releaseBranch:s,version:n,environment:l,skipTerraformDeploy:c,success:!0};return{content:h(JSON.stringify(d,null,2)),structuredContent:d}}catch(p){throw a.error({error:p},"\u274C Error launching workflow"),new g(p,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},oi=v({name:"gh-release-deploy-all",description:'Dispatch the deploy-all.yml GitHub Actions workflow to deploy every service from a release branch to the given environment. Fire-and-forget \u2014 returns once GitHub accepts the workflow_dispatch, NOT when the deployment finishes; watch the workflow run for completion status. Use gh-release-deploy-selected for a subset of services. Pass version="dev" to deploy from the dev branch instead of a release branch. Both "version" and "env" are required when invoked via MCP (interactive pickers are unavailable without a TTY).',inputSchema:{version:te.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign") \u2014 resolves to the release/vX.Y.Z or release/n/<name> branch. Pass "dev" to deploy from the dev branch instead. Required for MCP calls.'),env:te.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),skipTerraform:te.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:te.string().describe("The release branch that was deployed"),version:te.string().describe("The version that was deployed"),environment:te.string().describe("The environment deployed to"),skipTerraformDeploy:te.boolean().describe("Whether terraform deployment was skipped"),success:te.boolean().describe("Whether the deployment was successful")},handler:Dr});import si from"@inquirer/checkbox";import Ao from"@inquirer/select";import ni from"node:fs/promises";import{resolve as ii}from"node:path";import ai from"yaml";import{z as W}from"zod";import{$ as Ft}from"zx";var Mr=async e=>{let{version:r,env:t,services:o,skipTerraform:s}=e;m.start("release-deploy-selected");let n="";if(r)n=r==="dev"?"dev":z(r);else{m.setInteractive();let w=await P(),S=w.map(Re=>Re.branch),I=new Map(w.map(Re=>[Re.branch,C(Re.title)])),_=await T();n=await Ao({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...A({branches:S,descriptions:_,types:I})]})}let i=or(n);m.addOption("--version",i);let{environments:l}=await x(),c="";if(t?c=t:(m.setInteractive(),c=await Ao({message:"\u{1F9EA} Select environment",choices:l.map(w=>({name:w,value:w}))})),m.addOption("--env",c),!l.includes(c))throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`pass one of: ${l.join(", ")}`,stderrExcerpt:`invalid environment: ${c}`});let p=await ci();if(p.length===0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:"check .github/workflows/deploy-selected-services.yml for boolean service inputs",stderrExcerpt:"no services found in workflow file"});let d=[];if(o&&o.length>0?d=o:(m.setInteractive(),d=await si({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:p.map(w=>({name:w,value:w}))})),m.addOption("--services",d),d.length===0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${p.join(", ")}`,stderrExcerpt:"no services selected"});let u=d.filter(w=>!p.includes(w));if(u.length>0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${p.join(", ")}`,stderrExcerpt:`invalid services: ${u.join(", ")}`});let f=s??!1;f&&m.addOption("--skip-terraform",!0);try{Ft.quiet=!0;let w=d.flatMap(_=>["-f",`${_}=true`]);await Ft`gh workflow run deploy-selected-services.yml --ref ${n} -f environment=${c} ${w} ${f?["-f","skip_terraform_deploy=true"]:[]}`,Ft.quiet=!1,a.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${n}, environment: ${c}, services: ${d.join(", ")}`),m.print();let I={releaseBranch:n,version:i,environment:c,services:d,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"})}},ci=async()=>{let e=await b(),r=ii(e,".github/workflows/deploy-selected-services.yml"),t=await ni.readFile(r,"utf-8"),s=ai.parse(t).on.workflow_dispatch.inputs,n=[];for(let[i,l]of Object.entries(s))l.type==="boolean"&&i!=="skip_terraform_deploy"&&n.push(i);return n},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:W.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign") \u2014 resolves to the release/vX.Y.Z or release/n/<name> branch. Pass "dev" to deploy from the dev branch instead. Required for MCP calls.'),env:W.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),services:W.array(W.string()).describe('Service names to deploy. Each must match a boolean input declared in .github/workflows/deploy-selected-services.yml (e.g. "client-be", "client-fe"). Required for MCP calls.'),skipTerraform:W.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:W.string().describe("The release branch that was deployed"),version:W.string().describe("The version that was deployed"),environment:W.string().describe("The environment deployed to"),services:W.array(W.string()).describe("The services that were deployed"),skipTerraformDeploy:W.boolean().describe("Whether terraform deployment was skipped"),success:W.boolean().describe("Whether the deployment was successful")},handler:Mr});import{z as Oe}from"zod";var Wr=async()=>{let r=(await P()).flatMap(i=>{let l=R(i.branch);return l?[{version:E(l),jiraKey:D(l),type:C(i.title)}]:[]}),t=await T(),o=Math.max(...r.map(i=>i.version.length)),s=r.map(i=>{let l=Ae(i.version,i.type,o),c=t.get(i.jiraKey);return c?`${l} ${c}`:l});a.info(`All release branches:
|
|
79
|
+
git switch ${m} && git pull origin ${m} && git merge origin/dev
|
|
80
|
+
git push origin ${m} && git switch dev
|
|
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}},ci=async e=>{try{return await K`git switch ${e}`,await K`git pull origin ${e}`,await K`git merge origin/dev --no-edit`,await K`git push origin ${e}`,await K`git switch dev`,a.info(`Successfully merged dev into ${e}`),!0}catch(r){let t=new g(r,{operation:`merge dev into ${e}`,remediation:"resolve conflicts manually or rerun after 'git fetch origin'"});return a.error({error:r,branch:e,msg:t.message}),await K`git reset --merge HEAD~1`,!1}},li=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:Je.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:Je.number().describe("Number of successful merges"),failedMerges:Je.number().describe("Number of failed merges"),failedBranches:Je.array(Je.string()).describe("List of branches that failed to merge"),totalBranches:Je.number().describe("Total number of branches processed")},handler:Hr});import gi from"@inquirer/confirm";import hi from"@inquirer/select";import wi from"node:process";import{z as br}from"zod";import{$ as M}from"zx";var Bo=(e,r)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-r).trim()},zt=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=Bo(r.stderr,500);n&&(t.stderr=n);let s=Bo(r.stdout,200);return s&&(t.stdout=s),t};import{$ as Ht}from"zx";var pi=/\bv(\d+\.\d+\.\d+)\b/g,U=e=>e.trim().replace(/\s+/g," ").replace(pi,"$1");import{$ as Ko}from"zx";var wr=async e=>{try{let r=(await Ko`cmux list-workspaces`.quiet()).stdout,t=mi(r,e);if(!t)return;await Ko`cmux close-workspace --workspace ${t}`.quiet()}catch(r){a.debug({error:r,title:e},"cmux: skipped closing workspace")}},mi=(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 di}from"zx";var vr=async()=>{try{let e=(await di`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 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:
|
|
78
85
|
`),a.info(`
|
|
79
|
-
${
|
|
86
|
+
${n.join(`
|
|
80
87
|
`)}
|
|
81
|
-
`);let
|
|
82
|
-
`).map(r=>{let t=r.indexOf(" ");return t===-1?null:R(r.slice(t+1))}).filter(r=>r!==null&&r.kind==="version").map(r=>r.raw),
|
|
83
|
-
- `),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}},Fi=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:Ke.array(Ke.object({version:Ke.string().describe("Release version"),type:Ke.enum(["regular","hotfix"]).describe("Release type"),description:Ke.string().nullable().describe("Jira version description")})).describe("List of all release branches"),count:Ke.number().describe("Number of release branches")},handler:Qr});import tn from"@inquirer/confirm";import en from"@inquirer/select";import tt from"node:process";import{z as P}from"zod";import{question as io}from"zx";import{$ as rt}from"zx";var ae=e=>e.slice(1).split(".").map(Number),Zt=e=>[...e].sort((r,t)=>{let[o,n,s]=ae(r),[i,l,c]=ae(t);return o!==i?(o??0)-(i??0):n!==l?(n??0)-(l??0):(s??0)-(c??0)});var Xo="next",Mi=/^v?(\d+)\.(\d+)\.(\d+)$/,Di=e=>e.replace(/^.*release\//,""),Yo=e=>{let r=Di(e.trim()),t=Mi.exec(r);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null},Ho=e=>`${e[0]}.${e[1]}.${e[2]}`,eo=e=>{let r=[...e.remoteBranches??[],...e.jiraVersions??[]],t=[],o=new Set;for(let n of r){let s=Yo(n);if(!s)continue;let i=Ho(s);o.has(i)||(o.add(i),t.push(s))}return Zt(t.map(n=>Ho(n))).map(n=>ae(`v${n}`))},Pe=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},et=(e,r)=>{if(e.length===0)throw new Pe;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`},Zo=e=>e.trim().toLowerCase()===Xo,Li=e=>e==="regular"||e==="hotfix",Qo=e=>"name"in e,ro=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(!Li(c))throw new Error(`Invalid release type "${i}". Expected "regular" or "hotfix".`);let p={version:o,type:c};return l!==""&&(p.description=l),p},Qt=(e,r)=>r!==void 0&&r!==""?{...e,description:r}:e,Wi=e=>{let r=e.name.trim();return ue(r),Qt({id:{kind:"name",name:r,raw:r},type:e.type},e.description)},to=(e,r)=>{let t=[...r];return e.map(o=>{if(Qo(o))return Wi(o);let n=o.version.trim();if(n==="")throw new Error("Release entry has an empty version");if(Zo(n)){let l=et(t,o.type);return t.push(ae(`v${l}`)),Qt({id:G(l),type:o.type},o.description)}let s=Yo(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),Qt({id:G(i),type:o.type},o.description)})},oo=e=>e.some(r=>!Qo(r)&&Zo(r.version));var Vi=e=>e.split(`
|
|
89
|
+
`).map(r=>{let t=r.indexOf(" ");return t===-1?null:R(r.slice(t+1))}).filter(r=>r!==null&&r.kind==="version").map(r=>r.raw),Ji=async()=>{let e=rt.quiet;try{rt.quiet=!0;let r=await rt`git ls-remote --heads origin 'release/v*'`;return Vi(r.stdout)}finally{rt.quiet=e}},Bi=async()=>{let e=await Ce();return e?(await Le(e)).map(t=>t.name):[]},no=async()=>{let[e,r]=await Promise.allSettled([Ji(),Bi()]);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"),eo({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:r.status==="fulfilled"?r.value:[]})};var Ki='"1.2.5" or "next"',Gi=(e,r)=>{try{return et(e,r)}catch(t){if(t instanceof Pe)return null;throw t}},so=(e,r)=>{try{return to(e,r)}catch(t){throw t instanceof Pe?new g(t,{operation:"resolve release version",remediation:'pass an explicit version (e.g. "1.2.5") instead of "next" when there are no prior versions'}):t instanceof q?new g(t,{operation:"validate release name",remediation:'use a kebab-case name like "checkout-redesign" (lowercase, digits, single hyphens, not a reserved word)'}):t}},Ui=async(e,r)=>{let t=Gi(e,r),o=t?` [${t}]`:"",n=(await io(` Version (e.g. ${Ki})${o}: `)).trim(),s=n===""?t??"":n;return s===""&&(a.error("No version provided. Exiting..."),tt.exit(1)),s},qi=async()=>{let e=(await io(' Name (kebab-case, e.g. "checkout-redesign"): ')).trim();e===""&&(a.error("No name provided. Exiting..."),tt.exit(1));try{ue(e)}catch(r){let t=r instanceof Error?r.message:String(r);a.error(`${t} Exiting...`),tt.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 en({message:`Release #${i} \u2014 version or name?`,choices:[{name:"version (semver / next)",value:"version"},{name:"name (free-form)",value:"name"}],default:"version"}),c=await en({message:`Release #${i} \u2014 select type:`,choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"}),p;if(l==="name"){let u=await qi();p=so([{name:u,type:c}],[])[0]}else{let u=await Ui(await o(),c);p=so([{version:u,type:c}],t)[0],p.id.kind==="version"&&t.push(ae(`v${p.id.raw}`))}let m=(await io(" Description (optional, press Enter to skip): ")).trim();n.push({...p,...m!==""?{description:m}:{}}),s=await tn({message:"Add another release?",default:!1})}return n},Hi=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 ")},rn=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)}},Xi=async(e,r)=>{if(e&&e.length>0){let o=oo(e)?await r():[],n=so(e,o);return rn(n),n}let t=await zi(r);return rn(t),t},Yi=async(e,r)=>{let t=e.map(Hi).join(`
|
|
90
|
+
- `),o=r?!0:await tn({message:`Create the following ${e.length} release(s)?
|
|
84
91
|
- ${t}
|
|
85
|
-
`});r||
|
|
86
|
-
`),{result:
|
|
87
|
-
`),{failure:{version:o,error:i.message}}}},
|
|
92
|
+
`});r||d.setInteractive(),o||(a.info("Operation cancelled. Exiting..."),tt.exit(0)),d.addOption("--yes",!0)},Zi=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 Ut(r.type);let s=await qt({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 g(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}}}},Qi=(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.`)},ot=async e=>{let{releases:r,confirmedCommand:t}=e;d.start("release-create");let o=await We(),n=null,i=await Xi(r,async()=>(n===null&&(n=await no()),n));if(i.length===0)throw new g(void 0,{operation:"create release",remediation:'pass at least one entry in "releases" (e.g. [{ version: "1.2.5", type: "regular" }])',stderrExcerpt:"no releases provided"});await Yi(i,!!t);let l=[],c=[];for(let m of i){let{result:u,failure:f}=await Zi({entry:m,jiraConfig:o});u&&l.push(u),f&&c.push(f)}Qi(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}},ea=v({name:"release-create",description:'Create one or more releases in a single call. Each entry in "releases" carries EITHER a "version" (semver or the literal token "next") OR a "name" (free-form kebab-case identifier) \u2014 exactly one is required and they are mutually exclusive. Each entry also has its own type (regular|hotfix, default regular) and optional description, so regular and hotfix releases can be mixed in the same invocation. For each release this tool switches to the appropriate base branch (dev for regular, main for hotfix), cuts the release branch (release/v<semver> for versions, release/n/<name> for names), opens a GitHub release PR, and creates the matching Jira fix version (v<semver> for versions, <name> for names). The literal token "next" auto-increments from the union of remote release branches and Jira fix versions (regular bumps minor + resets patch; hotfix bumps patch on the highest minor); multiple "next" tokens advance sequentially across mixed types. Named releases never auto-bump and "next" is version-only. Confirmation is auto-skipped for MCP calls, so the caller is responsible for gating. Continues on per-release failure and reports successes/failures.',inputSchema:{releases: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:ot});import ra from"@inquirer/confirm";import ta from"@inquirer/select";import oa from"node:process";import{z as ce}from"zod";import{question as na}from"zx";var on=(e,r)=>`${e.baseUrl}/projects/${r.projectId}/versions/${r.id}/tab/release-report-all-issues`,sa=(e,r)=>r.trim()!==""?`${e}
|
|
88
95
|
|
|
89
96
|
${r}`:`${e}
|
|
90
|
-
`,
|
|
91
|
-
(press Enter to keep current): `)).replace(/\n$/,"");return o===""?e:o},
|
|
92
|
-
from: "${
|
|
97
|
+
`,ia=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 ta({message:"\u{1F33F} Select release branch",choices:A({branches:r,descriptions:o,types:t})});return{branch:n,type:t.get(n)||"regular"}},aa=async e=>{let t=(await E()).find(o=>o.branch===e);if(!t)throw new g(void 0,{operation:`edit description for ${e}`,remediation:`confirm an open PR exists for ${e} ('gh pr list')`});return C(t.title)},ca=async e=>{let r=e===""?"(no current description)":`current: "${e}"`,o=(await na(` New description ${r}
|
|
98
|
+
(press Enter to keep current): `)).replace(/\n$/,"");return o===""?e:o},nt=async e=>{let{version:r,description:t,confirmedCommand:o}=e;d.start("release-desc-edit");let n=await We(),s;r?(s=X(r),await aa(s)):(d.setInteractive(),s=(await ia()).branch);let i=R(s);if(!i)throw new g(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=D(i),p=await Jr(c,n);if(!p)throw new g(void 0,{operation:`edit description for ${c}`,remediation:`create the Jira fix version "${c}" first or pick a different release`});let m=p.description??"",u;if(t!==void 0?(u=t,d.addOption("--description",u)):(d.setInteractive(),u=await ca(m)),u===m){a.info(`No change \u2014 description for ${c} is already: "${m}"`),d.print();let N={version:l,branch:s,jiraVersionUrl:on(n,p),previousDescription:m,newDescription:u,changed:!1};return{content:h(JSON.stringify(N,null,2)),structuredContent:N}}let f=o?!0:await ra({message:`Update description for ${c}?
|
|
99
|
+
from: "${m}"
|
|
93
100
|
to: "${u}"
|
|
94
|
-
`});o||
|
|
95
|
-
`),
|
|
96
|
-
`,"utf-8"),{added:c,skipped:p}};import
|
|
97
|
-
`,"utf-8");let
|
|
101
|
+
`});o||d.setInteractive(),f||(a.info("Operation cancelled. Exiting..."),oa.exit(0)),d.addOption("--yes",!0),await Br({versionId:p.id,description:u},n);let w=on(n,p),S=sa(w,u);await zr({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}},la=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:ce.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:ce.string().describe("New description. Empty string clears the description.")},outputSchema:{version:ce.string().describe("Release version"),branch:ce.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/n/checkout-redesign")'),jiraVersionUrl:ce.string().describe("Jira fix version URL"),previousDescription:ce.string().describe("The description before the update"),newDescription:ce.string().describe("The description after the update"),changed:ce.boolean().describe("Whether the description actually changed")},handler:nt});import{z as pa}from"zod";var st=async()=>{let e=Nr.version;a.info(e);let r={version:e};return{content:h(JSON.stringify(r,null,2)),structuredContent:r}},ma=v({name:"version",description:"Print the installed infra-kit CLI version",inputSchema:{},outputSchema:{version:pa.string().describe("Installed infra-kit CLI version (from package.json)")},handler:st});import ua from"@inquirer/checkbox";import co from"@inquirer/confirm";import fa from"@inquirer/select";import ga from"node:process";import{z as le}from"zod";import{$ as $e}from"zx";import nn from"node:fs/promises";import it from"node:path";var xr=async e=>{let{workspacePath:r,folderPaths:t}=e,o=it.dirname(r),n;try{n=await nn.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=>it.resolve(o,m.path))),c=[],p=[];for(let m of t){let u=it.resolve(m);if(l.has(u)){p.push(m);continue}let f=it.relative(o,u);i.push({path:f}),l.add(u),c.push(m)}return s.folders=i,await nn.writeFile(r,`${JSON.stringify(s,null,2)}
|
|
103
|
+
`,"utf-8"),{added:c,skipped:p}};import da from"node:fs/promises";import ct from"node:path";import sn from"node:fs/promises";import at from"node:path";var Te=async e=>{let{workspacePath:r,folderPaths:t}=e,o=at.dirname(r),n;try{n=await sn.readFile(r,"utf-8")}catch(f){throw new Error(`Cursor workspace file not found at ${r}: ${f.message}`)}let s;try{s=JSON.parse(n)}catch(f){throw new Error(`Failed to parse ${r} as JSON. Comments (JSONC) are not supported. ${f.message}`)}let i=s.folders??[],l=new Set(t.map(f=>at.resolve(f))),c=new Set,p=i.filter(f=>{let w=at.resolve(o,f.path);return l.has(w)?(c.add(w),!1):!0});s.folders=p,await sn.writeFile(r,`${JSON.stringify(s,null,2)}
|
|
104
|
+
`,"utf-8");let m=[],u=[];for(let f of t){let w=at.resolve(f);c.has(w)?m.push(f):u.push(f)}return{removed:m,notFound:u}};var ao=async e=>{let{workspacePath:r,worktreeDir:t,currentBranches:o}=e,n=ct.dirname(r),s=ct.resolve(`${t}/release`),i=await da.readFile(r,"utf-8"),c=JSON.parse(i).folders??[],p=new Set(o.map(S=>ct.resolve(`${t}/${S}`))),m=[];for(let S of c){let I=ct.resolve(n,S.path);(I===s||I.startsWith(`${s}/`))&&!p.has(I)&&m.push(I)}let u=[];m.length>0&&(u=(await Te({workspacePath:r,folderPaths:m})).removed);let f=o.map(S=>`${t}/${S}`),{added:w}=f.length>0?await xr({workspacePath:r,folderPaths:f}):{added:[]};return{added:w,removed:u}};import an from"node:path";var Z=(e,r)=>an.isAbsolute(e)?e:an.resolve(r,e);var ha="feature",wa="release",Cr=["workspace","windows","none"],lt=async e=>{let{confirmedCommand:r,all:t,versions:o,cursor:n,githubDesktop:s,cmux:i}=e;d.start("worktrees-add");try{let l=await j("release"),c=await b(),p=`${c}${B}`;await cn(`${p}/${wa}`),await cn(`${p}/${ha}`);let m=[];if(o)m=o.split(",").map(O=>z(G(O.trim())));else{let O=await E(),me=O.map(Q=>Q.branch);if(me.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=me;else{d.setInteractive();let Q=new Map(O.map(Pr=>[Pr.branch,C(Pr.title)])),de=await $();m=await ua({required:!0,message:"\u{1F33F} Select release branches",choices:A({branches:me,descriptions:de,types:Q})})}}t?d.addOption("--all",!0):d.addOption("--versions",Ee(m));let u=r?!0:await co({message:"Are you sure you want to proceed with these worktree changes?"});r||d.setInteractive(),u||(a.info("Operation cancelled. Exiting..."),ga.exit(0)),r||d.addOption("--yes",!0);let f=await x(),w=f.ide?.provider==="cursor"?f.ide.config:void 0,S=n??w?.mode??await fa({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??f.worktrees?.openInGithubDesktop??await co({message:"Open created worktrees in GitHub Desktop?"});typeof s>"u"&&f.worktrees?.openInGithubDesktop===void 0&&d.setInteractive(),I?d.addOption("--github-desktop",!0):d.addOption("--no-github-desktop",!0);let N=i??f.worktrees?.openInCmux??await co({message:"Open created worktrees in cmux?"});typeof i>"u"&&f.worktrees?.openInCmux===void 0&&d.setInteractive(),N?d.addOption("--cmux",!0):d.addOption("--no-cmux",!0);let{branchesToCreate:Se}=va({selectedReleaseBranches:m,currentWorktrees:l}),pe=await ka(Se,p);if(ya(pe),S==="workspace")if(!w?.workspaceConfigPath)a.warn("\u26A0\uFE0F Skipping Cursor: ide.config.workspaceConfigPath is not set in infra-kit config");else{let O=Z(w.workspaceConfigPath,c),me=pe.map(dn=>`${p}/${dn}`),{added:Q,skipped:de}=await xr({workspacePath:O,folderPaths:me}),Pr=de.length>0?` (${de.length} already present)`:"";a.info(`\u2705 Added ${Q.length} folder(s) to ${O}${Pr}`),await $e`cursor ${O}`}else if(S==="windows")for(let O of pe)await $e`cursor ${p}/${O}`;if(I)for(let O of pe)await $e`github ${p}/${O}`,await $e`sleep 5`;if(N){let O=await F(),me=await vr();for(let Q of pe){let de=Y({repoName:O,branch:Q});me.has(U(de))||await yr({cwd:`${p}/${Q}`,title:de})}}d.print();let po={createdWorktrees:pe,count:pe.length};return{content:h(JSON.stringify(po,null,2)),structuredContent:po}}catch(l){throw a.error({error:l},"\u274C Error managing worktrees"),new g(l,{operation:"create worktrees",remediation:"verify branches don't already exist as worktrees: 'git worktree list'"})}},cn=async e=>{await $e`mkdir -p ${e}`},va=e=>{let{selectedReleaseBranches:r,currentWorktrees:t}=e,o=t.filter(s=>fe(s));return{branchesToCreate:r.filter(s=>!o.includes(s))}},ka=async(e,r)=>{let t=await Promise.allSettled(e.map(async n=>{let s=`${r}/${n}`;return await $e`git worktree add ${s} ${n}`,await $e({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 g(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},ya=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")},Ra=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:le.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:le.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:le.enum(Cr).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:le.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:le.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:le.array(le.string()).describe("List of created git worktree branches"),count:le.number().describe("Number of git worktrees created")},handler:lt});import{z as Ge}from"zod";var pt=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=R(c);if(!p)return[];let m=T(p),u=o.get(c)||"regular",f=t.get(D(p))||null;return[{version:m,type:u,description:f}]}),s=Math.max(...n.map(c=>c.version.length)),i=n.map(c=>{let p=Ve(c.version,c.type,s);return c.description?`${p} ${c.description}`:p});a.info("\u{1F33F} Active worktrees:"),a.info(`
|
|
98
105
|
${i.join(`
|
|
99
106
|
`)}
|
|
100
|
-
`);let l={worktrees:s,count:s.length};return{content:h(JSON.stringify(l,null,2)),structuredContent:l}},Yi=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:je.array(je.object({version:je.string().describe("Release version"),type:je.enum(["regular","hotfix"]).describe("Release type"),description:je.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:je.number().describe("Number of worktrees")},handler:Yr});import{z as Fe}from"zod";import{$ as Zi}from"zx";var Zr=async()=>{m.start("worktrees-open");try{let e=await b(),r=`${e}${J}`,t=await j("release"),o=await Qi({projectRoot:e,worktreeDir:r,currentBranches:t}),s=await ea({worktreeDir:r,currentBranches:t}),n={openedCmux:s.opened,skippedCmux:s.skipped,cursorFoldersAdded:o.added,cursorFoldersRemoved:o.removed};return ra(n,{cursorRan:o.ran,cmuxRan:s.ran}),m.print(),{content:h(JSON.stringify(n,null,2)),structuredContent:{...n}}}catch(e){throw a.error({error:e},"\u274C Error opening worktrees"),new g(e,{operation:"open worktrees",remediation:"run 'worktrees-list' to confirm the branches exist"})}},Qi=async e=>{let{projectRoot:r,worktreeDir:t,currentBranches:o}=e,s=await x(),n=s.ide?.provider==="cursor"?s.ide.config:void 0;if(!n||n.mode!=="workspace"||!n.workspaceConfigPath)return a.warn('\u26A0\uFE0F Skipping Cursor: ide.provider must be "cursor", mode "workspace", and workspaceConfigPath set.'),{ran:!1,added:0,removed:0};let i=X(n.workspaceConfigPath,r);try{let{added:l,removed:c}=await Ut({workspacePath:i,worktreeDir:t,currentBranches:o});return await Zi`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(),s=await _t(),n=[],i=[];for(let l of t){let c=H({repoName:o,branch:l});if(s.has(c)){i.push(c);continue}try{await ir({cwd:`${r}/${l}`,title:c}),n.push(c)}catch(p){a.warn({error:p,title:c},`\u26A0\uFE0F Failed to open cmux workspace for ${l}`)}}return{ran:!0,opened:n,skipped:i}},ra=(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:Fe.array(Fe.string()).describe("Titles of cmux workspaces opened during this run"),skippedCmux:Fe.array(Fe.string()).describe("Titles of cmux workspaces that were already open"),cursorFoldersAdded:Fe.number().describe("Number of worktree folders added to the Cursor workspace file"),cursorFoldersRemoved:Fe.number().describe("Number of dangling worktree folders removed from the Cursor workspace file")},handler:Zr});import oa from"@inquirer/checkbox";import sa from"@inquirer/confirm";import na from"node:process";import{z as mr}from"zod";var Qr=async e=>{let{confirmedCommand:r,all:t,versions:o}=e;m.start("worktrees-remove");try{let s=await j("release");if(s.length===0)return a.info("\u2139\uFE0F No active worktrees to remove"),m.print(),{content:h(JSON.stringify({removedWorktrees:[],count:0},null,2)),structuredContent:{removedWorktrees:[],count:0}};let n=await b(),i=`${n}${J}`,l=[];if(t)l=s;else if(o)l=o.split(",").map(w=>q(B(w.trim())));else{m.setInteractive();let[w,S]=await Promise.all([T(),P()]),I=new Map(S.map(_=>[_.branch,C(_.title)]));l=await oa({required:!0,message:"\u{1F33F} Select release branches",choices:A({branches:s,descriptions:w,types:I})})}let c=l.length===s.length;c?m.addOption("--all",!0):m.addOption("--versions",we(l));let p=r?!0:await sa({message:"Are you sure you want to proceed with these worktree changes?"});r||m.setInteractive(),p||(a.info("Operation cancelled. Exiting..."),na.exit(0)),r||m.addOption("--yes",!0);let d=await F(),u=await ar({branches:l,worktreeDir:i,repoName:d,pruneFolder:c});await ia({removedWorktrees:u,worktreeDir:i,projectRoot:n}),aa(u),m.print();let f={removedWorktrees:u,count:u.length};return{content:h(JSON.stringify(f,null,2)),structuredContent:f}}catch(s){throw a.error({error:s},"\u274C Error managing worktrees"),new g(s,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"})}},ia=async e=>{let{removedWorktrees:r,worktreeDir:t,projectRoot:o}=e;if(r.length===0)return;let s=await x(),n=s.ide?.provider==="cursor"?s.ide.config:void 0;if(!n||n.mode!=="workspace"||!n.workspaceConfigPath)return;let i=X(n.workspaceConfigPath,o),l=r.map(c=>`${t}/${c}`);try{let{removed:c}=await ke({workspacePath:i,folderPaths:l});c.length>0&&a.info(`\u2705 Removed ${c.length} folder(s) from ${i}`)}catch(c){a.warn({error:c},`\u26A0\uFE0F Failed to update Cursor workspace at ${i}`)}},aa=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")},ca=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:mr.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:mr.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:mr.array(mr.string()).describe("List of removed git worktree branches"),count:mr.number().describe("Number of git worktrees removed")},handler:Qr});import la from"@inquirer/confirm";import pa from"node:process";import{z as zt}from"zod";import{$ as ma}from"zx";var et=async e=>{let{confirmedCommand:r}=e;m.start("worktrees-sync");try{let t=await j("release"),o=await b(),s=`${o}${J}`,n=await Or(),i=r?!0:await la({message:"Are you sure you want to proceed with these worktree changes?"});r||m.setInteractive(),i||(a.info("Operation cancelled. Exiting..."),pa.exit(0)),r||m.addOption("--yes",!0);let{branchesToRemove:l}=da({releasePRsList:n,currentWorktrees:t}),c=await F(),p=await ua({branches:l,worktreeDir:s,repoName:c});await fa({removedWorktrees:p,worktreeDir:s,projectRoot:o}),ga(p),m.print();let d={removedWorktrees:p,count:p.length};return{content:h(JSON.stringify(d,null,2)),structuredContent:d}}catch(t){throw a.error({error:t},"\u274C Error managing worktrees"),new g(t,{operation:"sync worktrees with remote",remediation:"ensure 'gh auth status' is ok and you can reach origin"})}},da=e=>{let{releasePRsList:r,currentWorktrees:t}=e;return{branchesToRemove:t.filter(n=>le(n)).filter(n=>!r.includes(n))}},ua=async e=>{let{branches:r,worktreeDir:t,repoName:o}=e,s=[];for(let n of r)try{let i=`${t}/${n}`,l=H({repoName:o,branch:n});await sr(l),await ma`git worktree remove ${i}`,s.push(n)}catch(i){let l=new g(i,{operation:`remove stale worktree for ${n}`,remediation:"inspect the worktree dir manually; rerun with the branch checked out elsewhere"});a.error({error:i,branch:n,msg:l.message})}return s},fa=async e=>{let{removedWorktrees:r,worktreeDir:t,projectRoot:o}=e;if(r.length===0)return;let s=await x(),n=s.ide?.provider==="cursor"?s.ide.config:void 0;if(!n||n.mode!=="workspace"||!n.workspaceConfigPath)return;let i=X(n.workspaceConfigPath,o),l=r.map(c=>`${t}/${c}`);try{let{removed:c}=await ke({workspacePath:i,folderPaths:l});c.length>0&&a.info(`\u2705 Removed ${c.length} folder(s) from ${i}`)}catch(c){a.warn({error:c},`\u26A0\uFE0F Failed to update Cursor workspace at ${i}`)}},ga=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")},ha=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:zt.array(zt.string()).describe("List of removed worktree branches"),count:zt.number().describe("Number of worktrees removed during sync")},handler:et});var y=new va,Uo=(e,r)=>[...r,e],ka=e=>{if(!(typeof e>"u")){if(e===!0)return"workspace";if(e===!1)return"none";if(typeof e=="string"&&pr.includes(e))return e;throw new Error(`Invalid --cursor value "${String(e)}". Expected one of: ${pr.join(", ")}.`)}},Go=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),rt.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 Fr({all:e.all,confirmedCommand:e.yes})});y.command("release-list").description("List all release branches").action(async()=>{await Wr()});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"',Uo,[]).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.',Uo,[]).option("-y, --yes","Skip confirmation prompt").action(async e=>{let r=e.release,t=e.name,o=r.map(Wt),s=t.map(l=>({name:l,type:"regular"})),n=[...o,...s],i=n.length>0?n:void 0;await Kr({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 qr({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 Dr({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 Mr({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 Lr({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 et({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 Xr({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 Yr()});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 Qr({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 Zr()});var zo=y.command("config").description("Manage infra-kit configuration files");zo.command("path").description("Show the resolved config merge chain and file paths").action(async()=>{await wt()});zo.command("edit").description("Open the user-scope per-project override file in $EDITOR").action(async()=>{await vt()});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 hr({all:e.all,root:e.root})).structuredContent.allPassed||(rt.exitCode=1)});y.command("doctor").description("Check installation and authentication status of gh and doppler CLIs").action(async()=>{await br()});y.command("version").description("Print the installed infra-kit CLI version").action(async()=>{await Ur()});y.command("env-status").description("Show Doppler authentication status and detected project info").action(async()=>{await Tr()});y.command("env-list").description("List available Doppler configs for the detected project").action(async()=>{await Pr()});y.command("init").description("Inject shell integration into your profile .zshrc").action(async()=>{await yt()});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 Er({config:e.config})});y.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{await Cr()});if(rt.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])),s=[...e,...r,...t],n=Math.max(...s.map(c=>c.length)),i=c=>c.filter(p=>o.has(p)).map(p=>({name:`${p.padEnd(n)} ${o.get(p).description()}`,value:p})),l=await wa({message:"Select a command to run",choices:[new Le(" "),new Le("\u2014 Release Management \u2014"),...i(e),new Le(" "),new Le("\u2014 Worktrees \u2014"),...i(r),new Le(" "),new Le("\u2014 Environment \u2014"),...i(t)]},{output:rt.stderr});await Go(["node","infra-kit",l])}else await Go();
|
|
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();
|
|
101
108
|
//# sourceMappingURL=cli.js.map
|