infra-kit 0.1.120 → 0.1.121

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.
@@ -1,22 +1,22 @@
1
- import{b as Pe,c as Tt,d as $t,e as dr,f as fn}from"./chunk-WA4BQRDC.js";import hn from"node:process";import It from"pino";import si from"pino-pretty";var gn="/tmp/mcp-infra-kit.log",vp=()=>{let e=hn.argv.includes("--debug")?"debug":"info",r=It({level:e},It.destination({dest:gn}));return r.info(`Logger initialized with level: ${e}. Logging to: ${gn}`),r},ii=()=>{let e=hn.argv.includes("--debug")?"debug":"info",r=["time","pid","hostname"];return e==="debug"&&r.push("level"),It({level:e},si({destination:2,ignore:r.join(","),colorize:!0}))},a=ii();import fr from"node:path";import Ti from"node:process";import{z as L}from"zod";import bn from"node:path";import{$ as X}from"zx";var ai=/^v?(\d+)\.(\d+)\.(\d+)$/,ci=/^(\d+)\.(\d+)\.(\d+)$/,li=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,qr="release/",Pt="release/v",wn="refs/heads/",pi="next";var vn=new Set(["dev","main","next","hotfix","regular","release"]),ae=class extends Error{constructor(r){super(r),this.name="InvalidReleaseNameError"}},Ue=class extends Error{constructor(r){super(r),this.name="InvalidReleaseRefError"}},kn=e=>e.startsWith(wn)?e.slice(wn.length):e,Rn=(e,r,t)=>({kind:"version",semver:{major:e,minor:r,patch:t},raw:`${e}.${r}.${t}`}),Se=e=>{if(e.length===0)throw new ae('Release name is empty. Provide a kebab-case name like "checkout-redesign".');if(e.length>50)throw new ae(`Release name "${e}" is ${e.length} characters; the maximum is 50.`);if(!li.test(e))throw new ae(`Release name "${e}" is not kebab-case. Use lowercase letters, digits, and single hyphens, e.g. "checkout-redesign".`);if(vn.has(e))throw new ae(`Release name "${e}" is reserved. Reserved names: ${[...vn].join(", ")}.`)},C=e=>{let r=kn(e.trim());if(!r.startsWith(qr))return null;if(r.startsWith(Pt)){let o=r.slice(Pt.length),n=ci.exec(o);if(n)return Rn(Number(n[1]),Number(n[2]),Number(n[3]))}let t=r.slice(qr.length);try{Se(t)}catch{return null}return{kind:"name",name:t,raw:t}},Z=e=>{let r=e.trim();if(kn(r).startsWith(qr)){let n=C(r);if(!n)throw new Ue(`"${e}" looks like a release branch but is not a valid release/v<semver> or release/<name> ref.`);return n}let o=ai.exec(r);if(o)return Rn(Number(o[1]),Number(o[2]),Number(o[3]));if(r.toLowerCase()===pi)throw new Ue('The "next" token must be resolved to a concrete version (via computeNextVersion) before parsing a release ref.');try{Se(r)}catch(n){let s=n instanceof Error?n.message:String(n);throw new Ue(`Cannot parse "${e}" as a release ref: ${s}`)}return{kind:"name",name:r,raw:r}},ce=e=>e.kind==="version"?`${Pt}${e.raw}`:`${qr}${e.name}`,St=(e,r)=>{let t=r==="hotfix"?"Hotfix":"Release";return e.kind==="version"?`${t} v${e.raw}`:`${t} ${e.name}`},Hr=e=>e.kind==="version"?`Release v${e.raw} (RC)`:`Release ${e.name} (RC)`,M=e=>e.kind==="version"?`v${e.raw}`:e.name,I=e=>e.raw,Ae=e=>e==null?!1:C(e)!==null,yn=e=>{if(e===void 0)return null;let r=e instanceof Date?e.getTime():new Date(e).getTime();return Number.isNaN(r)?null:r},At=(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=yn(t?.a),n=yn(t?.b);return o!==null&&n!==null&&o!==n?o-n:e.name<r.name?-1:e.name>r.name?1:0};var F=async e=>{let t=(await X`git worktree list`).stdout.split(`
2
- `).filter(Boolean),o={release:di,feature:mi};return t.map(o[e]).filter(n=>n!==null)},xn=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},di=e=>{let r=xn(e);return Ae(r)?r:null},mi=e=>{let r=xn(e);return r?.startsWith("feature/")?r:null},k=async()=>(await X`git rev-parse --show-toplevel`).stdout.trim(),Zr=async()=>(await X`git rev-parse --abbrev-ref HEAD`).stdout.trim(),Nt=async()=>(await X`git status --porcelain`).stdout.trim().length===0,_t=async()=>{let e=await k(),[r,t]=await Promise.all([X({cwd:e})`git rev-parse --absolute-git-dir`,X({cwd:e})`git rev-parse --git-common-dir`]),o=r.stdout.trim(),n=bn.resolve(e,t.stdout.trim());return o!==n},J=async()=>{let e=await k();return bn.basename(e)},Ot=async e=>{(await X`git branch --list ${e}`).stdout.trim().length!==0&&await Zr()!==e&&await X`git branch -D ${e}`},Ft=async e=>{(await X`git ls-remote --heads origin ${e}`).stdout.trim().length!==0&&await X`git push origin --delete ${e}`};import{z as he}from"zod";var Dt=he.strictObject({requiredScripts:he.array(he.string().min(1)).optional(),requiredFiles:he.array(he.string().min(1)).optional(),turbo:he.strictObject({requiredTasks:he.array(he.string().min(1)).optional()}).optional()});import ui from"node:fs/promises";var le=async e=>{try{return await ui.access(e),!0}catch{return!1}};import Ei from"node:path";import Cn from"node:fs/promises";import En from"node:path";import{pathToFileURL as fi}from"node:url";import{z as gi}from"zod";var we="infra-kit.config.ts",jt=async e=>{try{let r=await Cn.readFile(En.join(e,"package.json"),"utf-8");return JSON.parse(r)}catch{return{}}},mr=async(e,r=Pe)=>{let t=En.join(e,we);if(!await le(t))throw new Error(`${we} not found at ${t}`);let o=await Cn.stat(t),i=(await import(`${fi(t).href}?mtime=${Number(o.mtimeMs)}`)).default;if(i===void 0)throw new Error(`${we} at ${t} has no default export`);let l=typeof i=="function"?await i():i,c=Dt.safeParse(l);if(!c.success)throw new Error(`Invalid ${we} at ${t}: ${gi.prettifyError(c.error)}`);return $t(c.data,r)};import Tn from"node:fs/promises";import Xr from"node:path";import hi from"yaml";var wi="pnpm-workspace.yaml",vi=async e=>(await Tn.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(t=>t.isDirectory()).map(t=>Xr.join(e,t.name)),yi=async(e,r)=>{let t=[];for(let o of e){if(r==="*"){t.push(...await vi(o));continue}let n=Xr.join(o,r);await le(n)&&t.push(n)}return t},ki=async(e,r)=>{let t=[e];for(let o of r.split("/"))t=await yi(t,o);return t},ur=async e=>{let r=await Tn.readFile(Xr.join(e,wi),"utf-8"),o=((hi.parse(r)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),n=new Set;for(let s of o){let i=await ki(e,s);for(let l of i)await le(Xr.join(l,"package.json"))&&n.add(l)}return[...n].sort()};var Mt=async(e,r=Pe)=>{try{let t=await mr(e,r);return{check:{name:we,status:"pass",message:"present and valid"},rules:t}}catch(t){return{check:{name:we,status:"fail",message:t.message},rules:null}}};import Ri from"node:fs/promises";import bi from"node:path";var Lt=async(e,r)=>Promise.all(r.map(async t=>{let o=await Ri.stat(bi.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 Wt=(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 xi from"node:fs/promises";import Ci from"node:path";var qe="turbo.json",Vt=async(e,r)=>{if(r.length===0)return[];let t;try{let n=await xi.readFile(Ci.join(e,qe),"utf-8");t=JSON.parse(n)}catch(n){return[{name:qe,status:"fail",message:`cannot read/parse ${qe}: ${n.message}`}]}let o=t.tasks;return o===null||typeof o!="object"?[{name:qe,status:"fail",message:`no "tasks" object defined in ${qe}`}]: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 ${qe}`}})};var Bt=async(e,r=Pe)=>{let t=await jt(e),o=t.name??Ei.basename(e),{check:n,rules:s}=await Mt(e,r),i=[n];s&&(i.push(...Wt(t.scripts??{},s.requiredScripts)),i.push(...await Lt(e,s.requiredFiles)),i.push(...await Vt(e,s.turboTasks)));let l=i.every(c=>c.status==="pass");return{packageDir:e,packageName:o,checks:i,passed:l}};var g=e=>[{type:"text",text:e}],w=e=>e;var $i=async e=>{let r=fr.resolve(e);for(;r!==fr.dirname(r);){if(await le(fr.join(r,"package.json")))return r;r=fr.dirname(r)}if(await le(fr.join(r,"package.json")))return r;throw new Error(`No package.json found in or above ${e}`)},Ii=async e=>e.root?[{dir:await k(),baseline:Tt}]:e.all?(await ur(await k())).map(t=>({dir:t})):[{dir:await $i(e.cwd??Ti.cwd())}],Pi=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}`)}},$n=async(e={})=>{let r=await Ii(e),t=[];for(let s of r)t.push(await Bt(s.dir,s.baseline));for(let s of t)Pi(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:g(JSON.stringify(n,null,2)),structuredContent:n}},Si={all:L.boolean().optional().describe("Audit every non-vendor workspace package"),root:L.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},Ai={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")},Jt=w({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:Si,outputSchema:Ai,handler:e=>$n({all:e.all,root:e.root})});import ke from"node:fs";import Kn from"node:os";import Rr from"node:path";import ha from"node:process";var He=(e,r,t)=>{let o=e.indexOf(r),n=e.indexOf(t);return o!==-1&&n!==-1&&n>=o},ve=(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?`
5
- ${i}`:"")};var In=(e,r,t)=>`${e}
1
+ import{b as Pe,c as Et,d as Tt,e as dr,f as un}from"./chunk-WA4BQRDC.js";import gn from"node:process";import $t from"pino";import si from"pino-pretty";var fn="/tmp/mcp-infra-kit.log",vp=()=>{let e=gn.argv.includes("--debug")?"debug":"info",r=$t({level:e},$t.destination({dest:fn}));return r.info(`Logger initialized with level: ${e}. Logging to: ${fn}`),r},ii=()=>{let e=gn.argv.includes("--debug")?"debug":"info",r=["time","pid","hostname"];return e==="debug"&&r.push("level"),$t({level:e},si({destination:2,ignore:r.join(","),colorize:!0}))},a=ii();import fr from"node:path";import Ti from"node:process";import{z as L}from"zod";import Rn from"node:path";import{$ as X}from"zx";var ai=/^v?(\d+)\.(\d+)\.(\d+)$/,ci=/^(\d+)\.(\d+)\.(\d+)$/,li=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,qr="release/",It="release/v",hn="refs/heads/",pi="next";var wn=new Set(["dev","main","next","hotfix","regular","release"]),ae=class extends Error{constructor(r){super(r),this.name="InvalidReleaseNameError"}},Ue=class extends Error{constructor(r){super(r),this.name="InvalidReleaseRefError"}},yn=e=>e.startsWith(hn)?e.slice(hn.length):e,kn=(e,r,t)=>({kind:"version",semver:{major:e,minor:r,patch:t},raw:`${e}.${r}.${t}`}),Se=e=>{if(e.length===0)throw new ae('Release name is empty. Provide a kebab-case name like "checkout-redesign".');if(e.length>50)throw new ae(`Release name "${e}" is ${e.length} characters; the maximum is 50.`);if(!li.test(e))throw new ae(`Release name "${e}" is not kebab-case. Use lowercase letters, digits, and single hyphens, e.g. "checkout-redesign".`);if(wn.has(e))throw new ae(`Release name "${e}" is reserved. Reserved names: ${[...wn].join(", ")}.`)},C=e=>{let r=yn(e.trim());if(!r.startsWith(qr))return null;if(r.startsWith(It)){let o=r.slice(It.length),n=ci.exec(o);if(n)return kn(Number(n[1]),Number(n[2]),Number(n[3]))}let t=r.slice(qr.length);try{Se(t)}catch{return null}return{kind:"name",name:t,raw:t}},Z=e=>{let r=e.trim();if(yn(r).startsWith(qr)){let n=C(r);if(!n)throw new Ue(`"${e}" looks like a release branch but is not a valid release/v<semver> or release/<name> ref.`);return n}let o=ai.exec(r);if(o)return kn(Number(o[1]),Number(o[2]),Number(o[3]));if(r.toLowerCase()===pi)throw new Ue('The "next" token must be resolved to a concrete version (via computeNextVersion) before parsing a release ref.');try{Se(r)}catch(n){let s=n instanceof Error?n.message:String(n);throw new Ue(`Cannot parse "${e}" as a release ref: ${s}`)}return{kind:"name",name:r,raw:r}},ce=e=>e.kind==="version"?`${It}${e.raw}`:`${qr}${e.name}`,Pt=(e,r)=>{let t=r==="hotfix"?"Hotfix":"Release";return e.kind==="version"?`${t} v${e.raw}`:`${t} ${e.name}`},Hr=e=>e.kind==="version"?`Release v${e.raw} (RC)`:`Release ${e.name} (RC)`,M=e=>e.kind==="version"?`v${e.raw}`:e.name,I=e=>e.raw,Ae=e=>e==null?!1:C(e)!==null,vn=e=>{if(e===void 0)return null;let r=e instanceof Date?e.getTime():new Date(e).getTime();return Number.isNaN(r)?null:r},St=(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=vn(t?.a),n=vn(t?.b);return o!==null&&n!==null&&o!==n?o-n:e.name<r.name?-1:e.name>r.name?1:0};var F=async e=>{let t=(await X`git worktree list`).stdout.split(`
2
+ `).filter(Boolean),o={release:di,feature:mi};return t.map(o[e]).filter(n=>n!==null)},bn=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},di=e=>{let r=bn(e);return Ae(r)?r:null},mi=e=>{let r=bn(e);return r?.startsWith("feature/")?r:null},k=async()=>(await X`git rev-parse --show-toplevel`).stdout.trim(),Zr=async()=>(await X`git rev-parse --abbrev-ref HEAD`).stdout.trim(),At=async()=>(await X`git status --porcelain`).stdout.trim().length===0,Nt=async()=>{let e=await k(),[r,t]=await Promise.all([X({cwd:e})`git rev-parse --absolute-git-dir`,X({cwd:e})`git rev-parse --git-common-dir`]),o=r.stdout.trim(),n=Rn.resolve(e,t.stdout.trim());return o!==n},J=async()=>{let e=await k();return Rn.basename(e)},_t=async e=>{(await X`git branch --list ${e}`).stdout.trim().length!==0&&await Zr()!==e&&await X`git branch -D ${e}`},Ot=async e=>{(await X`git ls-remote --heads origin ${e}`).stdout.trim().length!==0&&await X`git push origin --delete ${e}`};import{z as he}from"zod";var Ft=he.strictObject({requiredScripts:he.array(he.string().min(1)).optional(),requiredFiles:he.array(he.string().min(1)).optional(),turbo:he.strictObject({requiredTasks:he.array(he.string().min(1)).optional()}).optional()});import ui from"node:fs/promises";var le=async e=>{try{return await ui.access(e),!0}catch{return!1}};import Ei from"node:path";import xn from"node:fs/promises";import Cn from"node:path";import{pathToFileURL as fi}from"node:url";import{z as gi}from"zod";var we="infra-kit.config.ts",Dt=async e=>{try{let r=await xn.readFile(Cn.join(e,"package.json"),"utf-8");return JSON.parse(r)}catch{return{}}},mr=async(e,r=Pe)=>{let t=Cn.join(e,we);if(!await le(t))throw new Error(`${we} not found at ${t}`);let o=await xn.stat(t),i=(await import(`${fi(t).href}?mtime=${Number(o.mtimeMs)}`)).default;if(i===void 0)throw new Error(`${we} at ${t} has no default export`);let l=typeof i=="function"?await i():i,c=Ft.safeParse(l);if(!c.success)throw new Error(`Invalid ${we} at ${t}: ${gi.prettifyError(c.error)}`);return Tt(c.data,r)};import En from"node:fs/promises";import Xr from"node:path";import hi from"yaml";var wi="pnpm-workspace.yaml",vi=async e=>(await En.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(t=>t.isDirectory()).map(t=>Xr.join(e,t.name)),yi=async(e,r)=>{let t=[];for(let o of e){if(r==="*"){t.push(...await vi(o));continue}let n=Xr.join(o,r);await le(n)&&t.push(n)}return t},ki=async(e,r)=>{let t=[e];for(let o of r.split("/"))t=await yi(t,o);return t},ur=async e=>{let r=await En.readFile(Xr.join(e,wi),"utf-8"),o=((hi.parse(r)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),n=new Set;for(let s of o){let i=await ki(e,s);for(let l of i)await le(Xr.join(l,"package.json"))&&n.add(l)}return[...n].sort()};var jt=async(e,r=Pe)=>{try{let t=await mr(e,r);return{check:{name:we,status:"pass",message:"present and valid"},rules:t}}catch(t){return{check:{name:we,status:"fail",message:t.message},rules:null}}};import Ri from"node:fs/promises";import bi from"node:path";var Mt=async(e,r)=>Promise.all(r.map(async t=>{let o=await Ri.stat(bi.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 Lt=(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 xi from"node:fs/promises";import Ci from"node:path";var qe="turbo.json",Wt=async(e,r)=>{if(r.length===0)return[];let t;try{let n=await xi.readFile(Ci.join(e,qe),"utf-8");t=JSON.parse(n)}catch(n){return[{name:qe,status:"fail",message:`cannot read/parse ${qe}: ${n.message}`}]}let o=t.tasks;return o===null||typeof o!="object"?[{name:qe,status:"fail",message:`no "tasks" object defined in ${qe}`}]: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 ${qe}`}})};var Vt=async(e,r=Pe)=>{let t=await Dt(e),o=t.name??Ei.basename(e),{check:n,rules:s}=await jt(e,r),i=[n];s&&(i.push(...Lt(t.scripts??{},s.requiredScripts)),i.push(...await Mt(e,s.requiredFiles)),i.push(...await Wt(e,s.turboTasks)));let l=i.every(c=>c.status==="pass");return{packageDir:e,packageName:o,checks:i,passed:l}};var g=e=>[{type:"text",text:e}],w=e=>e;var $i=async e=>{let r=fr.resolve(e);for(;r!==fr.dirname(r);){if(await le(fr.join(r,"package.json")))return r;r=fr.dirname(r)}if(await le(fr.join(r,"package.json")))return r;throw new Error(`No package.json found in or above ${e}`)},Ii=async e=>e.root?[{dir:await k(),baseline:Et}]:e.all?(await ur(await k())).map(t=>({dir:t})):[{dir:await $i(e.cwd??Ti.cwd())}],Pi=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}`)}},Tn=async(e={})=>{let r=await Ii(e),t=[];for(let s of r)t.push(await Vt(s.dir,s.baseline));for(let s of t)Pi(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:g(JSON.stringify(n,null,2)),structuredContent:n}},Si={all:L.boolean().optional().describe("Audit every non-vendor workspace package"),root:L.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},Ai={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")},Bt=w({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:Si,outputSchema:Ai,handler:e=>Tn({all:e.all,root:e.root})});import ke from"node:fs";import Jn from"node:os";import Rr from"node:path";import ha from"node:process";var He=(e,r,t)=>{let o=e.indexOf(r),n=e.indexOf(t);return o!==-1&&n!==-1&&n>=o},ve=(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?`
5
+ ${i}`:"")};var $n=(e,r,t)=>`${e}
6
6
  ${r}
7
- ${t}`,gr=({content:e,body:r,startMarker:t,endMarker:o,placement:n="replace-in-place"})=>{let s=In(t,r,o),i=He(e,t,o);if(n==="replace-in-place"&&i){let p=e.indexOf(t),d=e.indexOf(o)+o.length;return e.slice(0,p)+s+e.slice(d)}let c=(i?ve(e,t,o)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
7
+ ${t}`,gr=({content:e,body:r,startMarker:t,endMarker:o,placement:n="replace-in-place"})=>{let s=$n(t,r,o),i=He(e,t,o);if(n==="replace-in-place"&&i){let p=e.indexOf(t),d=e.indexOf(o)+o.length;return e.slice(0,p)+s+e.slice(d)}let c=(i?ve(e,t,o)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
8
8
  ${s}
9
9
  `:`${s}
10
- `};import O from"node:fs";import vr from"node:path";import Gt from"node:fs/promises";import Ni from"node:os";import hr from"node:path";import{z as y}from"zod";var Pn="infra-kit.json",Yr=".infra-kit",_i="infra-kit.json",Oi="projects",Fi=y.object({provider:y.literal("doppler"),config:y.object({name:y.string().min(1)})}),Di=y.discriminatedUnion("provider",[Fi]),ji=y.object({workspaceConfigPath:y.string().min(1)}),Mi=y.object({provider:y.literal("cursor"),config:ji}),Li=y.object({}),Wi=y.object({provider:y.literal("zed"),config:Li}),Sn=y.discriminatedUnion("provider",[Mi,Wi]),Vi=y.union([Sn,y.array(Sn).min(1)]),Bi=y.object({provider:y.literal("jira"),config:y.object({baseUrl:y.string().url(),projectId:y.number().int().positive()})}),Ji=y.discriminatedUnion("provider",[Bi]),Ki=["two-columns","three-pane"],Gi=y.object({layout:y.enum(Ki).optional()}),zi=y.object({openInGithubDesktop:y.boolean().optional(),openInCmux:y.boolean().optional(),cmux:Gi.optional()}),Ui=y.object({trigger:y.enum(["shell-startup","cli-invocation"]),config:y.string().min(1)}).strict(),An=y.object({environments:y.array(y.string().min(1)).min(1),envManagement:Di,ide:Vi.optional(),taskManager:Ji.optional(),worktrees:zi.optional(),envAutoLoad:Ui.optional()}),Qr=An.superRefine((e,r)=>{if(!Array.isArray(e.ide))return;let t=new Set;for(let o of e.ide){if(t.has(o.provider)){r.addIssue({code:"custom",message:"each IDE provider may appear at most once",path:["ide"]});return}t.add(o.provider)}}),wr=An.partial(),K=e=>{let r=e.ide;return r?Array.isArray(r)?r:[r]:[]},qi="two-columns",zt=e=>e.worktrees?.cmux?.layout??qi,Ze=null,W=async()=>{let e=await k(),r=hr.basename(e),t=hr.join(Ni.homedir(),Yr);return{main:hr.join(e,Pn),userGlobal:hr.join(t,_i),userProject:hr.join(t,Oi,r,Pn),projectName:r}},x=async()=>{let e=await W(),r;try{r=await Gt.stat(e.main)}catch{Ze=null;let c=e.main.replace(/\.json$/,".yml");throw await Kt(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([Kt(e.userGlobal),Kt(e.userProject)]),n={main:Number(r.mtimeMs),userGlobal:t?Number(t.mtimeMs):null,userProject:o?Number(o.mtimeMs):null};if(Ze&&Zi(Ze.mtimes,n))return Ze.value;let s=[{label:"infra-kit.json",path:e.main,required:!0},{label:"~/.infra-kit/infra-kit.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 Xi(c);p!==null&&(i={...i,...p})}let l=Qr.safeParse(i);if(!l.success)throw new Error(`Invalid merged infra-kit config: ${y.prettifyError(l.error)}`);return Ze={mtimes:n,value:l.data},l.data},ye=()=>{Ze=null},Kt=async e=>{try{return await Gt.stat(e)}catch{return null}},Hi=async e=>{try{return await Gt.readFile(e,"utf-8")}catch{return null}},Zi=(e,r)=>{let t=Object.keys(e);return t.length!==Object.keys(r).length?!1:t.every(o=>e[o]===r[o])},Xi=async e=>{let r=await Hi(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=wr.safeParse(t);if(!o.success)throw new Error(`Invalid ${e.label} at ${e.path}: ${y.prettifyError(o.error)}`);return o.data};var et={name:"infra-kit",type:"module",version:"0.1.120",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",ink:"^7.1.0",pino:"^10.3.1","pino-pretty":"^13.1.3",react:"catalog:",yaml:"^2.9.0",zod:"^4.4.3",zx:"^8.8.5"},devDependencies:{"@types/react":"catalog:","@wl/eslint-config":"workspace:*","@wl/vitest-config":"workspace:*",esbuild:"^0.28.1","ink-testing-library":"^4.0.0",typescript:"^6.0.3"}};var yr="<!-- infra-kit:begin -->",kr="<!-- infra-kit:end -->",Qi="<!-- infra-kit:version ",ea="<!-- infra-kit:import:begin -->",ra="<!-- infra-kit:import:end -->",ta="AGENTS.md",oa="CLAUDE.md",na=e=>`${Qi}${e} -->`,sa=e=>[na(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 reload` / `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 release 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(`
11
- `),Nn=e=>{if(O.existsSync(e)&&O.lstatSync(e).isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},_n=e=>{let r=new Date().toISOString().replace(/[:.]/g,"-");O.copyFileSync(e,`${e}.backup.${r}`)},On=(e,r)=>{Nn(e);let t=O.existsSync(e);return(t?O.readFileSync(e,"utf-8"):null)===r?"unchanged":(t&&_n(e),O.mkdirSync(vr.dirname(e),{recursive:!0}),O.writeFileSync(e,r,"utf-8"),t?"updated":"created")},ia=(e,r)=>O.existsSync(e)?O.readFileSync(e,"utf-8"):r,aa=(e,r,t)=>{let o=O.readFileSync(e,"utf-8");if(!He(o,r,t))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},ca=e=>{if(!O.existsSync(e))return"unchanged";Nn(e);let r=O.readFileSync(e,"utf-8"),t=ve(r,yr,kr);return t===null?"unchanged":t.trim()===""?(_n(e),O.rmSync(e),"removed"):On(e,t)},Fn=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(!O.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=vr.dirname(e),t=et.version,o=sa(t),n=vr.join(r,ta),s=vr.join(r,oa),i=ia(s,"");i=ve(i,ea,ra)??i,i=gr({content:i,body:o,startMarker:yr,endMarker:kr,placement:"replace-in-place"});let l=[{path:s,action:On(s,i)},{path:n,action:ca(n)}];aa(s,yr,kr);for(let c of l)c.action==="unchanged"&&c.path!==s||a.info(` ${c.action.padEnd(9)} ${vr.relative(r,c.path)}`);return a.info(`Agent-instruction files synced (infra-kit ${t})`),{skipped:!1,root:r,written:l}};import V from"node:fs/promises";import Y from"node:path";import{pathToFileURL as ua}from"node:url";import fa from"yaml";import{z as Ln}from"zod";import la from"node:fs/promises";import pa from"node:os";var pe=async e=>{try{return await la.access(e),!0}catch{return!1}},R=e=>{let r=pa.homedir();return e.startsWith(r)?`~${e.slice(r.length)}`:e};import da from"node:fs/promises";import Ut from"node:os";import qt from"node:path";import{z as ma}from"zod";import{z as rt}from"zod";var Dn="vendor.json",tt=rt.object({workspaceDir:rt.string().min(1),targets:rt.array(rt.string()).min(1)}).strict();var Ht=()=>qt.join(Ut.homedir(),Yr,Dn),jn=e=>{if(e==="~")return Ut.homedir();if(e.startsWith("~/"))return qt.join(Ut.homedir(),e.slice(2));if(qt.isAbsolute(e))return e;throw new Error(`workspaceDir must be absolute or ~-prefixed, got: ${e}`)},Xe=async()=>{let e=Ht(),r;try{r=await da.readFile(e,"utf-8")}catch{throw new Error(`Factory config not found at ${e}. infra-kit needs a machine-local factory registry to know where your project repos live and which to stamp. Run \`infra-kit vendor-config --init\` to scaffold it, or create it manually as JSON:
10
+ `};import O from"node:fs";import vr from"node:path";import Kt from"node:fs/promises";import Ni from"node:os";import hr from"node:path";import{z as y}from"zod";var In="infra-kit.json",Yr=".infra-kit",_i="infra-kit.json",Oi="projects",Fi=y.object({provider:y.literal("doppler"),config:y.object({name:y.string().min(1)})}),Di=y.discriminatedUnion("provider",[Fi]),ji=y.object({workspaceConfigPath:y.string().min(1)}),Mi=y.object({provider:y.literal("cursor"),config:ji}),Li=y.object({}),Wi=y.object({provider:y.literal("zed"),config:Li}),Pn=y.discriminatedUnion("provider",[Mi,Wi]),Vi=y.union([Pn,y.array(Pn).min(1)]),Bi=y.object({provider:y.literal("jira"),config:y.object({baseUrl:y.string().url(),projectId:y.number().int().positive()})}),Ji=y.discriminatedUnion("provider",[Bi]),Ki=["two-columns","three-pane"],Gi=y.object({layout:y.enum(Ki).optional()}),zi=y.object({openInGithubDesktop:y.boolean().optional(),openInCmux:y.boolean().optional(),cmux:Gi.optional()}),Ui=y.object({trigger:y.enum(["shell-startup","cli-invocation"]),config:y.string().min(1)}).strict(),Sn=y.object({environments:y.array(y.string().min(1)).min(1),envManagement:Di,ide:Vi.optional(),taskManager:Ji.optional(),worktrees:zi.optional(),envAutoLoad:Ui.optional()}),Qr=Sn.superRefine((e,r)=>{if(!Array.isArray(e.ide))return;let t=new Set;for(let o of e.ide){if(t.has(o.provider)){r.addIssue({code:"custom",message:"each IDE provider may appear at most once",path:["ide"]});return}t.add(o.provider)}}),wr=Sn.partial(),K=e=>{let r=e.ide;return r?Array.isArray(r)?r:[r]:[]},qi="two-columns",Gt=e=>e.worktrees?.cmux?.layout??qi,Ze=null,W=async()=>{let e=await k(),r=hr.basename(e),t=hr.join(Ni.homedir(),Yr);return{main:hr.join(e,In),userGlobal:hr.join(t,_i),userProject:hr.join(t,Oi,r,In),projectName:r}},x=async()=>{let e=await W(),r;try{r=await Kt.stat(e.main)}catch{Ze=null;let c=e.main.replace(/\.json$/,".yml");throw await Jt(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([Jt(e.userGlobal),Jt(e.userProject)]),n={main:Number(r.mtimeMs),userGlobal:t?Number(t.mtimeMs):null,userProject:o?Number(o.mtimeMs):null};if(Ze&&Zi(Ze.mtimes,n))return Ze.value;let s=[{label:"infra-kit.json",path:e.main,required:!0},{label:"~/.infra-kit/infra-kit.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 Xi(c);p!==null&&(i={...i,...p})}let l=Qr.safeParse(i);if(!l.success)throw new Error(`Invalid merged infra-kit config: ${y.prettifyError(l.error)}`);return Ze={mtimes:n,value:l.data},l.data},ye=()=>{Ze=null},Jt=async e=>{try{return await Kt.stat(e)}catch{return null}},Hi=async e=>{try{return await Kt.readFile(e,"utf-8")}catch{return null}},Zi=(e,r)=>{let t=Object.keys(e);return t.length!==Object.keys(r).length?!1:t.every(o=>e[o]===r[o])},Xi=async e=>{let r=await Hi(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=wr.safeParse(t);if(!o.success)throw new Error(`Invalid ${e.label} at ${e.path}: ${y.prettifyError(o.error)}`);return o.data};var et={name:"infra-kit",type:"module",version:"0.1.121",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",ink:"^7.1.0",pino:"^10.3.1","pino-pretty":"^13.1.3",react:"catalog:",yaml:"^2.9.0",zod:"^4.4.3",zx:"^8.8.5"},devDependencies:{"@types/react":"catalog:","@wl/eslint-config":"workspace:*","@wl/vitest-config":"workspace:*",esbuild:"^0.28.1","ink-testing-library":"^4.0.0",typescript:"^6.0.3"}};var yr="<!-- infra-kit:begin -->",kr="<!-- infra-kit:end -->",Qi="<!-- infra-kit:version ",ea="<!-- infra-kit:import:begin -->",ra="<!-- infra-kit:import:end -->",ta="AGENTS.md",oa="CLAUDE.md",na=e=>`${Qi}${e} -->`,sa=e=>[na(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 reload` / `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 release 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(`
11
+ `),An=e=>{if(O.existsSync(e)&&O.lstatSync(e).isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},Nn=e=>{let r=new Date().toISOString().replace(/[:.]/g,"-");O.copyFileSync(e,`${e}.backup.${r}`)},_n=(e,r)=>{An(e);let t=O.existsSync(e);return(t?O.readFileSync(e,"utf-8"):null)===r?"unchanged":(t&&Nn(e),O.mkdirSync(vr.dirname(e),{recursive:!0}),O.writeFileSync(e,r,"utf-8"),t?"updated":"created")},ia=(e,r)=>O.existsSync(e)?O.readFileSync(e,"utf-8"):r,aa=(e,r,t)=>{let o=O.readFileSync(e,"utf-8");if(!He(o,r,t))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},ca=e=>{if(!O.existsSync(e))return"unchanged";An(e);let r=O.readFileSync(e,"utf-8"),t=ve(r,yr,kr);return t===null?"unchanged":t.trim()===""?(Nn(e),O.rmSync(e),"removed"):_n(e,t)},On=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(!O.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=vr.dirname(e),t=et.version,o=sa(t),n=vr.join(r,ta),s=vr.join(r,oa),i=ia(s,"");i=ve(i,ea,ra)??i,i=gr({content:i,body:o,startMarker:yr,endMarker:kr,placement:"replace-in-place"});let l=[{path:s,action:_n(s,i)},{path:n,action:ca(n)}];aa(s,yr,kr);for(let c of l)c.action==="unchanged"&&c.path!==s||a.info(` ${c.action.padEnd(9)} ${vr.relative(r,c.path)}`);return a.info(`Agent-instruction files synced (infra-kit ${t})`),{skipped:!1,root:r,written:l}};import V from"node:fs/promises";import Y from"node:path";import{pathToFileURL as ua}from"node:url";import fa from"yaml";import{z as Mn}from"zod";import la from"node:fs/promises";import pa from"node:os";var pe=async e=>{try{return await la.access(e),!0}catch{return!1}},R=e=>{let r=pa.homedir();return e.startsWith(r)?`~${e.slice(r.length)}`:e};import da from"node:fs/promises";import zt from"node:os";import Ut from"node:path";import{z as ma}from"zod";import{z as rt}from"zod";var Fn="vendor.json",tt=rt.object({workspaceDir:rt.string().min(1),targets:rt.array(rt.string()).min(1)}).strict();var qt=()=>Ut.join(zt.homedir(),Yr,Fn),Dn=e=>{if(e==="~")return zt.homedir();if(e.startsWith("~/"))return Ut.join(zt.homedir(),e.slice(2));if(Ut.isAbsolute(e))return e;throw new Error(`workspaceDir must be absolute or ~-prefixed, got: ${e}`)},Xe=async()=>{let e=qt(),r;try{r=await da.readFile(e,"utf-8")}catch{throw new Error(`Factory config not found at ${e}. infra-kit needs a machine-local factory registry to know where your project repos live and which to stamp. Run \`infra-kit vendor-config --init\` to scaffold it, or create it manually as JSON:
12
12
 
13
13
  {
14
14
  "workspaceDir": "~/projects",
15
15
  "targets": ["my-repo"]
16
16
  }
17
- `)}let t;try{t=r.trim()===""?{}:JSON.parse(r)}catch(n){throw new Error(`Invalid JSON in vendor.json at ${e}: ${n.message}`)}let o=tt.safeParse(t);if(!o.success)throw new Error(`Invalid factory config at ${e}: ${ma.prettifyError(o.error)}`);return o.data};var Mn=e=>e.replace(/\.json$/,".yml"),Wn=async()=>{let e;try{e=await W()}catch{return}let r=[{label:"infra-kit.json",yml:Mn(e.main),json:e.main,schema:Qr},{label:"~/.infra-kit/infra-kit.json",yml:Y.join(Y.dirname(e.userGlobal),"config.yml"),json:e.userGlobal,schema:wr},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:Mn(e.userProject),json:e.userProject,schema:wr}],t=0;for(let o of r){let[n,s]=await Promise.all([pe(o.yml),pe(o.json)]);if(n){if(s){a.info(`\u26A0 Skipped ${R(o.yml)} \u2014 ${R(o.json)} already exists (remove the stale .yml manually)`);continue}try{let i=await V.readFile(o.yml,"utf-8"),l=fa.parse(i)??{},c=o.schema.safeParse(l);if(!c.success){a.info(`\u26A0 Skipped ${R(o.yml)} \u2014 invalid config: ${Ln.prettifyError(c.error)}`);continue}await V.mkdir(Y.dirname(o.json),{recursive:!0}),await V.writeFile(o.json,`${JSON.stringify(c.data,null,2)}
18
- `,"utf-8"),await V.rm(o.yml,{force:!0}),a.info(`\u2713 Migrated ${R(o.yml)} \u2192 ${R(o.json)}`),t++}catch(i){a.info(`\u26A0 Skipped ${R(o.yml)} \u2014 ${i.message}`)}}}t>0&&ye()},Vn=async()=>{let e;try{e=await W()}catch{return}let r=Y.dirname(e.userGlobal),t=[{from:Y.join(r,"config.json"),to:e.userGlobal},{from:Y.join(r,"config.example.jsonc"),to:Y.join(r,"infra-kit.example.jsonc")}],o=0;for(let{from:n,to:s}of t){let[i,l]=await Promise.all([pe(n),pe(s)]);if(i){if(l){a.info(`\u26A0 Skipped ${R(n)} \u2014 ${R(s)} already exists (remove the stale file manually)`);continue}try{await V.mkdir(Y.dirname(s),{recursive:!0}),await V.rename(n,s),a.info(`\u2713 Renamed ${R(n)} \u2192 ${R(s)}`),o++}catch(c){a.info(`\u26A0 Skipped ${R(n)} \u2014 ${c.message}`)}}}o>0&&ye()},Bn=async()=>{let e=Ht(),r=Y.dirname(e),t=Y.join(r,"vendor.config.ts"),[o,n]=await Promise.all([pe(t),pe(e)]);if(o){if(n){a.info(`\u26A0 Skipped ${R(t)} \u2014 ${R(e)} already exists (remove the stale vendor.config.ts manually)`);return}try{let s=await V.stat(t),c=(await import(`${ua(t).href}?mtime=${Number(s.mtimeMs)}`)).default,p=typeof c=="function",d=p?await c():c,u=tt.safeParse(d);if(!u.success){a.info(`\u26A0 Skipped ${R(t)} \u2014 invalid factory config: ${Ln.prettifyError(u.error)}`);return}await V.mkdir(r,{recursive:!0}),await V.writeFile(e,`${JSON.stringify(u.data,null,2)}
19
- `,"utf-8"),await V.rm(t,{force:!0}),p?a.info(`\u26A0 Migrated ${R(t)} \u2192 ${R(e)} as a STATIC SNAPSHOT \u2014 the old file was a function (export default () => ({...})); computed values (env vars, directory globbing) were frozen at their current values and no longer re-evaluate. Edit ${R(e)} directly to change them.`):a.info(`\u2713 Migrated ${R(t)} \u2192 ${R(e)}`)}catch(s){a.info(`\u26A0 Skipped ${R(t)} \u2014 ${s.message}`)}}},ga=e=>{let r=e.ide;if(r===null||typeof r!="object")return{changed:!1,result:e};let t=!1,o=s=>{if(s===null||typeof s!="object"||!("config"in s))return s;let i=s.config;if(i===null||typeof i!="object"||!("mode"in i))return s;t=!0;let l=Object.fromEntries(Object.entries(i).filter(([c])=>c!=="mode"));return{...s,config:l}},n=Array.isArray(r)?r.map(o):o(r);return t?{changed:!0,result:{...e,ide:n}}:{changed:!1,result:e}},Jn=async()=>{let e;try{e=await W()}catch{return}let r=[e.main,e.userGlobal,e.userProject],t=0;for(let o of r)if(await pe(o))try{let n=await V.readFile(o,"utf-8");if(n.trim()==="")continue;let s=JSON.parse(n),{changed:i,result:l}=ga(s);if(!i)continue;await V.writeFile(o,`${JSON.stringify(l,null,2)}
17
+ `)}let t;try{t=r.trim()===""?{}:JSON.parse(r)}catch(n){throw new Error(`Invalid JSON in vendor.json at ${e}: ${n.message}`)}let o=tt.safeParse(t);if(!o.success)throw new Error(`Invalid factory config at ${e}: ${ma.prettifyError(o.error)}`);return o.data};var jn=e=>e.replace(/\.json$/,".yml"),Ln=async()=>{let e;try{e=await W()}catch{return}let r=[{label:"infra-kit.json",yml:jn(e.main),json:e.main,schema:Qr},{label:"~/.infra-kit/infra-kit.json",yml:Y.join(Y.dirname(e.userGlobal),"config.yml"),json:e.userGlobal,schema:wr},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:jn(e.userProject),json:e.userProject,schema:wr}],t=0;for(let o of r){let[n,s]=await Promise.all([pe(o.yml),pe(o.json)]);if(n){if(s){a.info(`\u26A0 Skipped ${R(o.yml)} \u2014 ${R(o.json)} already exists (remove the stale .yml manually)`);continue}try{let i=await V.readFile(o.yml,"utf-8"),l=fa.parse(i)??{},c=o.schema.safeParse(l);if(!c.success){a.info(`\u26A0 Skipped ${R(o.yml)} \u2014 invalid config: ${Mn.prettifyError(c.error)}`);continue}await V.mkdir(Y.dirname(o.json),{recursive:!0}),await V.writeFile(o.json,`${JSON.stringify(c.data,null,2)}
18
+ `,"utf-8"),await V.rm(o.yml,{force:!0}),a.info(`\u2713 Migrated ${R(o.yml)} \u2192 ${R(o.json)}`),t++}catch(i){a.info(`\u26A0 Skipped ${R(o.yml)} \u2014 ${i.message}`)}}}t>0&&ye()},Wn=async()=>{let e;try{e=await W()}catch{return}let r=Y.dirname(e.userGlobal),t=[{from:Y.join(r,"config.json"),to:e.userGlobal},{from:Y.join(r,"config.example.jsonc"),to:Y.join(r,"infra-kit.example.jsonc")}],o=0;for(let{from:n,to:s}of t){let[i,l]=await Promise.all([pe(n),pe(s)]);if(i){if(l){a.info(`\u26A0 Skipped ${R(n)} \u2014 ${R(s)} already exists (remove the stale file manually)`);continue}try{await V.mkdir(Y.dirname(s),{recursive:!0}),await V.rename(n,s),a.info(`\u2713 Renamed ${R(n)} \u2192 ${R(s)}`),o++}catch(c){a.info(`\u26A0 Skipped ${R(n)} \u2014 ${c.message}`)}}}o>0&&ye()},Vn=async()=>{let e=qt(),r=Y.dirname(e),t=Y.join(r,"vendor.config.ts"),[o,n]=await Promise.all([pe(t),pe(e)]);if(o){if(n){a.info(`\u26A0 Skipped ${R(t)} \u2014 ${R(e)} already exists (remove the stale vendor.config.ts manually)`);return}try{let s=await V.stat(t),c=(await import(`${ua(t).href}?mtime=${Number(s.mtimeMs)}`)).default,p=typeof c=="function",d=p?await c():c,u=tt.safeParse(d);if(!u.success){a.info(`\u26A0 Skipped ${R(t)} \u2014 invalid factory config: ${Mn.prettifyError(u.error)}`);return}await V.mkdir(r,{recursive:!0}),await V.writeFile(e,`${JSON.stringify(u.data,null,2)}
19
+ `,"utf-8"),await V.rm(t,{force:!0}),p?a.info(`\u26A0 Migrated ${R(t)} \u2192 ${R(e)} as a STATIC SNAPSHOT \u2014 the old file was a function (export default () => ({...})); computed values (env vars, directory globbing) were frozen at their current values and no longer re-evaluate. Edit ${R(e)} directly to change them.`):a.info(`\u2713 Migrated ${R(t)} \u2192 ${R(e)}`)}catch(s){a.info(`\u26A0 Skipped ${R(t)} \u2014 ${s.message}`)}}},ga=e=>{let r=e.ide;if(r===null||typeof r!="object")return{changed:!1,result:e};let t=!1,o=s=>{if(s===null||typeof s!="object"||!("config"in s))return s;let i=s.config;if(i===null||typeof i!="object"||!("mode"in i))return s;t=!0;let l=Object.fromEntries(Object.entries(i).filter(([c])=>c!=="mode"));return{...s,config:l}},n=Array.isArray(r)?r.map(o):o(r);return t?{changed:!0,result:{...e,ide:n}}:{changed:!1,result:e}},Bn=async()=>{let e;try{e=await W()}catch{return}let r=[e.main,e.userGlobal,e.userProject],t=0;for(let o of r)if(await pe(o))try{let n=await V.readFile(o,"utf-8");if(n.trim()==="")continue;let s=JSON.parse(n),{changed:i,result:l}=ga(s);if(!i)continue;await V.writeFile(o,`${JSON.stringify(l,null,2)}
20
20
  `,"utf-8"),a.info(`\u2713 Normalized ide config in ${R(o)} (removed legacy "mode")`),t++}catch(n){a.info(`\u26A0 Skipped normalizing ${R(o)} \u2014 ${n.message}`)}t>0&&ye()};var br="# -- infra-kit:begin --",Ye="# -- infra-kit:end --",wa=[["# region infra-kit","# endregion infra-kit"]],va="# infra-kit shell functions",ya=`{}
21
21
  `,ka=`// infra-kit user-global config \u2014 ~/.infra-kit/infra-kit.json
22
22
  //
@@ -89,53 +89,53 @@ ${s}
89
89
  // "workspaceDir": "~/projects", // string (absolute or ~-prefixed) \u2014 where target repos are cloned
90
90
  // "targets": ["my-repo-a", "my-repo-b"] // string[] (>=1) \u2014 repo dir names resolved under workspaceDir
91
91
  }
92
- `,_m=async()=>{let e=Rr.join(Kn.homedir(),".zshrc"),r=ke.existsSync(e)?Ca(ke.readFileSync(e,"utf-8")):"",t=gr({content:r,body:Gn(),startMarker:br,endMarker:Ye,placement:"append-end"});ke.writeFileSync(e,t),a.info(`Added infra-kit shell functions to ${e}`),await Wn(),await Jn(),await Vn(),await Bn(),ba(),await Fn();let o=ha.env.SHELL??"";o.includes("zsh")||a.warn(`Your login shell ($SHELL=${o||"unset"}) is not zsh. The infra-kit shell integration (env-load/env-clear/auto-load) is zsh-only and won't activate in bash/fish.`),a.info("Run `source ~/.zshrc` or open a new terminal to activate.")},ba=()=>{let e=Rr.join(Kn.homedir(),".infra-kit"),r=Rr.join(e,"infra-kit.json");if(ke.mkdirSync(e,{recursive:!0}),ke.writeFileSync(Rr.join(e,"infra-kit.example.jsonc"),ka,"utf-8"),ke.writeFileSync(Rr.join(e,"vendor.example.jsonc"),Ra,"utf-8"),ke.existsSync(r)){a.info(`User-global config already present at ${r} (refreshed reference examples)`);return}ke.writeFileSync(r,ya,"utf-8"),a.info(`Wrote user-global config to ${r} (see the sibling .example.jsonc files for reference)`)},xa=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"),Ca=e=>{let r=ve(e,br,Ye);if(r!==null)return r;for(let[l,c]of wa){let p=ve(e,l,c);if(p!==null)return p}let t=e.indexOf(va);if(t===-1)return e;let o=e.slice(0,t).replace(/\n+$/,""),n=e.slice(t).split(`
92
+ `,_m=async()=>{let e=Rr.join(Jn.homedir(),".zshrc"),r=ke.existsSync(e)?Ca(ke.readFileSync(e,"utf-8")):"",t=gr({content:r,body:Kn(),startMarker:br,endMarker:Ye,placement:"append-end"});ke.writeFileSync(e,t),a.info(`Added infra-kit shell functions to ${e}`),await Ln(),await Bn(),await Wn(),await Vn(),ba(),await On();let o=ha.env.SHELL??"";o.includes("zsh")||a.warn(`Your login shell ($SHELL=${o||"unset"}) is not zsh. The infra-kit shell integration (env-load/env-clear/auto-load) is zsh-only and won't activate in bash/fish.`),a.info("Run `source ~/.zshrc` or open a new terminal to activate.")},ba=()=>{let e=Rr.join(Jn.homedir(),".infra-kit"),r=Rr.join(e,"infra-kit.json");if(ke.mkdirSync(e,{recursive:!0}),ke.writeFileSync(Rr.join(e,"infra-kit.example.jsonc"),ka,"utf-8"),ke.writeFileSync(Rr.join(e,"vendor.example.jsonc"),Ra,"utf-8"),ke.existsSync(r)){a.info(`User-global config already present at ${r} (refreshed reference examples)`);return}ke.writeFileSync(r,ya,"utf-8"),a.info(`Wrote user-global config to ${r} (see the sibling .example.jsonc files for reference)`)},xa=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"),Ca=e=>{let r=ve(e,br,Ye);if(r!==null)return r;for(let[l,c]of wa){let p=ve(e,l,c);if(p!==null)return p}let t=e.indexOf(va);if(t===-1)return e;let o=e.slice(0,t).replace(/\n+$/,""),n=e.slice(t).split(`
93
93
  `),s=0;for(;s<n.length&&xa(n[s]);)s++;let i=n.slice(s).join(`
94
94
  `);return o+(i?`
95
- ${i}`:"")},Gn=()=>{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","_infra_kit_startup_autoload() {",' [[ -z "$INFRA_KIT_SESSION" ]] && return',' [[ -n "$INFRA_KIT_ENV_CONFIG" ]] && return',' local dir="$PWD"',' while [[ "$dir" != / ]]; do',' if [[ -f "$dir/infra-kit.json" ]]; then',` ( ${e} env-autoload & ) >/dev/null 2>&1`," return"," fi",' dir="${dir:h}"'," done","}","if (( _INFRA_KIT_SHELL_STARTED > 0 )); then"," _infra_kit_startup_autoload","fi"].join(`
96
- `)},zn=()=>`${br}
97
- ${Gn()}
98
- ${Ye}`;import Q from"node:fs";import Zn from"node:os";import er from"node:path";import{z as Qe}from"zod";import{$ as Qt}from"zx";import{$ as Un}from"zx";var qn=5e3,ot=async()=>{try{await Un`doppler --version`.timeout(qn)}catch(e){throw new Error("Doppler CLI is not installed. Install it from: https://docs.doppler.com/docs/install-cli",{cause:e})}try{await Un`doppler me`.timeout(qn)}catch(e){throw new Error("Doppler CLI is not authenticated (or timed out). Run: doppler login",{cause:e})}};var Ea="Could not find requested project",Ta="Could not find requested config",Zt=e=>e.includes(Ea)?"project":e.includes(Ta)?"config":"unknown",Xt=({kind:e,project:r,config:t,available:o})=>{let n=e==="project"?[`Doppler project "${r}" not found (set in infra-kit.json \u2192 envManagement.config.name).`]:[`Doppler config "${t}" not found in project "${r}" (set in infra-kit.json \u2192 environments).`];if(o&&o.length>0){let s=e==="project"?"Available projects":`Available configs in "${r}"`;n.push(`${s}: ${o.join(", ")}.`)}return n.push(e==="project"?"Fix: update envManagement.config.name to an existing project, or create it in Doppler.":"Fix: update environments to an existing config, or create it in Doppler."),n.join(`
99
- `)};import{$ as xr}from"zx";var $a=5e3,Ne=async()=>{let{envManagement:e}=await x();return e.config.name},Cr=async()=>Hn(()=>xr`doppler projects --json`),Yt=async e=>Hn(()=>xr`doppler configs --project ${e} --json`),Hn=async e=>{let r=xr.quiet;xr.quiet=!0;try{let t=await e().timeout($a);return Ia(t.stdout)}catch{return null}finally{xr.quiet=r}},Ia=e=>{let r;try{r=JSON.parse(e)}catch{return null}return Array.isArray(r)?r.map(t=>t!==null&&typeof t=="object"?t.name:void 0).filter(t=>typeof t=="string"):null};var _e=async(e,r,t,o)=>{try{return await Qt`${r}`,{name:e,status:"pass",message:t}}catch{return{name:e,status:"fail",message:o}}},Pa=()=>{let e="zshrc init block",r=er.join(Zn.homedir(),".zshrc");if(!Q.existsSync(r))return{name:e,status:"fail",message:"~/.zshrc not found. Run: infra-kit init"};let t=Q.readFileSync(r,"utf-8"),o=t.indexOf(br),n=t.indexOf(Ye);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+Ye.length).trim(),i=zn().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"}},Sa=async()=>{let e="pnpm enableGlobalVirtualStore";try{let r=await k(),t=er.join(r,"pnpm-workspace.yaml");if(!Q.existsSync(t))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${t}`};let o=Q.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}`}}},Aa=async()=>{let e="infra-kit config valid";try{return ye(),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}}},Na=async()=>{let e="doppler project exists",r;try{r=await Ne()}catch{return{name:e,status:"pass",message:"Skipped \u2014 infra-kit config could not be read (see config check)"}}let t=await Cr();return t===null?{name:e,status:"pass",message:"Skipped \u2014 could not list Doppler projects (see doppler auth check)"}:t.includes(r)?{name:e,status:"pass",message:`Doppler project "${r}" exists`}:{name:e,status:"fail",message:`Doppler project "${r}" not found (set in infra-kit.json \u2192 envManagement.config.name). Available: ${t.length>0?t.join(", "):"none"}`}},_a=async()=>{let e="user override path";try{let r=await W(),t=Zn.homedir(),o=r.userProject.startsWith(t)?`~${r.userProject.slice(t.length)}`:r.userProject,s=Q.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}}},Oa=async()=>{let e="legacy user-global config",r;try{r=await W()}catch{return{name:e,status:"pass",message:"Skipped \u2014 infra-kit config paths could not be resolved"}}let t=er.join(er.dirname(r.userGlobal),"config.json");return Q.existsSync(t)?Q.existsSync(r.userGlobal)?{name:e,status:"fail",message:`Stale legacy config.json found at ${R(t)} \u2014 ${R(r.userGlobal)} is active; remove the old file.`}:{name:e,status:"fail",message:`Legacy user-global config.json found at ${R(t)} \u2014 run \`infra-kit init\` to migrate it (your overrides are not being applied).`}:{name:e,status:"pass",message:"No legacy user-global config.json"}},Fa={cursor:{command:["cursor","--version"],label:"Cursor",failMsg:"Cursor is not installed. Install from: https://cursor.com/"},zed:{command:["zed","--version"],label:"Zed",failMsg:"Zed is not installed. Install from: https://zed.dev/"}},Da=async e=>{let r=Fa[e];try{return await Qt`${r.command}`,{ok:!0,label:r.label,failMsg:r.failMsg}}catch{return{ok:!1,label:r.label,failMsg:r.failMsg}}},ja=async()=>{let e="ide installed",r;try{ye();let n=await x();r=K(n).map(s=>s.provider)}catch{return{name:e,status:"pass",message:"Skipped \u2014 infra-kit config could not be read (see config check)"}}if(r.length===0)return{name:e,status:"pass",message:"No IDE configured (ide unset)"};let t=await Promise.all(r.map(n=>Da(n))),o=t.filter(n=>!n.ok);return o.length===0?{name:e,status:"pass",message:`Installed: ${t.map(n=>n.label).join(", ")}`}:{name:e,status:"fail",message:o.map(n=>n.failMsg).join("; ")}},Ma=[1,2,3,5,7],La=async()=>{let e="rtk configured";try{let t=(await Qt`rtk init --show`).stdout.split(`
100
- `).map(n=>n.trim()).filter(n=>n.startsWith("[ok]")||n.startsWith("[--]")),o=[];for(let n of Ma){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}`}}},Wa=async()=>{let e;try{e=(await W()).main}catch{return[]}if(!Q.existsSync(e))return[];let r=er.join(er.dirname(e),"CLAUDE.md"),t=Q.existsSync(r)?Q.readFileSync(r,"utf-8"):"",o=He(t,yr,kr);return[{name:"CLAUDE.md block",status:o?"pass":"fail",message:o?"CLAUDE.md block present":"infra-kit block missing from CLAUDE.md. Run: infra-kit init"}]},Xn=async()=>{let r=[...await Promise.all([_e("gh installed",["gh","--version"],"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/"),_e("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),_e("doppler installed",["doppler","--version"],"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli"),_e("doppler authenticated",["doppler","me"],"Doppler CLI is authenticated","Doppler CLI is not authenticated. Run: doppler login"),_e("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"),_e("rtk installed",["rtk","--version"],"RTK is installed","RTK is not installed. Install from: https://github.com/rtk-ai/rtk"),_e("typescript-language-server installed",["typescript-language-server","--version"],"typescript-language-server is installed","typescript-language-server is not installed. Install from: https://github.com/typescript-language-server/typescript-language-server#installing"),La(),Promise.resolve(Pa()),Sa(),Aa(),Na(),_a(),Oa(),ja()]),...await Wa()];a.info(`Doctor check results:
101
- `);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:g(JSON.stringify(t,null,2)),structuredContent:t}},eo=w({name:"doctor",description:"Check installation and authentication status of gh, doppler, aws, and rtk CLIs",inputSchema:{},outputSchema:{checks:Qe.array(Qe.object({name:Qe.string().describe("Name of the check"),status:Qe.enum(["pass","fail"]).describe("Check result"),message:Qe.string().describe("Details about the check result")})).describe("List of all check results"),allPassed:Qe.boolean().describe("Whether all checks passed")},handler:Xn});import Ka from"@inquirer/select";import{Buffer as Ga}from"node:buffer";import za from"node:fs";import Ua from"node:path";import Qn from"node:process";import{z as Sr}from"zod";import{$ as nt}from"zx";var Va=()=>{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:
95
+ ${i}`:"")},Kn=()=>{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","_infra_kit_startup_autoload() {",' [[ -z "$INFRA_KIT_SESSION" ]] && return',' [[ -n "$INFRA_KIT_ENV_CONFIG" ]] && return',' local dir="$PWD"',' while [[ "$dir" != / ]]; do',' if [[ -f "$dir/infra-kit.json" ]]; then',` ( ${e} env-autoload & ) >/dev/null 2>&1`," return"," fi",' dir="${dir:h}"'," done","}","if (( _INFRA_KIT_SHELL_STARTED > 0 )); then"," _infra_kit_startup_autoload","fi"].join(`
96
+ `)},Gn=()=>`${br}
97
+ ${Kn()}
98
+ ${Ye}`;import Q from"node:fs";import Hn from"node:os";import er from"node:path";import{z as Qe}from"zod";import{$ as Yt}from"zx";import{$ as zn}from"zx";var Un=5e3,ot=async()=>{try{await zn`doppler --version`.timeout(Un)}catch(e){throw new Error("Doppler CLI is not installed. Install it from: https://docs.doppler.com/docs/install-cli",{cause:e})}try{await zn`doppler me`.timeout(Un)}catch(e){throw new Error("Doppler CLI is not authenticated (or timed out). Run: doppler login",{cause:e})}};var Ea="Could not find requested project",Ta="Could not find requested config",Ht=e=>e.includes(Ea)?"project":e.includes(Ta)?"config":"unknown",Zt=({kind:e,project:r,config:t,available:o})=>{let n=e==="project"?[`Doppler project "${r}" not found (set in infra-kit.json \u2192 envManagement.config.name).`]:[`Doppler config "${t}" not found in project "${r}" (set in infra-kit.json \u2192 environments).`];if(o&&o.length>0){let s=e==="project"?"Available projects":`Available configs in "${r}"`;n.push(`${s}: ${o.join(", ")}.`)}return n.push(e==="project"?"Fix: update envManagement.config.name to an existing project, or create it in Doppler.":"Fix: update environments to an existing config, or create it in Doppler."),n.join(`
99
+ `)};import{$ as xr}from"zx";var $a=5e3,Ne=async()=>{let{envManagement:e}=await x();return e.config.name},Cr=async()=>qn(()=>xr`doppler projects --json`),Xt=async e=>qn(()=>xr`doppler configs --project ${e} --json`),qn=async e=>{let r=xr.quiet;xr.quiet=!0;try{let t=await e().timeout($a);return Ia(t.stdout)}catch{return null}finally{xr.quiet=r}},Ia=e=>{let r;try{r=JSON.parse(e)}catch{return null}return Array.isArray(r)?r.map(t=>t!==null&&typeof t=="object"?t.name:void 0).filter(t=>typeof t=="string"):null};var _e=async(e,r,t,o)=>{try{return await Yt`${r}`,{name:e,status:"pass",message:t}}catch{return{name:e,status:"fail",message:o}}},Pa=()=>{let e="zshrc init block",r=er.join(Hn.homedir(),".zshrc");if(!Q.existsSync(r))return{name:e,status:"fail",message:"~/.zshrc not found. Run: infra-kit init"};let t=Q.readFileSync(r,"utf-8"),o=t.indexOf(br),n=t.indexOf(Ye);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+Ye.length).trim(),i=Gn().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"}},Sa=async()=>{let e="pnpm enableGlobalVirtualStore";try{let r=await k(),t=er.join(r,"pnpm-workspace.yaml");if(!Q.existsSync(t))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${t}`};let o=Q.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}`}}},Aa=async()=>{let e="infra-kit config valid";try{return ye(),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}}},Na=async()=>{let e="doppler project exists",r;try{r=await Ne()}catch{return{name:e,status:"pass",message:"Skipped \u2014 infra-kit config could not be read (see config check)"}}let t=await Cr();return t===null?{name:e,status:"pass",message:"Skipped \u2014 could not list Doppler projects (see doppler auth check)"}:t.includes(r)?{name:e,status:"pass",message:`Doppler project "${r}" exists`}:{name:e,status:"fail",message:`Doppler project "${r}" not found (set in infra-kit.json \u2192 envManagement.config.name). Available: ${t.length>0?t.join(", "):"none"}`}},_a=async()=>{let e="user override path";try{let r=await W(),t=Hn.homedir(),o=r.userProject.startsWith(t)?`~${r.userProject.slice(t.length)}`:r.userProject,s=Q.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}}},Oa=async()=>{let e="legacy user-global config",r;try{r=await W()}catch{return{name:e,status:"pass",message:"Skipped \u2014 infra-kit config paths could not be resolved"}}let t=er.join(er.dirname(r.userGlobal),"config.json");return Q.existsSync(t)?Q.existsSync(r.userGlobal)?{name:e,status:"fail",message:`Stale legacy config.json found at ${R(t)} \u2014 ${R(r.userGlobal)} is active; remove the old file.`}:{name:e,status:"fail",message:`Legacy user-global config.json found at ${R(t)} \u2014 run \`infra-kit init\` to migrate it (your overrides are not being applied).`}:{name:e,status:"pass",message:"No legacy user-global config.json"}},Fa={cursor:{command:["cursor","--version"],label:"Cursor",failMsg:"Cursor is not installed. Install from: https://cursor.com/"},zed:{command:["zed","--version"],label:"Zed",failMsg:"Zed is not installed. Install from: https://zed.dev/"}},Da=async e=>{let r=Fa[e];try{return await Yt`${r.command}`,{ok:!0,label:r.label,failMsg:r.failMsg}}catch{return{ok:!1,label:r.label,failMsg:r.failMsg}}},ja=async()=>{let e="ide installed",r;try{ye();let n=await x();r=K(n).map(s=>s.provider)}catch{return{name:e,status:"pass",message:"Skipped \u2014 infra-kit config could not be read (see config check)"}}if(r.length===0)return{name:e,status:"pass",message:"No IDE configured (ide unset)"};let t=await Promise.all(r.map(n=>Da(n))),o=t.filter(n=>!n.ok);return o.length===0?{name:e,status:"pass",message:`Installed: ${t.map(n=>n.label).join(", ")}`}:{name:e,status:"fail",message:o.map(n=>n.failMsg).join("; ")}},Ma=[1,2,3,5,7],La=async()=>{let e="rtk configured";try{let t=(await Yt`rtk init --show`).stdout.split(`
100
+ `).map(n=>n.trim()).filter(n=>n.startsWith("[ok]")||n.startsWith("[--]")),o=[];for(let n of Ma){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}`}}},Wa=async()=>{let e;try{e=(await W()).main}catch{return[]}if(!Q.existsSync(e))return[];let r=er.join(er.dirname(e),"CLAUDE.md"),t=Q.existsSync(r)?Q.readFileSync(r,"utf-8"):"",o=He(t,yr,kr);return[{name:"CLAUDE.md block",status:o?"pass":"fail",message:o?"CLAUDE.md block present":"infra-kit block missing from CLAUDE.md. Run: infra-kit init"}]},Zn=async()=>{let r=[...await Promise.all([_e("gh installed",["gh","--version"],"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/"),_e("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),_e("doppler installed",["doppler","--version"],"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli"),_e("doppler authenticated",["doppler","me"],"Doppler CLI is authenticated","Doppler CLI is not authenticated. Run: doppler login"),_e("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"),_e("rtk installed",["rtk","--version"],"RTK is installed","RTK is not installed. Install from: https://github.com/rtk-ai/rtk"),_e("typescript-language-server installed",["typescript-language-server","--version"],"typescript-language-server is installed","typescript-language-server is not installed. Install from: https://github.com/typescript-language-server/typescript-language-server#installing"),La(),Promise.resolve(Pa()),Sa(),Aa(),Na(),_a(),Oa(),ja()]),...await Wa()];a.info(`Doctor check results:
101
+ `);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:g(JSON.stringify(t,null,2)),structuredContent:t}},Qt=w({name:"doctor",description:"Check installation and authentication status of gh, doppler, aws, and rtk CLIs",inputSchema:{},outputSchema:{checks:Qe.array(Qe.object({name:Qe.string().describe("Name of the check"),status:Qe.enum(["pass","fail"]).describe("Check result"),message:Qe.string().describe("Details about the check result")})).describe("List of all check results"),allPassed:Qe.boolean().describe("Whether all checks passed")},handler:Zn});import Ka from"@inquirer/select";import{Buffer as Ga}from"node:buffer";import za from"node:fs";import Ua from"node:path";import Yn from"node:process";import{z as Sr}from"zod";import{$ as nt}from"zx";var Va=()=>{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:
102
102
  pnpm exec infra-kit ${e} ${o}
103
- `)},reset(){e="",r=[],t=!1}}},m=Va();import Er from"node:fs";import Ba from"node:os";import ro from"node:path";import to from"node:process";var Oe="env-load.sh",oo="env-clear.sh",Tr="INFRA_KIT_SESSION",Fe="INFRA_KIT_ENV_CONFIG",De="INFRA_KIT_ENV_PROJECT",je="INFRA_KIT_ENV_LOADED_AT",Re="INFRA_KIT_ENV_AUTOLOADED",Me="INFRA_KIT_ENV_CLEARED",$r=/^([A-Z_]\w*)=/i,Ir=e=>{if(!Er.existsSync(e))return[];let r=Er.readFileSync(e,"utf-8"),t=[];for(let o of r.split(`
104
- `)){let n=$r.exec(o);n&&t.push(n[1])}return t},Yn=()=>{let e=to.env.XDG_CACHE_HOME,r=e&&e.length>0?e:ro.join(Ba.homedir(),".cache");return ro.join(r,"infra-kit")},Le=()=>{let e=to.env[Tr];if(!e)throw new Error(`${Tr} is not set. Run \`infra-kit init\` then \`source ~/.zshrc\`.`);return ro.join(Yn(),e)},Pr=(e,r,t)=>{let o=`${e}.tmp.${to.pid}`;Er.writeFileSync(o,r,{mode:t});try{Er.renameSync(o,e)}catch(n){throw Er.rmSync(o,{force:!0}),n}},G="-worktrees";var no=e=>{if(e===null||typeof e!="object")return;let r=e.stderr;return typeof r=="string"&&r.length>0?r:void 0},Ja=(e,r)=>{let t=r.stderrExcerpt??no(e),o=[`failed to ${r.operation}`];return t&&o.push(`stderr: ${t.slice(0,200).trim()}`),r.remediation&&o.push(`try: ${r.remediation}`),o.join(" \u2014 ")},f=class extends Error{operation;remediation;constructor(r,t){super(Ja(r,t),{cause:r}),this.name="OperationError",this.operation=t.operation,this.remediation=t.remediation}};var qa=e=>e?[`${Re}=${st("1")}`]:[`unset ${Re}`,`unset ${Me}`],rs=({envContent:e,config:r,project:t,loadedAt:o,autoLoaded:n})=>["set -a",e,`${Fe}=${st(r)}`,`${De}=${st(t)}`,`${je}=${st(o)}`,...qa(n),"set +a"],ts=async({config:e,autoLoaded:r=!1})=>{await ot();let t=await Ne(),o=await Za(t,e);rc(o);let n=new Date().toISOString(),s=rs({envContent:o,config:e,project:t,loadedAt:n,autoLoaded:r}),i=Le(),l=Ua.resolve(i,Oe);return za.mkdirSync(i,{recursive:!0,mode:448}),Pr(l,`${s.join(`
103
+ `)},reset(){e="",r=[],t=!1}}},m=Va();import Er from"node:fs";import Ba from"node:os";import eo from"node:path";import ro from"node:process";var Oe="env-load.sh",to="env-clear.sh",Tr="INFRA_KIT_SESSION",Fe="INFRA_KIT_ENV_CONFIG",De="INFRA_KIT_ENV_PROJECT",je="INFRA_KIT_ENV_LOADED_AT",Re="INFRA_KIT_ENV_AUTOLOADED",Me="INFRA_KIT_ENV_CLEARED",$r=/^([A-Z_]\w*)=/i,Ir=e=>{if(!Er.existsSync(e))return[];let r=Er.readFileSync(e,"utf-8"),t=[];for(let o of r.split(`
104
+ `)){let n=$r.exec(o);n&&t.push(n[1])}return t},Xn=()=>{let e=ro.env.XDG_CACHE_HOME,r=e&&e.length>0?e:eo.join(Ba.homedir(),".cache");return eo.join(r,"infra-kit")},Le=()=>{let e=ro.env[Tr];if(!e)throw new Error(`${Tr} is not set. Run \`infra-kit init\` then \`source ~/.zshrc\`.`);return eo.join(Xn(),e)},Pr=(e,r,t)=>{let o=`${e}.tmp.${ro.pid}`;Er.writeFileSync(o,r,{mode:t});try{Er.renameSync(o,e)}catch(n){throw Er.rmSync(o,{force:!0}),n}},G="-worktrees";var oo=e=>{if(e===null||typeof e!="object")return;let r=e.stderr;return typeof r=="string"&&r.length>0?r:void 0},Ja=(e,r)=>{let t=r.stderrExcerpt??oo(e),o=[`failed to ${r.operation}`];return t&&o.push(`stderr: ${t.slice(0,200).trim()}`),r.remediation&&o.push(`try: ${r.remediation}`),o.join(" \u2014 ")},f=class extends Error{operation;remediation;constructor(r,t){super(Ja(r,t),{cause:r}),this.name="OperationError",this.operation=t.operation,this.remediation=t.remediation}};var qa=e=>e?[`${Re}=${st("1")}`]:[`unset ${Re}`,`unset ${Me}`],es=({envContent:e,config:r,project:t,loadedAt:o,autoLoaded:n})=>["set -a",e,`${Fe}=${st(r)}`,`${De}=${st(t)}`,`${je}=${st(o)}`,...qa(n),"set +a"],rs=async({config:e,autoLoaded:r=!1})=>{await ot();let t=await Ne(),o=await Za(t,e);rc(o);let n=new Date().toISOString(),s=es({envContent:o,config:e,project:t,loadedAt:n,autoLoaded:r}),i=Le(),l=Ua.resolve(i,Oe);return za.mkdirSync(i,{recursive:!0,mode:448}),Pr(l,`${s.join(`
105
105
  `)}
106
- `,384),{filePath:l,variableCount:Qa(o),project:t,config:e}},os=async e=>{let{config:r}=e;m.start("env-load");let t="";if(r)t=r;else{await ot();let{environments:s}=await x();m.setInteractive(),t=await Ka({message:"Select environment config",choices:s.map(i=>({name:i,value:i}))},{output:Qn.stderr})}m.addOption("--config",t);let o=await ts({config:t,autoLoaded:!1});Qn.stdout.write(`${o.filePath}
107
- `),m.print();let n={filePath:o.filePath,variableCount:o.variableCount,project:o.project,config:o.config};return{content:g(JSON.stringify(n,null,2)),structuredContent:n}},es=1024*1024,Ha=3e4,Za=async(e,r)=>{let t=nt.quiet;nt.quiet=!0;try{let o;try{o=await nt`doppler secrets download --no-file --format env --project ${e} --config ${r}`.timeout(Ha)}catch(n){throw await Xa(n,e,r)}return Ya(o.stdout),o.stdout.trim()}finally{nt.quiet=t}},Xa=async(e,r,t)=>{let o=no(e)??(e instanceof Error?e.message:String(e)),n=Zt(o);if(n==="unknown")return e instanceof Error?e:new Error(String(e));let s=n==="project"?await Cr():await Yt(r);return new Error(Xt({kind:n,project:r,config:t,available:s}))},Ya=e=>{let r=Ga.byteLength(e,"utf-8");if(r>es)throw new Error(`doppler returned unexpectedly large output (${r} bytes > ${es}) \u2014 refusing to write to disk`)},Qa=e=>e.split(`
106
+ `,384),{filePath:l,variableCount:Qa(o),project:t,config:e}},ts=async e=>{let{config:r}=e;m.start("env-load");let t="";if(r)t=r;else{await ot();let{environments:s}=await x();m.setInteractive(),t=await Ka({message:"Select environment config",choices:s.map(i=>({name:i,value:i}))},{output:Yn.stderr})}m.addOption("--config",t);let o=await rs({config:t,autoLoaded:!1});Yn.stdout.write(`${o.filePath}
107
+ `),m.print();let n={filePath:o.filePath,variableCount:o.variableCount,project:o.project,config:o.config};return{content:g(JSON.stringify(n,null,2)),structuredContent:n}},Qn=1024*1024,Ha=3e4,Za=async(e,r)=>{let t=nt.quiet;nt.quiet=!0;try{let o;try{o=await nt`doppler secrets download --no-file --format env --project ${e} --config ${r}`.timeout(Ha)}catch(n){throw await Xa(n,e,r)}return Ya(o.stdout),o.stdout.trim()}finally{nt.quiet=t}},Xa=async(e,r,t)=>{let o=oo(e)??(e instanceof Error?e.message:String(e)),n=Ht(o);if(n==="unknown")return e instanceof Error?e:new Error(String(e));let s=n==="project"?await Cr():await Xt(r);return new Error(Zt({kind:n,project:r,config:t,available:s}))},Ya=e=>{let r=Ga.byteLength(e,"utf-8");if(r>Qn)throw new Error(`doppler returned unexpectedly large output (${r} bytes > ${Qn}) \u2014 refusing to write to disk`)},Qa=e=>e.split(`
108
108
  `).filter(r=>$r.test(r)).length,ec=new Set(["set -a","set +a"]),st=e=>`'${e.replaceAll("'","'\\''")}'`,rc=e=>{if(e.trim().length===0)throw new Error("doppler returned empty output for env-load");for(let r of e.split(`
109
- `)){let t=r.trim();if(!(t.length===0||ec.has(t))&&!$r.test(t))throw new Error(`doppler returned unexpected output for env-load (expected KEY=value lines, got: ${JSON.stringify(t.slice(0,80))})`)}},so=w({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:Sr.string().describe('Doppler config / environment name to load (e.g. "dev", "arthur", "renana"). Required for MCP calls.')},outputSchema:{filePath:Sr.string().describe("Path to the file that must be sourced to apply variables"),variableCount:Sr.number().describe("Number of variables loaded"),project:Sr.string().describe("Doppler project name"),config:Sr.string().describe("Doppler config name")},handler:os});import io from"node:fs";import ns from"node:path";import tc from"node:process";import{z as it}from"zod";var oc=e=>[...e.map(r=>`unset ${r}`),`unset ${Fe}`,`unset ${De}`,`unset ${je}`,`unset ${Re}`,`export ${Me}='1'`],ss=async()=>{let e=Le(),r=ns.join(e,Oe);if(!io.existsSync(r))throw new Error("No loaded environment found. Run `env-load` first.");let t=Ir(r),o=oc(t),n=ns.resolve(e,oo);io.mkdirSync(e,{recursive:!0,mode:448}),Pr(n,`${o.join(`
109
+ `)){let t=r.trim();if(!(t.length===0||ec.has(t))&&!$r.test(t))throw new Error(`doppler returned unexpected output for env-load (expected KEY=value lines, got: ${JSON.stringify(t.slice(0,80))})`)}},no=w({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:Sr.string().describe('Doppler config / environment name to load (e.g. "dev", "arthur", "renana"). Required for MCP calls.')},outputSchema:{filePath:Sr.string().describe("Path to the file that must be sourced to apply variables"),variableCount:Sr.number().describe("Number of variables loaded"),project:Sr.string().describe("Doppler project name"),config:Sr.string().describe("Doppler config name")},handler:ts});import so from"node:fs";import os from"node:path";import tc from"node:process";import{z as it}from"zod";var oc=e=>[...e.map(r=>`unset ${r}`),`unset ${Fe}`,`unset ${De}`,`unset ${je}`,`unset ${Re}`,`export ${Me}='1'`],ns=async()=>{let e=Le(),r=os.join(e,Oe);if(!so.existsSync(r))throw new Error("No loaded environment found. Run `env-load` first.");let t=Ir(r),o=oc(t),n=os.resolve(e,to);so.mkdirSync(e,{recursive:!0,mode:448}),Pr(n,`${o.join(`
110
110
  `)}
111
111
  `,384),tc.stdout.write(`${n}
112
- `),io.unlinkSync(r);let s={filePath:n,variableCount:t.length,unsetStatements:o};return{content:g(JSON.stringify(s,null,2)),structuredContent:s}},ao=w({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:it.string().describe("Path to the file that must be sourced to apply"),variableCount:it.number().describe("Number of variables cleared"),unsetStatements:it.array(it.string()).describe("Unset statements generated")},handler:ss});import{z as co}from"zod";var is=async()=>{let e=await Ne(),{environments:r}=await x();a.info(`Doppler project: ${e}
113
- `),a.info("Available configs:");for(let o of r)a.info(` - ${o}`);let t={project:e,configs:r};return{content:g(JSON.stringify(t,null,2)),structuredContent:t}},lo=w({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:co.string().describe("Detected Doppler project name"),configs:co.array(co.string()).describe("Available environment configs")},handler:is});import nc from"node:path";import We from"node:process";import{z as be}from"zod";var as=async()=>{a.info("Environment session status:");let e=Le(),r=We.env[Tr],t=nc.join(e,Oe),o=0,n=0,s=We.env[Fe]??null,i=We.env[De]??null,l=We.env[je]??null,c=We.env[Re]==="1",p=!!We.env[Me];if(s){let u=Ir(t);u.length>0&&(n=u.length,o=u.filter(v=>v in We.env).length);let h=l?.replace(/\.\d{3}Z$/,"")??null,b=c?"auto-loaded":"manually loaded";if(a.info(` ${s}: ${o} of ${n} vars loaded (${b}, project: ${i}, loadedAt: ${h}, session: ${r})
112
+ `),so.unlinkSync(r);let s={filePath:n,variableCount:t.length,unsetStatements:o};return{content:g(JSON.stringify(s,null,2)),structuredContent:s}},io=w({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:it.string().describe("Path to the file that must be sourced to apply"),variableCount:it.number().describe("Number of variables cleared"),unsetStatements:it.array(it.string()).describe("Unset statements generated")},handler:ns});import{z as ao}from"zod";var ss=async()=>{let e=await Ne(),{environments:r}=await x();a.info(`Doppler project: ${e}
113
+ `),a.info("Available configs:");for(let o of r)a.info(` - ${o}`);let t={project:e,configs:r};return{content:g(JSON.stringify(t,null,2)),structuredContent:t}},co=w({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:ao.string().describe("Detected Doppler project name"),configs:ao.array(ao.string()).describe("Available environment configs")},handler:ss});import nc from"node:path";import We from"node:process";import{z as be}from"zod";var is=async()=>{a.info("Environment session status:");let e=Le(),r=We.env[Tr],t=nc.join(e,Oe),o=0,n=0,s=We.env[Fe]??null,i=We.env[De]??null,l=We.env[je]??null,c=We.env[Re]==="1",p=!!We.env[Me];if(s){let u=Ir(t);u.length>0&&(n=u.length,o=u.filter(v=>v in We.env).length);let h=l?.replace(/\.\d{3}Z$/,"")??null,b=c?"auto-loaded":"manually loaded";if(a.info(` ${s}: ${o} of ${n} vars loaded (${b}, project: ${i}, loadedAt: ${h}, session: ${r})
114
114
  `),n>0&&o<n){let v=n-o;a.warn(` ${v} cached var(s) are not present in the current process \u2014 env-load needs to be re-sourced, or vars were unset manually.`)}}else{let u=p?" (cleared \u2014 auto-load suppressed until a new shell or explicit env-load)":"";a.info(` Session ${r}: no env loaded${u}
115
- `)}let d={sessionId:r,sessionLoadedCount:o,sessionTotalCount:n,sessionConfig:s,sessionProject:i,sessionLoadedAt:l,autoLoaded:c,cleared:p};return{content:g(JSON.stringify(d,null,2)),structuredContent:d}},po=w({name:"env-status",description:"Report which Doppler project/config is currently loaded in the terminal session, when it was loaded, how many variables are cached, whether it was auto-loaded, and whether a clear is suppressing auto-load. Pure local introspection \u2014 makes NO Doppler call (use doctor for auth). Read-only \u2014 use env-load / env-clear to change the terminal session.",inputSchema:{},outputSchema:{sessionId:be.string().describe("Current terminal session ID"),sessionLoadedCount:be.number().describe("Number of cached vars active in the current session"),sessionTotalCount:be.number().describe("Total number of cached var names"),sessionConfig:be.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:be.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:be.string().nullable().describe("ISO 8601 timestamp of when the env was loaded"),autoLoaded:be.boolean().describe("True when the loaded env was applied by env auto-load (not a manual env-load)"),cleared:be.boolean().describe("True when env-clear is currently suppressing auto-load in this shell")},handler:as});import ic from"@inquirer/checkbox";import ac from"@inquirer/confirm";import cc from"node:process";import{z as sr}from"zod";import{$ as z}from"zx";import{$ as df}from"zx";import{$ as N}from"zx";import{$ as Nr}from"zx";import Ar from"node:process";var mo=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}},rr=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}},at=async(e,r)=>{try{return(await rr(r)).find(n=>n.name===e)||null}catch(t){throw a.error({error:t,versionName:e},"Error finding Jira version by name"),t}},ct=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 d=await c.text();throw a.error({status:c.status,statusText:c.statusText,error:d},"Failed to update Jira version"),new Error(`HTTP ${c.status}: ${c.statusText}`)}return{success:!0,version:await c.json()}}catch(t){throw a.error({error:t},"Error updating Jira version"),t}},uo=async(e,r)=>{try{let{versionName:t}=e,o=await at(t,r);if(!o)throw a.error({versionName:t},"Jira version not found"),new Error(`Version "${t}" not found in Jira project`);return await ct({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}},tr=async()=>{let e=Ar.env.JIRA_BASE_URL,r=Ar.env.JIRA_TOKEN||Ar.env.JIRA_API_TOKEN,t=Ar.env.JIRA_PROJECT_ID,o=Ar.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(`
116
- `);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}},Ve=async()=>{try{return await tr()}catch(e){return a.warn({error:e},"Jira configuration not available, skipping Jira integration"),null}};var cs="dev",or=e=>e==="hotfix"?"main":"dev",fo=async(e="regular")=>{let r=or(e);Nr.quiet=!0,await Nr`git fetch origin`,await Nr`git switch ${r}`,await Nr`git pull origin ${r}`,Nr.quiet=!1},go=async e=>{let{id:r,jiraConfig:t,description:o,type:n="regular"}=e,s=M(r),i=await mo({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 lt({id:r,jiraVersionUrl:l,type:n,description:o});return{version:I(r),type:n,branchName:c.branchName,prUrl:c.prUrl,jiraVersionUrl:l}},P=async()=>{let e=new Map,r=await Ve();if(!r)return e;try{let t=await rr(r);for(let o of t)o.description&&e.set(o.name,o.description)}catch{}return e},nr=(e,r,t)=>{let o=t?" ".repeat(t-e.length+3):" ",n=`[${r}]`.padEnd(11);return`${e}${o}${n}`},E=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",ls=e=>e.flatMap(r=>{let t=C(r);return t?[{branch:r,id:t,label:I(t)}]:[]}),de=e=>{try{return ce(Z(e))}catch(r){throw new f(r,{operation:`resolve release ref "${e}"`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'})}},_r=e=>{if(e===cs)return cs;let r=C(e);return r?I(r):e},Be=e=>e.flatMap(r=>{let t=C(r);return t?[I(t)]:[]}),A=e=>{let{branches:r,descriptions:t,types:o}=e,n=ls(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,d=t.get(M(l)),u=" ".repeat(s-c.length+3),h=p?nr(c,p,s):c;return d&&(h=p?`${h} ${d}`:`${c}${u}${d}`),{name:h,value:i}})};var ps=e=>e.map(r=>({pr:r,id:C(r.headRefName)})).filter(r=>r.id!==null).sort((r,t)=>At(r.id,t.id,{a:r.pr.createdAt,b:t.pr.createdAt})).map(r=>r.pr),ds=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))},pt=async()=>{try{let e=await ds();if(e.length===0)throw new f(void 0,{operation:"find open release PRs",remediation:"open a release PR first, or check you are in the right repo"});return ps(e).map(r=>r.headRefName)}catch(e){throw e instanceof f?e:(a.error({error:e},"\u274C Error fetching release PRs"),new f(e,{operation:"fetch release PRs"}))}},T=async()=>{try{let e=await ds();if(e.length===0)throw new f(void 0,{operation:"find open release PRs",remediation:"open a release PR first, or check you are in the right repo"});return ps(e).map(r=>({branch:r.headRefName,title:r.title,createdAt:r.createdAt}))}catch(e){throw e instanceof f?e:(a.error({error:e},"\u274C Error fetching release PRs"),new f(e,{operation:"fetch release PRs"}))}},dt=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}},lt=async e=>{let{id:r,jiraVersionUrl:t,type:o,description:n}=e,s=St(r,o),i=or(o),l=ce(r),c=n&&n.trim()!==""?`${t}
115
+ `)}let d={sessionId:r,sessionLoadedCount:o,sessionTotalCount:n,sessionConfig:s,sessionProject:i,sessionLoadedAt:l,autoLoaded:c,cleared:p};return{content:g(JSON.stringify(d,null,2)),structuredContent:d}},lo=w({name:"env-status",description:"Report which Doppler project/config is currently loaded in the terminal session, when it was loaded, how many variables are cached, whether it was auto-loaded, and whether a clear is suppressing auto-load. Pure local introspection \u2014 makes NO Doppler call (use doctor for auth). Read-only \u2014 use env-load / env-clear to change the terminal session.",inputSchema:{},outputSchema:{sessionId:be.string().describe("Current terminal session ID"),sessionLoadedCount:be.number().describe("Number of cached vars active in the current session"),sessionTotalCount:be.number().describe("Total number of cached var names"),sessionConfig:be.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:be.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:be.string().nullable().describe("ISO 8601 timestamp of when the env was loaded"),autoLoaded:be.boolean().describe("True when the loaded env was applied by env auto-load (not a manual env-load)"),cleared:be.boolean().describe("True when env-clear is currently suppressing auto-load in this shell")},handler:is});import ic from"@inquirer/checkbox";import ac from"@inquirer/confirm";import cc from"node:process";import{z as sr}from"zod";import{$ as z}from"zx";import{$ as df}from"zx";import{$ as N}from"zx";import{$ as Nr}from"zx";import Ar from"node:process";var po=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}},rr=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}},at=async(e,r)=>{try{return(await rr(r)).find(n=>n.name===e)||null}catch(t){throw a.error({error:t,versionName:e},"Error finding Jira version by name"),t}},ct=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 d=await c.text();throw a.error({status:c.status,statusText:c.statusText,error:d},"Failed to update Jira version"),new Error(`HTTP ${c.status}: ${c.statusText}`)}return{success:!0,version:await c.json()}}catch(t){throw a.error({error:t},"Error updating Jira version"),t}},mo=async(e,r)=>{try{let{versionName:t}=e,o=await at(t,r);if(!o)throw a.error({versionName:t},"Jira version not found"),new Error(`Version "${t}" not found in Jira project`);return await ct({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}},tr=async()=>{let e=Ar.env.JIRA_BASE_URL,r=Ar.env.JIRA_TOKEN||Ar.env.JIRA_API_TOKEN,t=Ar.env.JIRA_PROJECT_ID,o=Ar.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(`
116
+ `);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}},Ve=async()=>{try{return await tr()}catch(e){return a.warn({error:e},"Jira configuration not available, skipping Jira integration"),null}};var as="dev",or=e=>e==="hotfix"?"main":"dev",uo=async(e="regular")=>{let r=or(e);Nr.quiet=!0,await Nr`git fetch origin`,await Nr`git switch ${r}`,await Nr`git pull origin ${r}`,Nr.quiet=!1},fo=async e=>{let{id:r,jiraConfig:t,description:o,type:n="regular"}=e,s=M(r),i=await po({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 lt({id:r,jiraVersionUrl:l,type:n,description:o});return{version:I(r),type:n,branchName:c.branchName,prUrl:c.prUrl,jiraVersionUrl:l}},P=async()=>{let e=new Map,r=await Ve();if(!r)return e;try{let t=await rr(r);for(let o of t)o.description&&e.set(o.name,o.description)}catch{}return e},nr=(e,r,t)=>{let o=t?" ".repeat(t-e.length+3):" ",n=`[${r}]`.padEnd(11);return`${e}${o}${n}`},E=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",cs=e=>e.flatMap(r=>{let t=C(r);return t?[{branch:r,id:t,label:I(t)}]:[]}),de=e=>{try{return ce(Z(e))}catch(r){throw new f(r,{operation:`resolve release ref "${e}"`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'})}},_r=e=>{if(e===as)return as;let r=C(e);return r?I(r):e},Be=e=>e.flatMap(r=>{let t=C(r);return t?[I(t)]:[]}),A=e=>{let{branches:r,descriptions:t,types:o}=e,n=cs(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,d=t.get(M(l)),u=" ".repeat(s-c.length+3),h=p?nr(c,p,s):c;return d&&(h=p?`${h} ${d}`:`${c}${u}${d}`),{name:h,value:i}})};var ls=e=>e.map(r=>({pr:r,id:C(r.headRefName)})).filter(r=>r.id!==null).sort((r,t)=>St(r.id,t.id,{a:r.pr.createdAt,b:t.pr.createdAt})).map(r=>r.pr),ps=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))},pt=async()=>{try{let e=await ps();if(e.length===0)throw new f(void 0,{operation:"find open release PRs",remediation:"open a release PR first, or check you are in the right repo"});return ls(e).map(r=>r.headRefName)}catch(e){throw e instanceof f?e:(a.error({error:e},"\u274C Error fetching release PRs"),new f(e,{operation:"fetch release PRs"}))}},T=async()=>{try{let e=await ps();if(e.length===0)throw new f(void 0,{operation:"find open release PRs",remediation:"open a release PR first, or check you are in the right repo"});return ls(e).map(r=>({branch:r.headRefName,title:r.title,createdAt:r.createdAt}))}catch(e){throw e instanceof f?e:(a.error({error:e},"\u274C Error fetching release PRs"),new f(e,{operation:"fetch release PRs"}))}},dt=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}},lt=async e=>{let{id:r,jiraVersionUrl:t,type:o,description:n}=e,s=Pt(r,o),i=or(o),l=ce(r),c=n&&n.trim()!==""?`${t}
117
117
 
118
118
  ${n}`:`${t}
119
- `;try{N.quiet=!0,await N`git switch ${i}`,await N`git pull origin ${i}`,await N`git checkout -b ${l}`,await N`git push -u origin ${l}`,await N`git commit --allow-empty-message --allow-empty --message ''`,await N`git push origin ${l}`;let d=(await N`gh pr create --title ${s} --body ${c} --base ${i} --head ${l}`).stdout.trim();return await N`git switch ${i}`,N.quiet=!1,{branchName:l,prUrl:d}}catch(p){throw a.error({error:p,branchName:l},`Error creating release branch ${l}`),p}};var D=async e=>{let{operation:r,requiredBranch:t}=e;if(await _t())throw new f(void 0,{operation:r,remediation:"run this from the main repository checkout, not a linked git worktree",stderrExcerpt:"command run from inside a linked worktree"});if(t){let o=await Zr();if(o!==t)throw new f(void 0,{operation:r,remediation:`switch to ${t} first (git switch ${t})`,stderrExcerpt:`current branch is "${o}", expected "${t}"`})}if(!await Nt())throw new f(void 0,{operation:r,remediation:"commit or stash your changes, then retry",stderrExcerpt:"working tree has uncommitted changes"})};var ms=async e=>{let{all:r,confirmedCommand:t}=e;m.start("merge-dev"),await D({operation:"merge dev into release branches",requiredBranch:"dev"});let n=(await T()).filter(d=>E(d.title)==="regular").map(d=>d.branch);if(n.length===0)return a.info("\u2139\uFE0F No open release branches found"),m.print(),{content:g(JSON.stringify({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0},null,2)),structuredContent:{successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0}};let s=[];if(r)s=n;else{m.setInteractive();let d=await P();s=await ic({required:!0,message:"\u{1F33F} Select release branches",choices:A({branches:n,descriptions:d})})}s.length===n.length?m.addOption("--all",!0):m.addOption("--versions",Be(s));let l=t?!0:await ac({message:`Are you sure you want to merge dev into these branches: ${s.join(", ")}?`});t||m.setInteractive(),l||(a.info("Operation cancelled. Exiting..."),cc.exit(0)),t||m.addOption("--yes",!0),z.quiet=!0,await z`git fetch origin`,await z`git switch dev`,await z`git pull origin dev`;let c=[];for(let d of s)await lc(d)||c.push(d);if(z.quiet=!1,c.length>0){a.info(`
119
+ `;try{N.quiet=!0,await N`git switch ${i}`,await N`git pull origin ${i}`,await N`git checkout -b ${l}`,await N`git push -u origin ${l}`,await N`git commit --allow-empty-message --allow-empty --message ''`,await N`git push origin ${l}`;let d=(await N`gh pr create --title ${s} --body ${c} --base ${i} --head ${l}`).stdout.trim();return await N`git switch ${i}`,N.quiet=!1,{branchName:l,prUrl:d}}catch(p){throw a.error({error:p,branchName:l},`Error creating release branch ${l}`),p}};var D=async e=>{let{operation:r,requiredBranch:t}=e;if(await Nt())throw new f(void 0,{operation:r,remediation:"run this from the main repository checkout, not a linked git worktree",stderrExcerpt:"command run from inside a linked worktree"});if(t){let o=await Zr();if(o!==t)throw new f(void 0,{operation:r,remediation:`switch to ${t} first (git switch ${t})`,stderrExcerpt:`current branch is "${o}", expected "${t}"`})}if(!await At())throw new f(void 0,{operation:r,remediation:"commit or stash your changes, then retry",stderrExcerpt:"working tree has uncommitted changes"})};var ds=async e=>{let{all:r,confirmedCommand:t}=e;m.start("merge-dev"),await D({operation:"merge dev into release branches",requiredBranch:"dev"});let n=(await T()).filter(d=>E(d.title)==="regular").map(d=>d.branch);if(n.length===0)return a.info("\u2139\uFE0F No open release branches found"),m.print(),{content:g(JSON.stringify({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0},null,2)),structuredContent:{successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0}};let s=[];if(r)s=n;else{m.setInteractive();let d=await P();s=await ic({required:!0,message:"\u{1F33F} Select release branches",choices:A({branches:n,descriptions:d})})}s.length===n.length?m.addOption("--all",!0):m.addOption("--versions",Be(s));let l=t?!0:await ac({message:`Are you sure you want to merge dev into these branches: ${s.join(", ")}?`});t||m.setInteractive(),l||(a.info("Operation cancelled. Exiting..."),cc.exit(0)),t||m.addOption("--yes",!0),z.quiet=!0,await z`git fetch origin`,await z`git switch dev`,await z`git pull origin dev`;let c=[];for(let d of s)await lc(d)||c.push(d);if(z.quiet=!1,c.length>0){a.info(`
120
120
  \u26A0\uFE0F ${c.length} branch(es) failed to merge automatically.
121
121
  `),a.info("\u{1F4CB} Manual merge script for failed branches:");for(let d of c)a.info(`# Merge dev into ${d} and resolve conflicts if any
122
122
 
123
123
  git switch ${d} && git pull origin ${d} && git merge origin/dev
124
124
  git push origin ${d} && git switch dev
125
125
  `);a.info(`\u2705 ${s.length-c.length}/${s.length} merges completed successfully.`)}else a.info(`\u2705 All merges completed successfully!
126
- `);m.print();let p={successfulMerges:s.length-c.length,failedMerges:c.length,failedBranches:c,totalBranches:s.length};return{content:g(JSON.stringify(p,null,2)),structuredContent:p}},lc=async e=>{try{return await z`git switch ${e}`,await z`git pull origin ${e}`,await z`git merge origin/dev --no-edit`,await z`git push origin ${e}`,await z`git switch dev`,a.info(`Successfully merged dev into ${e}`),!0}catch(r){let t=new f(r,{operation:`merge dev into ${e}`,remediation:"resolve conflicts manually or rerun after 'git fetch origin'"});return a.error({error:r,branch:e,msg:t.message}),await z`git reset --merge HEAD~1`,!1}},ho=w({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:sr.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:sr.number().describe("Number of successful merges"),failedMerges:sr.number().describe("Number of failed merges"),failedBranches:sr.array(sr.string()).describe("List of branches that failed to merge"),totalBranches:sr.number().describe("Total number of branches processed")},handler:ms});import gc from"@inquirer/confirm";import hc from"@inquirer/select";import wc from"node:process";import{z as Lr}from"zod";import{$ as j}from"zx";var us=(e,r)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-r).trim()},Or=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=us(r.stderr,500);n&&(t.stderr=n);let s=us(r.stdout,200);return s&&(t.stdout=s),t};import{$ as mt}from"zx";var pc=/\bv(\d+\.\d+\.\d+)\b/g,ee=e=>e.trim().replace(/\s+/g," ").replace(pc,"$1");import{$ as fs}from"zx";var Je=async e=>{try{let r=(await fs`cmux list-workspaces`.quiet()).stdout,t=dc(r,e);if(!t)return;await fs`cmux close-workspace --workspace ${t}`.quiet()}catch(r){a.debug({error:r,title:e},"cmux: skipped closing workspace")}},dc=(e,r)=>{let t=ee(r);for(let o of e.split(`
126
+ `);m.print();let p={successfulMerges:s.length-c.length,failedMerges:c.length,failedBranches:c,totalBranches:s.length};return{content:g(JSON.stringify(p,null,2)),structuredContent:p}},lc=async e=>{try{return await z`git switch ${e}`,await z`git pull origin ${e}`,await z`git merge origin/dev --no-edit`,await z`git push origin ${e}`,await z`git switch dev`,a.info(`Successfully merged dev into ${e}`),!0}catch(r){let t=new f(r,{operation:`merge dev into ${e}`,remediation:"resolve conflicts manually or rerun after 'git fetch origin'"});return a.error({error:r,branch:e,msg:t.message}),await z`git reset --merge HEAD~1`,!1}},go=w({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:sr.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:sr.number().describe("Number of successful merges"),failedMerges:sr.number().describe("Number of failed merges"),failedBranches:sr.array(sr.string()).describe("List of branches that failed to merge"),totalBranches:sr.number().describe("Total number of branches processed")},handler:ds});import gc from"@inquirer/confirm";import hc from"@inquirer/select";import wc from"node:process";import{z as Lr}from"zod";import{$ as j}from"zx";var ms=(e,r)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-r).trim()},Or=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=ms(r.stderr,500);n&&(t.stderr=n);let s=ms(r.stdout,200);return s&&(t.stdout=s),t};import{$ as fs}from"zx";var pc=/\bv(\d+\.\d+\.\d+)\b/g,ee=e=>e.trim().replace(/\s+/g," ").replace(pc,"$1");import{$ as us}from"zx";var Je=async e=>{try{let r=(await us`cmux list-workspaces`.quiet()).stdout,t=dc(r,e);if(!t)return;await us`cmux close-workspace --workspace ${t}`.quiet()}catch(r){a.debug({error:r,title:e},"cmux: skipped closing workspace")}},dc=(e,r)=>{let t=ee(r);for(let o of e.split(`
127
127
  `)){let n=o.match(/^[* ]\s*(workspace:\d+)\s+(.+?)(?:\s+\[selected\])?\s*$/);if(!n)continue;let s=n[1],i=n[2]?.trim()??"";if(ee(i)===t)return s}};import{$ as mc}from"zx";var Fr=async()=>{try{let e=(await mc`cmux list-workspaces`.quiet()).stdout,r=new Set;for(let t of e.split(`
128
- `)){let o=t.match(/^[* ]\s*workspace:\d+\s+(.+?)(?:\s+\[selected\])?\s*$/);if(!o)continue;let n=o[1]?.trim();n&&r.add(ee(n))}return r}catch(e){return a.debug({error:e},"cmux: skipped listing workspace titles"),new Set}};import{$ as Dr}from"zx";var jr=async e=>{let{cwd:r,title:t}=e,o=zt(await x()),n=(await Dr`cmux workspace create --cwd ${r}`).stdout,s=fc(n),i=(await Dr`cmux list-pane-surfaces --workspace ${s}`).stdout,l=uc(i);await Dr`cmux new-split right --workspace ${s} --surface ${l}`,o==="three-pane"&&await Dr`cmux new-split down --workspace ${s} --surface ${l}`,t&&await Dr`cmux workspace rename --workspace ${s} --title ${t}`},uc=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]},fc=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 re=e=>{let{repoName:r,branch:t}=e,o=C(t),n=o?I(o):t;return`${r} ${n}`};var Mr=async e=>{let{branches:r,worktreeDir:t,repoName:o,pruneFolder:n=!1}=e,s=await Promise.allSettled(r.map(async c=>{let p=`${t}/${c}`,d=re({repoName:o,branch:c});return await Je(d),await mt`git worktree remove ${p}`,c})),i=[];for(let[c,p]of s.entries())if(p.status==="fulfilled")i.push(p.value);else{let d=r[c],u=new f(p.reason,{operation:`remove worktree for ${d}`,remediation:"check 'git worktree list' for the path; uncommitted changes block removal"});a.error({error:p.reason,msg:u.message})}let l=new Set;for(let c of i)c.includes("/")&&l.add(`${t}/${c.split("/")[0]}`);for(let c of l)await mt`rmdir ${c}`.nothrow();return n&&i.length===r.length&&(await mt`git worktree prune`,await mt`rm -rf ${t}`,a.info(`\u{1F5D1}\uFE0F Removed worktree folder: ${t}`),a.info("")),i};var ir=async(e,r,t)=>{try{return await t()}catch(o){throw a.error({err:Or(o)},`\u274C Failed to ${e}`),new f(o,{operation:e,remediation:r})}},hs=async e=>{let r=await j`gh pr list --head ${e} --state all --json number,state,title --limit 1`;return JSON.parse(r.stdout)[0]??null},vc=async e=>{let r=Hr(e),t=await j`gh pr list --head dev --base main --state merged --json number,state,title --limit 20`;return JSON.parse(t.stdout).find(s=>s.title===r)??null},gs=async()=>{let e=await j`gh pr list --head dev --base main --state open --json number,state,title --limit 5`;return JSON.parse(e.stdout)[0]??null},yc=async e=>{let r=de(e),t=await hs(r);if(!t)throw a.error(`\u274C No PR found for branch ${r}.`),new f(void 0,{operation:`deliver release ${r}`,remediation:`confirm a PR exists ('gh pr list --head ${r} --state all')`});return{selectedReleaseBranch:r,releasePrTitle:t.title}},kc=async()=>{let e=await T(),r=e.map(i=>i.branch),t=new Map(e.map(i=>[i.branch,E(i.title)]));m.setInteractive();let o=await P(),n=await hc({message:"\u{1F33F} Select release branch",choices:A({branches:r,descriptions:o,types:t})}),s=e.find(i=>i.branch===n);if(!s)throw a.error(`\u274C Release branch ${n} not found in open PRs.`),new f(void 0,{operation:`deliver release ${n}`,remediation:`confirm an open PR exists for ${n} ('gh pr list')`});return{selectedReleaseBranch:n,releasePrTitle:s.title}},Rc=async e=>{if(!(await F("release")).includes(e))return;let[t,o]=await Promise.all([k(),J()]),n=`${t}${G}`;if((await Mr({branches:[e],worktreeDir:n,repoName:o})).length===0)throw new f(void 0,{operation:`remove worktree for ${e} before merge`,remediation:`run manually: git worktree remove ${n}/${e} (use --force if uncommitted changes)`})},bc=async e=>{let{selectedReleaseBranch:r,releaseType:t}=e,o=t==="hotfix"?"main":"dev",n=await hs(r);if(!n)throw new f(void 0,{operation:`look up release PR for ${r}`,remediation:"verify the PR exists in GitHub"});if(n.state==="MERGED"){a.info(`\u2713 Release PR ${r} already merged \u2014 skipping`);return}if(n.state==="CLOSED")throw new f(void 0,{operation:`merge release PR ${r} into ${o}`,remediation:"the PR is closed without merge; reopen it or create a new release"});await ir(`merge release PR ${r} into ${o}`,`check 'gh pr view ${r}' for mergeability and required reviews`,async()=>{await j`gh pr merge ${r} --squash --admin --delete-branch`})},xc=async e=>{let r=I(e),t=Hr(e),o=await gs();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 ir(`retitle dev \u2192 main PR #${s} to "${t}"`,`update manually: gh pr edit ${s} --title "${t}"`,async()=>{await j`gh pr edit ${s} --title ${t}`})),s}await ir(`create RC PR (dev \u2192 main) for ${r}`,"run 'gh pr create --base main --head dev' manually to surface the underlying error (e.g. no commits between dev and main)",async()=>{await j`gh pr create --base main --head dev --title ${t} --body ""`});let n=await gs();if(!n)throw new f(void 0,{operation:`look up RC PR for ${r}`,remediation:"verify the RC PR was created ('gh pr list --head dev --base main')"});return n.number},Cc=async e=>{let r=I(e);if(await vc(e)){a.info(`\u2713 RC PR for ${r} already merged into main \u2014 skipping`);return}let o=await xc(e);await ir(`merge RC PR #${o} (dev \u2192 main) for ${r}`,`check 'gh pr view ${o}' for mergeability and required reviews`,async()=>{await j`gh pr merge ${o} --squash --admin`})},Ec=async()=>{j.quiet=!1,await ir("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await j`gh workflow run deploy-all.yml --ref main -f environment=prod`}),j.quiet=!0},Tc=async()=>{await ir("sync main back into dev","run manually: git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push",async()=>{await j`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},$c=async e=>{try{await Ot(e)}catch(r){a.warn({err:Or(r)},`Failed to delete local branch ${e} (non-blocking)`)}try{await Ft(e)}catch(r){a.warn({err:Or(r)},`Failed to delete remote branch ${e} (non-blocking)`)}},Ic=async e=>{let r=await Ve();if(!r){a.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let t=M(e);await uo({versionName:t},r)}catch(t){a.error({err:Or(t)},"Failed to deliver Jira release (non-blocking)")}},ws=async e=>{let{version:r,confirmedCommand:t}=e;m.start("release-deliver"),await D({operation:"deliver release"});let{selectedReleaseBranch:o,releasePrTitle:n}=r?await yc(r):await kc(),s=C(o);if(!s)throw new f(void 0,{operation:`deliver release ${o}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let i=I(s);m.addOption("--version",i),a.info(`Delivering ${s.kind==="name"?"named release":"version"} ${o}`);let l=E(n),c=t?!0:await gc({message:`Are you sure you want to deliver version ${o} to production?`});t||m.setInteractive(),c||(a.info("Operation cancelled. Exiting..."),wc.exit(0)),m.addOption("--yes",!0),j.quiet=!0,await Rc(o),await bc({selectedReleaseBranch:o,releaseType:l}),l!=="hotfix"&&await Cc(s),await Ec(),await Tc(),await $c(o),j.quiet=!1,await Ic(s),a.info(`Successfully delivered ${o} to production!`),m.print();let p={releaseBranch:o,version:i,type:l,success:!0};return{content:g(JSON.stringify(p,null,2)),structuredContent:p}},wo=w({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:Lr.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:Lr.string().describe("The release branch that was delivered"),version:Lr.string().describe("The version that was delivered"),type:Lr.enum(["regular","hotfix"]).describe("Release type"),success:Lr.boolean().describe("Whether the delivery was successful")},handler:ws});import Pc from"@inquirer/confirm";import vs from"@inquirer/select";import{z as xe}from"zod";import{$ as vo}from"zx";var Sc=async e=>{let{confirmedCommand:r,branch:t,env:o}=e;if(r)return!0;m.setInteractive();let n=await Pc({message:`Deploy ${t} \u2192 ${o}?`,default:!1});return n&&m.addOption("--yes",!0),n},ys=async e=>{let{version:r,env:t,skipTerraform:o,confirmedCommand:n}=e;m.start("release-deploy-all");let s="";if(r)s=r==="dev"?"dev":de(r);else{m.setInteractive();let d=await T(),u=d.map(v=>v.branch),h=new Map(d.map(v=>[v.branch,E(v.title)])),b=await P();s=await vs({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...A({branches:u,descriptions:b,types:h})]})}let i=_r(s);m.addOption("--version",i);let{environments:l}=await x(),c="";if(t?c=t:(m.setInteractive(),c=await vs({message:"\u{1F9EA} Select environment",choices:l.map(d=>({name:d,value:d}))})),m.addOption("--env",c),!l.includes(c))throw new f(void 0,{operation:"launch deploy-all workflow",remediation:`pass one of: ${l.join(", ")}`,stderrExcerpt:`invalid environment: ${c}`});let p=o??!1;if(p&&m.addOption("--skip-terraform",!0),!await Sc({confirmedCommand:n,branch:s,env:c})){a.info("Deployment cancelled");let d={releaseBranch:s,version:i,environment:c,skipTerraformDeploy:p,success:!1};return{content:g(JSON.stringify(d,null,2)),structuredContent:d}}try{vo.quiet=!0,await vo`gh workflow run deploy-all.yml --ref ${s} -f environment=${c} ${p?["-f","skip_terraform_deploy=true"]:[]}`,vo.quiet=!1,a.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${s} and environment: ${c}`),m.print();let u={releaseBranch:s,version:i,environment:c,skipTerraformDeploy:p,success:!0};return{content:g(JSON.stringify(u,null,2)),structuredContent:u}}catch(d){throw a.error({error:d},"\u274C Error launching workflow"),new f(d,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},yo=w({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:xe.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign") \u2014 resolves to the release/vX.Y.Z or release/<name> branch. Pass "dev" to deploy from the dev branch instead. Required for MCP calls.'),env:xe.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),skipTerraform:xe.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:xe.string().describe("The release branch that was deployed"),version:xe.string().describe("The version that was deployed"),environment:xe.string().describe("The environment deployed to"),skipTerraformDeploy:xe.boolean().describe("Whether terraform deployment was skipped"),success:xe.boolean().describe("Whether the deployment was successful")},handler:ys});import Ac from"@inquirer/checkbox";import Nc from"@inquirer/confirm";import ks from"@inquirer/select";import _c from"node:fs/promises";import{resolve as Oc}from"node:path";import Fc from"yaml";import{z as B}from"zod";import{$ as ko}from"zx";var Dc=async e=>{let{confirmedCommand:r,branch:t,env:o}=e;if(r)return!0;m.setInteractive();let n=await Nc({message:`Deploy ${t} \u2192 ${o}?`,default:!1});return n&&m.addOption("--yes",!0),n},Rs=async e=>{let{version:r,env:t,services:o,skipTerraform:n,confirmedCommand:s}=e;m.start("release-deploy-selected");let i="";if(r)i=r==="dev"?"dev":de(r);else{m.setInteractive();let v=await T(),S=v.map(Ie=>Ie.branch),_=new Map(v.map(Ie=>[Ie.branch,E(Ie.title)])),H=await P();i=await ks({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...A({branches:S,descriptions:H,types:_})]})}let l=_r(i);m.addOption("--version",l);let{environments:c}=await x(),p="";if(t?p=t:(m.setInteractive(),p=await ks({message:"\u{1F9EA} Select environment",choices:c.map(v=>({name:v,value:v}))})),m.addOption("--env",p),!c.includes(p))throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass one of: ${c.join(", ")}`,stderrExcerpt:`invalid environment: ${p}`});let d=await jc();if(d.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:"check .github/workflows/deploy-selected-services.yml for boolean service inputs",stderrExcerpt:"no services found in workflow file"});let u=[];if(o&&o.length>0?u=o:(m.setInteractive(),u=await Ac({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:d.map(v=>({name:v,value:v}))})),m.addOption("--services",u),u.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${d.join(", ")}`,stderrExcerpt:"no services selected"});let h=u.filter(v=>!d.includes(v));if(h.length>0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${d.join(", ")}`,stderrExcerpt:`invalid services: ${h.join(", ")}`});let b=n??!1;if(b&&m.addOption("--skip-terraform",!0),!await Dc({confirmedCommand:s,branch:i,env:p})){a.info("Deployment cancelled");let v={releaseBranch:i,version:l,environment:p,services:u,skipTerraformDeploy:b,success:!1};return{content:g(JSON.stringify(v,null,2)),structuredContent:v}}try{ko.quiet=!0;let v=u.flatMap(H=>["-f",`${H}=true`]);await ko`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${p} ${v} ${b?["-f","skip_terraform_deploy=true"]:[]}`,ko.quiet=!1,a.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${p}, services: ${u.join(", ")}`),m.print();let _={releaseBranch:i,version:l,environment:p,services:u,skipTerraformDeploy:b,success:!0};return{content:g(JSON.stringify(_,null,2)),structuredContent:_}}catch(v){throw a.error({error:v},"\u274C Error launching workflow"),new f(v,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},jc=async()=>{let e=await k(),r=Oc(e,".github/workflows/deploy-selected-services.yml"),t=await _c.readFile(r,"utf-8"),n=Fc.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},Ro=w({name:"gh-release-deploy-selected",description:'Dispatch the deploy-selected-services.yml GitHub Actions workflow to deploy a chosen subset of services from a release branch to the given environment. Fire-and-forget \u2014 returns once GitHub accepts the workflow_dispatch, NOT when the deployment finishes; watch the workflow run for completion status. Service names are validated against the boolean inputs declared in the workflow. Use gh-release-deploy-all for every service. "version", "env", and "services" are all required when invoked via MCP (interactive pickers are unavailable without a TTY).',inputSchema:{version:B.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign") \u2014 resolves to the release/vX.Y.Z or release/<name> branch. Pass "dev" to deploy from the dev branch instead. Required for MCP calls.'),env:B.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),services:B.array(B.string()).describe('Service names to deploy. Each must match a boolean input declared in .github/workflows/deploy-selected-services.yml (e.g. "client-be", "client-fe"). Required for MCP calls.'),skipTerraform:B.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:B.string().describe("The release branch that was deployed"),version:B.string().describe("The version that was deployed"),environment:B.string().describe("The environment deployed to"),services:B.array(B.string()).describe("The services that were deployed"),skipTerraformDeploy:B.boolean().describe("Whether terraform deployment was skipped"),success:B.boolean().describe("Whether the deployment was successful")},handler:Rs});import{z as ar}from"zod";var bs=async()=>{let r=(await T()).flatMap(i=>{let l=C(i.branch);return l?[{version:I(l),jiraKey:M(l),type:E(i.title)}]:[]}),t=await P(),o=Math.max(...r.map(i=>i.version.length)),n=r.map(i=>{let l=nr(i.version,i.type,o),c=t.get(i.jiraKey);return c?`${l} ${c}`:l});a.info(`All release branches:
128
+ `)){let o=t.match(/^[* ]\s*workspace:\d+\s+(.+?)(?:\s+\[selected\])?\s*$/);if(!o)continue;let n=o[1]?.trim();n&&r.add(ee(n))}return r}catch(e){return a.debug({error:e},"cmux: skipped listing workspace titles"),new Set}};import{$ as Dr}from"zx";var jr=async e=>{let{cwd:r,title:t}=e,o=Gt(await x()),n=(await Dr`cmux workspace create --cwd ${r}`).stdout,s=fc(n),i=(await Dr`cmux list-pane-surfaces --workspace ${s}`).stdout,l=uc(i);await Dr`cmux new-split right --workspace ${s} --surface ${l}`,o==="three-pane"&&await Dr`cmux new-split down --workspace ${s} --surface ${l}`,t&&await Dr`cmux workspace rename --workspace ${s} --title ${t}`},uc=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]},fc=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 re=e=>{let{repoName:r,branch:t}=e,o=C(t),n=o?I(o):t;return`${r} ${n}`};var Mr=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=re({repoName:o,branch:l});return await Je(p),await fs`git worktree remove ${c}`,l})),i=[];for(let[l,c]of s.entries())if(c.status==="fulfilled")i.push(c.value);else{let p=r[l],d=new f(c.reason,{operation:`remove worktree for ${p}`,remediation:"check 'git worktree list' for the path; uncommitted changes block removal"});a.error({error:c.reason,msg:d.message})}return n&&i.length===r.length&&await fs`git worktree prune`,i};var ir=async(e,r,t)=>{try{return await t()}catch(o){throw a.error({err:Or(o)},`\u274C Failed to ${e}`),new f(o,{operation:e,remediation:r})}},hs=async e=>{let r=await j`gh pr list --head ${e} --state all --json number,state,title --limit 1`;return JSON.parse(r.stdout)[0]??null},vc=async e=>{let r=Hr(e),t=await j`gh pr list --head dev --base main --state merged --json number,state,title --limit 20`;return JSON.parse(t.stdout).find(s=>s.title===r)??null},gs=async()=>{let e=await j`gh pr list --head dev --base main --state open --json number,state,title --limit 5`;return JSON.parse(e.stdout)[0]??null},yc=async e=>{let r=de(e),t=await hs(r);if(!t)throw a.error(`\u274C No PR found for branch ${r}.`),new f(void 0,{operation:`deliver release ${r}`,remediation:`confirm a PR exists ('gh pr list --head ${r} --state all')`});return{selectedReleaseBranch:r,releasePrTitle:t.title}},kc=async()=>{let e=await T(),r=e.map(i=>i.branch),t=new Map(e.map(i=>[i.branch,E(i.title)]));m.setInteractive();let o=await P(),n=await hc({message:"\u{1F33F} Select release branch",choices:A({branches:r,descriptions:o,types:t})}),s=e.find(i=>i.branch===n);if(!s)throw a.error(`\u274C Release branch ${n} not found in open PRs.`),new f(void 0,{operation:`deliver release ${n}`,remediation:`confirm an open PR exists for ${n} ('gh pr list')`});return{selectedReleaseBranch:n,releasePrTitle:s.title}},Rc=async e=>{if(!(await F("release")).includes(e))return;let[t,o]=await Promise.all([k(),J()]),n=`${t}${G}`;if((await Mr({branches:[e],worktreeDir:n,repoName:o})).length===0)throw new f(void 0,{operation:`remove worktree for ${e} before merge`,remediation:`run manually: git worktree remove ${n}/${e} (use --force if uncommitted changes)`})},bc=async e=>{let{selectedReleaseBranch:r,releaseType:t}=e,o=t==="hotfix"?"main":"dev",n=await hs(r);if(!n)throw new f(void 0,{operation:`look up release PR for ${r}`,remediation:"verify the PR exists in GitHub"});if(n.state==="MERGED"){a.info(`\u2713 Release PR ${r} already merged \u2014 skipping`);return}if(n.state==="CLOSED")throw new f(void 0,{operation:`merge release PR ${r} into ${o}`,remediation:"the PR is closed without merge; reopen it or create a new release"});await ir(`merge release PR ${r} into ${o}`,`check 'gh pr view ${r}' for mergeability and required reviews`,async()=>{await j`gh pr merge ${r} --squash --admin --delete-branch`})},xc=async e=>{let r=I(e),t=Hr(e),o=await gs();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 ir(`retitle dev \u2192 main PR #${s} to "${t}"`,`update manually: gh pr edit ${s} --title "${t}"`,async()=>{await j`gh pr edit ${s} --title ${t}`})),s}await ir(`create RC PR (dev \u2192 main) for ${r}`,"run 'gh pr create --base main --head dev' manually to surface the underlying error (e.g. no commits between dev and main)",async()=>{await j`gh pr create --base main --head dev --title ${t} --body ""`});let n=await gs();if(!n)throw new f(void 0,{operation:`look up RC PR for ${r}`,remediation:"verify the RC PR was created ('gh pr list --head dev --base main')"});return n.number},Cc=async e=>{let r=I(e);if(await vc(e)){a.info(`\u2713 RC PR for ${r} already merged into main \u2014 skipping`);return}let o=await xc(e);await ir(`merge RC PR #${o} (dev \u2192 main) for ${r}`,`check 'gh pr view ${o}' for mergeability and required reviews`,async()=>{await j`gh pr merge ${o} --squash --admin`})},Ec=async()=>{j.quiet=!1,await ir("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await j`gh workflow run deploy-all.yml --ref main -f environment=prod`}),j.quiet=!0},Tc=async()=>{await ir("sync main back into dev","run manually: git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push",async()=>{await j`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},$c=async e=>{try{await _t(e)}catch(r){a.warn({err:Or(r)},`Failed to delete local branch ${e} (non-blocking)`)}try{await Ot(e)}catch(r){a.warn({err:Or(r)},`Failed to delete remote branch ${e} (non-blocking)`)}},Ic=async e=>{let r=await Ve();if(!r){a.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let t=M(e);await mo({versionName:t},r)}catch(t){a.error({err:Or(t)},"Failed to deliver Jira release (non-blocking)")}},ws=async e=>{let{version:r,confirmedCommand:t}=e;m.start("release-deliver"),await D({operation:"deliver release"});let{selectedReleaseBranch:o,releasePrTitle:n}=r?await yc(r):await kc(),s=C(o);if(!s)throw new f(void 0,{operation:`deliver release ${o}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let i=I(s);m.addOption("--version",i),a.info(`Delivering ${s.kind==="name"?"named release":"version"} ${o}`);let l=E(n),c=t?!0:await gc({message:`Are you sure you want to deliver version ${o} to production?`});t||m.setInteractive(),c||(a.info("Operation cancelled. Exiting..."),wc.exit(0)),m.addOption("--yes",!0),j.quiet=!0,await Rc(o),await bc({selectedReleaseBranch:o,releaseType:l}),l!=="hotfix"&&await Cc(s),await Ec(),await Tc(),await $c(o),j.quiet=!1,await Ic(s),a.info(`Successfully delivered ${o} to production!`),m.print();let p={releaseBranch:o,version:i,type:l,success:!0};return{content:g(JSON.stringify(p,null,2)),structuredContent:p}},ho=w({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:Lr.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:Lr.string().describe("The release branch that was delivered"),version:Lr.string().describe("The version that was delivered"),type:Lr.enum(["regular","hotfix"]).describe("Release type"),success:Lr.boolean().describe("Whether the delivery was successful")},handler:ws});import Pc from"@inquirer/confirm";import vs from"@inquirer/select";import{z as xe}from"zod";import{$ as wo}from"zx";var Sc=async e=>{let{confirmedCommand:r,branch:t,env:o}=e;if(r)return!0;m.setInteractive();let n=await Pc({message:`Deploy ${t} \u2192 ${o}?`,default:!1});return n&&m.addOption("--yes",!0),n},ys=async e=>{let{version:r,env:t,skipTerraform:o,confirmedCommand:n}=e;m.start("release-deploy-all");let s="";if(r)s=r==="dev"?"dev":de(r);else{m.setInteractive();let d=await T(),u=d.map(v=>v.branch),h=new Map(d.map(v=>[v.branch,E(v.title)])),b=await P();s=await vs({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...A({branches:u,descriptions:b,types:h})]})}let i=_r(s);m.addOption("--version",i);let{environments:l}=await x(),c="";if(t?c=t:(m.setInteractive(),c=await vs({message:"\u{1F9EA} Select environment",choices:l.map(d=>({name:d,value:d}))})),m.addOption("--env",c),!l.includes(c))throw new f(void 0,{operation:"launch deploy-all workflow",remediation:`pass one of: ${l.join(", ")}`,stderrExcerpt:`invalid environment: ${c}`});let p=o??!1;if(p&&m.addOption("--skip-terraform",!0),!await Sc({confirmedCommand:n,branch:s,env:c})){a.info("Deployment cancelled");let d={releaseBranch:s,version:i,environment:c,skipTerraformDeploy:p,success:!1};return{content:g(JSON.stringify(d,null,2)),structuredContent:d}}try{wo.quiet=!0,await wo`gh workflow run deploy-all.yml --ref ${s} -f environment=${c} ${p?["-f","skip_terraform_deploy=true"]:[]}`,wo.quiet=!1,a.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${s} and environment: ${c}`),m.print();let u={releaseBranch:s,version:i,environment:c,skipTerraformDeploy:p,success:!0};return{content:g(JSON.stringify(u,null,2)),structuredContent:u}}catch(d){throw a.error({error:d},"\u274C Error launching workflow"),new f(d,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},vo=w({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:xe.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign") \u2014 resolves to the release/vX.Y.Z or release/<name> branch. Pass "dev" to deploy from the dev branch instead. Required for MCP calls.'),env:xe.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),skipTerraform:xe.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:xe.string().describe("The release branch that was deployed"),version:xe.string().describe("The version that was deployed"),environment:xe.string().describe("The environment deployed to"),skipTerraformDeploy:xe.boolean().describe("Whether terraform deployment was skipped"),success:xe.boolean().describe("Whether the deployment was successful")},handler:ys});import Ac from"@inquirer/checkbox";import Nc from"@inquirer/confirm";import ks from"@inquirer/select";import _c from"node:fs/promises";import{resolve as Oc}from"node:path";import Fc from"yaml";import{z as B}from"zod";import{$ as yo}from"zx";var Dc=async e=>{let{confirmedCommand:r,branch:t,env:o}=e;if(r)return!0;m.setInteractive();let n=await Nc({message:`Deploy ${t} \u2192 ${o}?`,default:!1});return n&&m.addOption("--yes",!0),n},Rs=async e=>{let{version:r,env:t,services:o,skipTerraform:n,confirmedCommand:s}=e;m.start("release-deploy-selected");let i="";if(r)i=r==="dev"?"dev":de(r);else{m.setInteractive();let v=await T(),S=v.map(Ie=>Ie.branch),_=new Map(v.map(Ie=>[Ie.branch,E(Ie.title)])),H=await P();i=await ks({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...A({branches:S,descriptions:H,types:_})]})}let l=_r(i);m.addOption("--version",l);let{environments:c}=await x(),p="";if(t?p=t:(m.setInteractive(),p=await ks({message:"\u{1F9EA} Select environment",choices:c.map(v=>({name:v,value:v}))})),m.addOption("--env",p),!c.includes(p))throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass one of: ${c.join(", ")}`,stderrExcerpt:`invalid environment: ${p}`});let d=await jc();if(d.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:"check .github/workflows/deploy-selected-services.yml for boolean service inputs",stderrExcerpt:"no services found in workflow file"});let u=[];if(o&&o.length>0?u=o:(m.setInteractive(),u=await Ac({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:d.map(v=>({name:v,value:v}))})),m.addOption("--services",u),u.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${d.join(", ")}`,stderrExcerpt:"no services selected"});let h=u.filter(v=>!d.includes(v));if(h.length>0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${d.join(", ")}`,stderrExcerpt:`invalid services: ${h.join(", ")}`});let b=n??!1;if(b&&m.addOption("--skip-terraform",!0),!await Dc({confirmedCommand:s,branch:i,env:p})){a.info("Deployment cancelled");let v={releaseBranch:i,version:l,environment:p,services:u,skipTerraformDeploy:b,success:!1};return{content:g(JSON.stringify(v,null,2)),structuredContent:v}}try{yo.quiet=!0;let v=u.flatMap(H=>["-f",`${H}=true`]);await yo`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${p} ${v} ${b?["-f","skip_terraform_deploy=true"]:[]}`,yo.quiet=!1,a.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${p}, services: ${u.join(", ")}`),m.print();let _={releaseBranch:i,version:l,environment:p,services:u,skipTerraformDeploy:b,success:!0};return{content:g(JSON.stringify(_,null,2)),structuredContent:_}}catch(v){throw a.error({error:v},"\u274C Error launching workflow"),new f(v,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},jc=async()=>{let e=await k(),r=Oc(e,".github/workflows/deploy-selected-services.yml"),t=await _c.readFile(r,"utf-8"),n=Fc.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},ko=w({name:"gh-release-deploy-selected",description:'Dispatch the deploy-selected-services.yml GitHub Actions workflow to deploy a chosen subset of services from a release branch to the given environment. Fire-and-forget \u2014 returns once GitHub accepts the workflow_dispatch, NOT when the deployment finishes; watch the workflow run for completion status. Service names are validated against the boolean inputs declared in the workflow. Use gh-release-deploy-all for every service. "version", "env", and "services" are all required when invoked via MCP (interactive pickers are unavailable without a TTY).',inputSchema:{version:B.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign") \u2014 resolves to the release/vX.Y.Z or release/<name> branch. Pass "dev" to deploy from the dev branch instead. Required for MCP calls.'),env:B.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),services:B.array(B.string()).describe('Service names to deploy. Each must match a boolean input declared in .github/workflows/deploy-selected-services.yml (e.g. "client-be", "client-fe"). Required for MCP calls.'),skipTerraform:B.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:B.string().describe("The release branch that was deployed"),version:B.string().describe("The version that was deployed"),environment:B.string().describe("The environment deployed to"),services:B.array(B.string()).describe("The services that were deployed"),skipTerraformDeploy:B.boolean().describe("Whether terraform deployment was skipped"),success:B.boolean().describe("Whether the deployment was successful")},handler:Rs});import{z as ar}from"zod";var bs=async()=>{let r=(await T()).flatMap(i=>{let l=C(i.branch);return l?[{version:I(l),jiraKey:M(l),type:E(i.title)}]:[]}),t=await P(),o=Math.max(...r.map(i=>i.version.length)),n=r.map(i=>{let l=nr(i.version,i.type,o),c=t.get(i.jiraKey);return c?`${l} ${c}`:l});a.info(`All release branches:
129
129
  `),a.info(`
130
130
  ${n.join(`
131
131
  `)}
132
- `);let s={releases:r.map(i=>({version:i.version,type:i.type,description:t.get(i.jiraKey)||null})),count:r.length};return{content:g(JSON.stringify(s,null,2)),structuredContent:s}},bo=w({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:ar.array(ar.object({version:ar.string().describe("Release version"),type:ar.enum(["regular","hotfix"]).describe("Release type"),description:ar.string().nullable().describe("Jira version description")})).describe("List of all release branches"),count:ar.number().describe("Number of release branches")},handler:bs});var Ce=e=>e.slice(1).split(".").map(Number),xo=e=>[...e].sort((r,t)=>{let[o,n,s]=Ce(r),[i,l,c]=Ce(t);return o!==i?(o??0)-(i??0):n!==l?(n??0)-(l??0):(s??0)-(c??0)});var Cs="next",Mc=/^v?(\d+)\.(\d+)\.(\d+)$/,Lc=e=>e.replace(/^.*release\//,""),Eo=e=>{let r=Lc(e.trim()),t=Mc.exec(r);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null},xs=e=>`${e[0]}.${e[1]}.${e[2]}`,To=e=>{let r=[...e.remoteBranches??[],...e.jiraVersions??[]],t=[],o=new Set;for(let n of r){let s=Eo(n);if(!s)continue;let i=xs(s);o.has(i)||(o.add(i),t.push(s))}return xo(t.map(n=>xs(n))).map(n=>Ce(`v${n}`))},Ke=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},ut=(e,r)=>{if(e.length===0)throw new Ke;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`},$o=e=>e.trim().toLowerCase()===Cs,Wc=e=>e==="regular"||e==="hotfix",Es=e=>"name"in e,Vc=e=>{let r=e.trim();if(r==="")throw new Error("Release spec is empty");let t=r.indexOf(":"),o=r,n="regular",s="";if(t!==-1){o=r.slice(0,t).trim();let l=r.slice(t+1),c=l.indexOf(":"),p=c===-1?l.trim():l.slice(0,c).trim();s=c===-1?"":l.slice(c+1).trim();let d=p.toLowerCase();if(!Wc(d))throw new Error(`Invalid release type "${p}". Expected "regular" or "hotfix".`);n=d}if($o(o)||Eo(o)!==null){let l={version:o,type:n};return s!==""&&(l.description=s),l}let i={name:o,type:n};return s!==""&&(i.description=s),i},Io=e=>{let r=e.id.raw;return e.description!==void 0&&e.description!==""?`${r}:${e.type}:${e.description}`:e.type==="hotfix"?`${r}:hotfix`:r},Co=(e,r)=>r!==void 0&&r!==""?{...e,description:r}:e,Bc=e=>{let r=e.name.trim();return Se(r),Co({id:{kind:"name",name:r,raw:r},type:e.type},e.description)},Po=(e,r)=>{let t=[...r];return e.map(o=>{if(Es(o))return Bc(o);let n=o.version.trim();if(n==="")throw new Error("Release entry has an empty version");if($o(n)){let l=ut(t,o.type);return t.push(Ce(`v${l}`)),Co({id:Z(l),type:o.type},o.description)}let s=Eo(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),Co({id:Z(i),type:o.type},o.description)})},So=e=>e.some(r=>!Es(r)&&$o(r.version));import{$ as ft}from"zx";var Jc=e=>e.split(`
133
- `).map(r=>{let t=r.indexOf(" ");return t===-1?null:C(r.slice(t+1))}).filter(r=>r!==null&&r.kind==="version").map(r=>r.raw),Kc=async()=>{let e=ft.quiet;try{ft.quiet=!0;let r=await ft`git ls-remote --heads origin 'release/v*'`;return Jc(r.stdout)}finally{ft.quiet=e}},Gc=async()=>{let e=await Ve();return e?(await rr(e)).map(t=>t.name):[]},Ao=async()=>{let[e,r]=await Promise.allSettled([Kc(),Gc()]);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"),To({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:r.status==="fulfilled"?r.value:[]})};import Is from"@inquirer/confirm";import Ts from"@inquirer/select";import gt from"node:process";import{z as $}from"zod";import{question as _o}from"zx";var zc='"1.2.5" or "next"',Uc=(e,r)=>{try{return ut(e,r)}catch(t){if(t instanceof Ke)return null;throw t}},No=(e,r)=>{try{return Po(e,r)}catch(t){throw t instanceof Ke?new f(t,{operation:"resolve release version",remediation:'pass an explicit version (e.g. "1.2.5") instead of "next" when there are no prior versions'}):t instanceof ae?new f(t,{operation:"validate release name",remediation:'use a kebab-case name like "checkout-redesign" (lowercase, digits, single hyphens, not a reserved word)'}):t}},qc=async(e,r)=>{let t=Uc(e,r),o=t?` [${t}]`:"",n=(await _o(` Version (e.g. ${zc})${o}: `)).trim(),s=n===""?t??"":n;return s===""&&(a.error("No version provided. Exiting..."),gt.exit(1)),s},Hc=async()=>{let e=(await _o(' Name (kebab-case, e.g. "checkout-redesign"): ')).trim();e===""&&(a.error("No name provided. Exiting..."),gt.exit(1));try{Se(e)}catch(r){let t=r instanceof Error?r.message:String(r);a.error(`${t} Exiting...`),gt.exit(1)}return e},Zc=async e=>{m.setInteractive();let r=null,t=[],o=async()=>(r===null&&(r=await e(),t.push(...r)),t),n=[],s=!0;for(;s;){let i=n.length+1,l=await Ts({message:`Release #${i} \u2014 version or name?`,choices:[{name:"version (semver / next)",value:"version"},{name:"name (free-form)",value:"name"}],default:"version"}),c=await Ts({message:`Release #${i} \u2014 select type:`,choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"}),p;if(l==="name"){let u=await Hc();p=No([{name:u,type:c}],[])[0]}else{let u=await qc(await o(),c);p=No([{version:u,type:c}],t)[0],p.id.kind==="version"&&t.push(Ce(`v${p.id.raw}`))}let d=(await _o(" Description (optional, press Enter to skip): ")).trim();n.push({...p,...d!==""?{description:d}:{}}),s=await Is({message:"Add another release?",default:!1})}return n},Xc=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 ")},$s=e=>{for(let r of e)m.addOption("--release",Io(r))},Yc=async(e,r)=>{if(e&&e.length>0){let o=So(e)?await r():[],n=No(e,o);return $s(n),n}let t=await Zc(r);return $s(t),t},Qc=e=>{if(new Set(e.map(t=>t.type)).size>1)throw new f(void 0,{operation:"create release",remediation:"create regular and hotfix releases in separate invocations",stderrExcerpt:"mixed regular and hotfix releases in one batch are not supported"})},el=async(e,r)=>{let t=e.map(Xc).join(`
132
+ `);let s={releases:r.map(i=>({version:i.version,type:i.type,description:t.get(i.jiraKey)||null})),count:r.length};return{content:g(JSON.stringify(s,null,2)),structuredContent:s}},Ro=w({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:ar.array(ar.object({version:ar.string().describe("Release version"),type:ar.enum(["regular","hotfix"]).describe("Release type"),description:ar.string().nullable().describe("Jira version description")})).describe("List of all release branches"),count:ar.number().describe("Number of release branches")},handler:bs});var Ce=e=>e.slice(1).split(".").map(Number),bo=e=>[...e].sort((r,t)=>{let[o,n,s]=Ce(r),[i,l,c]=Ce(t);return o!==i?(o??0)-(i??0):n!==l?(n??0)-(l??0):(s??0)-(c??0)});var Cs="next",Mc=/^v?(\d+)\.(\d+)\.(\d+)$/,Lc=e=>e.replace(/^.*release\//,""),Co=e=>{let r=Lc(e.trim()),t=Mc.exec(r);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null},xs=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=Co(n);if(!s)continue;let i=xs(s);o.has(i)||(o.add(i),t.push(s))}return bo(t.map(n=>xs(n))).map(n=>Ce(`v${n}`))},Ke=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},mt=(e,r)=>{if(e.length===0)throw new Ke;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`},To=e=>e.trim().toLowerCase()===Cs,Wc=e=>e==="regular"||e==="hotfix",Es=e=>"name"in e,Vc=e=>{let r=e.trim();if(r==="")throw new Error("Release spec is empty");let t=r.indexOf(":"),o=r,n="regular",s="";if(t!==-1){o=r.slice(0,t).trim();let l=r.slice(t+1),c=l.indexOf(":"),p=c===-1?l.trim():l.slice(0,c).trim();s=c===-1?"":l.slice(c+1).trim();let d=p.toLowerCase();if(!Wc(d))throw new Error(`Invalid release type "${p}". Expected "regular" or "hotfix".`);n=d}if(To(o)||Co(o)!==null){let l={version:o,type:n};return s!==""&&(l.description=s),l}let i={name:o,type:n};return s!==""&&(i.description=s),i},$o=e=>{let r=e.id.raw;return e.description!==void 0&&e.description!==""?`${r}:${e.type}:${e.description}`:e.type==="hotfix"?`${r}:hotfix`:r},xo=(e,r)=>r!==void 0&&r!==""?{...e,description:r}:e,Bc=e=>{let r=e.name.trim();return Se(r),xo({id:{kind:"name",name:r,raw:r},type:e.type},e.description)},Io=(e,r)=>{let t=[...r];return e.map(o=>{if(Es(o))return Bc(o);let n=o.version.trim();if(n==="")throw new Error("Release entry has an empty version");if(To(n)){let l=mt(t,o.type);return t.push(Ce(`v${l}`)),xo({id:Z(l),type:o.type},o.description)}let s=Co(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),xo({id:Z(i),type:o.type},o.description)})},Po=e=>e.some(r=>!Es(r)&&To(r.version));import{$ as ut}from"zx";var Jc=e=>e.split(`
133
+ `).map(r=>{let t=r.indexOf(" ");return t===-1?null:C(r.slice(t+1))}).filter(r=>r!==null&&r.kind==="version").map(r=>r.raw),Kc=async()=>{let e=ut.quiet;try{ut.quiet=!0;let r=await ut`git ls-remote --heads origin 'release/v*'`;return Jc(r.stdout)}finally{ut.quiet=e}},Gc=async()=>{let e=await Ve();return e?(await rr(e)).map(t=>t.name):[]},So=async()=>{let[e,r]=await Promise.allSettled([Kc(),Gc()]);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:[]})};import Is from"@inquirer/confirm";import Ts from"@inquirer/select";import ft from"node:process";import{z as $}from"zod";import{question as No}from"zx";var zc='"1.2.5" or "next"',Uc=(e,r)=>{try{return mt(e,r)}catch(t){if(t instanceof Ke)return null;throw t}},Ao=(e,r)=>{try{return Io(e,r)}catch(t){throw t instanceof Ke?new f(t,{operation:"resolve release version",remediation:'pass an explicit version (e.g. "1.2.5") instead of "next" when there are no prior versions'}):t instanceof ae?new f(t,{operation:"validate release name",remediation:'use a kebab-case name like "checkout-redesign" (lowercase, digits, single hyphens, not a reserved word)'}):t}},qc=async(e,r)=>{let t=Uc(e,r),o=t?` [${t}]`:"",n=(await No(` Version (e.g. ${zc})${o}: `)).trim(),s=n===""?t??"":n;return s===""&&(a.error("No version provided. Exiting..."),ft.exit(1)),s},Hc=async()=>{let e=(await No(' Name (kebab-case, e.g. "checkout-redesign"): ')).trim();e===""&&(a.error("No name provided. Exiting..."),ft.exit(1));try{Se(e)}catch(r){let t=r instanceof Error?r.message:String(r);a.error(`${t} Exiting...`),ft.exit(1)}return e},Zc=async e=>{m.setInteractive();let r=null,t=[],o=async()=>(r===null&&(r=await e(),t.push(...r)),t),n=[],s=!0;for(;s;){let i=n.length+1,l=await Ts({message:`Release #${i} \u2014 version or name?`,choices:[{name:"version (semver / next)",value:"version"},{name:"name (free-form)",value:"name"}],default:"version"}),c=await Ts({message:`Release #${i} \u2014 select type:`,choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"}),p;if(l==="name"){let u=await Hc();p=Ao([{name:u,type:c}],[])[0]}else{let u=await qc(await o(),c);p=Ao([{version:u,type:c}],t)[0],p.id.kind==="version"&&t.push(Ce(`v${p.id.raw}`))}let d=(await No(" Description (optional, press Enter to skip): ")).trim();n.push({...p,...d!==""?{description:d}:{}}),s=await Is({message:"Add another release?",default:!1})}return n},Xc=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 ")},$s=e=>{for(let r of e)m.addOption("--release",$o(r))},Yc=async(e,r)=>{if(e&&e.length>0){let o=Po(e)?await r():[],n=Ao(e,o);return $s(n),n}let t=await Zc(r);return $s(t),t},Qc=e=>{if(new Set(e.map(t=>t.type)).size>1)throw new f(void 0,{operation:"create release",remediation:"create regular and hotfix releases in separate invocations",stderrExcerpt:"mixed regular and hotfix releases in one batch are not supported"})},el=async(e,r)=>{let t=e.map(Xc).join(`
134
134
  - `),o=r?!0:await Is({message:`Create the following ${e.length} release(s)?
135
135
  - ${t}
136
- `});r||m.setInteractive(),o||(a.info("Operation cancelled. Exiting..."),gt.exit(0)),m.addOption("--yes",!0)},rl=async e=>{let{entry:r,jiraConfig:t}=e,o=I(r.id),n=r.id.kind==="version"?`v${r.id.raw}`:r.id.name;try{await fo(r.type);let s=await go({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}
136
+ `});r||m.setInteractive(),o||(a.info("Operation cancelled. Exiting..."),ft.exit(0)),m.addOption("--yes",!0)},rl=async e=>{let{entry:r,jiraConfig:t}=e,o=I(r.id),n=r.id.kind==="version"?`v${r.id.raw}`:r.id.name;try{await uo(r.type);let s=await fo({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}
137
137
  `),{result:s}}catch(s){let i=new f(s,{operation:`create release ${n} (${r.type})`,remediation:"verify the version or name is unique and the base branch is clean"});return a.error(`\u274C ${i.message}
138
- `),{failure:{version:o,error:i.message}}}},tl=(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.`)},Ps=async e=>{let{releases:r,confirmedCommand:t}=e;m.start("release-create");let o=await tr(),n=null,i=await Yc(r,async()=>(n===null&&(n=await Ao()),n));if(i.length===0)throw new f(void 0,{operation:"create release",remediation:'pass at least one entry in "releases" (e.g. [{ version: "1.2.5", type: "regular" }])',stderrExcerpt:"no releases provided"});Qc(i),await D({operation:"create release",requiredBranch:or(i[0].type)}),await el(i,!!t);let l=[],c=[];for(let d of i){let{result:u,failure:h}=await rl({entry:d,jiraConfig:o});u&&l.push(u),h&&c.push(h)}tl(i.length,l.length,c.length),m.print();let p={createdBranches:l.map(d=>d.branchName),successCount:l.length,failureCount:c.length,releases:l,failedReleases:c};return{content:g(JSON.stringify(p,null,2)),structuredContent:p}},Oo=w({name:"release-create",description:'Create one or more releases in a single call. Each entry in "releases" carries EITHER a "version" (semver or the literal token "next") OR a "name" (free-form kebab-case identifier) \u2014 exactly one is required and they are mutually exclusive. Each entry also has its own type (regular|hotfix, default regular) and optional description; all entries in one call must share the same type \u2014 mixed regular+hotfix batches are rejected (create them in separate invocations). For each release this tool switches to the appropriate base branch (dev for regular, main for hotfix), cuts the release branch (release/v<semver> for versions, release/<name> for names), opens a GitHub release PR, and creates the matching Jira fix version (v<semver> for versions, <name> for names). The literal token "next" auto-increments from the union of remote release branches and Jira fix versions (regular bumps minor + resets patch; hotfix bumps patch on the highest minor); multiple "next" tokens advance sequentially. Named releases never auto-bump and "next" is version-only. Must be run from the main repository checkout (not a linked worktree) on the matching base branch with a clean working tree. Confirmation is auto-skipped for MCP calls, so the caller is responsible for gating. Continues on per-release failure and reports successes/failures.',inputSchema:{releases:$.array($.object({version:$.string().optional().describe('Version to create (e.g., "1.2.5") or the literal token "next" for auto-increment. Mutually exclusive with "name".'),name:$.string().optional().describe('Free-form kebab-case release name (e.g., "checkout-redesign"). Mutually exclusive with "version". Named releases never auto-bump.'),type:$.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" (branches off dev) or "hotfix" (branches off main).'),description:$.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:$.array($.string()).describe("List of created release branch names"),successCount:$.number().describe("Number of releases created successfully"),failureCount:$.number().describe("Number of releases that failed"),releases:$.array($.object({version:$.string().describe("Version number"),type:$.enum(["regular","hotfix"]).describe("Release type"),branchName:$.string().describe("Release branch name"),prUrl:$.string().describe("GitHub PR URL"),jiraVersionUrl:$.string().describe("Jira version URL")})).describe("Detailed information for each created release with URLs"),failedReleases:$.array($.object({version:$.string().describe("Version number that failed"),error:$.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:Ps});import ol from"@inquirer/confirm";import nl from"@inquirer/select";import sl from"node:process";import{z as Ee}from"zod";import{question as il}from"zx";var Ss=(e,r)=>`${e.baseUrl}/projects/${r.projectId}/versions/${r.id}/tab/release-report-all-issues`,al=(e,r)=>r.trim()!==""?`${e}
138
+ `),{failure:{version:o,error:i.message}}}},tl=(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.`)},Ps=async e=>{let{releases:r,confirmedCommand:t}=e;m.start("release-create");let o=await tr(),n=null,i=await Yc(r,async()=>(n===null&&(n=await So()),n));if(i.length===0)throw new f(void 0,{operation:"create release",remediation:'pass at least one entry in "releases" (e.g. [{ version: "1.2.5", type: "regular" }])',stderrExcerpt:"no releases provided"});Qc(i),await D({operation:"create release",requiredBranch:or(i[0].type)}),await el(i,!!t);let l=[],c=[];for(let d of i){let{result:u,failure:h}=await rl({entry:d,jiraConfig:o});u&&l.push(u),h&&c.push(h)}tl(i.length,l.length,c.length),m.print();let p={createdBranches:l.map(d=>d.branchName),successCount:l.length,failureCount:c.length,releases:l,failedReleases:c};return{content:g(JSON.stringify(p,null,2)),structuredContent:p}},_o=w({name:"release-create",description:'Create one or more releases in a single call. Each entry in "releases" carries EITHER a "version" (semver or the literal token "next") OR a "name" (free-form kebab-case identifier) \u2014 exactly one is required and they are mutually exclusive. Each entry also has its own type (regular|hotfix, default regular) and optional description; all entries in one call must share the same type \u2014 mixed regular+hotfix batches are rejected (create them in separate invocations). For each release this tool switches to the appropriate base branch (dev for regular, main for hotfix), cuts the release branch (release/v<semver> for versions, release/<name> for names), opens a GitHub release PR, and creates the matching Jira fix version (v<semver> for versions, <name> for names). The literal token "next" auto-increments from the union of remote release branches and Jira fix versions (regular bumps minor + resets patch; hotfix bumps patch on the highest minor); multiple "next" tokens advance sequentially. Named releases never auto-bump and "next" is version-only. Must be run from the main repository checkout (not a linked worktree) on the matching base branch with a clean working tree. Confirmation is auto-skipped for MCP calls, so the caller is responsible for gating. Continues on per-release failure and reports successes/failures.',inputSchema:{releases:$.array($.object({version:$.string().optional().describe('Version to create (e.g., "1.2.5") or the literal token "next" for auto-increment. Mutually exclusive with "name".'),name:$.string().optional().describe('Free-form kebab-case release name (e.g., "checkout-redesign"). Mutually exclusive with "version". Named releases never auto-bump.'),type:$.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" (branches off dev) or "hotfix" (branches off main).'),description:$.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:$.array($.string()).describe("List of created release branch names"),successCount:$.number().describe("Number of releases created successfully"),failureCount:$.number().describe("Number of releases that failed"),releases:$.array($.object({version:$.string().describe("Version number"),type:$.enum(["regular","hotfix"]).describe("Release type"),branchName:$.string().describe("Release branch name"),prUrl:$.string().describe("GitHub PR URL"),jiraVersionUrl:$.string().describe("Jira version URL")})).describe("Detailed information for each created release with URLs"),failedReleases:$.array($.object({version:$.string().describe("Version number that failed"),error:$.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:Ps});import ol from"@inquirer/confirm";import nl from"@inquirer/select";import sl from"node:process";import{z as Ee}from"zod";import{question as il}from"zx";var Ss=(e,r)=>`${e.baseUrl}/projects/${r.projectId}/versions/${r.id}/tab/release-report-all-issues`,al=(e,r)=>r.trim()!==""?`${e}
139
139
 
140
140
  ${r}`:`${e}
141
141
  `,cl=async()=>{let e=await T(),r=e.map(s=>s.branch),t=new Map(e.map(s=>[s.branch,E(s.title)])),o=await P(),n=await nl({message:"\u{1F33F} Select release branch",choices:A({branches:r,descriptions:o,types:t})});return{branch:n,type:t.get(n)||"regular"}},ll=async e=>{let t=(await T()).find(o=>o.branch===e);if(!t)throw new f(void 0,{operation:`edit description for ${e}`,remediation:`confirm an open PR exists for ${e} ('gh pr list')`});return E(t.title)},pl=async e=>{let r=e===""?"(no current description)":`current: "${e}"`,o=(await il(` New description ${r}
@@ -143,9 +143,9 @@ ${r}`:`${e}
143
143
  from: "${d}"
144
144
  to: "${u}"
145
145
  `});o||m.setInteractive(),h||(a.info("Operation cancelled. Exiting..."),sl.exit(0)),m.addOption("--yes",!0),await ct({versionId:p.id,description:u},n);let b=Ss(n,p),v=al(b,u);await dt({branch:s,body:v}),a.info(`\u2705 Updated description for ${c}`),a.info(`\u{1F517} Jira Version: ${b}`),a.info(`\u{1F517} PR branch: ${s}
146
- `),m.print();let S={version:l,branch:s,jiraVersionUrl:b,previousDescription:d,newDescription:u,changed:!0};return{content:g(JSON.stringify(S,null,2)),structuredContent:S}},Fo=w({name:"release-desc-edit",description:"Edit a release's description in Jira and in the matching GitHub release PR body. Accepts a release version or a release name: targets the Jira fix version named `v<version>` (versioned) or `<name>` (named) and the open PR on branch `release/v<version>` or `release/<name>`. The PR body is rewritten canonically to `<jiraVersionUrl>\\n\\n<description>` \u2014 any prior manual edits to the body are overwritten. Both `version` and `description` are required for MCP calls (the picker/prompt are unreachable without a TTY). Empty `description` clears the description on both sides. Confirmation is auto-skipped for MCP, so the caller is responsible for gating.",inputSchema:{version:Ee.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:Ee.string().describe("New description. Empty string clears the description.")},outputSchema:{version:Ee.string().describe("Release version"),branch:Ee.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:Ee.string().describe("Jira fix version URL"),previousDescription:Ee.string().describe("The description before the update"),newDescription:Ee.string().describe("The description after the update"),changed:Ee.boolean().describe("Whether the description actually changed")},handler:As});import{existsSync as Fs}from"node:fs";import Ds from"node:path";import Rl from"node:process";import{z as me}from"zod";import{createHash as dl}from"node:crypto";import{readFileSync as ml}from"node:fs";var ht=e=>dl("sha256").update(ml(e)).digest("hex");import{readFileSync as vl,writeFileSync as yl}from"node:fs";import yt from"node:path";import{z as te}from"zod";import{readdirSync as hl}from"node:fs";import Do from"node:path";var U="vendor",ul=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack"]),fl=new Set([".sync-manifest.json",".eslintcache","log.txt"]),gl=[".tsbuildinfo"],Ns=e=>ul.has(e),_s=e=>fl.has(e)?!0:gl.some(r=>e.endsWith(r));var wl=e=>e.split(Do.sep).join("/"),wt=e=>{let r=[],t=o=>{for(let n of hl(o,{withFileTypes:!0})){let s=Do.join(o,n.name);if(n.isDirectory()){if(Ns(n.name))continue;t(s);continue}_s(n.name)||r.push(wl(Do.relative(e,s)))}};return t(e),r.sort()};var oe=".sync-manifest.json",vt=1,kl=te.object({schemaVersion:te.number().optional(),source:te.string(),commit:te.string(),syncedAt:te.string(),fileCount:te.number(),files:te.record(te.string(),te.string())}),jo=e=>(e.schemaVersion??vt)>vt,Os=e=>{let r={};for(let t of wt(e))try{r[t]=ht(yt.join(e,t))}catch(o){let n=o instanceof Error?o.message:String(o);throw new Error(`Cannot hash vendor file "${t}" (broken symlink or unreadable file): ${n}`)}return r},Mo=e=>{let r=yt.join(e,oe),t;try{t=vl(r,"utf8")}catch{throw new Error(`Missing ${oe} at ${r}`)}let o=kl.safeParse(JSON.parse(t));if(!o.success)throw new Error(`Invalid ${oe} at ${r}: ${te.prettifyError(o.error)}`);return o.data},Lo=(e,r)=>{let t=Os(e),o={schemaVersion:vt,source:r.source,commit:r.commit,syncedAt:new Date().toISOString(),fileCount:Object.keys(t).length,files:t};return yl(yt.join(e,oe),`${JSON.stringify(o,null,2)}
147
- `),o},Wo=(e,r)=>{let t=r.files,o=wt(e),n=[],s=[];for(let c of o){if(!(c in t)){s.push(c);continue}ht(yt.join(e,c))!==t[c]&&n.push(c)}let i=new Set(o),l=Object.keys(t).filter(c=>!i.has(c));return{modified:n,added:s,removed:l}};var Vo=30,Bo=(e,r)=>{if(r.length!==0){a.info(`
148
- ${e} (${r.length}):`);for(let t of r.slice(0,Vo))a.info(` ${t}`);r.length>Vo&&a.info(` \u2026and ${r.length-Vo} more`)}},js=async(e={})=>{let r=e.cwd??await k(),t=Ds.join(r,U),o={modified:[],added:[],removed:[],fileCount:0};if(!Fs(t)){a.info(`\u2139\uFE0F No ${U}/ folder found \u2014 nothing to check.`);let d={status:"skipped",ok:!0,...o};return{content:g(JSON.stringify(d,null,2)),structuredContent:d}}if(!Fs(Ds.join(t,oe))){a.error(`\u274C Missing ${U}/${oe}. Re-run the vendor sync to generate it.`);let d={status:"missing-manifest",ok:!1,...o};return{content:g(JSON.stringify(d,null,2)),structuredContent:d}}let n=Mo(t);if(jo(n)){a.error(`\u274C ${U}/${oe} has a newer schemaVersion (${String(n.schemaVersion)}) than this CLI supports. Upgrade infra-kit.`);let d={status:"unknown-schema",ok:!1,...o};return{content:g(JSON.stringify(d,null,2)),structuredContent:d}}let{modified:s,added:i,removed:l}=Wo(t,n),c=s.length>0||i.length>0||l.length>0;c?(a.error(`\u274C ${U}/ has drifted from ${U}/${oe}.`),a.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),Bo("Modified",s),Bo("Added (not in manifest)",i),Bo("Removed (in manifest, now missing)",l)):a.info(`\u2705 ${U}/ matches manifest (${n.fileCount} files).`);let p={status:c?"drift":"clean",ok:!c,fileCount:n.fileCount,modified:s,added:i,removed:l};return{content:g(JSON.stringify(p,null,2)),structuredContent:p}},bl={status:me.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:me.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:me.number(),modified:me.array(me.string()),added:me.array(me.string()),removed:me.array(me.string())},Jo=w({name:"vendor-check",description:"Verify that files under vendor/ match the checksums in vendor/.sync-manifest.json. Self-contained (no source repo or config needed). Returns ok=false on drift, missing manifest, or an unknown future schemaVersion; ok=true when clean or when no vendor/ folder exists.",inputSchema:{},outputSchema:bl,handler:()=>js({cwd:Rl.cwd()})});import{z as se}from"zod";import xl from"node:fs/promises";import Cl from"node:path";import{pathToFileURL as El}from"node:url";import{z as Tl}from"zod";var kt=async e=>{let r=Cl.join(e,dr),t;try{t=await xl.stat(r)}catch{throw new Error(`${dr} not found at ${r}`)}let s=(await import(`${El(r).href}?mtime=${Number(t.mtimeMs)}`)).default;if(s===void 0)throw new Error(`${dr} at ${r} has no default export`);let i=typeof s=="function"?await s():s,l=fn.safeParse(i);if(!l.success)throw new Error(`Invalid ${dr} at ${r}: ${Tl.prettifyError(l.error)}`);return l.data};import{existsSync as ne,mkdirSync as $l,writeFileSync as Il}from"node:fs";import q from"node:path";import{$ as Wr}from"zx";var Pl=["node_modules","dist","*.tsbuildinfo",".turbo",".eslintcache",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack","log.txt"],Sl=`# vendor/ \u2014 mirrored from the source repo
146
+ `),m.print();let S={version:l,branch:s,jiraVersionUrl:b,previousDescription:d,newDescription:u,changed:!0};return{content:g(JSON.stringify(S,null,2)),structuredContent:S}},Oo=w({name:"release-desc-edit",description:"Edit a release's description in Jira and in the matching GitHub release PR body. Accepts a release version or a release name: targets the Jira fix version named `v<version>` (versioned) or `<name>` (named) and the open PR on branch `release/v<version>` or `release/<name>`. The PR body is rewritten canonically to `<jiraVersionUrl>\\n\\n<description>` \u2014 any prior manual edits to the body are overwritten. Both `version` and `description` are required for MCP calls (the picker/prompt are unreachable without a TTY). Empty `description` clears the description on both sides. Confirmation is auto-skipped for MCP, so the caller is responsible for gating.",inputSchema:{version:Ee.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:Ee.string().describe("New description. Empty string clears the description.")},outputSchema:{version:Ee.string().describe("Release version"),branch:Ee.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:Ee.string().describe("Jira fix version URL"),previousDescription:Ee.string().describe("The description before the update"),newDescription:Ee.string().describe("The description after the update"),changed:Ee.boolean().describe("Whether the description actually changed")},handler:As});import{existsSync as Fs}from"node:fs";import Ds from"node:path";import Rl from"node:process";import{z as me}from"zod";import{createHash as dl}from"node:crypto";import{readFileSync as ml}from"node:fs";var gt=e=>dl("sha256").update(ml(e)).digest("hex");import{readFileSync as vl,writeFileSync as yl}from"node:fs";import vt from"node:path";import{z as te}from"zod";import{readdirSync as hl}from"node:fs";import Fo from"node:path";var U="vendor",ul=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack"]),fl=new Set([".sync-manifest.json",".eslintcache","log.txt"]),gl=[".tsbuildinfo"],Ns=e=>ul.has(e),_s=e=>fl.has(e)?!0:gl.some(r=>e.endsWith(r));var wl=e=>e.split(Fo.sep).join("/"),ht=e=>{let r=[],t=o=>{for(let n of hl(o,{withFileTypes:!0})){let s=Fo.join(o,n.name);if(n.isDirectory()){if(Ns(n.name))continue;t(s);continue}_s(n.name)||r.push(wl(Fo.relative(e,s)))}};return t(e),r.sort()};var oe=".sync-manifest.json",wt=1,kl=te.object({schemaVersion:te.number().optional(),source:te.string(),commit:te.string(),syncedAt:te.string(),fileCount:te.number(),files:te.record(te.string(),te.string())}),Do=e=>(e.schemaVersion??wt)>wt,Os=e=>{let r={};for(let t of ht(e))try{r[t]=gt(vt.join(e,t))}catch(o){let n=o instanceof Error?o.message:String(o);throw new Error(`Cannot hash vendor file "${t}" (broken symlink or unreadable file): ${n}`)}return r},jo=e=>{let r=vt.join(e,oe),t;try{t=vl(r,"utf8")}catch{throw new Error(`Missing ${oe} at ${r}`)}let o=kl.safeParse(JSON.parse(t));if(!o.success)throw new Error(`Invalid ${oe} at ${r}: ${te.prettifyError(o.error)}`);return o.data},Mo=(e,r)=>{let t=Os(e),o={schemaVersion:wt,source:r.source,commit:r.commit,syncedAt:new Date().toISOString(),fileCount:Object.keys(t).length,files:t};return yl(vt.join(e,oe),`${JSON.stringify(o,null,2)}
147
+ `),o},Lo=(e,r)=>{let t=r.files,o=ht(e),n=[],s=[];for(let c of o){if(!(c in t)){s.push(c);continue}gt(vt.join(e,c))!==t[c]&&n.push(c)}let i=new Set(o),l=Object.keys(t).filter(c=>!i.has(c));return{modified:n,added:s,removed:l}};var Wo=30,Vo=(e,r)=>{if(r.length!==0){a.info(`
148
+ ${e} (${r.length}):`);for(let t of r.slice(0,Wo))a.info(` ${t}`);r.length>Wo&&a.info(` \u2026and ${r.length-Wo} more`)}},js=async(e={})=>{let r=e.cwd??await k(),t=Ds.join(r,U),o={modified:[],added:[],removed:[],fileCount:0};if(!Fs(t)){a.info(`\u2139\uFE0F No ${U}/ folder found \u2014 nothing to check.`);let d={status:"skipped",ok:!0,...o};return{content:g(JSON.stringify(d,null,2)),structuredContent:d}}if(!Fs(Ds.join(t,oe))){a.error(`\u274C Missing ${U}/${oe}. Re-run the vendor sync to generate it.`);let d={status:"missing-manifest",ok:!1,...o};return{content:g(JSON.stringify(d,null,2)),structuredContent:d}}let n=jo(t);if(Do(n)){a.error(`\u274C ${U}/${oe} has a newer schemaVersion (${String(n.schemaVersion)}) than this CLI supports. Upgrade infra-kit.`);let d={status:"unknown-schema",ok:!1,...o};return{content:g(JSON.stringify(d,null,2)),structuredContent:d}}let{modified:s,added:i,removed:l}=Lo(t,n),c=s.length>0||i.length>0||l.length>0;c?(a.error(`\u274C ${U}/ has drifted from ${U}/${oe}.`),a.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),Vo("Modified",s),Vo("Added (not in manifest)",i),Vo("Removed (in manifest, now missing)",l)):a.info(`\u2705 ${U}/ matches manifest (${n.fileCount} files).`);let p={status:c?"drift":"clean",ok:!c,fileCount:n.fileCount,modified:s,added:i,removed:l};return{content:g(JSON.stringify(p,null,2)),structuredContent:p}},bl={status:me.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:me.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:me.number(),modified:me.array(me.string()),added:me.array(me.string()),removed:me.array(me.string())},Bo=w({name:"vendor-check",description:"Verify that files under vendor/ match the checksums in vendor/.sync-manifest.json. Self-contained (no source repo or config needed). Returns ok=false on drift, missing manifest, or an unknown future schemaVersion; ok=true when clean or when no vendor/ folder exists.",inputSchema:{},outputSchema:bl,handler:()=>js({cwd:Rl.cwd()})});import{z as se}from"zod";import xl from"node:fs/promises";import Cl from"node:path";import{pathToFileURL as El}from"node:url";import{z as Tl}from"zod";var yt=async e=>{let r=Cl.join(e,dr),t;try{t=await xl.stat(r)}catch{throw new Error(`${dr} not found at ${r}`)}let s=(await import(`${El(r).href}?mtime=${Number(t.mtimeMs)}`)).default;if(s===void 0)throw new Error(`${dr} at ${r} has no default export`);let i=typeof s=="function"?await s():s,l=un.safeParse(i);if(!l.success)throw new Error(`Invalid ${dr} at ${r}: ${Tl.prettifyError(l.error)}`);return l.data};import{existsSync as ne,mkdirSync as $l,writeFileSync as Il}from"node:fs";import q from"node:path";import{$ as Wr}from"zx";var Pl=["node_modules","dist","*.tsbuildinfo",".turbo",".eslintcache",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack","log.txt"],Sl=`# vendor/ \u2014 mirrored from the source repo
149
149
 
150
150
  **DO NOT EDIT files in this folder here.**
151
151
 
@@ -156,11 +156,11 @@ overwritten on the next sync and will fail \`infra-kit vendor check\` in CI.
156
156
  To change a vendored package, edit it in the source repo and re-run the sync.
157
157
 
158
158
  See \`.sync-manifest.json\` for the source commit and per-file checksums.
159
- `,Ls=()=>Pl.map(e=>`--exclude=${e}`),Rt=async e=>{try{return(await Wr({cwd:e})`git rev-parse HEAD`).stdout.trim()}catch{return"unknown"}},Al=async(e,r)=>{if(!ne(e))return!1;ne(r)&&await Wr`rm -rf ${r}`;let t=`${e}/`,o=`${r}/`;return await Wr`rsync -a ${Ls()} ${t} ${o}`,!0},Nl=async(e,r)=>{if(!ne(e))return!1;let t=q.dirname(r);return ne(t)||$l(t,{recursive:!0}),await Wr`cp ${e} ${r}`,!0},_l=async(e,r)=>{if(!ne(e))return[];if(!ne(r))return[`missing target: ${r}`];let t=`${e}/`,o=`${r}/`;return(await Wr`rsync -ai --dry-run --delete ${Ls()} ${t} ${o}`).stdout.split(`
160
- `).map(s=>s.trim()).filter(Boolean)},Ws=(e,r)=>{let t=q.join(e,U);ne(t)&&(Il(q.join(t,"README.md"),Sl),Lo(t,r))},Ko=(e,r)=>q.join(jn(e),r),cr=(e,r)=>r?e.filter(t=>r.includes(t)):e,Ms=(e,r,t,o,n)=>{let s=q.resolve(e),i=q.resolve(r);if(i!==s&&!i.startsWith(s+q.sep))throw new f(void 0,{operation:`sync vendor item ${n}`,stderrExcerpt:`${t} escapes repo root: ${o}`})},Vs=async(e,r,t,o,n)=>{let s=[];for(let i of o){let l=Ko(t,i);if(!ne(l)){s.push({repo:i,copied:0,total:e.copy.length,skipped:!0});continue}let c=0;for(let p of e.copy){let d=q.join(r,p.source),u=q.join(l,p.target);Ms(r,d,"source",p.source,p.name),Ms(l,u,"target",p.target,p.name),(p.type==="directory"?await Al(d,u):await Nl(d,u))&&c++}Ws(l,n),s.push({repo:i,copied:c,total:e.copy.length,skipped:!1})}return{source:n.source,commit:n.commit,repos:s}},Bs=async(e,r,t)=>{let o=[];for(let n of r){let s=Ko(e,n),i=!ne(s);i||Ws(s,t),o.push({repo:n,skipped:i})}return o},Js=async(e,r,t,o)=>{let n=[],s=e.copy.filter(i=>i.vendored===!0);for(let i of o){let l=Ko(t,i);if(ne(l))for(let c of s){let p=q.join(r,c.source),d=q.join(l,c.target),u=await _l(p,d);u.length>0&&n.push({repo:i,target:c.target,changes:u})}}return n};var Go=20,Ks=async(e={})=>{let r=e.cwd??await k(),t=await kt(r),o=await Xe(),n=cr(o.targets,e.repos),s=await Js(t,r,o.workspaceDir,n);if(s.length===0)a.info("\u{1F389} No drift detected.");else for(let l of s){a.info(`\u274C ${l.repo} \u2192 ${l.target} (${l.changes.length} change(s)):`);for(let c of l.changes.slice(0,Go))a.info(` ${c}`);l.changes.length>Go&&a.info(` \u2026and ${l.changes.length-Go} more`)}let i={ok:s.length===0,drifted:s.length,entries:s};return{content:g(JSON.stringify(i,null,2)),structuredContent:i}},Ol={ok:se.boolean().describe("Whether every target is in sync with the source"),drifted:se.number(),entries:se.array(se.object({repo:se.string(),target:se.string(),changes:se.array(se.string())}))},zo=w({name:"vendor-diff",description:"Source-aware drift check: compare each target repo vendored subtree against the source via rsync dry-run. Read-only; run from the source repo root. ok=false when any target has drifted.",inputSchema:{repos:se.array(se.string()).optional().describe("Restrict to these target repo names")},outputSchema:Ol,handler:e=>Ks({repos:e.repos})});import Fl from"node:path";import{z as Te}from"zod";var Gs=async e=>{let r=e.cwd??await k(),t=await Xe(),o=cr(t.targets,e.repos),n=await Rt(r),s=Fl.basename(r),i=await Bs(t.workspaceDir,o,{source:s,commit:n});for(let c of i)a.info(c.skipped?`\u26A0\uFE0F ${c.repo}: target does not exist \u2014 skipped`:`\u{1F4DD} ${c.repo}: manifest written`);let l={source:s,commit:n,repos:i};return{content:g(JSON.stringify(l,null,2)),structuredContent:l}},Dl={source:Te.string(),commit:Te.string(),repos:Te.array(Te.object({repo:Te.string(),skipped:Te.boolean()}))},Uo=w({name:"vendor-manifest",description:"Regenerate each target repo vendor/.sync-manifest.json + README from current content without copying. Mutating; run from the source repo root.",inputSchema:{repos:Te.array(Te.string()).optional().describe("Restrict to these target repo names")},outputSchema:Dl,handler:e=>Gs({repos:e.repos,confirmedCommand:e.confirmedCommand})});import jl from"@inquirer/confirm";import zs from"node:path";import Us from"node:process";import{z as ie}from"zod";var qs=async e=>{let r=e.cwd??await k(),t=await kt(r),o=await Xe(),n=cr(o.targets,e.repos);e.confirmedCommand||await jl({message:`Sync vendor files from ${zs.basename(r)} into ${n.length} repo(s)?`},{output:Us.stderr})||Us.exit(0);let s=await Rt(r),i=zs.basename(r),l=await Vs(t,r,o.workspaceDir,n,{source:i,commit:s});for(let c of l.repos)c.skipped?a.info(`\u26A0\uFE0F ${c.repo}: target does not exist \u2014 skipped`):a.info(`\u2705 ${c.repo}: copied ${c.copied}/${c.total} items + manifest`);return{content:g(JSON.stringify(l,null,2)),structuredContent:l}},Ml={source:ie.string(),commit:ie.string(),repos:ie.array(ie.object({repo:ie.string(),copied:ie.number(),total:ie.number(),skipped:ie.boolean()}))},qo=w({name:"vendor-sync",description:"Copy vendored files from the source repo (vendor.config.ts) into each target repo and regenerate their vendor/.sync-manifest.json + README. Mutating; run from the source repo root.",inputSchema:{repos:ie.array(ie.string()).optional().describe("Restrict to these target repo names")},outputSchema:Ml,handler:e=>qs({repos:e.repos,confirmedCommand:e.confirmedCommand})});import{z as Ll}from"zod";var Hs=async()=>{let e=et.version;a.info(e);let r={version:e};return{content:g(JSON.stringify(r,null,2)),structuredContent:r}},Ho=w({name:"version",description:"Print the installed infra-kit CLI version",inputSchema:{},outputSchema:{version:Ll.string().describe("Installed infra-kit CLI version (from package.json)")},handler:Hs});var bt=["workspace","none"];import Zs from"node:fs/promises";import xt from"node:path";var Vr=async e=>{let{workspacePath:r,folderPaths:t}=e,o=xt.dirname(r),n;try{n=await Zs.readFile(r,"utf-8")}catch(d){throw new Error(`Cursor workspace file not found at ${r}: ${d.message}`)}let s;try{s=JSON.parse(n)}catch(d){throw new Error(`Failed to parse ${r} as JSON. Comments (JSONC) are not supported. ${d.message}`)}let i=s.folders??[],l=new Set(i.map(d=>xt.resolve(o,d.path))),c=[],p=[];for(let d of t){let u=xt.resolve(d);if(l.has(u)){p.push(d);continue}let h=xt.relative(o,u);i.push({path:h}),l.add(u),c.push(d)}return s.folders=i,await Zs.writeFile(r,`${JSON.stringify(s,null,2)}
161
- `,"utf-8"),{added:c,skipped:p}};import{$ as Wl}from"zx";var Br=async e=>{await Wl`cursor ${e}`};import Vl from"node:fs/promises";import Et from"node:path";import Xs from"node:fs/promises";import Ct from"node:path";var Jr=async e=>{let{workspacePath:r,folderPaths:t}=e,o=Ct.dirname(r),n;try{n=await Xs.readFile(r,"utf-8")}catch(h){throw new Error(`Cursor workspace file not found at ${r}: ${h.message}`)}let s;try{s=JSON.parse(n)}catch(h){throw new Error(`Failed to parse ${r} as JSON. Comments (JSONC) are not supported. ${h.message}`)}let i=s.folders??[],l=new Set(t.map(h=>Ct.resolve(h))),c=new Set,p=i.filter(h=>{let b=Ct.resolve(o,h.path);return l.has(b)?(c.add(b),!1):!0});s.folders=p,await Xs.writeFile(r,`${JSON.stringify(s,null,2)}
162
- `,"utf-8");let d=[],u=[];for(let h of t){let b=Ct.resolve(h);c.has(b)?d.push(h):u.push(h)}return{removed:d,notFound:u}};var Zo=async e=>{let{workspacePath:r,worktreeDir:t,currentBranches:o}=e,n=Et.dirname(r),s=Et.resolve(`${t}/release`),i=await Vl.readFile(r,"utf-8"),c=JSON.parse(i).folders??[],p=new Set(o.map(v=>Et.resolve(`${t}/${v}`))),d=[];for(let v of c){let S=Et.resolve(n,v.path);(S===s||S.startsWith(`${s}/`))&&!p.has(S)&&d.push(S)}let u=[];d.length>0&&(u=(await Jr({workspacePath:r,folderPaths:d})).removed);let h=o.map(v=>`${t}/${v}`),{added:b}=h.length>0?await Vr({workspacePath:r,folderPaths:h}):{added:[]};return{added:b,removed:u}};import Ys from"node:path";var Ge=(e,r)=>Ys.isAbsolute(e)?e:Ys.resolve(r,e);var Xo=async e=>{let{projectRoot:r,worktreeDir:t,currentBranches:o,cursorConfig:n}=e;if(!n.workspaceConfigPath)return a.warn("\u26A0\uFE0F Skipping Cursor: workspaceConfigPath is not set."),{ran:!1,added:0,removed:0};let s=Ge(n.workspaceConfigPath,r);try{let{added:i,removed:l}=await Zo({workspacePath:s,worktreeDir:t,currentBranches:o});return o.length>0&&await Br(s),{ran:!0,added:i.length,removed:l.length}}catch(i){return a.warn({error:i},`\u26A0\uFE0F Failed to reconcile/open Cursor workspace at ${s}`),{ran:!1,added:0,removed:0}}};import{$ as Bl}from"zx";var Yo=async e=>{let{folderPaths:r}=e;for(let t of r)await Bl`zed --add ${t}`;return{added:r}};import{$ as Jl}from"zx";var Qo=async e=>{let{projectRoot:r,worktreeDir:t,currentBranches:o}=e;if(o.length===0)return{ran:!1,added:0,removed:0};let n=[r,...o.map(s=>`${t}/${s}`)];try{return await Jl`zed ${n}`,{ran:!0,added:o.length,removed:0}}catch(s){return a.warn({error:s},"\u26A0\uFE0F Failed to open Zed workspace"),{ran:!1,added:0,removed:0}}};import{$ as Kl}from"zx";var en=async e=>{let{projectRoot:r,worktreeDir:t,remainingBranches:o}=e,n=[r,...o.map(s=>`${t}/${s}`)];try{return await Kl`zed --reuse ${n}`,a.info(`\u21BB Refreshed Zed workspace to root + ${o.length} release worktree(s) (other folders in the focused window are not preserved)`),{ran:!0}}catch(s){return a.warn({error:s},"\u26A0\uFE0F Failed to refresh Zed workspace"),{ran:!1}}};var ue=e=>{throw new Error(`Unexpected value: ${JSON.stringify(e)}`)};var rn=async e=>{let{projectRoot:r,worktreeDir:t,branches:o}=e,n=await x(),s=K(n),i=o.map(c=>`${t}/${c}`),l=[];for(let c of s)switch(c.provider){case"cursor":{if(!c.config.workspaceConfigPath){a.warn("\u26A0\uFE0F Skipping Cursor: ide.config.workspaceConfigPath is not set in infra-kit config"),l.push({ran:!1,provider:"cursor",added:0,skipped:0});break}let p=Ge(c.config.workspaceConfigPath,r),{added:d,skipped:u}=await Vr({workspacePath:p,folderPaths:i}),h=u.length>0?` (${u.length} already present)`:"";a.info(`\u2705 Added ${d.length} folder(s) to ${p}${h}`),await Br(p),l.push({ran:!0,provider:"cursor",added:d.length,skipped:u.length});break}case"zed":{let{added:p}=await Yo({folderPaths:i});a.info(`\u2705 Added ${p.length} folder(s) to Zed workspace`),l.push({ran:!0,provider:"zed",added:p.length,skipped:0});break}default:ue(c)}return l};var tn=async e=>{let r=await x(),t=K(r),o=[];for(let n of t)switch(n.provider){case"cursor":{let s=await Xo({...e,cursorConfig:n.config});o.push({...s,provider:"cursor"});break}case"zed":{let s=await Qo(e);o.push({...s,provider:"zed"});break}default:ue(n)}return o};var on=e=>{switch(e){case"cursor":return"Cursor";case"zed":return"Zed";case void 0:return"IDE";default:return ue(e)}};var Kr=async e=>{let{projectRoot:r,worktreeDir:t,currentWorktrees:o,removedWorktrees:n,allowEditorRelaunch:s}=e;if(n.length===0)return[];let i=await x(),l=K(i),c=n.map(u=>`${t}/${u}`),p=o.filter(u=>!n.includes(u)),d=[];for(let u of l)switch(u.provider){case"cursor":{d.push(await Gl({ide:u,projectRoot:r,folderPaths:c}));break}case"zed":{d.push(await zl({projectRoot:r,worktreeDir:t,remainingBranches:p,allowEditorRelaunch:s}));break}default:ue(u)}return d},Gl=async e=>{let{ide:r,projectRoot:t,folderPaths:o}=e;if(!r.config.workspaceConfigPath)return{provider:"cursor",supported:!0,removed:[]};let n=Ge(r.config.workspaceConfigPath,t);try{let{removed:s}=await Jr({workspacePath:n,folderPaths:o});return s.length>0&&a.info(`\u2705 Removed ${s.length} folder(s) from ${n}`),{provider:"cursor",supported:!0,removed:s}}catch(s){return a.warn({error:s},`\u26A0\uFE0F Failed to update Cursor workspace at ${n}`),{provider:"cursor",supported:!0,removed:[]}}},zl=async e=>{let{projectRoot:r,worktreeDir:t,remainingBranches:o,allowEditorRelaunch:n}=e;return n?(await en({projectRoot:r,worktreeDir:t,remainingBranches:o}),{provider:"zed",supported:!0,removed:[]}):(a.info("\u2139\uFE0F Zed folder removal skipped (no interactive session); close removed worktree folders in Zed manually if needed."),{provider:"zed",supported:!0,removed:[]})};import Ul from"@inquirer/checkbox";import nn from"@inquirer/confirm";import ql from"node:process";import{z as fe}from"zod";import{$ as Gr}from"zx";var Hl="feature",Zl="release",ei=async e=>{let{confirmedCommand:r,all:t,versions:o,githubDesktop:n,cmux:s}=e,i=e.ide??e.cursor;m.start("worktrees-add"),await D({operation:"create worktrees",requiredBranch:"dev"});try{let l=await F("release"),c=await k(),p=`${c}${G}`;await Qs(`${p}/${Zl}`),await Qs(`${p}/${Hl}`);let d=[];if(o)d=o.split(",").map(ge=>ce(Z(ge.trim())));else{let ge=await T(),pr=ge.map(ze=>ze.branch);if(pr.length===0)return a.info("\u2139\uFE0F No open release branches found"),m.print(),{content:g(JSON.stringify({createdWorktrees:[],count:0},null,2)),structuredContent:{createdWorktrees:[],count:0}};if(t)d=pr;else{m.setInteractive();let ze=new Map(ge.map(un=>[un.branch,E(un.title)])),Ur=await P();d=await Ul({required:!0,message:"\u{1F33F} Select release branches",choices:A({branches:pr,descriptions:Ur,types:ze})})}}t?m.addOption("--all",!0):m.addOption("--versions",Be(d));let u=r?!0:await nn({message:"Are you sure you want to proceed with these worktree changes?"});r||m.setInteractive(),u||(a.info("Operation cancelled. Exiting..."),ql.exit(0)),r||m.addOption("--yes",!0);let h=await x(),b=i??(K(h).length>0?"workspace":"none");m.addOption("--ide",b);let v=n??h.worktrees?.openInGithubDesktop??await nn({message:"Open created worktrees in GitHub Desktop?"});typeof n>"u"&&h.worktrees?.openInGithubDesktop===void 0&&m.setInteractive(),v?m.addOption("--github-desktop",!0):m.addOption("--no-github-desktop",!0);let S=s??h.worktrees?.openInCmux??await nn({message:"Open created worktrees in cmux?"});typeof s>"u"&&h.worktrees?.openInCmux===void 0&&m.setInteractive(),S?m.addOption("--cmux",!0):m.addOption("--no-cmux",!0);let{branchesToCreate:_}=Xl({selectedReleaseBranches:d,currentWorktrees:l}),H=await Yl(_,p);if(Ql(H),b==="workspace"&&await rn({projectRoot:c,worktreeDir:p,branches:H}),v)for(let ge of H)await Gr`github ${p}/${ge}`,await Gr`sleep 5`;if(S){let ge=await J(),pr=await Fr();for(let ze of H){let Ur=re({repoName:ge,branch:ze});pr.has(ee(Ur))||await jr({cwd:`${p}/${ze}`,title:Ur})}}m.print();let Ie={createdWorktrees:H,count:H.length};return{content:g(JSON.stringify(Ie,null,2)),structuredContent:Ie}}catch(l){throw a.error({error:l},"\u274C Error managing worktrees"),new f(l,{operation:"create worktrees",remediation:"verify branches don't already exist as worktrees: 'git worktree list'"})}},Qs=async e=>{await Gr`mkdir -p ${e}`},Xl=e=>{let{selectedReleaseBranches:r,currentWorktrees:t}=e,o=t.filter(s=>Ae(s));return{branchesToCreate:r.filter(s=>!o.includes(s))}},Yl=async(e,r)=>{let t=await Promise.allSettled(e.map(async n=>{let s=`${r}/${n}`;return await Gr`git worktree add ${s} ${n}`,await Gr({cwd:s})`pnpm install`,n})),o=[];for(let[n,s]of t.entries())if(s.status==="fulfilled")o.push(s.value);else{let i=e[n],l=new f(s.reason,{operation:`git worktree add for ${i}`,remediation:"check the branch name and that the parent dir is writable"});a.error({error:s.reason,msg:l.message})}return o},Ql=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")},sn=w({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:fe.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:fe.string().optional().describe('Comma-separated release versions or names to target (e.g. "1.2.5, 1.2.6" or "checkout-redesign, 1.2.5"). Either "versions" or all=true must be provided for MCP calls. Overrides "all" when set.'),ide:fe.enum(bt).optional().describe('Editor open mode for created worktrees, applied to all configured editors (Cursor and/or Zed, per the "ide" config). "workspace" (the only attach style) adds each worktree to every configured editor workspace and opens it. "none" skips the editor. Resolution order: this flag \u2192 "workspace" when at least one "ide" is configured \u2192 "none" otherwise.'),cursor:fe.enum(bt).optional().describe('Deprecated alias for "ide". Prefer "ide". Ignored when "ide" is provided.'),githubDesktop:fe.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:fe.boolean().optional().describe('Open each created worktree in a new cmux workspace, all rooted at the worktree directory. Pane layout follows "worktrees.cmux.layout" (default "two-columns": left | right; or "three-pane": left split top/bottom + full-height right). Resolution order: this flag \u2192 "worktrees.openInCmux" from infra-kit config \u2192 interactive prompt (CLI) / false (MCP, no TTY).')},outputSchema:{createdWorktrees:fe.array(fe.string()).describe("List of created git worktree branches"),count:fe.number().describe("Number of git worktrees created")},handler:ei});import{z as lr}from"zod";var ri=async()=>{let e=await F("release");if(e.length===0)return a.info("\u2139\uFE0F No active worktrees found"),{content:g(JSON.stringify({worktrees:[],count:0},null,2)),structuredContent:{worktrees:[],count:0}};let[r,t]=await Promise.all([T(),P()]),o=new Map(r.map(c=>[c.branch,E(c.title)])),n=e.flatMap(c=>{let p=C(c);if(!p)return[];let d=I(p),u=o.get(c)||"regular",h=t.get(M(p))||null;return[{version:d,type:u,description:h}]}),s=Math.max(...n.map(c=>c.version.length)),i=n.map(c=>{let p=nr(c.version,c.type,s);return c.description?`${p} ${c.description}`:p});a.info("\u{1F33F} Active worktrees:"),a.info(`
159
+ `,Ls=()=>Pl.map(e=>`--exclude=${e}`),kt=async e=>{try{return(await Wr({cwd:e})`git rev-parse HEAD`).stdout.trim()}catch{return"unknown"}},Al=async(e,r)=>{if(!ne(e))return!1;ne(r)&&await Wr`rm -rf ${r}`;let t=`${e}/`,o=`${r}/`;return await Wr`rsync -a ${Ls()} ${t} ${o}`,!0},Nl=async(e,r)=>{if(!ne(e))return!1;let t=q.dirname(r);return ne(t)||$l(t,{recursive:!0}),await Wr`cp ${e} ${r}`,!0},_l=async(e,r)=>{if(!ne(e))return[];if(!ne(r))return[`missing target: ${r}`];let t=`${e}/`,o=`${r}/`;return(await Wr`rsync -ai --dry-run --delete ${Ls()} ${t} ${o}`).stdout.split(`
160
+ `).map(s=>s.trim()).filter(Boolean)},Ws=(e,r)=>{let t=q.join(e,U);ne(t)&&(Il(q.join(t,"README.md"),Sl),Mo(t,r))},Jo=(e,r)=>q.join(Dn(e),r),cr=(e,r)=>r?e.filter(t=>r.includes(t)):e,Ms=(e,r,t,o,n)=>{let s=q.resolve(e),i=q.resolve(r);if(i!==s&&!i.startsWith(s+q.sep))throw new f(void 0,{operation:`sync vendor item ${n}`,stderrExcerpt:`${t} escapes repo root: ${o}`})},Vs=async(e,r,t,o,n)=>{let s=[];for(let i of o){let l=Jo(t,i);if(!ne(l)){s.push({repo:i,copied:0,total:e.copy.length,skipped:!0});continue}let c=0;for(let p of e.copy){let d=q.join(r,p.source),u=q.join(l,p.target);Ms(r,d,"source",p.source,p.name),Ms(l,u,"target",p.target,p.name),(p.type==="directory"?await Al(d,u):await Nl(d,u))&&c++}Ws(l,n),s.push({repo:i,copied:c,total:e.copy.length,skipped:!1})}return{source:n.source,commit:n.commit,repos:s}},Bs=async(e,r,t)=>{let o=[];for(let n of r){let s=Jo(e,n),i=!ne(s);i||Ws(s,t),o.push({repo:n,skipped:i})}return o},Js=async(e,r,t,o)=>{let n=[],s=e.copy.filter(i=>i.vendored===!0);for(let i of o){let l=Jo(t,i);if(ne(l))for(let c of s){let p=q.join(r,c.source),d=q.join(l,c.target),u=await _l(p,d);u.length>0&&n.push({repo:i,target:c.target,changes:u})}}return n};var Ko=20,Ks=async(e={})=>{let r=e.cwd??await k(),t=await yt(r),o=await Xe(),n=cr(o.targets,e.repos),s=await Js(t,r,o.workspaceDir,n);if(s.length===0)a.info("\u{1F389} No drift detected.");else for(let l of s){a.info(`\u274C ${l.repo} \u2192 ${l.target} (${l.changes.length} change(s)):`);for(let c of l.changes.slice(0,Ko))a.info(` ${c}`);l.changes.length>Ko&&a.info(` \u2026and ${l.changes.length-Ko} more`)}let i={ok:s.length===0,drifted:s.length,entries:s};return{content:g(JSON.stringify(i,null,2)),structuredContent:i}},Ol={ok:se.boolean().describe("Whether every target is in sync with the source"),drifted:se.number(),entries:se.array(se.object({repo:se.string(),target:se.string(),changes:se.array(se.string())}))},Go=w({name:"vendor-diff",description:"Source-aware drift check: compare each target repo vendored subtree against the source via rsync dry-run. Read-only; run from the source repo root. ok=false when any target has drifted.",inputSchema:{repos:se.array(se.string()).optional().describe("Restrict to these target repo names")},outputSchema:Ol,handler:e=>Ks({repos:e.repos})});import Fl from"node:path";import{z as Te}from"zod";var Gs=async e=>{let r=e.cwd??await k(),t=await Xe(),o=cr(t.targets,e.repos),n=await kt(r),s=Fl.basename(r),i=await Bs(t.workspaceDir,o,{source:s,commit:n});for(let c of i)a.info(c.skipped?`\u26A0\uFE0F ${c.repo}: target does not exist \u2014 skipped`:`\u{1F4DD} ${c.repo}: manifest written`);let l={source:s,commit:n,repos:i};return{content:g(JSON.stringify(l,null,2)),structuredContent:l}},Dl={source:Te.string(),commit:Te.string(),repos:Te.array(Te.object({repo:Te.string(),skipped:Te.boolean()}))},zo=w({name:"vendor-manifest",description:"Regenerate each target repo vendor/.sync-manifest.json + README from current content without copying. Mutating; run from the source repo root.",inputSchema:{repos:Te.array(Te.string()).optional().describe("Restrict to these target repo names")},outputSchema:Dl,handler:e=>Gs({repos:e.repos,confirmedCommand:e.confirmedCommand})});import jl from"@inquirer/confirm";import zs from"node:path";import Us from"node:process";import{z as ie}from"zod";var qs=async e=>{let r=e.cwd??await k(),t=await yt(r),o=await Xe(),n=cr(o.targets,e.repos);e.confirmedCommand||await jl({message:`Sync vendor files from ${zs.basename(r)} into ${n.length} repo(s)?`},{output:Us.stderr})||Us.exit(0);let s=await kt(r),i=zs.basename(r),l=await Vs(t,r,o.workspaceDir,n,{source:i,commit:s});for(let c of l.repos)c.skipped?a.info(`\u26A0\uFE0F ${c.repo}: target does not exist \u2014 skipped`):a.info(`\u2705 ${c.repo}: copied ${c.copied}/${c.total} items + manifest`);return{content:g(JSON.stringify(l,null,2)),structuredContent:l}},Ml={source:ie.string(),commit:ie.string(),repos:ie.array(ie.object({repo:ie.string(),copied:ie.number(),total:ie.number(),skipped:ie.boolean()}))},Uo=w({name:"vendor-sync",description:"Copy vendored files from the source repo (vendor.config.ts) into each target repo and regenerate their vendor/.sync-manifest.json + README. Mutating; run from the source repo root.",inputSchema:{repos:ie.array(ie.string()).optional().describe("Restrict to these target repo names")},outputSchema:Ml,handler:e=>qs({repos:e.repos,confirmedCommand:e.confirmedCommand})});import{z as Ll}from"zod";var Hs=async()=>{let e=et.version;a.info(e);let r={version:e};return{content:g(JSON.stringify(r,null,2)),structuredContent:r}},qo=w({name:"version",description:"Print the installed infra-kit CLI version",inputSchema:{},outputSchema:{version:Ll.string().describe("Installed infra-kit CLI version (from package.json)")},handler:Hs});var Rt=["workspace","none"];import Zs from"node:fs/promises";import bt from"node:path";var Vr=async e=>{let{workspacePath:r,folderPaths:t}=e,o=bt.dirname(r),n;try{n=await Zs.readFile(r,"utf-8")}catch(d){throw new Error(`Cursor workspace file not found at ${r}: ${d.message}`)}let s;try{s=JSON.parse(n)}catch(d){throw new Error(`Failed to parse ${r} as JSON. Comments (JSONC) are not supported. ${d.message}`)}let i=s.folders??[],l=new Set(i.map(d=>bt.resolve(o,d.path))),c=[],p=[];for(let d of t){let u=bt.resolve(d);if(l.has(u)){p.push(d);continue}let h=bt.relative(o,u);i.push({path:h}),l.add(u),c.push(d)}return s.folders=i,await Zs.writeFile(r,`${JSON.stringify(s,null,2)}
161
+ `,"utf-8"),{added:c,skipped:p}};import{$ as Wl}from"zx";var Br=async e=>{await Wl`cursor ${e}`};import Vl from"node:fs/promises";import Ct from"node:path";import Xs from"node:fs/promises";import xt from"node:path";var Jr=async e=>{let{workspacePath:r,folderPaths:t}=e,o=xt.dirname(r),n;try{n=await Xs.readFile(r,"utf-8")}catch(h){throw new Error(`Cursor workspace file not found at ${r}: ${h.message}`)}let s;try{s=JSON.parse(n)}catch(h){throw new Error(`Failed to parse ${r} as JSON. Comments (JSONC) are not supported. ${h.message}`)}let i=s.folders??[],l=new Set(t.map(h=>xt.resolve(h))),c=new Set,p=i.filter(h=>{let b=xt.resolve(o,h.path);return l.has(b)?(c.add(b),!1):!0});s.folders=p,await Xs.writeFile(r,`${JSON.stringify(s,null,2)}
162
+ `,"utf-8");let d=[],u=[];for(let h of t){let b=xt.resolve(h);c.has(b)?d.push(h):u.push(h)}return{removed:d,notFound:u}};var Ho=async e=>{let{workspacePath:r,worktreeDir:t,currentBranches:o}=e,n=Ct.dirname(r),s=Ct.resolve(`${t}/release`),i=await Vl.readFile(r,"utf-8"),c=JSON.parse(i).folders??[],p=new Set(o.map(v=>Ct.resolve(`${t}/${v}`))),d=[];for(let v of c){let S=Ct.resolve(n,v.path);(S===s||S.startsWith(`${s}/`))&&!p.has(S)&&d.push(S)}let u=[];d.length>0&&(u=(await Jr({workspacePath:r,folderPaths:d})).removed);let h=o.map(v=>`${t}/${v}`),{added:b}=h.length>0?await Vr({workspacePath:r,folderPaths:h}):{added:[]};return{added:b,removed:u}};import Ys from"node:path";var Ge=(e,r)=>Ys.isAbsolute(e)?e:Ys.resolve(r,e);var Zo=async e=>{let{projectRoot:r,worktreeDir:t,currentBranches:o,cursorConfig:n}=e;if(!n.workspaceConfigPath)return a.warn("\u26A0\uFE0F Skipping Cursor: workspaceConfigPath is not set."),{ran:!1,added:0,removed:0};let s=Ge(n.workspaceConfigPath,r);try{let{added:i,removed:l}=await Ho({workspacePath:s,worktreeDir:t,currentBranches:o});return o.length>0&&await Br(s),{ran:!0,added:i.length,removed:l.length}}catch(i){return a.warn({error:i},`\u26A0\uFE0F Failed to reconcile/open Cursor workspace at ${s}`),{ran:!1,added:0,removed:0}}};import{$ as Bl}from"zx";var Xo=async e=>{let{folderPaths:r}=e;for(let t of r)await Bl`zed --add ${t}`;return{added:r}};import{$ as Jl}from"zx";var Yo=async e=>{let{projectRoot:r,worktreeDir:t,currentBranches:o}=e;if(o.length===0)return{ran:!1,added:0,removed:0};let n=[r,...o.map(s=>`${t}/${s}`)];try{return await Jl`zed ${n}`,{ran:!0,added:o.length,removed:0}}catch(s){return a.warn({error:s},"\u26A0\uFE0F Failed to open Zed workspace"),{ran:!1,added:0,removed:0}}};import{$ as Kl}from"zx";var Qo=async e=>{let{projectRoot:r,worktreeDir:t,remainingBranches:o}=e,n=[r,...o.map(s=>`${t}/${s}`)];try{return await Kl`zed --reuse ${n}`,a.info(`\u21BB Refreshed Zed workspace to root + ${o.length} release worktree(s) (other folders in the focused window are not preserved)`),{ran:!0}}catch(s){return a.warn({error:s},"\u26A0\uFE0F Failed to refresh Zed workspace"),{ran:!1}}};var ue=e=>{throw new Error(`Unexpected value: ${JSON.stringify(e)}`)};var en=async e=>{let{projectRoot:r,worktreeDir:t,branches:o}=e,n=await x(),s=K(n),i=o.map(c=>`${t}/${c}`),l=[];for(let c of s)switch(c.provider){case"cursor":{if(!c.config.workspaceConfigPath){a.warn("\u26A0\uFE0F Skipping Cursor: ide.config.workspaceConfigPath is not set in infra-kit config"),l.push({ran:!1,provider:"cursor",added:0,skipped:0});break}let p=Ge(c.config.workspaceConfigPath,r),{added:d,skipped:u}=await Vr({workspacePath:p,folderPaths:i}),h=u.length>0?` (${u.length} already present)`:"";a.info(`\u2705 Added ${d.length} folder(s) to ${p}${h}`),await Br(p),l.push({ran:!0,provider:"cursor",added:d.length,skipped:u.length});break}case"zed":{let{added:p}=await Xo({folderPaths:i});a.info(`\u2705 Added ${p.length} folder(s) to Zed workspace`),l.push({ran:!0,provider:"zed",added:p.length,skipped:0});break}default:ue(c)}return l};var rn=async e=>{let r=await x(),t=K(r),o=[];for(let n of t)switch(n.provider){case"cursor":{let s=await Zo({...e,cursorConfig:n.config});o.push({...s,provider:"cursor"});break}case"zed":{let s=await Yo(e);o.push({...s,provider:"zed"});break}default:ue(n)}return o};var tn=e=>{switch(e){case"cursor":return"Cursor";case"zed":return"Zed";case void 0:return"IDE";default:return ue(e)}};var Kr=async e=>{let{projectRoot:r,worktreeDir:t,currentWorktrees:o,removedWorktrees:n,allowEditorRelaunch:s}=e;if(n.length===0)return[];let i=await x(),l=K(i),c=n.map(u=>`${t}/${u}`),p=o.filter(u=>!n.includes(u)),d=[];for(let u of l)switch(u.provider){case"cursor":{d.push(await Gl({ide:u,projectRoot:r,folderPaths:c}));break}case"zed":{d.push(await zl({projectRoot:r,worktreeDir:t,remainingBranches:p,allowEditorRelaunch:s}));break}default:ue(u)}return d},Gl=async e=>{let{ide:r,projectRoot:t,folderPaths:o}=e;if(!r.config.workspaceConfigPath)return{provider:"cursor",supported:!0,removed:[]};let n=Ge(r.config.workspaceConfigPath,t);try{let{removed:s}=await Jr({workspacePath:n,folderPaths:o});return s.length>0&&a.info(`\u2705 Removed ${s.length} folder(s) from ${n}`),{provider:"cursor",supported:!0,removed:s}}catch(s){return a.warn({error:s},`\u26A0\uFE0F Failed to update Cursor workspace at ${n}`),{provider:"cursor",supported:!0,removed:[]}}},zl=async e=>{let{projectRoot:r,worktreeDir:t,remainingBranches:o,allowEditorRelaunch:n}=e;return n?(await Qo({projectRoot:r,worktreeDir:t,remainingBranches:o}),{provider:"zed",supported:!0,removed:[]}):(a.info("\u2139\uFE0F Zed folder removal skipped (no interactive session); close removed worktree folders in Zed manually if needed."),{provider:"zed",supported:!0,removed:[]})};import Ul from"@inquirer/checkbox";import on from"@inquirer/confirm";import ql from"node:process";import{z as fe}from"zod";import{$ as Gr}from"zx";var Hl="feature",Zl="release",ei=async e=>{let{confirmedCommand:r,all:t,versions:o,githubDesktop:n,cmux:s}=e,i=e.ide??e.cursor;m.start("worktrees-add"),await D({operation:"create worktrees",requiredBranch:"dev"});try{let l=await F("release"),c=await k(),p=`${c}${G}`;await Qs(`${p}/${Zl}`),await Qs(`${p}/${Hl}`);let d=[];if(o)d=o.split(",").map(ge=>ce(Z(ge.trim())));else{let ge=await T(),pr=ge.map(ze=>ze.branch);if(pr.length===0)return a.info("\u2139\uFE0F No open release branches found"),m.print(),{content:g(JSON.stringify({createdWorktrees:[],count:0},null,2)),structuredContent:{createdWorktrees:[],count:0}};if(t)d=pr;else{m.setInteractive();let ze=new Map(ge.map(mn=>[mn.branch,E(mn.title)])),Ur=await P();d=await Ul({required:!0,message:"\u{1F33F} Select release branches",choices:A({branches:pr,descriptions:Ur,types:ze})})}}t?m.addOption("--all",!0):m.addOption("--versions",Be(d));let u=r?!0:await on({message:"Are you sure you want to proceed with these worktree changes?"});r||m.setInteractive(),u||(a.info("Operation cancelled. Exiting..."),ql.exit(0)),r||m.addOption("--yes",!0);let h=await x(),b=i??(K(h).length>0?"workspace":"none");m.addOption("--ide",b);let v=n??h.worktrees?.openInGithubDesktop??await on({message:"Open created worktrees in GitHub Desktop?"});typeof n>"u"&&h.worktrees?.openInGithubDesktop===void 0&&m.setInteractive(),v?m.addOption("--github-desktop",!0):m.addOption("--no-github-desktop",!0);let S=s??h.worktrees?.openInCmux??await on({message:"Open created worktrees in cmux?"});typeof s>"u"&&h.worktrees?.openInCmux===void 0&&m.setInteractive(),S?m.addOption("--cmux",!0):m.addOption("--no-cmux",!0);let{branchesToCreate:_}=Xl({selectedReleaseBranches:d,currentWorktrees:l}),H=await Yl(_,p);if(Ql(H),b==="workspace"&&await en({projectRoot:c,worktreeDir:p,branches:H}),v)for(let ge of H)await Gr`github ${p}/${ge}`,await Gr`sleep 5`;if(S){let ge=await J(),pr=await Fr();for(let ze of H){let Ur=re({repoName:ge,branch:ze});pr.has(ee(Ur))||await jr({cwd:`${p}/${ze}`,title:Ur})}}m.print();let Ie={createdWorktrees:H,count:H.length};return{content:g(JSON.stringify(Ie,null,2)),structuredContent:Ie}}catch(l){throw a.error({error:l},"\u274C Error managing worktrees"),new f(l,{operation:"create worktrees",remediation:"verify branches don't already exist as worktrees: 'git worktree list'"})}},Qs=async e=>{await Gr`mkdir -p ${e}`},Xl=e=>{let{selectedReleaseBranches:r,currentWorktrees:t}=e,o=t.filter(s=>Ae(s));return{branchesToCreate:r.filter(s=>!o.includes(s))}},Yl=async(e,r)=>{let t=await Promise.allSettled(e.map(async n=>{let s=`${r}/${n}`;return await Gr`git worktree add ${s} ${n}`,await Gr({cwd:s})`pnpm install`,n})),o=[];for(let[n,s]of t.entries())if(s.status==="fulfilled")o.push(s.value);else{let i=e[n],l=new f(s.reason,{operation:`git worktree add for ${i}`,remediation:"check the branch name and that the parent dir is writable"});a.error({error:s.reason,msg:l.message})}return o},Ql=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")},nn=w({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:fe.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:fe.string().optional().describe('Comma-separated release versions or names to target (e.g. "1.2.5, 1.2.6" or "checkout-redesign, 1.2.5"). Either "versions" or all=true must be provided for MCP calls. Overrides "all" when set.'),ide:fe.enum(Rt).optional().describe('Editor open mode for created worktrees, applied to all configured editors (Cursor and/or Zed, per the "ide" config). "workspace" (the only attach style) adds each worktree to every configured editor workspace and opens it. "none" skips the editor. Resolution order: this flag \u2192 "workspace" when at least one "ide" is configured \u2192 "none" otherwise.'),cursor:fe.enum(Rt).optional().describe('Deprecated alias for "ide". Prefer "ide". Ignored when "ide" is provided.'),githubDesktop:fe.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:fe.boolean().optional().describe('Open each created worktree in a new cmux workspace, all rooted at the worktree directory. Pane layout follows "worktrees.cmux.layout" (default "two-columns": left | right; or "three-pane": left split top/bottom + full-height right). Resolution order: this flag \u2192 "worktrees.openInCmux" from infra-kit config \u2192 interactive prompt (CLI) / false (MCP, no TTY).')},outputSchema:{createdWorktrees:fe.array(fe.string()).describe("List of created git worktree branches"),count:fe.number().describe("Number of git worktrees created")},handler:ei});import{z as lr}from"zod";var ri=async()=>{let e=await F("release");if(e.length===0)return a.info("\u2139\uFE0F No active worktrees found"),{content:g(JSON.stringify({worktrees:[],count:0},null,2)),structuredContent:{worktrees:[],count:0}};let[r,t]=await Promise.all([T(),P()]),o=new Map(r.map(c=>[c.branch,E(c.title)])),n=e.flatMap(c=>{let p=C(c);if(!p)return[];let d=I(p),u=o.get(c)||"regular",h=t.get(M(p))||null;return[{version:d,type:u,description:h}]}),s=Math.max(...n.map(c=>c.version.length)),i=n.map(c=>{let p=nr(c.version,c.type,s);return c.description?`${p} ${c.description}`:p});a.info("\u{1F33F} Active worktrees:"),a.info(`
163
163
  ${i.join(`
164
164
  `)}
165
- `);let l={worktrees:n,count:n.length};return{content:g(JSON.stringify(l,null,2)),structuredContent:l}},an=w({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:lr.array(lr.object({version:lr.string().describe("Release version"),type:lr.enum(["regular","hotfix"]).describe("Release type"),description:lr.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:lr.number().describe("Number of worktrees")},handler:ri});import{z as $e}from"zod";var ti=async()=>{m.start("worktrees-reload");try{let e=await k(),r=`${e}${G}`,t=await F("release"),o=await J(),n=await ep({currentBranches:t,repoName:o}),[s,{opened:i}]=await Promise.all([tn({projectRoot:e,worktreeDir:r,currentBranches:t}),rp({worktreeDir:r,currentBranches:t,repoName:o})]),l={closedCmux:n,openedCmux:i,ideProviders:s.filter(c=>c.ran).map(c=>c.provider),ideFoldersAdded:s.reduce((c,p)=>c+p.added,0),ideFoldersRemoved:s.reduce((c,p)=>c+p.removed,0)};return tp(l,{ideRan:s.some(c=>c.ran)}),m.print(),{content:g(JSON.stringify(l,null,2)),structuredContent:{...l}}}catch(e){throw a.error({error:e},"\u274C Error reloading worktrees"),new f(e,{operation:"reload worktrees",remediation:"run 'worktrees-list' to confirm the branches exist"})}},ep=async e=>{let{currentBranches:r,repoName:t}=e;if(r.length===0)return[];let o=await Fr(),n=[];for(let s of r){let i=re({repoName:t,branch:s});o.has(ee(i))&&(await Je(i),n.push(i))}return n},rp=async e=>{let{worktreeDir:r,currentBranches:t,repoName:o}=e,n=[];for(let s of t){let i=re({repoName:o,branch:s});try{await jr({cwd:`${r}/${s}`,title:i}),n.push(i)}catch(l){a.warn({error:l,title:i},`\u26A0\uFE0F Failed to reopen cmux workspace for ${s}`)}}return{opened:n}},tp=(e,r)=>{if(e.closedCmux.length>0&&a.info(`\u{1F9F9} Closed ${e.closedCmux.length} cmux workspace(s)`),r.ideRan){let t=e.ideProviders.map(o=>on(o)).join(", ");e.ideFoldersAdded>0&&a.info(`\u2705 Added ${e.ideFoldersAdded} folder(s) to ${t} workspace(s)`),e.ideFoldersRemoved>0&&a.info(`\u{1F9F9} Removed ${e.ideFoldersRemoved} dangling folder(s) from ${t} workspace(s)`)}if(e.openedCmux.length>0){a.info("\u2705 Reopened cmux workspaces:");for(let t of e.openedCmux)a.info(t)}!r.ideRan&&e.closedCmux.length===0&&e.openedCmux.length===0&&e.ideFoldersAdded===0&&e.ideFoldersRemoved===0&&a.info("\u2139\uFE0F Nothing to reload")},cn=w({name:"worktrees-reload",description:"Close all open cmux workspaces for the current release worktrees, then reopen the full set \u2014 the single window-restore command. Every configured editor (Cursor and/or Zed) is reconciled + relaunched (no per-window close). Disruptive: closes live cmux windows first. Safe to run from any branch. Use to refresh stale windows or to restore everything after a cold start (editor + cmux closed).",inputSchema:{},outputSchema:{closedCmux:$e.array($e.string()).describe("Titles of cmux workspaces a close was attempted for (best-effort)"),openedCmux:$e.array($e.string()).describe("Titles of cmux workspaces reopened during this run"),ideProviders:$e.array($e.string()).describe("Configured IDE providers that were reloaded (cursor | zed); empty if none configured"),ideFoldersAdded:$e.number().describe("Total worktree folders added across all configured editor workspaces"),ideFoldersRemoved:$e.number().describe("Total dangling worktree folders removed across all configured editor workspaces")},handler:ti});import op from"@inquirer/checkbox";import np from"@inquirer/confirm";import sp from"node:process";import{z as zr}from"zod";var oi=async e=>{let{confirmedCommand:r,all:t,versions:o}=e;m.start("worktrees-remove"),await D({operation:"remove worktrees",requiredBranch:"dev"});try{let n=await F("release");if(n.length===0)return a.info("\u2139\uFE0F No active worktrees to remove"),m.print(),{content:g(JSON.stringify({removedWorktrees:[],count:0},null,2)),structuredContent:{removedWorktrees:[],count:0}};let s=await k(),i=`${s}${G}`,l=[];if(t)l=n;else if(o)l=o.split(",").map(b=>ce(Z(b.trim())));else{m.setInteractive();let[b,v]=await Promise.all([P(),T()]),S=new Map(v.map(_=>[_.branch,E(_.title)]));l=await op({required:!0,message:"\u{1F33F} Select release branches",choices:A({branches:n,descriptions:b,types:S})})}let c=l.length===n.length;c?m.addOption("--all",!0):m.addOption("--versions",Be(l));let p=r?!0:await np({message:"Are you sure you want to proceed with these worktree changes?"});r||m.setInteractive(),p||(a.info("Operation cancelled. Exiting..."),sp.exit(0)),r||m.addOption("--yes",!0);let d=await J(),u=await Mr({branches:l,worktreeDir:i,repoName:d,pruneFolder:c});await Kr({projectRoot:s,worktreeDir:i,currentWorktrees:n,removedWorktrees:u,allowEditorRelaunch:!r}),ip(u),m.print();let h={removedWorktrees:u,count:u.length};return{content:g(JSON.stringify(h,null,2)),structuredContent:h}}catch(n){throw a.error({error:n},"\u274C Error managing worktrees"),new f(n,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"})}},ip=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")},ln=w({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:zr.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:zr.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:zr.array(zr.string()).describe("List of removed git worktree branches"),count:zr.number().describe("Number of git worktrees removed")},handler:oi});import ap from"@inquirer/confirm";import cp from"node:process";import{z as pn}from"zod";import{$ as lp}from"zx";var ni=async e=>{let{confirmedCommand:r}=e;m.start("worktrees-sync"),await D({operation:"sync worktrees",requiredBranch:"dev"});try{let t=await F("release"),o=await k(),n=`${o}${G}`,s=await pt(),i=r?!0:await ap({message:"Are you sure you want to proceed with these worktree changes?"});r||m.setInteractive(),i||(a.info("Operation cancelled. Exiting..."),cp.exit(0)),r||m.addOption("--yes",!0);let{branchesToRemove:l}=pp({releasePRsList:s,currentWorktrees:t}),c=await J(),p=await dp({branches:l,worktreeDir:n,repoName:c});await Kr({projectRoot:o,worktreeDir:n,currentWorktrees:t,removedWorktrees:p,allowEditorRelaunch:!1}),mp(p),m.print();let d={removedWorktrees:p,count:p.length};return{content:g(JSON.stringify(d,null,2)),structuredContent:d}}catch(t){throw a.error({error:t},"\u274C Error managing worktrees"),new f(t,{operation:"sync worktrees with remote",remediation:"ensure 'gh auth status' is ok and you can reach origin"})}},pp=e=>{let{releasePRsList:r,currentWorktrees:t}=e;return{branchesToRemove:t.filter(s=>Ae(s)).filter(s=>!r.includes(s))}},dp=async e=>{let{branches:r,worktreeDir:t,repoName:o}=e,n=[];for(let s of r)try{let i=`${t}/${s}`,l=re({repoName:o,branch:s});await Je(l),await lp`git worktree remove ${i}`,n.push(s)}catch(i){let l=new f(i,{operation:`remove stale worktree for ${s}`,remediation:"inspect the worktree dir manually; rerun with the branch checked out elsewhere"});a.error({error:i,branch:s,msg:l.message})}return n},mp=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")},dn=w({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:pn.array(pn.string()).describe("List of removed worktree branches"),count:pn.number().describe("Number of worktrees removed during sync")},handler:ni});var mn=[{cliName:"merge-dev",menuGroup:"release",mcpTool:ho,mcpExposed:!0},{cliName:"release-list",menuGroup:"release",mcpTool:bo,mcpExposed:!0},{cliName:"release-create",menuGroup:"release",mcpTool:Oo,mcpExposed:!0},{cliName:"release-desc-edit",menuGroup:"release",mcpTool:Fo,mcpExposed:!0},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:yo,mcpExposed:!0},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:Ro,mcpExposed:!0},{cliName:"release-deliver",menuGroup:"release",mcpTool:wo,mcpExposed:!1},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:sn,mcpExposed:!0},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:an,mcpExposed:!0},{cliName:"worktrees-reload",menuGroup:"worktrees",mcpTool:cn,mcpExposed:!0},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:ln,mcpExposed:!1},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:dn,mcpExposed:!0},{cliName:"audit",menuGroup:"environment",mcpTool:Jt,mcpExposed:!0},{cliName:"vendor",menuGroup:"environment",mcpTool:null,mcpExposed:!1},{cliName:"vendor-config",menuGroup:"environment",mcpTool:null,mcpExposed:!1},{cliName:"doctor",menuGroup:"environment",mcpTool:eo,mcpExposed:!1},{cliName:"init",menuGroup:"environment",mcpTool:null,mcpExposed:!1},{cliName:"version",menuGroup:"environment",mcpTool:Ho,mcpExposed:!0},{cliName:"config",menuGroup:"environment",mcpTool:null,mcpExposed:!1},{cliName:"env-status",menuGroup:"environment",mcpTool:po,mcpExposed:!0},{cliName:"env-list",menuGroup:"environment",mcpTool:lo,mcpExposed:!0},{cliName:"env-load",menuGroup:"environment",mcpTool:so,mcpExposed:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:ao,mcpExposed:!0},{cliName:"env-autoload",menuGroup:null,mcpTool:null,mcpExposed:!1},{cliName:"vendor-check",menuGroup:null,mcpTool:Jo,mcpExposed:!0},{cliName:"vendor-diff",menuGroup:null,mcpTool:zo,mcpExposed:!0},{cliName:"vendor-manifest",menuGroup:null,mcpTool:Uo,mcpExposed:!1},{cliName:"vendor-sync",menuGroup:null,mcpTool:qo,mcpExposed:!1}],up=()=>mn.flatMap(e=>e.mcpExposed&&e.mcpTool?[e.mcpTool]:[]),fp=e=>mn.flatMap(r=>r.menuGroup===e?[r.cliName]:[]);export{k as a,gn as b,vp as c,a as d,$n as e,W as f,x as g,ye as h,pe as i,R as j,Ht as k,jn as l,Xe as m,_m as n,Xn as o,Oe as p,oo as q,Tr as r,Fe as s,De as t,Re as u,Me as v,Le as w,ts as x,os as y,ss as z,is as A,as as B,ms as C,ws as D,ys as E,Rs as F,bs as G,Vc as H,Ps as I,As as J,js as K,Ks as L,Gs as M,qs as N,Hs as O,bt as P,ei as Q,ri as R,ti as S,oi as T,ni as U,up as V,fp as W};
166
- //# sourceMappingURL=chunk-RAAKYDVP.js.map
165
+ `);let l={worktrees:n,count:n.length};return{content:g(JSON.stringify(l,null,2)),structuredContent:l}},sn=w({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:lr.array(lr.object({version:lr.string().describe("Release version"),type:lr.enum(["regular","hotfix"]).describe("Release type"),description:lr.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:lr.number().describe("Number of worktrees")},handler:ri});import{z as $e}from"zod";var ti=async()=>{m.start("worktrees-reload");try{let e=await k(),r=`${e}${G}`,t=await F("release"),o=await J(),n=await ep({currentBranches:t,repoName:o}),[s,{opened:i}]=await Promise.all([rn({projectRoot:e,worktreeDir:r,currentBranches:t}),rp({worktreeDir:r,currentBranches:t,repoName:o})]),l={closedCmux:n,openedCmux:i,ideProviders:s.filter(c=>c.ran).map(c=>c.provider),ideFoldersAdded:s.reduce((c,p)=>c+p.added,0),ideFoldersRemoved:s.reduce((c,p)=>c+p.removed,0)};return tp(l,{ideRan:s.some(c=>c.ran)}),m.print(),{content:g(JSON.stringify(l,null,2)),structuredContent:{...l}}}catch(e){throw a.error({error:e},"\u274C Error reloading worktrees"),new f(e,{operation:"reload worktrees",remediation:"run 'worktrees-list' to confirm the branches exist"})}},ep=async e=>{let{currentBranches:r,repoName:t}=e;if(r.length===0)return[];let o=await Fr(),n=[];for(let s of r){let i=re({repoName:t,branch:s});o.has(ee(i))&&(await Je(i),n.push(i))}return n},rp=async e=>{let{worktreeDir:r,currentBranches:t,repoName:o}=e,n=[];for(let s of t){let i=re({repoName:o,branch:s});try{await jr({cwd:`${r}/${s}`,title:i}),n.push(i)}catch(l){a.warn({error:l,title:i},`\u26A0\uFE0F Failed to reopen cmux workspace for ${s}`)}}return{opened:n}},tp=(e,r)=>{if(e.closedCmux.length>0&&a.info(`\u{1F9F9} Closed ${e.closedCmux.length} cmux workspace(s)`),r.ideRan){let t=e.ideProviders.map(o=>tn(o)).join(", ");e.ideFoldersAdded>0&&a.info(`\u2705 Added ${e.ideFoldersAdded} folder(s) to ${t} workspace(s)`),e.ideFoldersRemoved>0&&a.info(`\u{1F9F9} Removed ${e.ideFoldersRemoved} dangling folder(s) from ${t} workspace(s)`)}if(e.openedCmux.length>0){a.info("\u2705 Reopened cmux workspaces:");for(let t of e.openedCmux)a.info(t)}!r.ideRan&&e.closedCmux.length===0&&e.openedCmux.length===0&&e.ideFoldersAdded===0&&e.ideFoldersRemoved===0&&a.info("\u2139\uFE0F Nothing to reload")},an=w({name:"worktrees-reload",description:"Close all open cmux workspaces for the current release worktrees, then reopen the full set \u2014 the single window-restore command. Every configured editor (Cursor and/or Zed) is reconciled + relaunched (no per-window close). Disruptive: closes live cmux windows first. Safe to run from any branch. Use to refresh stale windows or to restore everything after a cold start (editor + cmux closed).",inputSchema:{},outputSchema:{closedCmux:$e.array($e.string()).describe("Titles of cmux workspaces a close was attempted for (best-effort)"),openedCmux:$e.array($e.string()).describe("Titles of cmux workspaces reopened during this run"),ideProviders:$e.array($e.string()).describe("Configured IDE providers that were reloaded (cursor | zed); empty if none configured"),ideFoldersAdded:$e.number().describe("Total worktree folders added across all configured editor workspaces"),ideFoldersRemoved:$e.number().describe("Total dangling worktree folders removed across all configured editor workspaces")},handler:ti});import op from"@inquirer/checkbox";import np from"@inquirer/confirm";import sp from"node:process";import{z as zr}from"zod";var oi=async e=>{let{confirmedCommand:r,all:t,versions:o}=e;m.start("worktrees-remove"),await D({operation:"remove worktrees",requiredBranch:"dev"});try{let n=await F("release");if(n.length===0)return a.info("\u2139\uFE0F No active worktrees to remove"),m.print(),{content:g(JSON.stringify({removedWorktrees:[],count:0},null,2)),structuredContent:{removedWorktrees:[],count:0}};let s=await k(),i=`${s}${G}`,l=[];if(t)l=n;else if(o)l=o.split(",").map(b=>ce(Z(b.trim())));else{m.setInteractive();let[b,v]=await Promise.all([P(),T()]),S=new Map(v.map(_=>[_.branch,E(_.title)]));l=await op({required:!0,message:"\u{1F33F} Select release branches",choices:A({branches:n,descriptions:b,types:S})})}let c=l.length===n.length;c?m.addOption("--all",!0):m.addOption("--versions",Be(l));let p=r?!0:await np({message:"Are you sure you want to proceed with these worktree changes?"});r||m.setInteractive(),p||(a.info("Operation cancelled. Exiting..."),sp.exit(0)),r||m.addOption("--yes",!0);let d=await J(),u=await Mr({branches:l,worktreeDir:i,repoName:d,pruneFolder:c});await Kr({projectRoot:s,worktreeDir:i,currentWorktrees:n,removedWorktrees:u,allowEditorRelaunch:!r}),ip(u),m.print();let h={removedWorktrees:u,count:u.length};return{content:g(JSON.stringify(h,null,2)),structuredContent:h}}catch(n){throw a.error({error:n},"\u274C Error managing worktrees"),new f(n,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"})}},ip=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")},cn=w({name:"worktrees-remove",description:'Remove local git worktrees for release branches. When everything is removed, also runs "git worktree prune" to clear stale metadata; the worktrees directory and its release/feature subfolders are left in place. 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:zr.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:zr.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:zr.array(zr.string()).describe("List of removed git worktree branches"),count:zr.number().describe("Number of git worktrees removed")},handler:oi});import ap from"@inquirer/confirm";import cp from"node:process";import{z as ln}from"zod";import{$ as lp}from"zx";var ni=async e=>{let{confirmedCommand:r}=e;m.start("worktrees-sync"),await D({operation:"sync worktrees",requiredBranch:"dev"});try{let t=await F("release"),o=await k(),n=`${o}${G}`,s=await pt(),i=r?!0:await ap({message:"Are you sure you want to proceed with these worktree changes?"});r||m.setInteractive(),i||(a.info("Operation cancelled. Exiting..."),cp.exit(0)),r||m.addOption("--yes",!0);let{branchesToRemove:l}=pp({releasePRsList:s,currentWorktrees:t}),c=await J(),p=await dp({branches:l,worktreeDir:n,repoName:c});await Kr({projectRoot:o,worktreeDir:n,currentWorktrees:t,removedWorktrees:p,allowEditorRelaunch:!1}),mp(p),m.print();let d={removedWorktrees:p,count:p.length};return{content:g(JSON.stringify(d,null,2)),structuredContent:d}}catch(t){throw a.error({error:t},"\u274C Error managing worktrees"),new f(t,{operation:"sync worktrees with remote",remediation:"ensure 'gh auth status' is ok and you can reach origin"})}},pp=e=>{let{releasePRsList:r,currentWorktrees:t}=e;return{branchesToRemove:t.filter(s=>Ae(s)).filter(s=>!r.includes(s))}},dp=async e=>{let{branches:r,worktreeDir:t,repoName:o}=e,n=[];for(let s of r)try{let i=`${t}/${s}`,l=re({repoName:o,branch:s});await Je(l),await lp`git worktree remove ${i}`,n.push(s)}catch(i){let l=new f(i,{operation:`remove stale worktree for ${s}`,remediation:"inspect the worktree dir manually; rerun with the branch checked out elsewhere"});a.error({error:i,branch:s,msg:l.message})}return n},mp=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")},pn=w({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:ln.array(ln.string()).describe("List of removed worktree branches"),count:ln.number().describe("Number of worktrees removed during sync")},handler:ni});var dn=[{cliName:"merge-dev",menuGroup:"release",mcpTool:go,mcpExposed:!0},{cliName:"release-list",menuGroup:"release",mcpTool:Ro,mcpExposed:!0},{cliName:"release-create",menuGroup:"release",mcpTool:_o,mcpExposed:!0},{cliName:"release-desc-edit",menuGroup:"release",mcpTool:Oo,mcpExposed:!0},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:vo,mcpExposed:!0},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:ko,mcpExposed:!0},{cliName:"release-deliver",menuGroup:"release",mcpTool:ho,mcpExposed:!1},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:nn,mcpExposed:!0},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:sn,mcpExposed:!0},{cliName:"worktrees-reload",menuGroup:"worktrees",mcpTool:an,mcpExposed:!0},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:cn,mcpExposed:!1},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:pn,mcpExposed:!0},{cliName:"audit",menuGroup:"environment",mcpTool:Bt,mcpExposed:!0},{cliName:"vendor",menuGroup:"environment",mcpTool:null,mcpExposed:!1},{cliName:"vendor-config",menuGroup:"environment",mcpTool:null,mcpExposed:!1},{cliName:"doctor",menuGroup:"environment",mcpTool:Qt,mcpExposed:!1},{cliName:"init",menuGroup:"environment",mcpTool:null,mcpExposed:!1},{cliName:"version",menuGroup:"environment",mcpTool:qo,mcpExposed:!0},{cliName:"config",menuGroup:"environment",mcpTool:null,mcpExposed:!1},{cliName:"env-status",menuGroup:"environment",mcpTool:lo,mcpExposed:!0},{cliName:"env-list",menuGroup:"environment",mcpTool:co,mcpExposed:!0},{cliName:"env-load",menuGroup:"environment",mcpTool:no,mcpExposed:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:io,mcpExposed:!0},{cliName:"env-autoload",menuGroup:null,mcpTool:null,mcpExposed:!1},{cliName:"vendor-check",menuGroup:null,mcpTool:Bo,mcpExposed:!0},{cliName:"vendor-diff",menuGroup:null,mcpTool:Go,mcpExposed:!0},{cliName:"vendor-manifest",menuGroup:null,mcpTool:zo,mcpExposed:!1},{cliName:"vendor-sync",menuGroup:null,mcpTool:Uo,mcpExposed:!1}],up=()=>dn.flatMap(e=>e.mcpExposed&&e.mcpTool?[e.mcpTool]:[]),fp=e=>dn.flatMap(r=>r.menuGroup===e?[r.cliName]:[]);export{k as a,fn as b,vp as c,a as d,Tn as e,W as f,x as g,ye as h,pe as i,R as j,qt as k,Dn as l,Xe as m,_m as n,Zn as o,Oe as p,to as q,Tr as r,Fe as s,De as t,Re as u,Me as v,Le as w,rs as x,ts as y,ns as z,ss as A,is as B,ds as C,ws as D,ys as E,Rs as F,bs as G,Vc as H,Ps as I,As as J,js as K,Ks as L,Gs as M,qs as N,Hs as O,Rt as P,ei as Q,ri as R,ti as S,oi as T,ni as U,up as V,fp as W};
166
+ //# sourceMappingURL=chunk-PWOX6B3T.js.map