infra-kit 0.1.107 → 0.1.108

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