infra-kit 0.3.2 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-AJW5M44V.js → chunk-2C2U5ACS.js} +48 -48
- package/dist/chunk-2C2U5ACS.js.map +7 -0
- package/dist/{chunk-FTCM2766.js → chunk-OKKB3AOU.js} +2 -2
- package/dist/{chunk-FTCM2766.js.map → chunk-OKKB3AOU.js.map} +1 -1
- package/dist/cli.js +1 -1
- package/dist/dev-server.js +1 -1
- package/dist/dev-wizard-run-AYSSMBZV.js +2 -0
- package/dist/dev-wizard-run-AYSSMBZV.js.map +7 -0
- package/dist/mcp.js +1 -1
- package/dist/update-check.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-AJW5M44V.js.map +0 -7
- package/dist/dev-wizard-run-5NOQIMR5.js +0 -2
- package/dist/dev-wizard-run-5NOQIMR5.js.map +0 -7
|
@@ -1,23 +1,23 @@
|
|
|
1
|
-
import{a as ts,b as pt,c as Zt,d as os,e as ns,f as ss,g as is,h as Yt,i as as,j as dt,k as er,l as mt,p as ut,q as de,r as rr}from"./chunk-7F5YKMWK.js";import{a as lt}from"./chunk-
|
|
2
|
-
${e.packageName} \u2014 ${r}`);for(let t of e.checks){let o=t.status==="pass"?"[PASS]":"[FAIL]";l.info(` ${o} ${t.name}: ${t.message}`)}},ms=async(e={})=>{let r=await
|
|
3
|
-
${o?"\u2705 All valid":"\u274C Audit failed"} (${t.length} checked)`);let s={allPassed:o,packages:t.map(n=>({name:n.packageName,passed:n.passed,checks:n.checks}))};return{content:g(JSON.stringify(s,null,2)),structuredContent:s}},
|
|
4
|
-
`),fs=(e=
|
|
1
|
+
import{a as ts,b as pt,c as Zt,d as os,e as ns,f as ss,g as is,h as Yt,i as as,j as dt,k as er,l as mt,p as ut,q as de,r as rr}from"./chunk-7F5YKMWK.js";import{a as lt}from"./chunk-OKKB3AOU.js";import{a as ot,c as z,d as k,e as ct,f as q,i as u,k as rs,l as $,m as D}from"./chunk-IPF7ILCB.js";import{F as zn,G as qn,I as Hn,J as Zn,K as ze,L as Yn,M as Ht,N as re,P as N,Q as O,R as Xn,S as qe,a as jn,b as rt,c as _,d as pe,e as ye,f as Mn,g as qt,h as G,i as S,j as tt,k as Ln,l as V,m as w,n as Wn,o as Vn,p as Bn,q as ee,r as Jn,s as Kn,v as l,x as Un,y as Gn}from"./chunk-KHEUED4B.js";import{a as B,b as nt,c as wr,d as Qn,e as st,f as He,g as Ze,h as it,i as Ye,j as Ie,k as Xe,l as at,n as Qe,o as es,p as Ne,q as Oe,r as te}from"./chunk-CHETBZ6M.js";import Er from"node:path";import $a from"node:process";import{z as J}from"zod";var we={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},Xt={requiredScripts:["build","dev","test","qa","infra-kit-check","fix"],requiredFiles:["turbo.json","pnpm-workspace.yaml"],turboTasks:["build","test","ts-check","eslint-check","prettier-check","infra-kit-check"]},Qt=(e,r=we)=>({requiredScripts:e.requiredScripts??[...r.requiredScripts],requiredFiles:e.requiredFiles??[...r.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...r.turboTasks]});import pa from"node:fs/promises";var me=async e=>{try{return await pa.access(e),!0}catch{return!1}};import Ea from"node:path";import{packageConfigSchema as da}from"@slip-stream-kit/config/internal";import cs from"node:fs/promises";import ls from"node:path";import{pathToFileURL as ma}from"node:url";import{z as ua}from"zod";var Re="infra-kit.config.ts",eo=async e=>{try{let r=await cs.readFile(ls.join(e,"package.json"),"utf-8");return JSON.parse(r)}catch{return{}}},Rr=async(e,r=we)=>{let t=ls.join(e,Re);if(!await me(t))throw new Error(`${Re} not found at ${t}`);let o=await cs.stat(t),i=(await import(`${ma(t).href}?mtime=${Number(o.mtimeMs)}`)).default;if(i===void 0)throw new Error(`${Re} at ${t} has no default export`);let a=typeof i=="function"?await i():i,c=da.safeParse(a);if(!c.success)throw new Error(`Invalid ${Re} at ${t}: ${ua.prettifyError(c.error)}`);return Qt(c.data,r)};import ps from"node:fs/promises";import ft from"node:path";import fa from"yaml";var ga="pnpm-workspace.yaml",ha=async e=>(await ps.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(t=>t.isDirectory()).map(t=>ft.join(e,t.name)),va=async(e,r)=>{let t=[];for(let o of e){if(r==="*"){t.push(...await ha(o));continue}let s=ft.join(o,r);await me(s)&&t.push(s)}return t},ka=async(e,r)=>{let t=[e];for(let o of r.split("/"))t=await va(t,o);return t},br=async e=>{let r=await ps.readFile(ft.join(e,ga),"utf-8"),o=((fa.parse(r)??{}).packages??[]).filter(n=>!n.startsWith("!")&&!n.startsWith("vendor")),s=new Set;for(let n of o){let i=await ka(e,n);for(let a of i)await me(ft.join(a,"package.json"))&&s.add(a)}return[...s].sort()};var ro=async(e,r=we)=>{try{let t=await Rr(e,r);return{check:{name:Re,status:"pass",message:"present and valid"},rules:t}}catch(t){return{check:{name:Re,status:"fail",message:t.message},rules:null}}};import ya from"node:fs/promises";import wa from"node:path";var to=async(e,r)=>Promise.all(r.map(async t=>{let o=await ya.stat(wa.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 oo=(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 Ra from"node:fs/promises";import ba from"node:path";var tr="turbo.json",no=async(e,r)=>{if(r.length===0)return[];let t;try{let s=await Ra.readFile(ba.join(e,tr),"utf-8");t=JSON.parse(s)}catch(s){return[{name:tr,status:"fail",message:`cannot read/parse ${tr}: ${s.message}`}]}let o=t.tasks;return o===null||typeof o!="object"?[{name:tr,status:"fail",message:`no "tasks" object defined in ${tr}`}]:r.map(s=>{let n=s in o||`//#${s}`in o;return{name:`turbo:${s}`,status:n?"pass":"fail",message:n?"defined":`missing turbo task "${s}" in ${tr}`}})};var so=async(e,r=we)=>{let t=await eo(e),o=t.name??Ea.basename(e),{check:s,rules:n}=await ro(e,r),i=[s];n&&(i.push(...oo(t.scripts??{},n.requiredScripts)),i.push(...await to(e,n.requiredFiles)),i.push(...await no(e,n.turboTasks)));let a=i.every(c=>c.status==="pass");return{packageDir:e,packageName:o,checks:i,passed:a}};var g=e=>[{type:"text",text:e}],v=e=>e;import{loadDev as xa}from"@slip-stream-kit/config/internal";import Pa from"node:path";var Ta=(e,r)=>{let t=new Set;for(let o of Object.values(e))for(let s of Object.keys(qn(o,r).proxy))t.add(s);return[...t]},Ca=async(e,r)=>{let t={},o=[];return await Promise.all(r.map(async s=>{try{let i=(await xa(Pa.join(e,"apps",s,"ui")))?.proxy?.routes;if(!i)return;t[s]=Object.fromEntries(Object.entries(i).map(([a,c])=>[a,c.packageName]))}catch(n){o.push({app:s,message:n instanceof Error?n.message:String(n)})}})),{routePkg:(s,n)=>t[s]?.[n],loadErrors:o}},Sa=(e,r)=>[...r.map(t=>({name:`devServersPresets:config:${t.app}`,status:"fail",message:`could not load apps/${t.app}/ui/infra-kit.config.ts (referenced by a preset proxy override): ${t.message}`})),...e.map(t=>({name:`devServersPresets:${t.preset}`,status:"fail",message:t.message}))],ds=async e=>{let r=(await O()).devServersPresets;if(!r||Object.keys(r).length===0)return null;let t=zn(r);if(t.length>0){let m=t.map(h=>({name:`devServersPresets:${h.preset}`,status:"fail",message:h.message}));return{packageDir:e,packageName:"devServersPresets",checks:m,passed:!1}}let o=Un(e),s=Gn(e),n={api:o.map(m=>m.name),ui:s.map(m=>m.name)},{routePkg:i,loadErrors:a}=await Ca(e,Ta(r,n)),c={discovered:n,apiPkgByApp:Object.fromEntries(o.map(m=>[m.name,m.packageName])),routePkg:i},p=Sa(Hn(r,c),a),d=p.length===0?[{name:"devServersPresets:proxy-locality",status:"pass",message:"every local proxy override resolves to a backend the preset launches"}]:p;return{packageDir:e,packageName:"devServersPresets",checks:d,passed:p.length===0}};var _a=async e=>{let r=Er.resolve(e);for(;r!==Er.dirname(r);){if(await me(Er.join(r,"package.json")))return r;r=Er.dirname(r)}if(await me(Er.join(r,"package.json")))return r;throw new Error(`No package.json found in or above ${e}`)},Aa=async e=>e.root?[{dir:await w(),baseline:Xt}]:e.all?(await br(await w())).map(t=>({dir:t})):[{dir:await _a(e.cwd??$a.cwd())}],Ia=e=>{let r=e.passed?"PASS":"FAIL";l.info(`
|
|
2
|
+
${e.packageName} \u2014 ${r}`);for(let t of e.checks){let o=t.status==="pass"?"[PASS]":"[FAIL]";l.info(` ${o} ${t.name}: ${t.message}`)}},ms=async(e={})=>{let r=await Aa(e),t=[];for(let n of r)t.push(await so(n.dir,n.baseline));if(e.root){let n=await ds(r[0].dir);n&&t.push(n)}for(let n of t)Ia(n);let o=t.every(n=>n.passed);l.info(`
|
|
3
|
+
${o?"\u2705 All valid":"\u274C Audit failed"} (${t.length} checked)`);let s={allPassed:o,packages:t.map(n=>({name:n.packageName,passed:n.passed,checks:n.checks}))};return{content:g(JSON.stringify(s,null,2)),structuredContent:s}},Na={all:J.boolean().optional().describe("Audit every non-vendor workspace package"),root:J.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},Oa={allPassed:J.boolean().describe("Whether every audited package passed all checks"),packages:J.array(J.object({name:J.string(),passed:J.boolean(),checks:J.array(J.object({name:J.string(),status:J.enum(["pass","fail"]),message:J.string()}))})).describe("Per-package check results")},io=v({name:"audit",description:"Audit packages against infra-kit.config.ts rules (config present and valid, required scripts, required files, and turbo tasks for the root). Defaults to the current package; all=true audits every non-vendor workspace package; root=true audits the monorepo root.",inputSchema:Na,outputSchema:Oa,handler:e=>ms({all:e.all,root:e.root})});import j from"node:fs";import jc from"node:os";import ne from"node:path";import{z as pr}from"zod";import{$ as To}from"zx";import{execFileSync as Da}from"node:child_process";var us=(e,r)=>{let t=e.filter(o=>!o.live).map(o=>o.name);return r?{prunable:[],withheld:t}:{prunable:t,withheld:[]}},Fa=[/\binfra-kit\s+dev\b/,/cli\.js\s+dev\b/,/dev-server\.(?:js|ts)\b/],ja=e=>Fa.some(r=>r.test(e)),Ma="/bin/ps",La=()=>Da(Ma,["-eo","command="],{encoding:"utf8",maxBuffer:8<<20}).split(`
|
|
4
|
+
`),fs=(e=La)=>{try{return e().some(ja)}catch{return!0}};import Za from"@inquirer/select";import{Buffer as Ya}from"node:buffer";import Xa from"node:fs";import Qa from"node:path";import go from"node:process";import{z as _r}from"zod";import{$ as vt}from"zx";var Wa="Could not find requested project",Va="Could not find requested config",gs="Invalid Auth token",hs="does not have access to requested config",xr=e=>e.includes(gs)||e.includes(hs)?"auth":e.includes(Wa)?"project":e.includes(Va)?"config":"unknown",Pr=e=>e.includes(hs)?"mis-scoped":e.includes(gs)?"revoked":null;var vs=e=>[`Doppler rejected the service token for env "${e}" \u2014 it is invalid, revoked, or scoped to a different config.`,`Fix: run \`infra-kit env-token-set ${e}\` with a token scoped to that config.`,"CI / agents: set INFRA_KIT_ENV_TOKEN to a token scoped to that config."].join(`
|
|
5
5
|
`),or=class extends ot{authKind;constructor(r,t=null,o){super(o??vs(r),r),this.name="DopplerAuthError",this.authKind=t}};var ao=({kind:e,project:r,config:t,available:o})=>{let s=e==="project"?[`Doppler project "${r}" not found (set in infra-kit.json \u2192 envManagement.config.name).`]:[`Doppler config "${t}" not found in project "${r}".`];if(o&&o.length>0){let n=e==="project"?"Available projects":`Available configs in "${r}"`;s.push(`${n}: ${o.join(", ")}.`)}return s.push(e==="project"?"Fix: update envManagement.config.name to an existing project, or create it in Doppler.":"Fix: pass an existing config, or create it in Doppler."),s.join(`
|
|
6
|
-
`)};import{$ as gt}from"zx";var Tr=e=>{if(e===null||typeof e!="object")return;let r=e.stderr;return typeof r=="string"&&r.length>0?r:void 0},
|
|
7
|
-
`);import ys from"node:fs/promises";import co from"node:path";import
|
|
6
|
+
`)};import{$ as gt}from"zx";var Tr=e=>{if(e===null||typeof e!="object")return;let r=e.stderr;return typeof r=="string"&&r.length>0?r:void 0},Ba=(e,r)=>{let t=r.stderrExcerpt??Tr(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(Ba(r,t),{cause:r}),this.name="OperationError",this.operation=t.operation,this.remediation=t.remediation}};var Ja=5e3,Ka="DOPPLER_CONFIG",De=async()=>{let{envManagement:e}=await O();return e.config.name},Cr=async({childEnv:e,project:r,config:t})=>{let o=gt.quiet;gt.quiet=!0;try{let n=(await gt({env:e})`doppler secrets get ${Ka} --plain --project ${r} --config ${t}`.timeout(Ja)).stdout.trim();return n!==t?{outcome:"mis-scoped",scopedTo:n}:{outcome:"valid",scopedTo:n}}catch(s){return{outcome:Ua(s)}}finally{gt.quiet=o}},Ua=e=>{let r=Tr(e)??(e instanceof Error?e.message:String(e));return xr(r)!=="auth"?"unreachable":Pr(r)??"unreachable"};import ks from"node:process";var H="INFRA_KIT_ENV_TOKEN",nr=async e=>{let r=ks.env[H];if(r)return{token:r,source:"env"};let o=(await q())?.envs[e];if(o)return{token:o,source:"store"};throw new ot(Ga(e,await ct()),e)},Ym=async e=>ks.env[H]?!0:!!(await q())?.envs[e],Ga=(e,r)=>[`No Doppler service token for env "${e}".`,`Mint one at https://dashboard.doppler.com \u2014 this project \u2192 config "${e}" \u2192 Access tab \u2192 "Generate Service Token".`,`Fix: run \`infra-kit env-token-set ${e}\` and paste it.`,`It is stored in ${k(r)} (mode 0600, never in the repo).`,`CI / agents: set ${H} instead \u2014 it takes precedence and needs no home config.`].join(`
|
|
7
|
+
`);import ys from"node:fs/promises";import co from"node:path";import za from"yaml";var ws=".github/workflows",Sr=async e=>{let r=await w();return Rs(co.resolve(r,ws,e))},lo=async()=>{let e=await w(),r=co.resolve(e,ws),t;try{t=await ys.readdir(r)}catch{return[]}let o=t.filter(n=>n.endsWith(".yml")||n.endsWith(".yaml")).sort(),s=await Promise.all(o.map(n=>Rs(co.resolve(r,n))));return[...new Set(s.flat())]},Rs=async e=>{let r;try{r=za.parse(await ys.readFile(e,"utf-8"))}catch{return[]}let t=sr(r,"on")??sr(r,"true"),o=sr(sr(sr(sr(t,"workflow_dispatch"),"inputs"),"environment"),"options");return Array.isArray(o)?o.filter(s=>typeof s=="string"&&s.length>0):[]},sr=(e,r)=>{if(!(typeof e!="object"||e===null||Array.isArray(e)))return e[r]};var ht=async()=>{let e=await lo(),r=await q(),t=e.map(n=>({env:n,source:"gh-workflow"})),o=new Set(e),s=Object.keys(r?.envs??{}).filter(n=>!o.has(n)).sort().map(n=>({env:n,source:"token-only"}));return[...t,...s]},Fe=async()=>(await ht()).map(r=>r.env);import bs from"node:fs";import{$ as qa}from"zx";import je from"node:fs";import $r from"node:path";var po=({autoLoaded:e,projectDir:r,canonicalProjectRoot:t})=>!e||!r||!t?!1:t===r,ue=e=>{if(!e)return"";try{return je.realpathSync(e)}catch{return""}},mo=(e,r)=>{try{let t=Ne(e);je.mkdirSync(t,{recursive:!0,mode:448}),Oe($r.join(t,B),r,384)}catch(t){l.debug(`warm-cache write skipped: ${t.message}`)}},uo=(e=Date.now(),r=wr)=>{let t=es(),o;try{o=je.readdirSync(t,{withFileTypes:!0})}catch{return}for(let s of o){if(!s.isDirectory())continue;let n=$r.join(t,s.name);try{let{mtimeMs:i}=je.statSync($r.join(n,B));e-i>=r*1e3&&je.rmSync(n,{recursive:!0,force:!0})}catch{}}},fo=(e,r)=>{try{let t=Ne(e);if(r){je.rmSync(t,{recursive:!0,force:!0});return}if(!je.existsSync($r.join(t,B)))return;Oe($r.join(t,nt),`# infra-kit warm cache cleared
|
|
8
8
|
`,384)}catch(t){l.debug(`warm-cache invalidate skipped: ${t.message}`)}};var Es=e=>e.split(`
|
|
9
|
-
`).filter(r=>r.startsWith("worktree ")).map(r=>r.slice(9).trim()).filter(Boolean),
|
|
9
|
+
`).filter(r=>r.startsWith("worktree ")).map(r=>r.slice(9).trim()).filter(Boolean),Ha=async()=>{let e;try{e=(await qa({quiet:!0})`git worktree list --porcelain`).stdout}catch(t){return l.debug(`warm-cache purge skipped (not a git repo?): ${t.message}`),[]}let r=[];for(let t of Es(e)){let o=ue(t);if(!o)continue;let s=Ne(o);try{if(!bs.existsSync(s))continue;bs.rmSync(s,{recursive:!0,force:!0}),r.push(s)}catch(n){l.debug(`warm-cache purge skipped for ${s}: ${n.message}`)}}return r};var ec=e=>e?[`${Ie}=${Me("1")}`]:[`unset ${Ie}`,`unset ${Xe}`],rc="DOPPLER_CONFIG",xs=new Set(["DOPPLER_TOKEN",H]),Ps=!1,tc=e=>{e.length===0||Ps||(Ps=!0,l.warn(`infra-kit: not exporting ${e.join(", ")} from Doppler into your shell \u2014 a service token must not be sourced into every process.`))},Cs=({pairs:e,config:r,project:t,projectRoot:o,loadedAt:s,autoLoaded:n})=>{let i=e.filter(([a])=>!xs.has(a));return tc(e.filter(([a])=>xs.has(a)).map(([a])=>a)),["set -a",...i.map(([a,c])=>`${a}=${Me(c)}`),`${st}=${Me(r)}`,`${He}=${Me(r)}`,`${Ze}=${Me(t)}`,`${it}=${Me(o)}`,`${Ye}=${Me(s)}`,...ec(n),"set +a"]},oc=async()=>{try{return await w()}catch{return""}},Ss=async({config:e,autoLoaded:r=!1,beforeWrite:t,projectDir:o})=>{let s=await De(),n=await oc(),i=await ic(s,e),a=new Date().toISOString(),p=`${Cs({pairs:i,config:e,project:s,projectRoot:n,loadedAt:a,autoLoaded:r}).join(`
|
|
10
10
|
`)}
|
|
11
|
-
`,d=Qe(),m=
|
|
12
|
-
`),u.print();let s={filePath:o.filePath,variableCount:o.variableCount,project:o.project,config:o.config};return{content:g(JSON.stringify(s,null,2)),structuredContent:s}},Ts=1024*1024,
|
|
13
|
-
Fix: run \`infra-kit env-token-set ${r}\` with a token scoped to "${r}".`)},
|
|
11
|
+
`,d=Qe(),m=Qa.resolve(d,B);if(t&&!t())return null;Xa.mkdirSync(d,{recursive:!0,mode:448}),Oe(m,p,384);let h=ue(n);return po({autoLoaded:r,projectDir:o,canonicalProjectRoot:h})&&(mo(o,p),uo()),{filePath:m,variableCount:i.length,project:s,config:e}},$s=async e=>{let{config:r}=e,t="";if(r)t=r;else{let n=await Fe();u.setInteractive(),t=await $(i=>Za({message:"Select environment config",choices:n.map(a=>({name:a,value:a}))},i),{output:go.stderr})}u.addOption("--config",t);let o=await Ss({config:t,autoLoaded:!1});if(!o)throw new Error("env-load: write was unexpectedly aborted");go.stdout.write(`${o.filePath}
|
|
12
|
+
`),u.print();let s={filePath:o.filePath,variableCount:o.variableCount,project:o.project,config:o.config};return{content:g(JSON.stringify(s,null,2)),structuredContent:s}},Ts=1024*1024,nc=3e4,sc=["DOPPLER_TOKEN","DOPPLER_PROJECT","DOPPLER_CONFIG"],ir=(e,r=go.env)=>{let t={...r};for(let o of sc)delete t[o];return t.DOPPLER_TOKEN=e,t},ic=async(e,r)=>{let{token:t}=await nr(r),o=ir(t),s=vt.quiet;vt.quiet=!0;try{let n;try{n=await vt({env:o})`doppler secrets download --no-file --format json --project ${e} --config ${r}`.timeout(nc)}catch(a){throw ac(a,e,r)}cc(n.stdout);let i=As(n.stdout);return _s(i,r),i}finally{vt.quiet=s}},_s=(e,r)=>{let t=e.find(([o])=>o===rc)?.[1];if(!(t===void 0||t===r))throw new or(r,null,`Doppler returned secrets for config "${t}" but "${r}" was requested \u2014 the service token for env "${r}" is scoped to the wrong config. Refusing to load another environment's secrets.
|
|
13
|
+
Fix: run \`infra-kit env-token-set ${r}\` with a token scoped to "${r}".`)},ac=(e,r,t)=>{let o=Tr(e)??(e instanceof Error?e.message:String(e)),s=xr(o);return s==="auth"?new or(t,Pr(o)):s==="unknown"?e instanceof Error?e:new Error(String(e)):new Error(ao({kind:s,project:r,config:t,available:null}))},cc=e=>{let r=Ya.byteLength(e,"utf-8");if(r>Ts)throw new Error(`doppler returned unexpectedly large output (${r} bytes > ${Ts}) \u2014 refusing to write to disk`)},Me=e=>`'${e.replaceAll("'","'\\''")}'`,lc=/^[A-Z_]\w*$/i,As=e=>{let r;try{r=JSON.parse(e)}catch{throw new Error(`doppler returned non-JSON output for env-load (got: ${JSON.stringify(e.slice(0,80))})`)}if(r===null||typeof r!="object"||Array.isArray(r))throw new Error("doppler returned unexpected JSON shape for env-load (expected an object of KEY: value pairs)");let t=[];for(let[o,s]of Object.entries(r)){if(!lc.test(o))throw new Error(`doppler returned an invalid env var name for env-load (got: ${JSON.stringify(o.slice(0,80))})`);if(typeof s!="string")throw new TypeError(`doppler returned a non-string value for "${o}" (got ${typeof s})`);t.push([o,s])}if(t.length===0)throw new Error("doppler returned empty output for env-load");return t},ho=v({name:"env-load",description:'Download the env vars for a Doppler config and write them to a temporary shell script. Does NOT mutate the calling process \u2014 returns the path to a script that must be sourced ("source <filePath>") for the vars to take effect. The infra-kit shell wrapper auto-sources; direct MCP callers must handle sourcing themselves or surface filePath to the user. "config" is required when invoked via MCP (the CLI interactive picker is unreachable without a TTY).',inputSchema:{config:_r.string().describe('Doppler config / environment name to load (e.g. "dev", "arthur", "renana"). Required for MCP calls.')},outputSchema:{filePath:_r.string().describe("Path to the file that must be sourced to apply variables"),variableCount:_r.number().describe("Number of variables loaded"),project:_r.string().describe("Doppler project name"),config:_r.string().describe("Doppler config name")},handler:$s});import F from"node:fs";import Ir from"node:path";var ar=(e,r,t)=>{let o=e.indexOf(r),s=e.indexOf(t);return o!==-1&&s!==-1&&s>=o},be=(e,r,t)=>{let o=e.indexOf(r),s=e.indexOf(t);if(o===-1||s===-1||s<o)return null;let n=e.slice(0,o).replace(/\n+$/,""),i=e.slice(s+t.length).replace(/^\n+/,"");return n+(i?`
|
|
14
14
|
${i}`:"")};var Is=(e,r,t)=>`${e}
|
|
15
15
|
${r}
|
|
16
|
-
${t}`,Ar=({content:e,body:r,startMarker:t,endMarker:o,placement:s="replace-in-place"})=>{let n=Is(t,r,o),i=ar(e,t,o);if(s==="replace-in-place"&&i){let p=e.indexOf(t),d=e.indexOf(o)+o.length;return e.slice(0,p)+n+e.slice(d)}let c=(i?
|
|
16
|
+
${t}`,Ar=({content:e,body:r,startMarker:t,endMarker:o,placement:s="replace-in-place"})=>{let n=Is(t,r,o),i=ar(e,t,o);if(s==="replace-in-place"&&i){let p=e.indexOf(t),d=e.indexOf(o)+o.length;return e.slice(0,p)+n+e.slice(d)}let c=(i?be(e,t,o)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
|
|
17
17
|
${n}
|
|
18
18
|
`:`${n}
|
|
19
|
-
`};var Nr="<!-- infra-kit:begin -->",Or="<!-- infra-kit:end -->",
|
|
20
|
-
`),Ns=e=>{if(F.existsSync(e)&&F.lstatSync(e).isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},Os=e=>{let r=new Date().toISOString().replace(/[:.]/g,"-");F.copyFileSync(e,`${e}.backup.${r}`)},Ds=(e,r)=>{Ns(e);let t=F.existsSync(e);return(t?F.readFileSync(e,"utf-8"):null)===r?"unchanged":(t&&Os(e),F.mkdirSync(Ir.dirname(e),{recursive:!0}),F.writeFileSync(e,r,"utf-8"),t?"updated":"created")},
|
|
19
|
+
`};var Nr="<!-- infra-kit:begin -->",Or="<!-- infra-kit:end -->",pc="<!-- infra-kit:version ",dc="<!-- infra-kit:import:begin -->",mc="<!-- infra-kit:import:end -->",uc="AGENTS.md",fc="CLAUDE.md",gc=e=>`${pc}${e} -->`,hc=e=>[gc(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(`
|
|
20
|
+
`),Ns=e=>{if(F.existsSync(e)&&F.lstatSync(e).isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},Os=e=>{let r=new Date().toISOString().replace(/[:.]/g,"-");F.copyFileSync(e,`${e}.backup.${r}`)},Ds=(e,r)=>{Ns(e);let t=F.existsSync(e);return(t?F.readFileSync(e,"utf-8"):null)===r?"unchanged":(t&&Os(e),F.mkdirSync(Ir.dirname(e),{recursive:!0}),F.writeFileSync(e,r,"utf-8"),t?"updated":"created")},vc=(e,r)=>F.existsSync(e)?F.readFileSync(e,"utf-8"):r,kc=(e,r,t)=>{let o=F.readFileSync(e,"utf-8");if(!ar(o,r,t))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},yc=e=>{if(!F.existsSync(e))return"unchanged";Ns(e);let r=F.readFileSync(e,"utf-8"),t=be(r,Nr,Or);return t===null?"unchanged":t.trim()===""?(Os(e),F.rmSync(e),"removed"):Ds(e,t)},Fs=async()=>{let e;try{e=(await N()).main}catch{return l.info("Skipped agent-instruction files \u2014 not inside an infra-kit repo"),{skipped:!0,root:null,written:[]}}if(!F.existsSync(e))return l.info("Skipped agent-instruction files \u2014 no infra-kit.json at the repo root"),{skipped:!0,root:null,written:[]};let r=Ir.dirname(e),t=lt.version,o=hc(t),s=Ir.join(r,uc),n=Ir.join(r,fc),i=vc(n,"");i=be(i,dc,mc)??i,i=Ar({content:i,body:o,startMarker:Nr,endMarker:Or,placement:"replace-in-place"});let a=[{path:n,action:Ds(n,i)},{path:s,action:yc(s)}];kc(n,Nr,Or);for(let c of a)c.action==="unchanged"&&c.path!==n||l.info(` ${c.action.padEnd(9)} ${Ir.relative(r,c.path)}`);return l.info(`Agent-instruction files synced (infra-kit ${t})`),{skipped:!1,root:r,written:a}};import fe from"node:fs";import zs from"node:os";import Dr from"node:path";import qs from"node:process";import yt from"node:fs/promises";import wc from"node:path";import Rc from"node:process";var js=` // "envManagement": { // required in layer 1; provider-tagged
|
|
21
21
|
// "provider": "doppler",
|
|
22
22
|
// "config": { "name": "my-doppler-project" }
|
|
23
23
|
// },
|
|
@@ -152,65 +152,65 @@ ${js}
|
|
|
152
152
|
// "workspaceDir": "~/projects", // string (absolute or ~-prefixed) \u2014 where target repos are cloned
|
|
153
153
|
// "targets": ["my-repo-a", "my-repo-b"] // string[] (>=1) \u2014 repo dir names resolved under workspaceDir
|
|
154
154
|
}
|
|
155
|
-
`;var Ms=!1,
|
|
156
|
-
`,"utf-8");let s=ko(e.projectName),n=await
|
|
155
|
+
`;var Ms=!1,bc=e=>e.replace(/\.json$/,".example.jsonc"),Ec=async e=>{try{return await yt.readFile(e,"utf-8")}catch{return null}},wt=async e=>{let r=e.userProject,t=bc(r);await yt.mkdir(wc.dirname(r),{recursive:!0});let o=!await z(r);o&&await yt.writeFile(r,`{}
|
|
156
|
+
`,"utf-8");let s=ko(e.projectName),n=await Ec(t)!==s;return n&&await yt.writeFile(t,s,"utf-8"),o&&Xn(),{configPath:r,examplePath:t,createdConfig:o,refreshedExample:n}},Rt=e=>`Created ${k(e.configPath)} \u2014 see ${k(e.examplePath)} for the annotated reference.`,xc=async()=>{if(Rc.env.INFRA_KIT_NO_SEED||Ms)return;Ms=!0;let e;try{e=await N()}catch{return}if(await z(e.main))try{let r=await wt(e);r.createdConfig?l.info(Rt(r)):r.refreshedExample&&l.debug(`Refreshed ${k(r.examplePath)} to match the current schema.`)}catch(r){l.debug({err:r,msg:`Skipped seeding ${k(e.userProject)} (config bootstrap failed).`})}};import K from"node:fs/promises";import oe from"node:path";import{pathToFileURL as Cc}from"node:url";import Sc from"yaml";import{z as Bs}from"zod";import Pc from"node:fs/promises";import wo from"node:os";import Ro from"node:path";import{z as Tc}from"zod";import{z as bt}from"zod";var Ls="vendor.json",Et=bt.object({workspaceDir:bt.string().min(1),targets:bt.array(bt.string()).min(1)}).strict();var bo=()=>Ro.join(wo.homedir(),Zn,Ls),Ws=e=>{if(e==="~")return wo.homedir();if(e.startsWith("~/"))return Ro.join(wo.homedir(),e.slice(2));if(Ro.isAbsolute(e))return e;throw new Error(`workspaceDir must be absolute or ~-prefixed, got: ${e}`)},cr=async()=>{let e=bo(),r;try{r=await Pc.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:
|
|
157
157
|
|
|
158
158
|
{
|
|
159
159
|
"workspaceDir": "~/projects",
|
|
160
160
|
"targets": ["my-repo"]
|
|
161
161
|
}
|
|
162
|
-
`)}let t;try{t=r.trim()===""?{}:JSON.parse(r)}catch(s){throw new Error(`Invalid JSON in vendor.json at ${e}: ${s.message}`)}let o=Et.safeParse(t);if(!o.success)throw new Error(`Invalid factory config at ${e}: ${
|
|
163
|
-
`,"utf-8"),await K.rm(o.yml,{force:!0}),l.info(`\u2713 Migrated ${k(o.yml)} \u2192 ${k(o.json)}`),t++}catch(i){l.info(`\u26A0 Skipped ${k(o.yml)} \u2014 ${i.message}`)}}}t>0&&qe()},Ks=async()=>{let e;try{e=await N()}catch{return}let r=oe.dirname(e.userGlobal),t=[{from:oe.join(r,"config.json"),to:e.userGlobal},{from:oe.join(r,"config.example.jsonc"),to:oe.join(r,"infra-kit.example.jsonc")}],o=0;for(let{from:s,to:n}of t){let[i,a]=await Promise.all([z(s),z(n)]);if(i){if(a){l.info(`\u26A0 Skipped ${k(s)} \u2014 ${k(n)} already exists (remove the stale file manually)`);continue}try{await K.mkdir(oe.dirname(n),{recursive:!0}),await K.rename(s,n),l.info(`\u2713 Renamed ${k(s)} \u2192 ${k(n)}`),o++}catch(c){l.info(`\u26A0 Skipped ${k(s)} \u2014 ${c.message}`)}}}o>0&&qe()},Us=async()=>{let e=bo(),r=oe.dirname(e),t=oe.join(r,"vendor.config.ts"),[o,s]=await Promise.all([z(t),z(e)]);if(o){if(s){l.info(`\u26A0 Skipped ${k(t)} \u2014 ${k(e)} already exists (remove the stale vendor.config.ts manually)`);return}try{let n=await K.stat(t),c=(await import(`${
|
|
164
|
-
`,"utf-8"),await K.rm(t,{force:!0}),p?l.info(`\u26A0 Migrated ${k(t)} \u2192 ${k(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 ${k(e)} directly to change them.`):l.info(`\u2713 Migrated ${k(t)} \u2192 ${k(e)}`)}catch(n){l.info(`\u26A0 Skipped ${k(t)} \u2014 ${n.message}`)}}}
|
|
165
|
-
`,"utf-8"),l.info(`\u2713 Normalized ide config in ${k(o)} (removed legacy "mode")`),t++}catch(s){l.info(`\u26A0 Skipped normalizing ${k(o)} \u2014 ${s.message}`)}t>0&&qe()};var Fr="# -- infra-kit:begin --",lr="# -- infra-kit:end --"
|
|
166
|
-
`,"utf-8"),l.info(`Wrote user-global config to ${r} (see the sibling .example.jsonc files for reference)`)},
|
|
167
|
-
`),n=0;for(;n<s.length&&
|
|
162
|
+
`)}let t;try{t=r.trim()===""?{}:JSON.parse(r)}catch(s){throw new Error(`Invalid JSON in vendor.json at ${e}: ${s.message}`)}let o=Et.safeParse(t);if(!o.success)throw new Error(`Invalid factory config at ${e}: ${Tc.prettifyError(o.error)}`);return o.data};var Vs=e=>e.replace(/\.json$/,".yml"),Js=async()=>{let e;try{e=await N()}catch{return}let r=[{label:"infra-kit.json",yml:Vs(e.main),json:e.main,schema:Yn},{label:"~/.infra-kit/infra-kit.json",yml:oe.join(oe.dirname(e.userGlobal),"config.yml"),json:e.userGlobal,schema:Ht},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:Vs(e.userProject),json:e.userProject,schema:Ht}],t=0;for(let o of r){let[s,n]=await Promise.all([z(o.yml),z(o.json)]);if(s){if(n){l.info(`\u26A0 Skipped ${k(o.yml)} \u2014 ${k(o.json)} already exists (remove the stale .yml manually)`);continue}try{let i=await K.readFile(o.yml,"utf-8"),a=Sc.parse(i)??{},c=o.schema.safeParse(a);if(!c.success){l.info(`\u26A0 Skipped ${k(o.yml)} \u2014 invalid config: ${Bs.prettifyError(c.error)}`);continue}await K.mkdir(oe.dirname(o.json),{recursive:!0}),await K.writeFile(o.json,`${JSON.stringify(c.data,null,2)}
|
|
163
|
+
`,"utf-8"),await K.rm(o.yml,{force:!0}),l.info(`\u2713 Migrated ${k(o.yml)} \u2192 ${k(o.json)}`),t++}catch(i){l.info(`\u26A0 Skipped ${k(o.yml)} \u2014 ${i.message}`)}}}t>0&&qe()},Ks=async()=>{let e;try{e=await N()}catch{return}let r=oe.dirname(e.userGlobal),t=[{from:oe.join(r,"config.json"),to:e.userGlobal},{from:oe.join(r,"config.example.jsonc"),to:oe.join(r,"infra-kit.example.jsonc")}],o=0;for(let{from:s,to:n}of t){let[i,a]=await Promise.all([z(s),z(n)]);if(i){if(a){l.info(`\u26A0 Skipped ${k(s)} \u2014 ${k(n)} already exists (remove the stale file manually)`);continue}try{await K.mkdir(oe.dirname(n),{recursive:!0}),await K.rename(s,n),l.info(`\u2713 Renamed ${k(s)} \u2192 ${k(n)}`),o++}catch(c){l.info(`\u26A0 Skipped ${k(s)} \u2014 ${c.message}`)}}}o>0&&qe()},Us=async()=>{let e=bo(),r=oe.dirname(e),t=oe.join(r,"vendor.config.ts"),[o,s]=await Promise.all([z(t),z(e)]);if(o){if(s){l.info(`\u26A0 Skipped ${k(t)} \u2014 ${k(e)} already exists (remove the stale vendor.config.ts manually)`);return}try{let n=await K.stat(t),c=(await import(`${Cc(t).href}?mtime=${Number(n.mtimeMs)}`)).default,p=typeof c=="function",d=p?await c():c,m=Et.safeParse(d);if(!m.success){l.info(`\u26A0 Skipped ${k(t)} \u2014 invalid factory config: ${Bs.prettifyError(m.error)}`);return}await K.mkdir(r,{recursive:!0}),await K.writeFile(e,`${JSON.stringify(m.data,null,2)}
|
|
164
|
+
`,"utf-8"),await K.rm(t,{force:!0}),p?l.info(`\u26A0 Migrated ${k(t)} \u2192 ${k(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 ${k(e)} directly to change them.`):l.info(`\u2713 Migrated ${k(t)} \u2192 ${k(e)}`)}catch(n){l.info(`\u26A0 Skipped ${k(t)} \u2014 ${n.message}`)}}},$c=e=>{let r=e.ide;if(r===null||typeof r!="object")return{changed:!1,result:e};let t=!1,o=n=>{if(n===null||typeof n!="object"||!("config"in n))return n;let i=n.config;if(i===null||typeof i!="object"||!("mode"in i))return n;t=!0;let a=Object.fromEntries(Object.entries(i).filter(([c])=>c!=="mode"));return{...n,config:a}},s=Array.isArray(r)?r.map(o):o(r);return t?{changed:!0,result:{...e,ide:s}}:{changed:!1,result:e}},Gs=async()=>{let e;try{e=await N()}catch{return}let r=[e.main,e.userGlobal,e.userProject],t=0;for(let o of r)if(await z(o))try{let s=await K.readFile(o,"utf-8");if(s.trim()==="")continue;let n=JSON.parse(s),{changed:i,result:a}=$c(n);if(!i)continue;await K.writeFile(o,`${JSON.stringify(a,null,2)}
|
|
165
|
+
`,"utf-8"),l.info(`\u2713 Normalized ide config in ${k(o)} (removed legacy "mode")`),t++}catch(s){l.info(`\u26A0 Skipped normalizing ${k(o)} \u2014 ${s.message}`)}t>0&&qe()};var Fr="# -- infra-kit:begin --",lr="# -- infra-kit:end --",_c=[["# region infra-kit","# endregion infra-kit"]],Ac="# infra-kit shell functions",Qf=async()=>{let e=Dr.join(zs.homedir(),".zshrc"),r=fe.existsSync(e)?Dc(fe.readFileSync(e,"utf-8")):"",t=Ar({content:r,body:Hs(),startMarker:Fr,endMarker:lr,placement:"append-end"});fe.writeFileSync(e,t),l.info(`Added infra-kit shell functions to ${e}`),await Js(),await Gs(),await Ks(),await Us(),Ic(),await Fs(),await Nc();let o=qs.env.SHELL??"";o.includes("zsh")||l.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.`),l.info("Run `source ~/.zshrc` or open a new terminal to activate.")},Ic=()=>{let e=Dr.join(zs.homedir(),".infra-kit"),r=Dr.join(e,"infra-kit.json");if(fe.mkdirSync(e,{recursive:!0}),fe.writeFileSync(Dr.join(e,"infra-kit.example.jsonc"),vo(),"utf-8"),fe.writeFileSync(Dr.join(e,"vendor.example.jsonc"),yo(),"utf-8"),fe.existsSync(r)){l.info(`User-global config already present at ${r} (refreshed reference examples)`);return}fe.writeFileSync(r,`{}
|
|
166
|
+
`,"utf-8"),l.info(`Wrote user-global config to ${r} (see the sibling .example.jsonc files for reference)`)},Nc=async()=>{if(!qs.env.INFRA_KIT_NO_SEED)try{let e=await N();if(!fe.existsSync(e.main))return;let r=await wt(e);r.createdConfig&&l.info(Rt(r))}catch(e){l.debug({err:e,msg:"Skipped seeding the user-project config (init)."})}},Oc=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"),Dc=e=>{let r=be(e,Fr,lr);if(r!==null)return r;for(let[a,c]of _c){let p=be(e,a,c);if(p!==null)return p}let t=e.indexOf(Ac);if(t===-1)return e;let o=e.slice(0,t).replace(/\n+$/,""),s=e.slice(t).split(`
|
|
167
|
+
`),n=0;for(;n<s.length&&Oc(s[n]);)n++;let i=s.slice(n).join(`
|
|
168
168
|
`);return o+(i?`
|
|
169
169
|
${i}`:"")},Hs=()=>{let e="pnpm exec infra-kit";return["zmodload zsh/stat 2>/dev/null","zmodload zsh/datetime 2>/dev/null","zmodload zsh/sched 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}}",": ${_INFRA_KIT_WARM_TTL:=7200}","export _INFRA_KIT_LAST_LOAD_MTIME _INFRA_KIT_LAST_CLEAR_MTIME _INFRA_KIT_SHELL_STARTED _INFRA_KIT_WARM_TTL",`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; }`,"_infra_kit_notify() {"," zle && print -u2 -n $'\\r\\e[K'",' print -u2 -- "$1"'," zle && zle reset-prompt","}","_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 load_mtime=0 clear_mtime=0",' [[ -f "$load_file" ]] && load_mtime=$(zstat +mtime -- "$load_file" 2>/dev/null || echo 0)',' [[ -f "$clear_file" ]] && clear_mtime=$(zstat +mtime -- "$clear_file" 2>/dev/null || echo 0)'," if (( load_mtime > _INFRA_KIT_LAST_LOAD_MTIME && load_mtime >= _INFRA_KIT_SHELL_STARTED && load_mtime >= clear_mtime )); then",' source "$load_file"'," _INFRA_KIT_LAST_LOAD_MTIME=$load_mtime",' _infra_kit_notify "infra-kit: auto-loaded vars for ${INFRA_KIT_ENV_CONFIG:-?}"'," fi"," if (( clear_mtime > _INFRA_KIT_LAST_CLEAR_MTIME && clear_mtime >= _INFRA_KIT_SHELL_STARTED && clear_mtime > load_mtime )); then",' source "$clear_file"'," _INFRA_KIT_LAST_CLEAR_MTIME=$clear_mtime",' _infra_kit_notify "infra-kit: auto-cleared env"'," fi","}","autoload -Uz add-zsh-hook","if (( _INFRA_KIT_SHELL_STARTED > 0 )); then"," add-zsh-hook precmd _infra_kit_autoload","fi","_INFRA_KIT_AUTOLOAD_WINDOW=6","export _INFRA_KIT_AUTOLOAD_WINDOW","_infra_kit_poll_autoload() {"," _infra_kit_autoload"," if (( _INFRA_KIT_LAST_LOAD_MTIME < _INFRA_KIT_SHELL_STARTED )) && (( ${EPOCHSECONDS:-0} - _INFRA_KIT_SHELL_STARTED < _INFRA_KIT_AUTOLOAD_WINDOW )); then"," (( $+builtins[sched] )) && sched +1 _infra_kit_poll_autoload"," fi","}","_infra_kit_warm_source() {",' local canon="$1" key'," if (( $+commands[shasum] )); then",' key=$(printf %s "$canon" | shasum -a 256 | cut -c1-64)'," elif (( $+commands[sha256sum] )); then",' key=$(printf %s "$canon" | sha256sum | cut -c1-64)'," else"," return"," fi",' local cache_root="${XDG_CACHE_HOME:-$HOME/.cache}/infra-kit"',' local warm="$cache_root/projects/$key/env-load.sh"',' local wclear="$cache_root/projects/$key/env-clear.sh"',' [[ -f "$warm" ]] || return'," local wm=0 cm=0",' wm=$(zstat +mtime -- "$warm" 2>/dev/null || echo 0)',' [[ -f "$wclear" ]] && cm=$(zstat +mtime -- "$wclear" 2>/dev/null || echo 0)'," (( cm >= wm )) && return"," (( ${EPOCHSECONDS:-0} - wm >= _INFRA_KIT_WARM_TTL )) && return",' source "$warm"',' _infra_kit_notify "infra-kit: loaded cached vars for ${INFRA_KIT_ENV_CONFIG:-?} (refreshing\u2026)"',"}","_infra_kit_startup_autoload() {",' [[ -z "$INFRA_KIT_SESSION" ]] && return',' local dir="$PWD" prev=""',' while [[ -n "$dir" && "$dir" != "$prev" ]]; do',' if [[ -f "$dir/infra-kit.json" ]]; then',' [[ -n "$INFRA_KIT_ENV_CONFIG" && "$dir" == "$INFRA_KIT_ENV_PROJECT_ROOT" ]] && return',' local canon="${dir:A}"',' _infra_kit_warm_source "$canon"',` ( ${e} env-autoload --project-dir "$canon" & ) >/dev/null 2>&1`," (( $+builtins[sched] )) && sched +1 _infra_kit_poll_autoload"," return"," fi",' prev="$dir"',' dir="${dir:h}"'," done","}","if (( _INFRA_KIT_SHELL_STARTED > 0 )); then"," _infra_kit_startup_autoload","fi"].join(`
|
|
170
170
|
`)},Zs=()=>`${Fr}
|
|
171
171
|
${Hs()}
|
|
172
|
-
${lr}`;import
|
|
173
|
-
`).map(s=>s.trim()).filter(s=>s.startsWith("[ok]")||s.startsWith("[--]")),o=[];for(let s of
|
|
174
|
-
`);for(let i of s){let a=i.status==="pass"?"[PASS]":"[FAIL]";l.info(` ${a} ${i.name}: ${i.message}`)}let n={checks:s.map(i=>({name:i.name,status:i.status,message:i.message})),allPassed:s.every(i=>i.status==="pass")};return{content:g(JSON.stringify(n,null,2)),structuredContent:n}},Co=v({name:"doctor",description:"Check installation and authentication status of gh, doppler, aws, and rtk CLIs",inputSchema:{},outputSchema:{checks:pr.array(pr.object({name:pr.string().describe("Name of the check"),status:pr.enum(["pass","fail"]).describe("Check result"),message:pr.string().describe("Details about the check result")})).describe("List of all check results"),allPassed:pr.boolean().describe("Whether all checks passed")},handler:()=>ri()});import So from"node:fs";import ti from"node:path";import
|
|
172
|
+
${lr}`;import Fc from"node:fs/promises";var Eo=async(e,r)=>{if(!r)return{hasOverrides:!1,overrideKeys:[],unreadable:!1};try{let t=await Fc.readFile(e,"utf-8"),o=t.trim()===""?{}:JSON.parse(t);if(typeof o!="object"||o===null||Array.isArray(o))return{hasOverrides:!1,overrideKeys:[],unreadable:!0};let s=Object.keys(o);return{hasOverrides:s.length>0,overrideKeys:s,unreadable:!1}}catch{return{hasOverrides:!1,overrideKeys:[],unreadable:!0}}},xo=e=>e.unreadable?"(unreadable \u2014 invalid JSON)":e.overrideKeys.length===0?"(empty \u2014 no overrides)":`(${e.overrideKeys.length} override(s): ${e.overrideKeys.join(", ")})`;var Le=async(e,r,t,o)=>{try{return await To`${r}`,{name:e,status:"pass",message:t}}catch{return{name:e,status:"fail",message:o}}},Mc=()=>{let e="zshrc init block",r=ne.join(jc.homedir(),".zshrc");if(!j.existsSync(r))return{name:e,status:"fail",message:"~/.zshrc not found. Run: infra-kit init"};let t=j.readFileSync(r,"utf-8"),o=t.indexOf(Fr),s=t.indexOf(lr);if(o===-1||s===-1||s<o)return{name:e,status:"fail",message:"infra-kit shell block missing from ~/.zshrc. Run: infra-kit init"};let n=t.slice(o,s+lr.length).trim(),i=Zs().trim();return n!==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"}},Lc=async()=>{let e="warm cache",r;try{r=await w()}catch{return{name:e,status:"pass",message:"warm cache: not a git project"}}let t=ue(r);if(!t)return{name:e,status:"pass",message:"warm cache: unavailable"};let o=ne.join(Ne(t),B);if(!j.existsSync(o))return{name:e,status:"pass",message:"warm cache: none yet (populated on next auto-load)"};let s=Math.floor((Date.now()-j.statSync(o).mtimeMs)/1e3),n=Math.floor(s/60),i=Math.floor(wr/60);return s>=wr?{name:e,status:"pass",message:`warm cache: present but stale (${n}m old, TTL ${i}m) \u2014 will refresh`}:{name:e,status:"pass",message:`warm cache: present, ${n}m old`}},Wc=async()=>{let e="pnpm enableGlobalVirtualStore";try{let r=await w(),t=ne.join(r,"pnpm-workspace.yaml");if(!j.existsSync(t))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${t}`};let o=j.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}`}}},Vc=async()=>{try{return qe(),{config:await O(),error:null}}catch(e){return{config:null,error:e}}},Bc=e=>{let r="infra-kit config valid";return e.error?{name:r,status:"fail",message:e.error.message}:{name:r,status:"pass",message:"infra-kit.json is valid (user overrides applied if present)"}},Jc=384,Po=448,Kc=e=>e.map(r=>{let t=r.source===null?"no token":`token (${r.source})`;return`${r.env}: ${t}`}).join(", "),Uc=async(e,r)=>Promise.all(e.map(async t=>{try{let{source:o}=await r(t);return{env:t,source:o}}catch{return{env:t,source:null}}})),Gc=async(e,r={})=>{let t="env tokens configured",o=r.readStore??q,s=r.resolveToken??nr;if(!e.config)return{name:t,status:"pass",message:"Skipped \u2014 infra-kit config could not be read (see config check)"};try{await o()}catch(m){return{name:t,status:"fail",message:`Token store unreadable \u2014 ${m.message}`}}let n=await Fe(),i=e.config.envAutoLoad?.config,a=i&&!n.includes(i)?[...n,i]:n,c=await Uc(a,s),p=Kc(c);if(i===void 0)return{name:t,status:"pass",message:`No envAutoLoad configured \u2014 no env is load-bearing. ${p}`};let d=c.find(m=>m.env===i);return!d||d.source===null?{name:t,status:"fail",message:`No Doppler service token for the auto-load env "${i}" \u2014 your shell env will not load. Fix: run \`infra-kit env-token-set ${i}\`. ${p}`}:{name:t,status:"pass",message:`auto-load env "${i}": token (${d.source}). ${p}`}},zc={valid:{status:"pass",describe:"live and correctly scoped"},revoked:{status:"fail",describe:"REJECTED by Doppler (revoked or invalid)"},"mis-scoped":{status:"fail",describe:"live but scoped to a DIFFERENT config"},unreachable:{status:"pass",describe:"could not be checked (Doppler unreachable)"}},qc=async(e,r={})=>{let t="env token valid",o=r.resolveToken??nr,s=r.probe??Cr;if(!e.config)return{name:t,status:"pass",message:"Skipped \u2014 infra-kit config could not be read (see config check)"};let n=e.config.envAutoLoad?.config;if(n===void 0)return{name:t,status:"pass",message:"Skipped \u2014 no envAutoLoad env to probe"};let i;try{i=(await o(n)).token}catch{return{name:t,status:"pass",message:`Skipped \u2014 no token for env "${n}" (see env tokens configured)`}}let a=e.config.envManagement.config.name,c=await s({childEnv:ir(i),project:a,config:n}),p=zc[c.outcome],d=c.outcome==="revoked"||c.outcome==="mis-scoped"?` Fix: run \`infra-kit env-token-set ${n}\` with a token scoped to "${n}".`:"";return{name:t,status:p.status,message:`The token for env "${n}" (project "${a}") is ${p.describe}.${d}`}},jr=(e,r)=>{let t=r(e);return t===null?null:t.mode&511},Hc=async(e,r={})=>{let t="tokens.json perms",o=r.storePath??ct,s=r.statPath??Zc,n=r.chmodPath??j.chmodSync,i;try{i=await o()}catch{return{name:t,status:"pass",message:"Skipped \u2014 the token store path could not be resolved"}}if(jr(i,s)===null)return{name:t,status:"pass",message:`No token store yet at ${k(i)}`};let a=ne.dirname(i),c=ne.dirname(a),p=ne.dirname(c),m=[{target:p,expected:Po,actual:jr(p,s)},{target:c,expected:Po,actual:jr(c,s)},{target:a,expected:Po,actual:jr(a,s)},{target:i,expected:Jc,actual:jr(i,s)}].filter(y=>y.actual!==null&&y.actual!==y.expected);if(m.length===0)return{name:t,status:"pass",message:`${k(i)} is 0600 (0700 dirs)`};let h=m.map(y=>`${k(y.target)} is ${Ys(y.actual)}, expected ${Ys(y.expected)}`).join("; ");if(!e)return{name:t,status:"fail",message:`${h}. Fix: run \`infra-kit doctor --fix\`, or chmod them by hand.`};for(let y of m)n(y.target,y.expected);return{name:t,status:"pass",message:`Tightened ${m.length} path(s): ${h}`}},Ys=e=>`0${e.toString(8).padStart(3,"0")}`,Zc=e=>{try{return j.statSync(e)}catch{return null}},Yc=async()=>{let e="user override path";try{let r=await N(),t=j.existsSync(r.userProject),o=await Eo(r.userProject,t),s=t?xo(o):"(not created \u2014 seed failed?)";return{name:e,status:"pass",message:`${k(r.userProject)} ${s} \u2014 project: ${r.projectName}`}}catch(r){return{name:e,status:"fail",message:r.message}}},Xc=async()=>{let e="legacy user-global config",r;try{r=await N()}catch{return{name:e,status:"pass",message:"Skipped \u2014 infra-kit config paths could not be resolved"}}let t=ne.join(ne.dirname(r.userGlobal),"config.json");return j.existsSync(t)?j.existsSync(r.userGlobal)?{name:e,status:"fail",message:`Stale legacy config.json found at ${k(t)} \u2014 ${k(r.userGlobal)} is active; remove the old file.`}:{name:e,status:"fail",message:`Legacy user-global config.json found at ${k(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"}},Qc={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/"}},el=async e=>{let r=Qc[e];try{return await To`${r.command}`,{ok:!0,label:r.label,failMsg:r.failMsg}}catch{return{ok:!1,label:r.label,failMsg:r.failMsg}}},rl=async e=>{let r="ide installed";if(!e.config)return{name:r,status:"pass",message:"Skipped \u2014 infra-kit config could not be read (see config check)"};let t=re(e.config).map(n=>n.provider);if(t.length===0)return{name:r,status:"pass",message:"No IDE configured (ide unset)"};let o=await Promise.all(t.map(n=>el(n))),s=o.filter(n=>!n.ok);return s.length===0?{name:r,status:"pass",message:`Installed: ${o.map(n=>n.label).join(", ")}`}:{name:r,status:"fail",message:s.map(n=>n.failMsg).join("; ")}},tl=[1,2,3,5,7],ol=async()=>{let e="rtk configured";try{let t=(await To`rtk init --show`).stdout.split(`
|
|
173
|
+
`).map(s=>s.trim()).filter(s=>s.startsWith("[ok]")||s.startsWith("[--]")),o=[];for(let s of tl){let n=t[s-1];(!n||!n.startsWith("[ok]"))&&o.push(s)}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}`}}},nl=async()=>{let e;try{e=(await N()).main}catch{return[]}if(!j.existsSync(e))return[];let r=ne.join(ne.dirname(e),"CLAUDE.md"),t=j.existsSync(r)?j.readFileSync(r,"utf-8"):"",o=ar(t,Nr,Or);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"}]},Qs=e=>pt(["service","install"],{sudo:!0,bin:e}),ei=e=>pt(["trust"],{bin:e}),sl=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),Xs="ERR_TLS_CERT_ALTNAME_INVALID",il=async(e,r)=>{let t=`portless serving TLS on :${ze}`;return await e(ze,!0)?{name:t,status:"pass",message:`portless is serving HTTPS on :${ze}`}:{name:t,status:"fail",message:`No portless daemon is serving HTTPS on :${ze}. Install it once (needs root): \`${Qs(r)}\`.`}},al=async(e,r,t,o)=>{let s="portless CA chain valid",n=["localhost",...r.slice(0,1).map(p=>p.name)],a=(await Promise.all(n.map(async p=>({servername:p,result:await e(ze,p)})))).filter(p=>!p.result.ok);if(a.length===0)return{name:s,status:"pass",message:`Served certificate chains to ${k(t)} (${n.join(", ")})`};let c=a.map(p=>p.result.ok?"":p.result.code);return c.includes(Xs)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${Xs} for servername(s) ${a.map(p=>p.servername).join(", ")} \u2014 doctor's probe is wrong, your trust store is not implicated. Please report this.`}:c.some(p=>sl.has(p))?{name:s,status:"fail",message:`The daemon is serving a certificate that does not chain to ${k(t)}. Its CA was regenerated \u2014 run \`${ei(o)}\`, or reinstall: \`${Qs(o)}\`.`}:{name:s,status:"fail",message:`TLS handshake failed (${c.join(", ")})`}},cl=(e,r,t)=>{let o="portless CA trusted";return e?{name:o,status:"pass",message:`${k(r)} matches the recorded ca.trusted fingerprint`}:{name:o,status:"fail",message:`The portless CA is not trusted (or was regenerated). Run: \`${ei(t)}\` (no sudo needed).`}},ll=async(e,r,t)=>{let o="portless routes";if(e.length===0)return{name:o,status:"pass",message:"No portless routes registered"};let n=(await Promise.all(e.map(async i=>({route:i,live:await r(i.port)})))).filter(i=>!i.live).map(i=>i.route.name);return n.length===0?{name:o,status:"pass",message:`${e.length} portless route(s), all live`}:{name:o,status:"fail",message:`${n.length} stale portless route(s): ${n.join(", ")}. Remove with \`${pt(["alias","--remove","<name>"],{bin:t})}\`.`}},pl=async(e={})=>{let r=e.resolveBin??ts,t=e.isProxyServing??os,o=e.handshake??is,s=e.caTrusted??ss,n=e.routes??Yt,i=e.isListening??Zt,a=(e.caPath??ns)(),c=r();if(c===null)return[{name:"portless installed",status:"fail",message:"portless is not resolvable from node_modules \u2014 run `pnpm install`."}];let p={name:"portless installed",status:"pass",message:"portless is resolvable from node_modules"},d=n(),m=await il(t,c),h=m.status==="fail"?{name:"portless CA chain valid",status:"pass",message:"Skipped \u2014 no daemon to handshake with"}:await al(o,d,a,c);return[p,m,h,cl(s(),a,c),await ll(d,i,c)]},dl=async(e={})=>{let r="portless routes",t=e.routes??Yt,o=e.isListening??Zt,s=e.devSessionRunning??fs,n=t();if(n.length===0)return{name:r,status:"pass",message:"No portless routes registered"};let i=await Promise.all(n.map(async d=>({name:d.name,port:d.port,live:await o(d.port)}))),{prunable:a,withheld:c}=us(i,s());if(c.length>0)return{name:r,status:"fail",message:`${c.length} route(s) look stale (${c.join(", ")}), but a dev session is running \u2014 a UI that has not bound its port yet is indistinguishable from a dead one, so nothing was removed. Stop dev and re-run \`infra-kit doctor --fix\`.`};if(a.length===0)return{name:r,status:"pass",message:`${n.length} portless route(s), all live`};let p=e.removeAlias??as().removeAlias;for(let d of a)await p(d);return{name:r,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},ri=async(e={})=>{let r=await Vc(),t=await Promise.all([Le("gh installed",["gh","--version"],"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/"),Le("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),Le("doppler installed",["doppler","--version"],"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli"),Le("aws installed",["aws","--version"],"AWS CLI is installed","AWS CLI is not installed. Install from: https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html"),Le("rtk installed",["rtk","--version"],"RTK is installed","RTK is not installed. Install from: https://github.com/rtk-ai/rtk"),Le("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"),Le("cmux installed",["cmux","--version"],"cmux is installed","cmux is not installed. Install from: https://cmux.com/"),ol(),Promise.resolve(Mc()),Lc(),Wc(),Promise.resolve(Bc(r)),Gc(r),qc(r),Hc(e.fix??!1),Yc(),Xc(),rl(r)]),o=await pl();if(e.fix){let i=await dl(),a=o.findIndex(c=>c.name===i.name);a>=0?o[a]=i:o.push(i)}let s=[...t,...o,...await nl()];l.info(`Doctor check results:
|
|
174
|
+
`);for(let i of s){let a=i.status==="pass"?"[PASS]":"[FAIL]";l.info(` ${a} ${i.name}: ${i.message}`)}let n={checks:s.map(i=>({name:i.name,status:i.status,message:i.message})),allPassed:s.every(i=>i.status==="pass")};return{content:g(JSON.stringify(n,null,2)),structuredContent:n}},Co=v({name:"doctor",description:"Check installation and authentication status of gh, doppler, aws, and rtk CLIs",inputSchema:{},outputSchema:{checks:pr.array(pr.object({name:pr.string().describe("Name of the check"),status:pr.enum(["pass","fail"]).describe("Check result"),message:pr.string().describe("Details about the check result")})).describe("List of all check results"),allPassed:pr.boolean().describe("Whether all checks passed")},handler:()=>ri()});import So from"node:fs";import ti from"node:path";import ml from"node:process";import{z as Mr}from"zod";var ul=async e=>{let r="";try{r=await w()}catch{return}let t=ue(r);t&&fo(t,e)},fl=e=>[...e.map(r=>`unset ${r}`),`unset ${st}`,`unset ${He}`,`unset ${Ze}`,`unset ${it}`,`unset ${Ye}`,`unset ${Ie}`,`export ${Xe}='1'`],oi=async({purge:e=!1}={})=>{let r=Qe(),t=ti.join(r,B),o=So.existsSync(t);if(!o&&!e)throw new Error("No loaded environment found. Run `env-load` first.");await ul(e);let s=o?at(t):[],n=fl(s),i=ti.resolve(r,nt);So.mkdirSync(r,{recursive:!0,mode:448}),Oe(i,`${n.join(`
|
|
175
175
|
`)}
|
|
176
|
-
`,384),
|
|
177
|
-
`),o&&So.rmSync(t,{force:!0});let a={filePath:i,variableCount:s.length,unsetStatements:n,purged:e};return{content:g(JSON.stringify(a,null,2)),structuredContent:a}},$o=v({name:"env-clear",description:'Generate a shell script that unsets every env var previously loaded by env-load for this session, plus the infra-kit session metadata vars. Does NOT mutate the calling process. When `infra-kit init` has installed the zsh shell integration, the user\'s terminal auto-sources the unset script on its next prompt (precmd hook) \u2014 so calling this via MCP will clear the vars in the shell that launched Claude Code automatically. Other callers must source "<filePath>" themselves or surface it to the user. Errors if no env is currently loaded.',inputSchema:{},outputSchema:{filePath:Mr.string().describe("Path to the file that must be sourced to apply"),variableCount:Mr.number().describe("Number of variables cleared"),unsetStatements:Mr.array(Mr.string()).describe("Unset statements generated"),purged:Mr.boolean().describe("Whether the project warm cache was purged outright")},handler:()=>oi()});import
|
|
178
|
-
`),s.length===0)return l.info("No environments found."),l.info(" Declare them in a workflow's `workflow_dispatch` `environment.options`,"),l.info(" or add a token
|
|
176
|
+
`,384),ml.stdout.write(`${i}
|
|
177
|
+
`),o&&So.rmSync(t,{force:!0});let a={filePath:i,variableCount:s.length,unsetStatements:n,purged:e};return{content:g(JSON.stringify(a,null,2)),structuredContent:a}},$o=v({name:"env-clear",description:'Generate a shell script that unsets every env var previously loaded by env-load for this session, plus the infra-kit session metadata vars. Does NOT mutate the calling process. When `infra-kit init` has installed the zsh shell integration, the user\'s terminal auto-sources the unset script on its next prompt (precmd hook) \u2014 so calling this via MCP will clear the vars in the shell that launched Claude Code automatically. Other callers must source "<filePath>" themselves or surface it to the user. Errors if no env is currently loaded.',inputSchema:{},outputSchema:{filePath:Mr.string().describe("Path to the file that must be sourced to apply"),variableCount:Mr.number().describe("Number of variables cleared"),unsetStatements:Mr.array(Mr.string()).describe("Unset statements generated"),purged:Mr.boolean().describe("Whether the project warm cache was purged outright")},handler:()=>oi()});import gl from"node:process";import{z as Ee}from"zod";var hl=(e,r,t)=>e.map(({env:o,source:s})=>({env:o,source:s,hasToken:!!(t||r[o])})),ni=["Environment","Source","Token"],vl=e=>{let r=e.map(n=>[n.env,n.source,n.hasToken?"set":"not set"]),t=ni.map((n,i)=>Math.max(n.length,...r.map(a=>(a[i]??"").length))),o=n=>n.map((i,a)=>i.padEnd(t[a]??0)).join(" | ").trimEnd(),s=t.map(n=>"\u2500".repeat(n)).join("\u2500\u253C\u2500");return["Environments:","",o(ni),s,...r.map(o)]},ii=async()=>{let e=await De(),r=await ht(),t=await q(),o=gl.env[H],s=hl(r,t?.envs??{},o);if(l.info(`Doppler project: ${e}
|
|
178
|
+
`),s.length===0)return l.info("No environments found."),l.info(" Declare them in a workflow's `workflow_dispatch` `environment.options`,"),l.info(" or add a token for one manually."),si({project:e,envs:s});for(let n of vl(s))l.info(n);return si({project:e,envs:s})},si=({project:e,envs:r})=>{let t={project:e,configs:r.map(o=>o.env),tokens:r};return{content:g(JSON.stringify(t,null,2)),structuredContent:t}},_o=v({name:"env-list",description:"List the environments this project has. The list is the union of two local sources: every environment declared in a GitHub workflow's `workflow_dispatch` `environment.options` (source `gh-workflow`), and every environment the local token store holds a token for (source `token-only`). Not a live fetch from Doppler \u2014 a Doppler service token is config-scoped and cannot enumerate sibling configs. Also returns the Doppler project name, and reports per environment whether a service token resolves locally (from the token store or INFRA_KIT_ENV_TOKEN) \u2014 presence only, never the token value, and never a live Doppler probe. Read-only.",inputSchema:{},outputSchema:{project:Ee.string().describe("Detected Doppler project name"),configs:Ee.array(Ee.string()).describe("Every environment name known to this project"),tokens:Ee.array(Ee.object({env:Ee.string().describe("Environment / Doppler config name"),source:Ee.enum(["gh-workflow","token-only"]).describe("Where we learned this environment exists \u2014 a workflow declaration, or a token we hold"),hasToken:Ee.boolean().describe("Whether a service token resolves locally for this environment")})).describe("Per-environment token presence \u2014 never the token value")},handler:ii});import kl from"node:path";import We from"node:process";import{z as xe}from"zod";var ai=async()=>{l.info("Environment session status:");let e=Qe(),r=We.env[Qn],t=kl.join(e,B),o=0,s=0,n=We.env[He]??null,i=We.env[Ze]??null,a=We.env[Ye]??null,c=We.env[Ie]==="1",p=!!We.env[Xe];if(n){let m=at(t);m.length>0&&(s=m.length,o=m.filter(b=>b in We.env).length);let h=a?.replace(/\.\d{3}Z$/,"")??null,y=c?"auto-loaded":"manually loaded";if(l.info(` ${n}: ${o} of ${s} vars loaded (${y}, project: ${i}, loadedAt: ${h}, session: ${r})
|
|
179
179
|
`),s>0&&o<s){let b=s-o;l.warn(` ${b} 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 m=p?" (cleared \u2014 auto-load suppressed until a new shell or explicit env-load)":"";l.info(` Session ${r}: no env loaded${m}
|
|
180
|
-
`)}let d={sessionId:r,sessionLoadedCount:o,sessionTotalCount:s,sessionConfig:n,sessionProject:i,sessionLoadedAt:a,autoLoaded:c,cleared:p};return{content:g(JSON.stringify(d,null,2)),structuredContent:d}},Ao=v({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:xe.string().describe("Current terminal session ID"),sessionLoadedCount:xe.number().describe("Number of cached vars active in the current session"),sessionTotalCount:xe.number().describe("Total number of cached var names"),sessionConfig:xe.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:xe.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:xe.string().nullable().describe("ISO 8601 timestamp of when the env was loaded"),autoLoaded:xe.boolean().describe("True when the loaded env was applied by env auto-load (not a manual env-load)"),cleared:xe.boolean().describe("True when env-clear is currently suppressing auto-load in this shell")},handler:
|
|
181
|
-
No token for: ${n.map(a=>a.env).join(", ")}. Add one with \`infra-kit env-token-set <env>\`.`);let i={tokens:s};return{content:g(JSON.stringify(i,null,2)),structuredContent:i}},No=v({name:"env-token-list",description:'List the Doppler service tokens configured for this repo: one row per environment declared in infra-kit.json, with its source (the local token store, or the INFRA_KIT_ENV_TOKEN env var) and a REDACTED token (last 4 chars at most \u2014 the raw value is never returned). With check=true, also asks Doppler whether each token is valid and correctly scoped (valid | revoked | mis-scoped | unreachable; "unreachable" means the probe could not tell, NOT that the token is bad). Read-only.',inputSchema:{check:Pe.boolean().optional().describe("Probe Doppler for each token\u2019s validity and scope (one cheap call per environment).")},outputSchema:{tokens:Pe.array(Pe.object({env:Pe.string().describe("Environment / Doppler config name"),source:Pe.string().describe('"store", "env:INFRA_KIT_ENV_TOKEN", or "-" when absent'),redactedToken:Pe.string().describe("Redacted token \u2014 last 4 chars at most, never the raw value"),present:Pe.boolean().describe("Whether a token is configured for this environment"),status:Pe.string().optional().describe("Only with check=true: valid | revoked | mis-scoped | unreachable")})).describe("One row per declared environment")},handler:
|
|
182
|
-
`);throw new Error(i)}let n=Number.parseInt(t,10);if(Number.isNaN(n))throw new TypeError(`Invalid JIRA_PROJECT_ID: "${t}" must be a numeric value (e.g., 10001)`);return{baseUrl:e.replace(/\/$/,""),token:r,projectId:n,email:o}},Ve=async()=>{try{return await mr()}catch(e){return l.warn({error:e},"Jira configuration not available, skipping Jira integration"),null}};var
|
|
180
|
+
`)}let d={sessionId:r,sessionLoadedCount:o,sessionTotalCount:s,sessionConfig:n,sessionProject:i,sessionLoadedAt:a,autoLoaded:c,cleared:p};return{content:g(JSON.stringify(d,null,2)),structuredContent:d}},Ao=v({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:xe.string().describe("Current terminal session ID"),sessionLoadedCount:xe.number().describe("Number of cached vars active in the current session"),sessionTotalCount:xe.number().describe("Total number of cached var names"),sessionConfig:xe.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:xe.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:xe.string().nullable().describe("ISO 8601 timestamp of when the env was loaded"),autoLoaded:xe.boolean().describe("True when the loaded env was applied by env auto-load (not a manual env-load)"),cleared:xe.boolean().describe("True when env-clear is currently suppressing auto-load in this shell")},handler:ai});import yl from"node:process";import{z as Pe}from"zod";var ci="****",Io=e=>typeof e!="string"||e.length<8?ci:`${ci}${e.slice(-4)}`;var li=(e,r,t)=>e.map(o=>{let s=t||r[o];return s?{env:o,source:t?`env:${H}`:"store",redactedToken:Io(s),present:!0}:{env:o,source:"-",redactedToken:"-",present:!1}}),wl=["ENV","SOURCE","TOKEN","PRESENT"],pi=(e,r)=>{let t=[...wl,...r?["CHECK"]:[]],o=e.map(n=>[n.env,n.source,n.redactedToken,n.present?"yes":"no",...r?[n.status??"-"]:[]]),s=t.map((n,i)=>Math.max(n.length,...o.map(a=>(a[i]??"").length)));return[t,...o].map(n=>n.map((i,a)=>i.padEnd(s[a])).join(" ").trimEnd())},di=async({check:e}={})=>{let r=await Fe(),t=await q(),o=yl.env[H],s=li(r,t?.envs??{},o);if(e){let a=await De();for(let c of s){if(!c.present)continue;let p=o||t.envs[c.env],d=await Cr({childEnv:ir(p),project:a,config:c.env});c.status=d.outcome}}for(let a of pi(s,!!e))l.info(a);let n=s.filter(a=>!a.present);n.length>0&&l.info(`
|
|
181
|
+
No token for: ${n.map(a=>a.env).join(", ")}. Add one with \`infra-kit env-token-set <env>\`.`);let i={tokens:s};return{content:g(JSON.stringify(i,null,2)),structuredContent:i}},No=v({name:"env-token-list",description:'List the Doppler service tokens configured for this repo: one row per environment declared in infra-kit.json, with its source (the local token store, or the INFRA_KIT_ENV_TOKEN env var) and a REDACTED token (last 4 chars at most \u2014 the raw value is never returned). With check=true, also asks Doppler whether each token is valid and correctly scoped (valid | revoked | mis-scoped | unreachable; "unreachable" means the probe could not tell, NOT that the token is bad). Read-only.',inputSchema:{check:Pe.boolean().optional().describe("Probe Doppler for each token\u2019s validity and scope (one cheap call per environment).")},outputSchema:{tokens:Pe.array(Pe.object({env:Pe.string().describe("Environment / Doppler config name"),source:Pe.string().describe('"store", "env:INFRA_KIT_ENV_TOKEN", or "-" when absent'),redactedToken:Pe.string().describe("Redacted token \u2014 last 4 chars at most, never the raw value"),present:Pe.boolean().describe("Whether a token is configured for this environment"),status:Pe.string().optional().describe("Only with check=true: valid | revoked | mis-scoped | unreachable")})).describe("One row per declared environment")},handler:di});import{z as gr}from"zod";import{$ as Z}from"zx";import{$ as Ph}from"zx";import{$ as I}from"zx";import{$ as Wr}from"zx";import Lr from"node:process";var Oo=async(e,r)=>{if(e.ok)return;let t=await e.text();throw l.error({status:e.status,statusText:e.statusText,error:t},r),new Error(`HTTP ${e.status}: ${e.statusText}`)},Do=async(e,r)=>{try{let{baseUrl:t,token:o,email:s,projectId:n}=r,i={name:e.name,projectId:e.projectId||n,description:e.description||"",released:e.released||!1,archived:e.archived||!1},a=`${t}/rest/api/3/version`,c=btoa(`${s}:${o}`),p=await fetch(a,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${c}`},body:JSON.stringify(i)});return await Oo(p,"Failed to create Jira version"),{success:!0,version:await p.json()}}catch(t){throw l.error({error:t},"Error creating Jira version"),t}},dr=async e=>{try{let{baseUrl:r,token:t,email:o,projectId:s}=e,n=`${r}/rest/api/3/project/${s}/versions`,i=btoa(`${o}:${t}`),a=await fetch(n,{method:"GET",headers:{Accept:"application/json",Authorization:`Basic ${i}`}});return await Oo(a,"Failed to get Jira project versions"),await a.json()}catch(r){throw l.error({error:r},"Error getting Jira project versions"),r}},xt=async(e,r)=>{try{return(await dr(r)).find(s=>s.name===e)||null}catch(t){throw l.error({error:t,versionName:e},"Error finding Jira version by name"),t}},Pt=async(e,r)=>{try{let{baseUrl:t,token:o,email:s}=r,n={};e.released!==void 0&&(n.released=e.released),e.archived!==void 0&&(n.archived=e.archived),e.releaseDate!==void 0&&(n.releaseDate=e.releaseDate),e.description!==void 0&&(n.description=e.description);let i=`${t}/rest/api/3/version/${e.versionId}`,a=btoa(`${s}:${o}`),c=await fetch(i,{method:"PUT",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${a}`},body:JSON.stringify(n)});return await Oo(c,"Failed to update Jira version"),{success:!0,version:await c.json()}}catch(t){throw l.error({error:t},"Error updating Jira version"),t}},Fo=async(e,r)=>{try{let{versionName:t}=e,o=await xt(t,r);if(!o)throw l.error({versionName:t},"Jira version not found"),new Error(`Version "${t}" not found in Jira project`);return await Pt({versionId:o.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},r)}catch(t){throw l.error({error:t},"Error delivering Jira release"),t}},mr=async()=>{let e=Lr.env.JIRA_BASE_URL,r=Lr.env.JIRA_TOKEN||Lr.env.JIRA_API_TOKEN,t=Lr.env.JIRA_PROJECT_ID,o=Lr.env.JIRA_EMAIL,s=[];if(e||s.push("JIRA_BASE_URL (e.g., https://your-domain.atlassian.net)"),r||s.push("JIRA_TOKEN or JIRA_API_TOKEN (your Jira API token)"),t||s.push("JIRA_PROJECT_ID (numeric project ID)"),o||s.push("JIRA_EMAIL (your Jira email address)"),s.length>0){let i=["Jira configuration is required but incomplete.","Please configure the following environment variables:",...s.map(a=>` - ${a}`),"","You can set these in your .env file or as environment variables."].join(`
|
|
182
|
+
`);throw new Error(i)}let n=Number.parseInt(t,10);if(Number.isNaN(n))throw new TypeError(`Invalid JIRA_PROJECT_ID: "${t}" must be a numeric value (e.g., 10001)`);return{baseUrl:e.replace(/\/$/,""),token:r,projectId:n,email:o}},Ve=async()=>{try{return await mr()}catch(e){return l.warn({error:e},"Jira configuration not available, skipping Jira integration"),null}};var mi="dev",ur=e=>e==="hotfix"?"main":"dev",jo=async(e="regular")=>{let r=ur(e);Wr.quiet=!0,await Wr`git fetch origin`,await Wr`git switch ${r}`,await Wr`git pull origin ${r}`,Wr.quiet=!1},Mo=async e=>{let{id:r,jiraConfig:t,description:o,type:s="regular"}=e,n=G(r),i=await Do({name:n,projectId:t.projectId,description:o||"",released:!1,archived:!1},t),a=`${t.baseUrl}/projects/${i.version.projectId}/versions/${i.version.id}/tab/release-report-all-issues`,c=await Tt({id:r,jiraVersionUrl:a,type:s,description:o});return{version:S(r),type:s,branchName:c.branchName,prUrl:c.prUrl,jiraVersionUrl:a}},C=async()=>{let e=new Map,r=await Ve();if(!r)return e;try{let t=await dr(r);for(let o of t)o.description&&e.set(o.name,o.description)}catch{}return e},Vr=(e,r,t)=>{let o=t?" ".repeat(t-e.length+3):" ",s=`[${r}]`.padEnd(11);return`${e}${o}${s}`},E=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",ui=e=>e.flatMap(r=>{let t=_(r);return t?[{branch:r,id:t,label:S(t)}]:[]}),ge=e=>{try{return ye(pe(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")'})}},Br=e=>{if(e===mi)return mi;let r=_(e);return r?S(r):e},Be=e=>e.flatMap(r=>{let t=_(r);return t?[S(t)]:[]}),bl=(e,r)=>r?r.get(e)||"regular":void 0,A=e=>{let{branches:r,descriptions:t,types:o}=e;return ui(r).map(({branch:s,id:n,label:i})=>({value:s,label:i,description:t.get(G(n)),type:bl(s,o)}))};var El=e=>e.map(r=>({pr:r,id:_(r.headRefName)})).filter(r=>r.id!==null).sort((r,t)=>Ln(r.id,t.id,{a:r.pr.createdAt,b:t.pr.createdAt})).map(r=>r.pr),xl=async()=>{let e=await I`gh pr list --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,r=await I`gh pr list --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName,createdAt`,t=[...JSON.parse(e.stdout),...JSON.parse(r.stdout)],o=new Set;return t.filter(s=>o.has(s.headRefName)?!1:(o.add(s.headRefName),!0))},fi=async()=>{try{let e=await xl();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 El(e)}catch(e){throw e instanceof f?e:(l.error({error:e},"\u274C Error fetching release PRs"),new f(e,{operation:"fetch release PRs"}))}},Ct=async()=>(await fi()).map(r=>r.headRefName),x=async()=>(await fi()).map(r=>({branch:r.headRefName,title:r.title,createdAt:r.createdAt})),St=async e=>{let{branch:r,body:t}=e;try{I.quiet=!0,await I`gh pr edit ${r} --body ${t}`,I.quiet=!1}catch(o){throw l.error({error:o,branch:r},`Error updating release PR body for ${r}`),o}},Tt=async e=>{let{id:r,jiraVersionUrl:t,type:o,description:s}=e,n=Mn(r,o),i=ur(o),a=ye(r),c=s&&s.trim()!==""?`${t}
|
|
183
183
|
|
|
184
184
|
${s}`:`${t}
|
|
185
|
-
`;try{I.quiet=!0,await I`git switch ${i}`,await I`git pull origin ${i}`,await I`git checkout -b ${a}`,await I`git push -u origin ${a}`,await I`git commit --allow-empty-message --allow-empty --message ''`,await I`git push origin ${a}`;let d=(await I`gh pr create --title ${n} --body ${c} --base ${i} --head ${a}`).stdout.trim();return await I`git switch ${i}`,I.quiet=!1,{branchName:a,prUrl:d}}catch(p){throw l.error({error:p,branchName:a},`Error creating release branch ${a}`),p}};var M=async e=>{let{operation:r,requiredBranch:t}=e;if(await
|
|
186
|
-
`),e),
|
|
185
|
+
`;try{I.quiet=!0,await I`git switch ${i}`,await I`git pull origin ${i}`,await I`git checkout -b ${a}`,await I`git push -u origin ${a}`,await I`git commit --allow-empty-message --allow-empty --message ''`,await I`git push origin ${a}`;let d=(await I`gh pr create --title ${n} --body ${c} --base ${i} --head ${a}`).stdout.trim();return await I`git switch ${i}`,I.quiet=!1,{branchName:a,prUrl:d}}catch(p){throw l.error({error:p,branchName:a},`Error creating release branch ${a}`),p}};var M=async e=>{let{operation:r,requiredBranch:t}=e;if(await Bn())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 Wn();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 Vn())throw new f(void 0,{operation:r,remediation:"commit or stash your changes, then retry",stderrExcerpt:"working tree has uncommitted changes"})};import Cl from"node:process";var Jr=class extends Error{name="PromptCancelledError";constructor(){super("Prompt cancelled")}};import Pl from"node:process";var $t={enabled:!1},Tl=(e,r=t=>{Pl.stdout.write(t)})=>($t.enabled&&e&&e.structuredContent!=null&&r(`${JSON.stringify(e.structuredContent,null,2)}
|
|
186
|
+
`),e),gi=e=>{e.options.some(t=>t.long==="--json")||e.option("--json","Output the structured result as JSON on stdout (human logs stay on stderr)"),e.commands.forEach(gi)};var hi=()=>{if(rs()||!Cl.stdin.isTTY||$t.enabled)throw new f(void 0,{operation:"interactive branch selection",remediation:"pass the branch selection explicitly (CLI: `--version`/`--versions`/`--all`; MCP: the `version`/`versions`/`all` fields) for non-interactive, --json, or MCP runs"})},Te=async e=>{hi();let{runBranchPicker:r}=await import("./boot-EEEVHAMO.js"),t=await r(e);if(t===null)throw new Jr;return t},fr=async(e,r)=>{hi();let{runBranchMultiPicker:t}=await import("./boot-EEEVHAMO.js"),o=await t(e,r);if(o===null)throw new Jr;return o};var vi=async e=>{let{all:r,confirmedCommand:t}=e;await M({operation:"merge dev into release branches",requiredBranch:"dev"});let s=(await x()).filter(p=>E(p.title)==="regular").map(p=>p.branch);if(s.length===0)return l.info("\u2139\uFE0F No open release branches found"),u.print(),{content:g(JSON.stringify({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0},null,2)),structuredContent:{successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0}};let n=[];if(r)n=s;else{u.setInteractive();let p=await C();n=await fr(A({branches:s,descriptions:p}),{required:!0})}n.length===s.length?u.addOption("--all",!0):u.addOption("--versions",Be(n)),await D(t,`Are you sure you want to merge dev into these branches: ${n.join(", ")}?`),t||u.addOption("--yes",!0),Z.quiet=!0,await Z`git fetch origin`,await Z`git switch dev`,await Z`git pull origin dev`;let a=[];for(let p of n)await Sl(p)||a.push(p);if(Z.quiet=!1,a.length>0){l.info(`
|
|
187
187
|
\u26A0\uFE0F ${a.length} branch(es) failed to merge automatically.
|
|
188
188
|
`),l.info("\u{1F4CB} Manual merge script for failed branches:");for(let p of a)l.info(`# Merge dev into ${p} and resolve conflicts if any
|
|
189
189
|
|
|
190
190
|
git switch ${p} && git pull origin ${p} && git merge origin/dev
|
|
191
191
|
git push origin ${p} && git switch dev
|
|
192
192
|
`);l.info(`\u2705 ${n.length-a.length}/${n.length} merges completed successfully.`)}else l.info(`\u2705 All merges completed successfully!
|
|
193
|
-
`);u.print();let c={successfulMerges:n.length-a.length,failedMerges:a.length,failedBranches:a,totalBranches:n.length};return{content:g(JSON.stringify(c,null,2)),structuredContent:c}},Tl=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`,l.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 l.error({error:r,branch:e,msg:t.message}),await Z`git reset --merge HEAD~1`,!1}},Lo=v({name:"gh-merge-dev",description:"Merge origin/dev into every open regular (non-hotfix) release branch and push the result. Mutates local git state and the remote release branches. When invoked via MCP, pass all=true \u2014 the branch picker is unreachable without a TTY, and the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. Irreversible once pushed.",inputSchema:{all:gr.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:gr.number().describe("Number of successful merges"),failedMerges:gr.number().describe("Number of failed merges"),failedBranches:gr.array(gr.string()).describe("List of branches that failed to merge"),totalBranches:gr.number().describe("Total number of branches processed")},handler:hi});import{z as Gr}from"zod";import{$ as L}from"zx";var vi=(e,r)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-r).trim()},Kr=e=>{if(e===null||typeof e!="object")return{message:String(e)};let r=e,t={};e instanceof Error?(t.name=e.name,t.message=e.message):typeof r.message=="string"&&(t.message=r.message);let o=r.exitCode;(typeof o=="number"||o===null)&&(t.exitCode=o);let s=vi(r.stderr,500);s&&(t.stderr=s);let n=vi(r.stdout,200);return n&&(t.stdout=n),t};import{$ as ki}from"zx";var Ur=async e=>{let{branches:r,worktreeDir:t,repoName:o,pruneFolder:s=!1}=e,n=await Promise.allSettled(r.map(async a=>{let c=`${t}/${a}`,p=de({repoName:o,branch:a});return await er(p),await ki`git worktree remove ${c}`,a})),i=[];for(let[a,c]of n.entries())if(c.status==="fulfilled")i.push(c.value);else{let p=r[a],d=new f(c.reason,{operation:`remove worktree for ${p}`,remediation:"check 'git worktree list' for the path; uncommitted changes block removal"});l.error({error:c.reason,msg:d.message})}return s&&i.length===r.length&&await ki`git worktree prune`,i};var hr=async(e,r,t)=>{try{return await t()}catch(o){throw l.error({err:Kr(o)},`\u274C Failed to ${e}`),new f(o,{operation:e,remediation:r})}},wi=async e=>{let r=await L`gh pr list --head ${e} --state all --json number,state,title --limit 1`;return JSON.parse(r.stdout)[0]??null},Cl=async e=>{let r=qt(e),t=await L`gh pr list --head dev --base main --state merged --json number,state,title --limit 20`;return JSON.parse(t.stdout).find(n=>n.title===r)??null},yi=async()=>{let e=await L`gh pr list --head dev --base main --state open --json number,state,title --limit 5`;return JSON.parse(e.stdout)[0]??null},Sl=async e=>{let r=he(e),t=await wi(r);if(!t)throw l.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}},$l=async()=>{let e=await x(),r=e.map(i=>i.branch),t=new Map(e.map(i=>[i.branch,E(i.title)]));u.setInteractive();let o=await C(),s=await Te(A({branches:r,descriptions:o,types:t})),n=e.find(i=>i.branch===s);if(!n)throw l.error(`\u274C Release branch ${s} not found in open PRs.`),new f(void 0,{operation:`deliver release ${s}`,remediation:`confirm an open PR exists for ${s} ('gh pr list')`});return{selectedReleaseBranch:s,releasePrTitle:n.title}},_l=async e=>{if(!(await V("release")).includes(e))return;let[t,o]=await Promise.all([w(),ee()]),s=`${t}${te}`;if((await Ur({branches:[e],worktreeDir:s,repoName:o})).length===0)throw new f(void 0,{operation:`remove worktree for ${e} before merge`,remediation:`run manually: git worktree remove ${s}/${e} (use --force if uncommitted changes)`})},Al=async e=>{let{selectedReleaseBranch:r,releaseType:t}=e,o=t==="hotfix"?"main":"dev",s=await wi(r);if(!s)throw new f(void 0,{operation:`look up release PR for ${r}`,remediation:"verify the PR exists in GitHub"});if(s.state==="MERGED"){l.info(`\u2713 Release PR ${r} already merged \u2014 skipping`);return}if(s.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 hr(`merge release PR ${r} into ${o}`,`check 'gh pr view ${r}' for mergeability and required reviews`,async()=>{await L`gh pr merge ${r} --squash --admin --delete-branch`})},Il=async e=>{let r=S(e),t=qt(e),o=await yi();if(o){let n=o.number;return o.title!==t&&(l.info(`Adopting open dev \u2192 main PR #${n} ("${o.title}") and retitling for ${r}`),await hr(`retitle dev \u2192 main PR #${n} to "${t}"`,`update manually: gh pr edit ${n} --title "${t}"`,async()=>{await L`gh pr edit ${n} --title ${t}`})),n}await hr(`create RC PR (dev \u2192 main) for ${r}`,"run 'gh pr create --base main --head dev' manually to surface the underlying error (e.g. no commits between dev and main)",async()=>{await L`gh pr create --base main --head dev --title ${t} --body ""`});let s=await yi();if(!s)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 s.number},Nl=async e=>{let r=S(e);if(await Cl(e)){l.info(`\u2713 RC PR for ${r} already merged into main \u2014 skipping`);return}let o=await Il(e);await hr(`merge RC PR #${o} (dev \u2192 main) for ${r}`,`check 'gh pr view ${o}' for mergeability and required reviews`,async()=>{await L`gh pr merge ${o} --squash --admin`})},Ol=async()=>{L.quiet=!1,await hr("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await L`gh workflow run deploy-all.yml --ref main -f environment=prod`}),L.quiet=!0},Dl=async()=>{await hr("sync main back into dev","run manually: git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push",async()=>{await L`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},Fl=async e=>{try{await Bn(e)}catch(r){l.warn({err:Kr(r)},`Failed to delete local branch ${e} (non-blocking)`)}try{await Kn(e)}catch(r){l.warn({err:Kr(r)},`Failed to delete remote branch ${e} (non-blocking)`)}},jl=async e=>{let r=await Ve();if(!r){l.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let t=G(e);await Fo({versionName:t},r)}catch(t){l.error({err:Kr(t)},"Failed to deliver Jira release (non-blocking)")}},Ri=async e=>{let{version:r,confirmedCommand:t}=e;await M({operation:"deliver release"});let{selectedReleaseBranch:o,releasePrTitle:s}=r?await Sl(r):await $l(),n=_(o);if(!n)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=S(n);u.addOption("--version",i),l.info(`Delivering ${n.kind==="name"?"named release":"version"} ${o}`);let a=E(s);await D(t,`Are you sure you want to deliver version ${o} to production?`),u.addOption("--yes",!0),L.quiet=!0,await _l(o),await Al({selectedReleaseBranch:o,releaseType:a}),a!=="hotfix"&&await Nl(n),await Ol(),await Dl(),await Fl(o),L.quiet=!1,await jl(n),l.info(`Successfully delivered ${o} to production!`),u.print();let c={releaseBranch:o,version:i,type:a,success:!0};return{content:g(JSON.stringify(c,null,2)),structuredContent:c}},Wo=v({name:"gh-release-deliver",description:'Deliver a release to production. For hotfixes: squash-merges the release branch to main and dispatches the deploy-all workflow. For regular releases: squash-merges to dev, opens an RC PR, merges dev into main, dispatches the deploy-all workflow, then syncs main back to dev. Also releases the matching Jira fix version if Jira is configured. Dispatches the deploy workflow fire-and-forget \u2014 the tool returns once the workflow is accepted by GitHub, not when the deployment finishes. PR-merge steps are idempotent: re-running after a partial failure skips PRs that are already merged. Irreversible production operation: the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. "version" is required when invoked via MCP (the picker is unreachable without a TTY).',inputSchema:{version:Gr.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:Gr.string().describe("The release branch that was delivered"),version:Gr.string().describe("The version that was delivered"),type:Gr.enum(["regular","hotfix"]).describe("Release type"),success:Gr.boolean().describe("Whether the delivery was successful")},handler:Ri});import Wl from"@inquirer/confirm";import{z as Ce}from"zod";import{$ as Vo}from"zx";import Ml from"@inquirer/select";var _t=async(e,r)=>{if(e.length===0)throw new f(void 0,{operation:r,remediation:"pass --env <name> explicitly",stderrExcerpt:"the workflow declares no `environment` choices to pick from"});return $(t=>Ml({message:"\u{1F9EA} Select environment",choices:e.map(o=>({name:o,value:o}))},t))};var Ll=["prod"],bi=e=>Ll.includes(e),At=e=>e.filter(r=>!bi(r)),It=(e,r)=>{if(bi(e))throw new f(void 0,{operation:r,remediation:"use `infra-kit release deliver` \u2014 it merges the release to main, opens the RC PR, deploys from main, and releases the Jira version",stderrExcerpt:`"${e}" is delivered, not deployed ad-hoc`})};var Vl="deploy-all.yml",Jl=async e=>{let{confirmedCommand:r,branch:t,env:o}=e;if(r)return!0;u.setInteractive();let s=await $(n=>Wl({message:`Deploy ${t} \u2192 ${o}?`,default:!1},n));return s&&u.addOption("--yes",!0),s},Ei=async e=>{let{version:r,env:t,skipTerraform:o,confirmedCommand:s}=e,n="";if(r)n=r==="dev"?"dev":he(r);else{u.setInteractive();let d=await x(),m=d.map(b=>b.branch),h=new Map(d.map(b=>[b.branch,E(b.title)])),y=await C();n=await Te([{value:"dev",label:"dev"},...A({branches:m,descriptions:y,types:h})])}let i=Jr(n);u.addOption("--version",i);let a=At(await Sr(Vl)),c="";t?c=t:(u.setInteractive(),c=await _t(a,"launch deploy-all workflow")),u.addOption("--env",c),It(c,"launch deploy-all workflow");let p=o??!1;if(p&&u.addOption("--skip-terraform",!0),!await Jl({confirmedCommand:s,branch:n,env:c})){l.info("Deployment cancelled");let d={releaseBranch:n,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 ${n} -f environment=${c} ${p?["-f","skip_terraform_deploy=true"]:[]}`,Vo.quiet=!1,l.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${n} and environment: ${c}`),u.print();let m={releaseBranch:n,version:i,environment:c,skipTerraformDeploy:p,success:!0};return{content:g(JSON.stringify(m,null,2)),structuredContent:m}}catch(d){throw l.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"})}},Jo=v({name:"gh-release-deploy-all",description:'Dispatch the deploy-all.yml GitHub Actions workflow to deploy every service from a release branch to the given environment. Fire-and-forget \u2014 returns once GitHub accepts the workflow_dispatch, NOT when the deployment finishes; watch the workflow run for completion status. Use gh-release-deploy-selected for a subset of services. Pass version="dev" to deploy from the dev branch instead of a release branch. Both "version" and "env" are required when invoked via MCP (interactive pickers are unavailable without a TTY).',inputSchema:{version:Ce.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:Ce.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),skipTerraform:Ce.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:Ce.string().describe("The release branch that was deployed"),version:Ce.string().describe("The version that was deployed"),environment:Ce.string().describe("The environment deployed to"),skipTerraformDeploy:Ce.boolean().describe("Whether terraform deployment was skipped"),success:Ce.boolean().describe("Whether the deployment was successful")},handler:Ei});import Bl from"@inquirer/checkbox";import Kl from"@inquirer/confirm";import Ul from"node:fs/promises";import{resolve as Gl}from"node:path";import zl from"yaml";import{z as U}from"zod";import{$ as Bo}from"zx";var Nt="deploy-selected-services.yml",ql="skip_terraform_deploy",Hl=async e=>{let{confirmedCommand:r,branch:t,env:o}=e;if(r)return!0;u.setInteractive();let s=await $(n=>Kl({message:`Deploy ${t} \u2192 ${o}?`,default:!1},n));return s&&u.addOption("--yes",!0),s},xi=async e=>{let{version:r,env:t,services:o,skipTerraform:s,confirmedCommand:n}=e,i="";if(r)i=r==="dev"?"dev":he(r);else{u.setInteractive();let R=await x(),T=R.map(Q=>Q.branch),Ue=new Map(R.map(Q=>[Q.branch,E(Q.title)])),W=await C();i=await Te([{value:"dev",label:"dev"},...A({branches:T,descriptions:W,types:Ue})])}let a=Jr(i);u.addOption("--version",a);let c=At(await Sr(Nt)),p="";t?p=t:(u.setInteractive(),p=await _t(c,"launch deploy-selected workflow")),u.addOption("--env",p),It(p,"launch deploy-selected workflow");let d=await Zl();if(d.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${Nt}`,stderrExcerpt:`no services found in .github/workflows/${Nt}`});let m=[];if(o&&o.length>0?m=o:(u.setInteractive(),m=await $(R=>Bl({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:d.map(T=>({name:T,value:T}))},R))),u.addOption("--services",m),m.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=m.filter(R=>!d.includes(R));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 y=s??!1;y&&u.addOption("--skip-terraform",!0);let b=R=>{let T={releaseBranch:i,version:a,environment:p,services:m,skipTerraformDeploy:y,success:R};return{content:g(JSON.stringify(T,null,2)),structuredContent:T}};if(!await Hl({confirmedCommand:n,branch:i,env:p}))return l.info("Deployment cancelled"),b(!1);try{Bo.quiet=!0;let R=m.flatMap(Ue=>["-f",`${Ue}=true`]);return await Bo`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${p} ${R} ${y?["-f","skip_terraform_deploy=true"]:[]}`,Bo.quiet=!1,l.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${p}, services: ${m.join(", ")}`),u.print(),b(!0)}catch(R){throw l.error({error:R},"\u274C Error launching workflow"),new f(R,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},Zl=async()=>{let e=await w(),r=Gl(e,".github/workflows",Nt),t;try{t=zl.parse(await Ul.readFile(r,"utf-8"))}catch{return[]}let s=t?.on?.workflow_dispatch?.inputs;return typeof s!="object"||s===null?[]:Object.entries(s).filter(([n,i])=>i?.type==="boolean"&&n!==ql).map(([n])=>n)},Ko=v({name:"gh-release-deploy-selected",description:'Dispatch the deploy-selected-services.yml GitHub Actions workflow to deploy a chosen subset of services from a release branch to the given environment. Fire-and-forget \u2014 returns once GitHub accepts the workflow_dispatch, NOT when the deployment finishes; watch the workflow run for completion status. Service names are validated against the boolean inputs declared in the workflow. Use gh-release-deploy-all for every service. "version", "env", and "services" are all required when invoked via MCP (interactive pickers are unavailable without a TTY).',inputSchema:{version:U.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:U.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),services:U.array(U.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:U.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:U.string().describe("The release branch that was deployed"),version:U.string().describe("The version that was deployed"),environment:U.string().describe("The environment deployed to"),services:U.array(U.string()).describe("The services that were deployed"),skipTerraformDeploy:U.boolean().describe("Whether terraform deployment was skipped"),success:U.boolean().describe("Whether the deployment was successful")},handler:xi});import{z as vr}from"zod";var Pi=async()=>{let r=(await x()).flatMap(i=>{let a=_(i.branch);return a?[{version:S(a),jiraKey:G(a),type:E(i.title)}]:[]}),t=await C(),o=Math.max(...r.map(i=>i.version.length)),s=r.map(i=>{let a=Vr(i.version,i.type,o),c=t.get(i.jiraKey);return c?`${a} ${c}`:a});l.info(`All release branches:
|
|
193
|
+
`);u.print();let c={successfulMerges:n.length-a.length,failedMerges:a.length,failedBranches:a,totalBranches:n.length};return{content:g(JSON.stringify(c,null,2)),structuredContent:c}},Sl=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`,l.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 l.error({error:r,branch:e,msg:t.message}),await Z`git reset --merge HEAD~1`,!1}},Lo=v({name:"gh-merge-dev",description:"Merge origin/dev into every open regular (non-hotfix) release branch and push the result. Mutates local git state and the remote release branches. When invoked via MCP, pass all=true \u2014 the branch picker is unreachable without a TTY, and the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. Irreversible once pushed.",inputSchema:{all:gr.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:gr.number().describe("Number of successful merges"),failedMerges:gr.number().describe("Number of failed merges"),failedBranches:gr.array(gr.string()).describe("List of branches that failed to merge"),totalBranches:gr.number().describe("Total number of branches processed")},handler:vi});import{z as Gr}from"zod";import{$ as L}from"zx";var ki=(e,r)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-r).trim()},Kr=e=>{if(e===null||typeof e!="object")return{message:String(e)};let r=e,t={};e instanceof Error?(t.name=e.name,t.message=e.message):typeof r.message=="string"&&(t.message=r.message);let o=r.exitCode;(typeof o=="number"||o===null)&&(t.exitCode=o);let s=ki(r.stderr,500);s&&(t.stderr=s);let n=ki(r.stdout,200);return n&&(t.stdout=n),t};import{$ as yi}from"zx";var Ur=async e=>{let{branches:r,worktreeDir:t,repoName:o,pruneFolder:s=!1}=e,n=await Promise.allSettled(r.map(async a=>{let c=`${t}/${a}`,p=de({repoName:o,branch:a});return await er(p),await yi`git worktree remove ${c}`,a})),i=[];for(let[a,c]of n.entries())if(c.status==="fulfilled")i.push(c.value);else{let p=r[a],d=new f(c.reason,{operation:`remove worktree for ${p}`,remediation:"check 'git worktree list' for the path; uncommitted changes block removal"});l.error({error:c.reason,msg:d.message})}return s&&i.length===r.length&&await yi`git worktree prune`,i};var hr=async(e,r,t)=>{try{return await t()}catch(o){throw l.error({err:Kr(o)},`\u274C Failed to ${e}`),new f(o,{operation:e,remediation:r})}},Ri=async e=>{let r=await L`gh pr list --head ${e} --state all --json number,state,title --limit 1`;return JSON.parse(r.stdout)[0]??null},$l=async e=>{let r=qt(e),t=await L`gh pr list --head dev --base main --state merged --json number,state,title --limit 20`;return JSON.parse(t.stdout).find(n=>n.title===r)??null},wi=async()=>{let e=await L`gh pr list --head dev --base main --state open --json number,state,title --limit 5`;return JSON.parse(e.stdout)[0]??null},_l=async e=>{let r=ge(e),t=await Ri(r);if(!t)throw l.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}},Al=async()=>{let e=await x(),r=e.map(i=>i.branch),t=new Map(e.map(i=>[i.branch,E(i.title)]));u.setInteractive();let o=await C(),s=await Te(A({branches:r,descriptions:o,types:t})),n=e.find(i=>i.branch===s);if(!n)throw l.error(`\u274C Release branch ${s} not found in open PRs.`),new f(void 0,{operation:`deliver release ${s}`,remediation:`confirm an open PR exists for ${s} ('gh pr list')`});return{selectedReleaseBranch:s,releasePrTitle:n.title}},Il=async e=>{if(!(await V("release")).includes(e))return;let[t,o]=await Promise.all([w(),ee()]),s=`${t}${te}`;if((await Ur({branches:[e],worktreeDir:s,repoName:o})).length===0)throw new f(void 0,{operation:`remove worktree for ${e} before merge`,remediation:`run manually: git worktree remove ${s}/${e} (use --force if uncommitted changes)`})},Nl=async e=>{let{selectedReleaseBranch:r,releaseType:t}=e,o=t==="hotfix"?"main":"dev",s=await Ri(r);if(!s)throw new f(void 0,{operation:`look up release PR for ${r}`,remediation:"verify the PR exists in GitHub"});if(s.state==="MERGED"){l.info(`\u2713 Release PR ${r} already merged \u2014 skipping`);return}if(s.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 hr(`merge release PR ${r} into ${o}`,`check 'gh pr view ${r}' for mergeability and required reviews`,async()=>{await L`gh pr merge ${r} --squash --admin --delete-branch`})},Ol=async e=>{let r=S(e),t=qt(e),o=await wi();if(o){let n=o.number;return o.title!==t&&(l.info(`Adopting open dev \u2192 main PR #${n} ("${o.title}") and retitling for ${r}`),await hr(`retitle dev \u2192 main PR #${n} to "${t}"`,`update manually: gh pr edit ${n} --title "${t}"`,async()=>{await L`gh pr edit ${n} --title ${t}`})),n}await hr(`create RC PR (dev \u2192 main) for ${r}`,"run 'gh pr create --base main --head dev' manually to surface the underlying error (e.g. no commits between dev and main)",async()=>{await L`gh pr create --base main --head dev --title ${t} --body ""`});let s=await wi();if(!s)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 s.number},Dl=async e=>{let r=S(e);if(await $l(e)){l.info(`\u2713 RC PR for ${r} already merged into main \u2014 skipping`);return}let o=await Ol(e);await hr(`merge RC PR #${o} (dev \u2192 main) for ${r}`,`check 'gh pr view ${o}' for mergeability and required reviews`,async()=>{await L`gh pr merge ${o} --squash --admin`})},Fl=async()=>{L.quiet=!1,await hr("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await L`gh workflow run deploy-all.yml --ref main -f environment=prod`}),L.quiet=!0},jl=async()=>{await hr("sync main back into dev","run manually: git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push",async()=>{await L`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},Ml=async e=>{try{await Jn(e)}catch(r){l.warn({err:Kr(r)},`Failed to delete local branch ${e} (non-blocking)`)}try{await Kn(e)}catch(r){l.warn({err:Kr(r)},`Failed to delete remote branch ${e} (non-blocking)`)}},Ll=async e=>{let r=await Ve();if(!r){l.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let t=G(e);await Fo({versionName:t},r)}catch(t){l.error({err:Kr(t)},"Failed to deliver Jira release (non-blocking)")}},bi=async e=>{let{version:r,confirmedCommand:t}=e;await M({operation:"deliver release"});let{selectedReleaseBranch:o,releasePrTitle:s}=r?await _l(r):await Al(),n=_(o);if(!n)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=S(n);u.addOption("--version",i),l.info(`Delivering ${n.kind==="name"?"named release":"version"} ${o}`);let a=E(s);await D(t,`Are you sure you want to deliver version ${o} to production?`),u.addOption("--yes",!0),L.quiet=!0,await Il(o),await Nl({selectedReleaseBranch:o,releaseType:a}),a!=="hotfix"&&await Dl(n),await Fl(),await jl(),await Ml(o),L.quiet=!1,await Ll(n),l.info(`Successfully delivered ${o} to production!`),u.print();let c={releaseBranch:o,version:i,type:a,success:!0};return{content:g(JSON.stringify(c,null,2)),structuredContent:c}},Wo=v({name:"gh-release-deliver",description:'Deliver a release to production. For hotfixes: squash-merges the release branch to main and dispatches the deploy-all workflow. For regular releases: squash-merges to dev, opens an RC PR, merges dev into main, dispatches the deploy-all workflow, then syncs main back to dev. Also releases the matching Jira fix version if Jira is configured. Dispatches the deploy workflow fire-and-forget \u2014 the tool returns once the workflow is accepted by GitHub, not when the deployment finishes. PR-merge steps are idempotent: re-running after a partial failure skips PRs that are already merged. Irreversible production operation: the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. "version" is required when invoked via MCP (the picker is unreachable without a TTY).',inputSchema:{version:Gr.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:Gr.string().describe("The release branch that was delivered"),version:Gr.string().describe("The version that was delivered"),type:Gr.enum(["regular","hotfix"]).describe("Release type"),success:Gr.boolean().describe("Whether the delivery was successful")},handler:bi});import Bl from"@inquirer/confirm";import{z as Ce}from"zod";import{$ as Vo}from"zx";import Wl from"@inquirer/select";var _t=async(e,r)=>{if(e.length===0)throw new f(void 0,{operation:r,remediation:"pass --env <name> explicitly",stderrExcerpt:"the workflow declares no `environment` choices to pick from"});return $(t=>Wl({message:"\u{1F9EA} Select environment",choices:e.map(o=>({name:o,value:o}))},t))};var Vl=["prod"],Ei=e=>Vl.includes(e),At=e=>e.filter(r=>!Ei(r)),It=(e,r)=>{if(Ei(e))throw new f(void 0,{operation:r,remediation:"use `infra-kit release deliver` \u2014 it merges the release to main, opens the RC PR, deploys from main, and releases the Jira version",stderrExcerpt:`"${e}" is delivered, not deployed ad-hoc`})};var Jl="deploy-all.yml",Kl=async e=>{let{confirmedCommand:r,branch:t,env:o}=e;if(r)return!0;u.setInteractive();let s=await $(n=>Bl({message:`Deploy ${t} \u2192 ${o}?`,default:!1},n));return s&&u.addOption("--yes",!0),s},xi=async e=>{let{version:r,env:t,skipTerraform:o,confirmedCommand:s}=e,n="";if(r)n=r==="dev"?"dev":ge(r);else{u.setInteractive();let d=await x(),m=d.map(b=>b.branch),h=new Map(d.map(b=>[b.branch,E(b.title)])),y=await C();n=await Te([{value:"dev",label:"dev"},...A({branches:m,descriptions:y,types:h})])}let i=Br(n);u.addOption("--version",i);let a=At(await Sr(Jl)),c="";t?c=t:(u.setInteractive(),c=await _t(a,"launch deploy-all workflow")),u.addOption("--env",c),It(c,"launch deploy-all workflow");let p=o??!1;if(p&&u.addOption("--skip-terraform",!0),!await Kl({confirmedCommand:s,branch:n,env:c})){l.info("Deployment cancelled");let d={releaseBranch:n,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 ${n} -f environment=${c} ${p?["-f","skip_terraform_deploy=true"]:[]}`,Vo.quiet=!1,l.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${n} and environment: ${c}`),u.print();let m={releaseBranch:n,version:i,environment:c,skipTerraformDeploy:p,success:!0};return{content:g(JSON.stringify(m,null,2)),structuredContent:m}}catch(d){throw l.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"})}},Bo=v({name:"gh-release-deploy-all",description:'Dispatch the deploy-all.yml GitHub Actions workflow to deploy every service from a release branch to the given environment. Fire-and-forget \u2014 returns once GitHub accepts the workflow_dispatch, NOT when the deployment finishes; watch the workflow run for completion status. Use gh-release-deploy-selected for a subset of services. Pass version="dev" to deploy from the dev branch instead of a release branch. Both "version" and "env" are required when invoked via MCP (interactive pickers are unavailable without a TTY).',inputSchema:{version:Ce.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:Ce.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),skipTerraform:Ce.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:Ce.string().describe("The release branch that was deployed"),version:Ce.string().describe("The version that was deployed"),environment:Ce.string().describe("The environment deployed to"),skipTerraformDeploy:Ce.boolean().describe("Whether terraform deployment was skipped"),success:Ce.boolean().describe("Whether the deployment was successful")},handler:xi});import Ul from"@inquirer/checkbox";import Gl from"@inquirer/confirm";import zl from"node:fs/promises";import{resolve as ql}from"node:path";import Hl from"yaml";import{z as U}from"zod";import{$ as Jo}from"zx";var Nt="deploy-selected-services.yml",Zl="skip_terraform_deploy",Yl=async e=>{let{confirmedCommand:r,branch:t,env:o}=e;if(r)return!0;u.setInteractive();let s=await $(n=>Gl({message:`Deploy ${t} \u2192 ${o}?`,default:!1},n));return s&&u.addOption("--yes",!0),s},Pi=async e=>{let{version:r,env:t,services:o,skipTerraform:s,confirmedCommand:n}=e,i="";if(r)i=r==="dev"?"dev":ge(r);else{u.setInteractive();let R=await x(),T=R.map(Q=>Q.branch),Ue=new Map(R.map(Q=>[Q.branch,E(Q.title)])),W=await C();i=await Te([{value:"dev",label:"dev"},...A({branches:T,descriptions:W,types:Ue})])}let a=Br(i);u.addOption("--version",a);let c=At(await Sr(Nt)),p="";t?p=t:(u.setInteractive(),p=await _t(c,"launch deploy-selected workflow")),u.addOption("--env",p),It(p,"launch deploy-selected workflow");let d=await Xl();if(d.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${Nt}`,stderrExcerpt:`no services found in .github/workflows/${Nt}`});let m=[];if(o&&o.length>0?m=o:(u.setInteractive(),m=await $(R=>Ul({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:d.map(T=>({name:T,value:T}))},R))),u.addOption("--services",m),m.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=m.filter(R=>!d.includes(R));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 y=s??!1;y&&u.addOption("--skip-terraform",!0);let b=R=>{let T={releaseBranch:i,version:a,environment:p,services:m,skipTerraformDeploy:y,success:R};return{content:g(JSON.stringify(T,null,2)),structuredContent:T}};if(!await Yl({confirmedCommand:n,branch:i,env:p}))return l.info("Deployment cancelled"),b(!1);try{Jo.quiet=!0;let R=m.flatMap(Ue=>["-f",`${Ue}=true`]);return await Jo`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${p} ${R} ${y?["-f","skip_terraform_deploy=true"]:[]}`,Jo.quiet=!1,l.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${p}, services: ${m.join(", ")}`),u.print(),b(!0)}catch(R){throw l.error({error:R},"\u274C Error launching workflow"),new f(R,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},Xl=async()=>{let e=await w(),r=ql(e,".github/workflows",Nt),t;try{t=Hl.parse(await zl.readFile(r,"utf-8"))}catch{return[]}let s=t?.on?.workflow_dispatch?.inputs;return typeof s!="object"||s===null?[]:Object.entries(s).filter(([n,i])=>i?.type==="boolean"&&n!==Zl).map(([n])=>n)},Ko=v({name:"gh-release-deploy-selected",description:'Dispatch the deploy-selected-services.yml GitHub Actions workflow to deploy a chosen subset of services from a release branch to the given environment. Fire-and-forget \u2014 returns once GitHub accepts the workflow_dispatch, NOT when the deployment finishes; watch the workflow run for completion status. Service names are validated against the boolean inputs declared in the workflow. Use gh-release-deploy-all for every service. "version", "env", and "services" are all required when invoked via MCP (interactive pickers are unavailable without a TTY).',inputSchema:{version:U.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:U.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),services:U.array(U.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:U.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:U.string().describe("The release branch that was deployed"),version:U.string().describe("The version that was deployed"),environment:U.string().describe("The environment deployed to"),services:U.array(U.string()).describe("The services that were deployed"),skipTerraformDeploy:U.boolean().describe("Whether terraform deployment was skipped"),success:U.boolean().describe("Whether the deployment was successful")},handler:Pi});import{z as vr}from"zod";var Ti=async()=>{let r=(await x()).flatMap(i=>{let a=_(i.branch);return a?[{version:S(a),jiraKey:G(a),type:E(i.title)}]:[]}),t=await C(),o=Math.max(...r.map(i=>i.version.length)),s=r.map(i=>{let a=Vr(i.version,i.type,o),c=t.get(i.jiraKey);return c?`${a} ${c}`:a});l.info(`All release branches:
|
|
194
194
|
`),l.info(`
|
|
195
195
|
${s.join(`
|
|
196
196
|
`)}
|
|
197
|
-
`);let n={releases:r.map(i=>({version:i.version,type:i.type,description:t.get(i.jiraKey)||null})),count:r.length};return{content:g(JSON.stringify(n,null,2)),structuredContent:n}},Uo=v({name:"gh-release-list",description:"List every open release PR with its version, type (regular / hotfix), and associated Jira fix-version description. Read-only; sourced from GitHub and Jira.",inputSchema:{},outputSchema:{releases:vr.array(vr.object({version:vr.string().describe("Release version"),type:vr.enum(["regular","hotfix"]).describe("Release type"),description:vr.string().nullable().describe("Jira version description")})).describe("List of all release branches"),count:vr.number().describe("Number of release branches")},handler:
|
|
198
|
-
`).map(r=>{let t=r.indexOf(" ");return t===-1?null:_(r.slice(t+1))}).filter(r=>r!==null&&r.kind==="version").map(r=>r.raw),
|
|
197
|
+
`);let n={releases:r.map(i=>({version:i.version,type:i.type,description:t.get(i.jiraKey)||null})),count:r.length};return{content:g(JSON.stringify(n,null,2)),structuredContent:n}},Uo=v({name:"gh-release-list",description:"List every open release PR with its version, type (regular / hotfix), and associated Jira fix-version description. Read-only; sourced from GitHub and Jira.",inputSchema:{},outputSchema:{releases:vr.array(vr.object({version:vr.string().describe("Release version"),type:vr.enum(["regular","hotfix"]).describe("Release type"),description:vr.string().nullable().describe("Jira version description")})).describe("List of all release branches"),count:vr.number().describe("Number of release branches")},handler:Ti});import ap from"@inquirer/confirm";import _i from"@inquirer/select";import rn from"node:process";import{z as P}from"zod";import{question as on}from"zx";import{$ as Dt}from"zx";var Se=e=>e.slice(1).split(".").map(Number),Go=e=>[...e].sort((r,t)=>{let[o,s,n]=Se(r),[i,a,c]=Se(t);return o!==i?(o??0)-(i??0):s!==a?(s??0)-(a??0):(n??0)-(c??0)});var Si="next",Ql=/^v?(\d+)\.(\d+)\.(\d+)$/,ep=e=>e.replace(/^.*release\//,""),qo=e=>{let r=ep(e.trim()),t=Ql.exec(r);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null},Ci=e=>`${e[0]}.${e[1]}.${e[2]}`,Ho=e=>{let r=[...e.remoteBranches??[],...e.jiraVersions??[]],t=[],o=new Set;for(let s of r){let n=qo(s);if(!n)continue;let i=Ci(n);o.has(i)||(o.add(i),t.push(n))}return Go(t.map(s=>Ci(s))).map(s=>Se(`v${s}`))},Je=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},Ot=(e,r)=>{if(e.length===0)throw new Je;let t=e[e.length-1];if(r==="hotfix"){let[n,i]=t,a=e.reduce((c,p)=>p[0]===n&&p[1]===i?Math.max(c,p[2]):c,0);return`${n}.${i}.${a+1}`}let[o,s]=t;return`${o}.${s+1}.0`},Zo=e=>e.trim().toLowerCase()===Si,rp=e=>e==="regular"||e==="hotfix",$i=e=>"name"in e,tp=e=>{let r=e.trim();if(r==="")throw new Error("Release spec is empty");let t=r.indexOf(":"),o=r,s="regular",n="";if(t!==-1){o=r.slice(0,t).trim();let a=r.slice(t+1),c=a.indexOf(":"),p=c===-1?a.trim():a.slice(0,c).trim();n=c===-1?"":a.slice(c+1).trim();let d=p.toLowerCase();if(!rp(d))throw new Error(`Invalid release type "${p}". Expected "regular" or "hotfix".`);s=d}if(Zo(o)||qo(o)!==null){let a={version:o,type:s};return n!==""&&(a.description=n),a}let i={name:o,type:s};return n!==""&&(i.description=n),i},Yo=e=>{let r=e.id.raw;return e.description!==void 0&&e.description!==""?`${r}:${e.type}:${e.description}`:e.type==="hotfix"?`${r}:hotfix`:r},zo=(e,r)=>r!==void 0&&r!==""?{...e,description:r}:e,op=e=>{let r=e.name.trim();return rt(r),zo({id:{kind:"name",name:r,raw:r},type:e.type},e.description)},Xo=(e,r)=>{let t=[...r];return e.map(o=>{if($i(o))return op(o);let s=o.version.trim();if(s==="")throw new Error("Release entry has an empty version");if(Zo(s)){let a=Ot(t,o.type);return t.push(Se(`v${a}`)),zo({id:pe(a),type:o.type},o.description)}let n=qo(s);if(!n)throw new Error(`Invalid version "${s}". Expected semver like "1.2.5" or the token "next".`);let i=`${n[0]}.${n[1]}.${n[2]}`;return t.push(n),zo({id:pe(i),type:o.type},o.description)})},Qo=e=>e.some(r=>!$i(r)&&Zo(r.version));var np=e=>e.split(`
|
|
198
|
+
`).map(r=>{let t=r.indexOf(" ");return t===-1?null:_(r.slice(t+1))}).filter(r=>r!==null&&r.kind==="version").map(r=>r.raw),sp=async()=>{let e=Dt.quiet;try{Dt.quiet=!0;let r=await Dt`git ls-remote --heads origin 'release/v*'`;return np(r.stdout)}finally{Dt.quiet=e}},ip=async()=>{let e=await Ve();return e?(await dr(e)).map(t=>t.name):[]},en=async()=>{let[e,r]=await Promise.allSettled([sp(),ip()]);return e.status==="rejected"&&l.warn({error:e.reason},"Failed to list remote release branches; continuing without them"),r.status==="rejected"&&l.warn({error:r.reason},"Failed to fetch Jira versions; continuing without them"),Ho({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:r.status==="fulfilled"?r.value:[]})};var cp='"1.2.5" or "next"',lp=(e,r)=>{try{return Ot(e,r)}catch(t){if(t instanceof Je)return null;throw t}},tn=(e,r)=>{try{return Xo(e,r)}catch(t){throw t instanceof Je?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 jn?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}},pp=async(e,r)=>{let t=lp(e,r),o=t?` [${t}]`:"",s=(await on(` Version (e.g. ${cp})${o}: `)).trim(),n=s===""?t??"":s;return n===""&&(l.error("No version provided. Exiting..."),rn.exit(1)),n},dp=async()=>{let e=(await on(' Name (kebab-case, e.g. "checkout-redesign"): ')).trim();e===""&&(l.error("No name provided. Exiting..."),rn.exit(1));try{rt(e)}catch(r){let t=r instanceof Error?r.message:String(r);l.error(`${t} Exiting...`),rn.exit(1)}return e},mp=async e=>{u.setInteractive();let r=null,t=[],o=async()=>(r===null&&(r=await e(),t.push(...r)),t),s=[],n=!0;for(;n;){let i=s.length+1,a=await $(m=>_i({message:`Release #${i} \u2014 version or name?`,choices:[{name:"version (semver / next)",value:"version"},{name:"name (free-form)",value:"name"}],default:"version"},m)),c=await $(m=>_i({message:`Release #${i} \u2014 select type:`,choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"},m)),p;if(a==="name"){let m=await dp();p=tn([{name:m,type:c}],[])[0]}else{let m=await pp(await o(),c);p=tn([{version:m,type:c}],t)[0],p.id.kind==="version"&&t.push(Se(`v${p.id.raw}`))}let d=(await on(" Description (optional, press Enter to skip): ")).trim();s.push({...p,...d!==""?{description:d}:{}}),n=await $(m=>ap({message:"Add another release?",default:!1},m))}return s},up=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 ")},Ai=e=>{for(let r of e)u.addOption("--release",Yo(r))},fp=async(e,r)=>{if(e&&e.length>0){let o=Qo(e)?await r():[],s=tn(e,o);return Ai(s),s}let t=await mp(r);return Ai(t),t},gp=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"})},hp=async(e,r)=>{let t=e.map(up).join(`
|
|
199
199
|
- `);await D(r,`Create the following ${e.length} release(s)?
|
|
200
200
|
- ${t}
|
|
201
|
-
`),u.addOption("--yes",!0)},
|
|
201
|
+
`),u.addOption("--yes",!0)},vp=async e=>{let{entry:r,jiraConfig:t}=e,o=S(r.id),s=r.id.kind==="version"?`v${r.id.raw}`:r.id.name;try{await jo(r.type);let n=await Mo({id:r.id,jiraConfig:t,description:r.description,type:r.type});return l.info(`\u2705 Successfully created release: ${s} (${r.type})`),l.info(`\u{1F517} GitHub PR: ${n.prUrl}`),l.info(`\u{1F517} Jira Version: ${n.jiraVersionUrl}
|
|
202
202
|
`),{result:n}}catch(n){let i=new f(n,{operation:`create release ${s} (${r.type})`,remediation:"verify the version or name is unique and the base branch is clean"});return l.error(`\u274C ${i.message}
|
|
203
|
-
`),{failure:{version:o,error:i.message}}}},
|
|
203
|
+
`),{failure:{version:o,error:i.message}}}},kp=(e,r,t)=>{r===e?l.info(`\u2705 All ${e} release branch(es) were created successfully.`):r>0?(l.warn(`\u26A0\uFE0F ${r} of ${e} release branches were created successfully.`),l.warn(`\u274C ${t} release(s) failed.`)):l.error(`\u274C All ${e} release branch(es) failed to create.`)},Ii=async e=>{let{releases:r,confirmedCommand:t}=e,o=await mr(),s=null,i=await fp(r,async()=>(s===null&&(s=await en()),s));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"});gp(i),await M({operation:"create release",requiredBranch:ur(i[0].type)}),await hp(i,!!t);let a=[],c=[];for(let d of i){let{result:m,failure:h}=await vp({entry:d,jiraConfig:o});m&&a.push(m),h&&c.push(h)}kp(i.length,a.length,c.length),u.print();let p={createdBranches:a.map(d=>d.branchName),successCount:a.length,failureCount:c.length,releases:a,failedReleases:c};return{content:g(JSON.stringify(p,null,2)),structuredContent:p}},nn=v({name:"release-create",description:'Create one or more releases in a single call. Each entry in "releases" carries EITHER a "version" (semver or the literal token "next") OR a "name" (free-form kebab-case identifier) \u2014 exactly one is required and they are mutually exclusive. Each entry also has its own type (regular|hotfix, default regular) and optional description; all entries in one call must share the same type \u2014 mixed regular+hotfix batches are rejected (create them in separate invocations). For each release this tool switches to the appropriate base branch (dev for regular, main for hotfix), cuts the release branch (release/v<semver> for versions, release/<name> for names), opens a GitHub release PR, and creates the matching Jira fix version (v<semver> for versions, <name> for names). The literal token "next" auto-increments from the union of remote release branches and Jira fix versions (regular bumps minor + resets patch; hotfix bumps patch on the highest minor); multiple "next" tokens advance sequentially. Named releases never auto-bump and "next" is version-only. Must be run from the main repository checkout (not a linked worktree) on the matching base branch with a clean working tree. Confirmation is auto-skipped for MCP calls, so the caller is responsible for gating. Continues on per-release failure and reports successes/failures.',inputSchema:{releases:P.array(P.object({version:P.string().optional().describe('Version to create (e.g., "1.2.5") or the literal token "next" for auto-increment. Mutually exclusive with "name".'),name:P.string().optional().describe('Free-form kebab-case release name (e.g., "checkout-redesign"). Mutually exclusive with "version". Named releases never auto-bump.'),type:P.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" (branches off dev) or "hotfix" (branches off main).'),description:P.string().optional().describe("Optional description for the Jira version.")}).refine(e=>e.version===void 0!=(e.name===void 0),{message:'Each release entry must have exactly one of "version" or "name" (they are mutually exclusive).'}).transform(e=>e.name!==void 0?{name:e.name,type:e.type,...e.description?{description:e.description}:{}}:{version:e.version,type:e.type,...e.description?{description:e.description}:{}})).min(1).describe('One or more releases to create. Each entry has exactly one of "version" or "name", plus its own type and optional description.')},outputSchema:{createdBranches:P.array(P.string()).describe("List of created release branch names"),successCount:P.number().describe("Number of releases created successfully"),failureCount:P.number().describe("Number of releases that failed"),releases:P.array(P.object({version:P.string().describe("Version number"),type:P.enum(["regular","hotfix"]).describe("Release type"),branchName:P.string().describe("Release branch name"),prUrl:P.string().describe("GitHub PR URL"),jiraVersionUrl:P.string().describe("Jira version URL")})).describe("Detailed information for each created release with URLs"),failedReleases:P.array(P.object({version:P.string().describe("Version number that failed"),error:P.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:Ii});import{z as $e}from"zod";import{question as yp}from"zx";var Ni=(e,r)=>`${e.baseUrl}/projects/${r.projectId}/versions/${r.id}/tab/release-report-all-issues`,wp=(e,r)=>r.trim()!==""?`${e}
|
|
204
204
|
|
|
205
205
|
${r}`:`${e}
|
|
206
|
-
`,
|
|
207
|
-
(press Enter to keep current): `)).replace(/\n$/,"");return o===""?e:o},
|
|
206
|
+
`,Rp=async()=>{let e=await x(),r=e.map(n=>n.branch),t=new Map(e.map(n=>[n.branch,E(n.title)])),o=await C(),s=await Te(A({branches:r,descriptions:o,types:t}));return{branch:s,type:t.get(s)||"regular"}},bp=async e=>{let t=(await x()).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)},Ep=async e=>{let r=e===""?"(no current description)":`current: "${e}"`,o=(await yp(` New description ${r}
|
|
207
|
+
(press Enter to keep current): `)).replace(/\n$/,"");return o===""?e:o},Oi=async e=>{let{version:r,description:t,confirmedCommand:o}=e,s=await mr(),n;r?(n=ge(r),await bp(n)):(u.setInteractive(),n=(await Rp()).branch);let i=_(n);if(!i)throw new f(void 0,{operation:`edit description for ${n}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let a=S(i);u.addOption("--version",a);let c=G(i),p=await xt(c,s);if(!p)throw new f(void 0,{operation:`edit description for ${c}`,remediation:`create the Jira fix version "${c}" first or pick a different release`});let d=p.description??"",m;t!==void 0?(m=t,u.addOption("--description",m)):(u.setInteractive(),m=await Ep(d));let h=R=>{let T={version:a,branch:n,jiraVersionUrl:Ni(s,p),previousDescription:d,newDescription:m,changed:R};return{content:g(JSON.stringify(T,null,2)),structuredContent:T}};if(m===d)return l.info(`No change \u2014 description for ${c} is already: "${d}"`),u.print(),h(!1);await D(o,`Update description for ${c}?
|
|
208
208
|
from: "${d}"
|
|
209
209
|
to: "${m}"
|
|
210
|
-
`),u.addOption("--yes",!0),await Pt({versionId:p.id,description:m},s);let y=
|
|
211
|
-
`),u.print(),h(!0)},sn=v({name:"release-desc-edit",description:"Edit a release's description in Jira and in the matching GitHub release PR body. Accepts a release version or a release name: targets the Jira fix version named `v<version>` (versioned) or `<name>` (named) and the open PR on branch `release/v<version>` or `release/<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:$e.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:$e.string().describe("New description. Empty string clears the description.")},outputSchema:{version:$e.string().describe("Release version"),branch:$e.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:$e.string().describe("Jira fix version URL"),previousDescription:$e.string().describe("The description before the update"),newDescription:$e.string().describe("The description after the update"),changed:$e.boolean().describe("Whether the description actually changed")},handler:
|
|
210
|
+
`),u.addOption("--yes",!0),await Pt({versionId:p.id,description:m},s);let y=Ni(s,p),b=wp(y,m);return await St({branch:n,body:b}),l.info(`\u2705 Updated description for ${c}`),l.info(`\u{1F517} Jira Version: ${y}`),l.info(`\u{1F517} PR branch: ${n}
|
|
211
|
+
`),u.print(),h(!0)},sn=v({name:"release-desc-edit",description:"Edit a release's description in Jira and in the matching GitHub release PR body. Accepts a release version or a release name: targets the Jira fix version named `v<version>` (versioned) or `<name>` (named) and the open PR on branch `release/v<version>` or `release/<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:$e.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:$e.string().describe("New description. Empty string clears the description.")},outputSchema:{version:$e.string().describe("Release version"),branch:$e.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:$e.string().describe("Jira fix version URL"),previousDescription:$e.string().describe("The description before the update"),newDescription:$e.string().describe("The description after the update"),changed:$e.boolean().describe("Whether the description actually changed")},handler:Oi});import{existsSync as Mi}from"node:fs";import Li from"node:path";import Op from"node:process";import{z as he}from"zod";import{createHash as xp}from"node:crypto";import{readFileSync as Pp}from"node:fs";var Ft=e=>xp("sha256").update(Pp(e)).digest("hex");import{readFileSync as Ap,writeFileSync as Ip}from"node:fs";import Lt from"node:path";import{z as se}from"zod";import{readdirSync as $p}from"node:fs";import an from"node:path";var Y="vendor",Tp=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack"]),Cp=new Set([".sync-manifest.json",".eslintcache","log.txt"]),Sp=[".tsbuildinfo"],Di=e=>Tp.has(e),Fi=e=>Cp.has(e)?!0:Sp.some(r=>e.endsWith(r));var _p=e=>e.split(an.sep).join("/"),jt=e=>{let r=[],t=o=>{for(let s of $p(o,{withFileTypes:!0})){let n=an.join(o,s.name);if(s.isDirectory()){if(Di(s.name))continue;t(n);continue}Fi(s.name)||r.push(_p(an.relative(e,n)))}};return t(e),r.sort()};var ie=".sync-manifest.json",Mt=1,Np=se.object({schemaVersion:se.number().optional(),source:se.string(),commit:se.string(),syncedAt:se.string(),fileCount:se.number(),files:se.record(se.string(),se.string())}),cn=e=>(e.schemaVersion??Mt)>Mt,ji=e=>{let r={};for(let t of jt(e))try{r[t]=Ft(Lt.join(e,t))}catch(o){let s=o instanceof Error?o.message:String(o);throw new Error(`Cannot hash vendor file "${t}" (broken symlink or unreadable file): ${s}`)}return r},ln=e=>{let r=Lt.join(e,ie),t;try{t=Ap(r,"utf8")}catch{throw new Error(`Missing ${ie} at ${r}`)}let o=Np.safeParse(JSON.parse(t));if(!o.success)throw new Error(`Invalid ${ie} at ${r}: ${se.prettifyError(o.error)}`);return o.data},pn=(e,r)=>{let t=ji(e),o={schemaVersion:Mt,source:r.source,commit:r.commit,syncedAt:new Date().toISOString(),fileCount:Object.keys(t).length,files:t};return Ip(Lt.join(e,ie),`${JSON.stringify(o,null,2)}
|
|
212
212
|
`),o},dn=(e,r)=>{let t=r.files,o=jt(e),s=[],n=[];for(let c of o){if(!(c in t)){n.push(c);continue}Ft(Lt.join(e,c))!==t[c]&&s.push(c)}let i=new Set(o),a=Object.keys(t).filter(c=>!i.has(c));return{modified:s,added:n,removed:a}};var mn=30,un=(e,r)=>{if(r.length!==0){l.info(`
|
|
213
|
-
${e} (${r.length}):`);for(let t of r.slice(0,mn))l.info(` ${t}`);r.length>mn&&l.info(` \u2026and ${r.length-mn} more`)}},
|
|
213
|
+
${e} (${r.length}):`);for(let t of r.slice(0,mn))l.info(` ${t}`);r.length>mn&&l.info(` \u2026and ${r.length-mn} more`)}},Wi=async(e={})=>{let r=e.cwd??await w(),t=Li.join(r,Y),o={modified:[],added:[],removed:[],fileCount:0};if(!Mi(t)){l.info(`\u2139\uFE0F No ${Y}/ folder found \u2014 nothing to check.`);let d={status:"skipped",ok:!0,...o};return{content:g(JSON.stringify(d,null,2)),structuredContent:d}}if(!Mi(Li.join(t,ie))){l.error(`\u274C Missing ${Y}/${ie}. 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 s=ln(t);if(cn(s)){l.error(`\u274C ${Y}/${ie} has a newer schemaVersion (${String(s.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:n,added:i,removed:a}=dn(t,s),c=n.length>0||i.length>0||a.length>0;c?(l.error(`\u274C ${Y}/ has drifted from ${Y}/${ie}.`),l.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),un("Modified",n),un("Added (not in manifest)",i),un("Removed (in manifest, now missing)",a)):l.info(`\u2705 ${Y}/ matches manifest (${s.fileCount} files).`);let p={status:c?"drift":"clean",ok:!c,fileCount:s.fileCount,modified:n,added:i,removed:a};return{content:g(JSON.stringify(p,null,2)),structuredContent:p}},Dp={status:he.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:he.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:he.number(),modified:he.array(he.string()),added:he.array(he.string()),removed:he.array(he.string())},fn=v({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:Dp,handler:()=>Wi({cwd:Op.cwd()})});import{z as ce}from"zod";import{VENDOR_CONFIG_FILE as Wt,vendorConfigSchema as Fp}from"@slip-stream-kit/config/internal";import jp from"node:fs/promises";import Mp from"node:path";import{pathToFileURL as Lp}from"node:url";import{z as Wp}from"zod";import{defineVendorConfig as Iw}from"@slip-stream-kit/config/internal";var Vt=async e=>{let r=Mp.join(e,Wt),t;try{t=await jp.stat(r)}catch{throw new Error(`${Wt} not found at ${r}`)}let n=(await import(`${Lp(r).href}?mtime=${Number(t.mtimeMs)}`)).default;if(n===void 0)throw new Error(`${Wt} at ${r} has no default export`);let i=typeof n=="function"?await n():n,a=Fp.safeParse(i);if(!a.success)throw new Error(`Invalid ${Wt} at ${r}: ${Wp.prettifyError(a.error)}`);return a.data};import{existsSync as ae,mkdirSync as Vp,writeFileSync as Bp}from"node:fs";import X from"node:path";import{$ as zr}from"zx";var Jp=["node_modules","dist","*.tsbuildinfo",".turbo",".eslintcache",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack","log.txt"],Kp=`# vendor/ \u2014 mirrored from the source repo
|
|
214
214
|
|
|
215
215
|
**DO NOT EDIT files in this folder here.**
|
|
216
216
|
|
|
@@ -221,11 +221,11 @@ overwritten on the next sync and will fail \`infra-kit vendor check\` in CI.
|
|
|
221
221
|
To change a vendored package, edit it in the source repo and re-run the sync.
|
|
222
222
|
|
|
223
223
|
See \`.sync-manifest.json\` for the source commit and per-file checksums.
|
|
224
|
-
`,
|
|
225
|
-
`).map(n=>n.trim()).filter(Boolean)},Ji=(e,r)=>{let t=X.join(e,Y);ae(t)&&(
|
|
226
|
-
`,"utf-8"),{added:c,skipped:p}};import{$ as
|
|
227
|
-
`,"utf-8");let d=[],m=[];for(let h of t){let y=Kt.resolve(h);c.has(y)?d.push(h):m.push(h)}return{removed:d,notFound:m}};var Rn=async e=>{let{workspacePath:r,worktreeDir:t,currentBranches:o}=e,s=Ut.dirname(r),n=Ut.resolve(`${t}/release`),i=await Qp.readFile(r,"utf-8"),c=JSON.parse(i).folders??[],p=new Set(o.map(b=>Ut.resolve(`${t}/${b}`))),d=[];for(let b of c){let R=Ut.resolve(s,b.path);(R===n||R.startsWith(`${n}/`))&&!p.has(R)&&d.push(R)}let m=[];d.length>0&&(m=(await Zr({workspacePath:r,folderPaths:d})).removed);let h=o.map(b=>`${t}/${b}`),{added:y}=h.length>0?await qr({workspacePath:r,folderPaths:h}):{added:[]};return{added:y,removed:m}};import ea from"node:path";var Ke=(e,r)=>ea.isAbsolute(e)?e:ea.resolve(r,e);var bn=async e=>{let{projectRoot:r,worktreeDir:t,currentBranches:o,cursorConfig:s}=e;if(!s.workspaceConfigPath)return l.warn("\u26A0\uFE0F Skipping Cursor: workspaceConfigPath is not set."),{ran:!1,added:0,removed:0};let n=Ke(s.workspaceConfigPath,r);try{let{added:i,removed:a}=await Rn({workspacePath:n,worktreeDir:t,currentBranches:o});return o.length>0&&await Hr(n),{ran:!0,added:i.length,removed:a.length}}catch(i){return l.warn({error:i},`\u26A0\uFE0F Failed to reconcile/open Cursor workspace at ${n}`),{ran:!1,added:0,removed:0}}};import{$ as ed}from"zx";var En=async e=>{let{folderPaths:r}=e;for(let t of r)await ed`zed --add ${t}`;return{added:r}};import{$ as rd}from"zx";var xn=async e=>{let{projectRoot:r,worktreeDir:t,currentBranches:o}=e;if(o.length===0)return{ran:!1,added:0,removed:0};let s=[r,...o.map(n=>`${t}/${n}`)];try{return await rd`zed ${s}`,{ran:!0,added:o.length,removed:0}}catch(n){return l.warn({error:n},"\u26A0\uFE0F Failed to open Zed workspace"),{ran:!1,added:0,removed:0}}};import{$ as td}from"zx";var Pn=async e=>{let{projectRoot:r,worktreeDir:t,remainingBranches:o}=e,s=[r,...o.map(n=>`${t}/${n}`)];try{return await td`zed --reuse ${s}`,l.info(`\u21BB Refreshed Zed workspace to root + ${o.length} release worktree(s) (other folders in the focused window are not preserved)`),{ran:!0}}catch(n){return l.warn({error:n},"\u26A0\uFE0F Failed to refresh Zed workspace"),{ran:!1}}};var ke=e=>{throw new Error(`Unexpected value: ${JSON.stringify(e)}`)};var Tn=async e=>{let{projectRoot:r,worktreeDir:t,branches:o}=e,s=await O(),n=re(s),i=o.map(c=>`${t}/${c}`),a=[];for(let c of n)switch(c.provider){case"cursor":{if(!c.config.workspaceConfigPath){l.warn("\u26A0\uFE0F Skipping Cursor: ide.config.workspaceConfigPath is not set in infra-kit config"),a.push({ran:!1,provider:"cursor",added:0,skipped:0});break}let p=Ke(c.config.workspaceConfigPath,r),{added:d,skipped:m}=await qr({workspacePath:p,folderPaths:i}),h=m.length>0?` (${m.length} already present)`:"";l.info(`\u2705 Added ${d.length} folder(s) to ${p}${h}`),await Hr(p),a.push({ran:!0,provider:"cursor",added:d.length,skipped:m.length});break}case"zed":{let{added:p}=await En({folderPaths:i});l.info(`\u2705 Added ${p.length} folder(s) to Zed workspace`),a.push({ran:!0,provider:"zed",added:p.length,skipped:0});break}default:ke(c)}return a};var Cn=async e=>{let r=await O(),t=re(r),o=[];for(let s of t)switch(s.provider){case"cursor":{let n=await bn({...e,cursorConfig:s.config});o.push({...n,provider:"cursor"});break}case"zed":{let n=await xn(e);o.push({...n,provider:"zed"});break}default:ke(s)}return o};var Sn=e=>{switch(e){case"cursor":return"Cursor";case"zed":return"Zed";case void 0:return"IDE";default:return ke(e)}};var Yr=async e=>{let{projectRoot:r,worktreeDir:t,currentWorktrees:o,removedWorktrees:s,allowEditorRelaunch:n}=e;if(s.length===0)return[];let i=await O(),a=re(i),c=s.map(m=>`${t}/${m}`),p=o.filter(m=>!s.includes(m)),d=[];for(let m of a)switch(m.provider){case"cursor":{d.push(await od({ide:m,projectRoot:r,folderPaths:c}));break}case"zed":{d.push(await nd({projectRoot:r,worktreeDir:t,remainingBranches:p,allowEditorRelaunch:n}));break}default:ke(m)}return d},od=async e=>{let{ide:r,projectRoot:t,folderPaths:o}=e;if(!r.config.workspaceConfigPath)return{provider:"cursor",supported:!0,removed:[]};let s=Ke(r.config.workspaceConfigPath,t);try{let{removed:n}=await Zr({workspacePath:s,folderPaths:o});return n.length>0&&l.info(`\u2705 Removed ${n.length} folder(s) from ${s}`),{provider:"cursor",supported:!0,removed:n}}catch(n){return l.warn({error:n},`\u26A0\uFE0F Failed to update Cursor workspace at ${s}`),{provider:"cursor",supported:!0,removed:[]}}},nd=async e=>{let{projectRoot:r,worktreeDir:t,remainingBranches:o,allowEditorRelaunch:s}=e;return s?(await Pn({projectRoot:r,worktreeDir:t,remainingBranches:o}),{provider:"zed",supported:!0,removed:[]}):(l.info("\u2139\uFE0F Zed folder removal skipped (no interactive session); close removed worktree folders in Zed manually if needed."),{provider:"zed",supported:!0,removed:[]})};var Gt=["workspace","none"];var sd="feature",id="release",oa=async e=>{let{confirmedCommand:r,all:t,versions:o,githubDesktop:s,cmux:n}=e,i=e.ide??e.cursor;await M({operation:"create worktrees",requiredBranch:"dev"});try{let a=await V("release"),c=await w(),p=`${c}${te}`;await ta(`${p}/${id}`),await ta(`${p}/${sd}`);let d=[];if(o)d=o.split(",").map(W=>we(pe(W.trim())));else{let W=await x(),Q=W.map(Ge=>Ge.branch);if(Q.length===0)return l.info("\u2139\uFE0F No open release branches found"),u.print(),{content:g(JSON.stringify({createdWorktrees:[],count:0},null,2)),structuredContent:{createdWorktrees:[],count:0}};if(t)d=Q;else{u.setInteractive();let Ge=new Map(W.map(Fn=>[Fn.branch,E(Fn.title)])),et=await C();d=await fr(A({branches:Q,descriptions:et,types:Ge}),{required:!0})}}t?u.addOption("--all",!0):u.addOption("--versions",Je(d)),await D(r,"Are you sure you want to proceed with these worktree changes?"),r||u.addOption("--yes",!0);let m=await O(),h=i??(re(m).length>0?"workspace":"none");u.addOption("--ide",h);let y=s??m.worktrees?.openInGithubDesktop??await $(W=>ra({message:"Open created worktrees in GitHub Desktop?"},W));typeof s>"u"&&m.worktrees?.openInGithubDesktop===void 0&&u.setInteractive(),y?u.addOption("--github-desktop",!0):u.addOption("--no-github-desktop",!0);let b=n??m.worktrees?.openInCmux??await ra({message:"Open created worktrees in cmux?"});typeof n>"u"&&m.worktrees?.openInCmux===void 0&&u.setInteractive(),b?u.addOption("--cmux",!0):u.addOption("--no-cmux",!0);let{branchesToCreate:R}=ad({selectedReleaseBranches:d,currentWorktrees:a}),T=await cd(R,p);if(ld(T),h==="workspace"&&await Tn({projectRoot:c,worktreeDir:p,branches:T}),y)for(let W of T)await Xr`github ${p}/${W}`,await Xr`sleep 5`;if(b){let W=await ee(),Q=await mt();for(let Ge of T){let et=de({repoName:W,branch:Ge});Q.has(dt(et))||await ut({cwd:`${p}/${Ge}`,title:et})}}u.print();let Ue={createdWorktrees:T,count:T.length};return{content:g(JSON.stringify(Ue,null,2)),structuredContent:Ue}}catch(a){throw rr(a)?a:(l.error({error:a},"\u274C Error managing worktrees"),new f(a,{operation:"create worktrees",remediation:"verify branches don't already exist as worktrees: 'git worktree list'"}))}},ta=async e=>{await Xr`mkdir -p ${e}`},ad=e=>{let{selectedReleaseBranches:r,currentWorktrees:t}=e,o=t.filter(n=>tt(n));return{branchesToCreate:r.filter(n=>!o.includes(n))}},cd=async(e,r)=>{let t=await Promise.allSettled(e.map(async s=>{let n=`${r}/${s}`;return await Xr`git worktree add ${n} ${s}`,await Xr({cwd:n})`pnpm install`,s})),o=[];for(let[s,n]of t.entries())if(n.status==="fulfilled")o.push(n.value);else{let i=e[s],a=new f(n.reason,{operation:`git worktree add for ${i}`,remediation:"check the branch name and that the parent dir is writable"});l.error({error:n.reason,msg:a.message})}return o},ld=e=>{if(e.length>0){l.info("\u2705 Created git worktrees:");for(let r of e)l.info(r);l.info("")}else l.info("\u2139\uFE0F No new git worktrees to create")},$n=v({name:"worktrees-add",description:'Create local git worktrees for release branches under the worktrees directory and run "pnpm install" in each. Mutates the local filesystem. When invoked via MCP, pass either "versions" (comma-separated) or all=true \u2014 the branch picker and "open in Cursor / GitHub Desktop / cmux" follow-up prompts are unreachable without a TTY, and the CLI confirmation is auto-skipped for MCP calls.',inputSchema:{all:ye.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:ye.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:ye.enum(Gt).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:ye.enum(Gt).optional().describe('Deprecated alias for "ide". Prefer "ide". Ignored when "ide" is provided.'),githubDesktop:ye.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:ye.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:ye.array(ye.string()).describe("List of created git worktree branches"),count:ye.number().describe("Number of git worktrees created")},handler:oa});import{z as yr}from"zod";var na=async()=>{let e=await V("release");if(e.length===0)return l.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([x(),C()]),o=new Map(r.map(c=>[c.branch,E(c.title)])),s=e.flatMap(c=>{let p=_(c);if(!p)return[];let d=S(p),m=o.get(c)||"regular",h=t.get(G(p))||null;return[{version:d,type:m,description:h}]}),n=Math.max(...s.map(c=>c.version.length)),i=s.map(c=>{let p=Vr(c.version,c.type,n);return c.description?`${p} ${c.description}`:p});l.info(`\u{1F33F} Active worktrees:
|
|
224
|
+
`,Bi=()=>Jp.map(e=>`--exclude=${e}`),Bt=async e=>{try{return(await zr({cwd:e})`git rev-parse HEAD`).stdout.trim()}catch{return"unknown"}},Up=async(e,r)=>{if(!ae(e))return!1;ae(r)&&await zr`rm -rf ${r}`;let t=`${e}/`,o=`${r}/`;return await zr`rsync -a ${Bi()} ${t} ${o}`,!0},Gp=async(e,r)=>{if(!ae(e))return!1;let t=X.dirname(r);return ae(t)||Vp(t,{recursive:!0}),await zr`cp ${e} ${r}`,!0},zp=async(e,r)=>{if(!ae(e))return[];if(!ae(r))return[`missing target: ${r}`];let t=`${e}/`,o=`${r}/`;return(await zr`rsync -ai --dry-run --delete ${Bi()} ${t} ${o}`).stdout.split(`
|
|
225
|
+
`).map(n=>n.trim()).filter(Boolean)},Ji=(e,r)=>{let t=X.join(e,Y);ae(t)&&(Bp(X.join(t,"README.md"),Kp),pn(t,r))},gn=(e,r)=>X.join(Ws(e),r),kr=(e,r)=>r?e.filter(t=>r.includes(t)):e,Vi=(e,r,t,o,s)=>{let n=X.resolve(e),i=X.resolve(r);if(i!==n&&!i.startsWith(n+X.sep))throw new f(void 0,{operation:`sync vendor item ${s}`,stderrExcerpt:`${t} escapes repo root: ${o}`})},Ki=async(e,r,t,o,s)=>{let n=[];for(let i of o){let a=gn(t,i);if(!ae(a)){n.push({repo:i,copied:0,total:e.copy.length,skipped:!0});continue}let c=0;for(let p of e.copy){let d=X.join(r,p.source),m=X.join(a,p.target);Vi(r,d,"source",p.source,p.name),Vi(a,m,"target",p.target,p.name),(p.type==="directory"?await Up(d,m):await Gp(d,m))&&c++}Ji(a,s),n.push({repo:i,copied:c,total:e.copy.length,skipped:!1})}return{source:s.source,commit:s.commit,repos:n}},Ui=async(e,r,t)=>{let o=[];for(let s of r){let n=gn(e,s),i=!ae(n);i||Ji(n,t),o.push({repo:s,skipped:i})}return o},Gi=async(e,r,t,o)=>{let s=[],n=e.copy.filter(i=>i.vendored===!0);for(let i of o){let a=gn(t,i);if(ae(a))for(let c of n){let p=X.join(r,c.source),d=X.join(a,c.target),m=await zp(p,d);m.length>0&&s.push({repo:i,target:c.target,changes:m})}}return s};var hn=20,zi=async(e={})=>{let r=e.cwd??await w(),t=await Vt(r),o=await cr(),s=kr(o.targets,e.repos),n=await Gi(t,r,o.workspaceDir,s);if(n.length===0)l.info("\u{1F389} No drift detected.");else for(let a of n){l.info(`\u274C ${a.repo} \u2192 ${a.target} (${a.changes.length} change(s)):`);for(let c of a.changes.slice(0,hn))l.info(` ${c}`);a.changes.length>hn&&l.info(` \u2026and ${a.changes.length-hn} more`)}let i={ok:n.length===0,drifted:n.length,entries:n};return{content:g(JSON.stringify(i,null,2)),structuredContent:i}},qp={ok:ce.boolean().describe("Whether every target is in sync with the source"),drifted:ce.number(),entries:ce.array(ce.object({repo:ce.string(),target:ce.string(),changes:ce.array(ce.string())}))},vn=v({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:ce.array(ce.string()).optional().describe("Restrict to these target repo names")},outputSchema:qp,handler:e=>zi({repos:e.repos})});import Hp from"node:path";import{z as _e}from"zod";var qi=async e=>{let r=e.cwd??await w(),t=await cr(),o=kr(t.targets,e.repos),s=await Bt(r),n=Hp.basename(r),i=await Ui(t.workspaceDir,o,{source:n,commit:s});for(let c of i)l.info(c.skipped?`\u26A0\uFE0F ${c.repo}: target does not exist \u2014 skipped`:`\u{1F4DD} ${c.repo}: manifest written`);let a={source:n,commit:s,repos:i};return{content:g(JSON.stringify(a,null,2)),structuredContent:a}},Zp={source:_e.string(),commit:_e.string(),repos:_e.array(_e.object({repo:_e.string(),skipped:_e.boolean()}))},kn=v({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:_e.array(_e.string()).optional().describe("Restrict to these target repo names")},outputSchema:Zp,handler:e=>qi({repos:e.repos,confirmedCommand:e.confirmedCommand})});import Yp from"@inquirer/confirm";import Hi from"node:path";import Zi from"node:process";import{z as le}from"zod";var Yi=async e=>{let r=e.cwd??await w(),t=await Vt(r),o=await cr(),s=kr(o.targets,e.repos);e.confirmedCommand||await $(p=>Yp({message:`Sync vendor files from ${Hi.basename(r)} into ${s.length} repo(s)?`},p),{output:Zi.stderr})||Zi.exit(0);let n=await Bt(r),i=Hi.basename(r),a=await Ki(t,r,o.workspaceDir,s,{source:i,commit:n});for(let c of a.repos)c.skipped?l.info(`\u26A0\uFE0F ${c.repo}: target does not exist \u2014 skipped`):l.info(`\u2705 ${c.repo}: copied ${c.copied}/${c.total} items + manifest`);return{content:g(JSON.stringify(a,null,2)),structuredContent:a}},Xp={source:le.string(),commit:le.string(),repos:le.array(le.object({repo:le.string(),copied:le.number(),total:le.number(),skipped:le.boolean()}))},yn=v({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:le.array(le.string()).optional().describe("Restrict to these target repo names")},outputSchema:Xp,handler:e=>Yi({repos:e.repos,confirmedCommand:e.confirmedCommand})});import{z as Qp}from"zod";var Xi=async()=>{let e=lt.version;l.info(e);let r={version:e};return{content:g(JSON.stringify(r,null,2)),structuredContent:r}},wn=v({name:"version",description:"Print the installed infra-kit CLI version",inputSchema:{},outputSchema:{version:Qp.string().describe("Installed infra-kit CLI version (from package.json)")},handler:Xi});import ta from"@inquirer/confirm";import{z as ke}from"zod";import{$ as Xr}from"zx";import Qi from"node:fs/promises";import Jt from"node:path";var qr=async e=>{let{workspacePath:r,folderPaths:t}=e,o=Jt.dirname(r),s;try{s=await Qi.readFile(r,"utf-8")}catch(d){throw new Error(`Cursor workspace file not found at ${r}: ${d.message}`)}let n;try{n=JSON.parse(s)}catch(d){throw new Error(`Failed to parse ${r} as JSON. Comments (JSONC) are not supported. ${d.message}`)}let i=n.folders??[],a=new Set(i.map(d=>Jt.resolve(o,d.path))),c=[],p=[];for(let d of t){let m=Jt.resolve(d);if(a.has(m)){p.push(d);continue}let h=Jt.relative(o,m);i.push({path:h}),a.add(m),c.push(d)}return n.folders=i,await Qi.writeFile(r,`${JSON.stringify(n,null,2)}
|
|
226
|
+
`,"utf-8"),{added:c,skipped:p}};import{$ as ed}from"zx";var Hr=async e=>{await ed`cursor ${e}`};import rd from"node:fs/promises";import Ut from"node:path";import ea from"node:fs/promises";import Kt from"node:path";var Zr=async e=>{let{workspacePath:r,folderPaths:t}=e,o=Kt.dirname(r),s;try{s=await ea.readFile(r,"utf-8")}catch(h){throw new Error(`Cursor workspace file not found at ${r}: ${h.message}`)}let n;try{n=JSON.parse(s)}catch(h){throw new Error(`Failed to parse ${r} as JSON. Comments (JSONC) are not supported. ${h.message}`)}let i=n.folders??[],a=new Set(t.map(h=>Kt.resolve(h))),c=new Set,p=i.filter(h=>{let y=Kt.resolve(o,h.path);return a.has(y)?(c.add(y),!1):!0});n.folders=p,await ea.writeFile(r,`${JSON.stringify(n,null,2)}
|
|
227
|
+
`,"utf-8");let d=[],m=[];for(let h of t){let y=Kt.resolve(h);c.has(y)?d.push(h):m.push(h)}return{removed:d,notFound:m}};var Rn=async e=>{let{workspacePath:r,worktreeDir:t,currentBranches:o}=e,s=Ut.dirname(r),n=Ut.resolve(`${t}/release`),i=await rd.readFile(r,"utf-8"),c=JSON.parse(i).folders??[],p=new Set(o.map(b=>Ut.resolve(`${t}/${b}`))),d=[];for(let b of c){let R=Ut.resolve(s,b.path);(R===n||R.startsWith(`${n}/`))&&!p.has(R)&&d.push(R)}let m=[];d.length>0&&(m=(await Zr({workspacePath:r,folderPaths:d})).removed);let h=o.map(b=>`${t}/${b}`),{added:y}=h.length>0?await qr({workspacePath:r,folderPaths:h}):{added:[]};return{added:y,removed:m}};import ra from"node:path";var Ke=(e,r)=>ra.isAbsolute(e)?e:ra.resolve(r,e);var bn=async e=>{let{projectRoot:r,worktreeDir:t,currentBranches:o,cursorConfig:s}=e;if(!s.workspaceConfigPath)return l.warn("\u26A0\uFE0F Skipping Cursor: workspaceConfigPath is not set."),{ran:!1,added:0,removed:0};let n=Ke(s.workspaceConfigPath,r);try{let{added:i,removed:a}=await Rn({workspacePath:n,worktreeDir:t,currentBranches:o});return o.length>0&&await Hr(n),{ran:!0,added:i.length,removed:a.length}}catch(i){return l.warn({error:i},`\u26A0\uFE0F Failed to reconcile/open Cursor workspace at ${n}`),{ran:!1,added:0,removed:0}}};import{$ as td}from"zx";var En=async e=>{let{folderPaths:r}=e;for(let t of r)await td`zed --add ${t}`;return{added:r}};import{$ as od}from"zx";var xn=async e=>{let{projectRoot:r,worktreeDir:t,currentBranches:o}=e;if(o.length===0)return{ran:!1,added:0,removed:0};let s=[r,...o.map(n=>`${t}/${n}`)];try{return await od`zed ${s}`,{ran:!0,added:o.length,removed:0}}catch(n){return l.warn({error:n},"\u26A0\uFE0F Failed to open Zed workspace"),{ran:!1,added:0,removed:0}}};import{$ as nd}from"zx";var Pn=async e=>{let{projectRoot:r,worktreeDir:t,remainingBranches:o}=e,s=[r,...o.map(n=>`${t}/${n}`)];try{return await nd`zed --reuse ${s}`,l.info(`\u21BB Refreshed Zed workspace to root + ${o.length} release worktree(s) (other folders in the focused window are not preserved)`),{ran:!0}}catch(n){return l.warn({error:n},"\u26A0\uFE0F Failed to refresh Zed workspace"),{ran:!1}}};var ve=e=>{throw new Error(`Unexpected value: ${JSON.stringify(e)}`)};var Tn=async e=>{let{projectRoot:r,worktreeDir:t,branches:o}=e,s=await O(),n=re(s),i=o.map(c=>`${t}/${c}`),a=[];for(let c of n)switch(c.provider){case"cursor":{if(!c.config.workspaceConfigPath){l.warn("\u26A0\uFE0F Skipping Cursor: ide.config.workspaceConfigPath is not set in infra-kit config"),a.push({ran:!1,provider:"cursor",added:0,skipped:0});break}let p=Ke(c.config.workspaceConfigPath,r),{added:d,skipped:m}=await qr({workspacePath:p,folderPaths:i}),h=m.length>0?` (${m.length} already present)`:"";l.info(`\u2705 Added ${d.length} folder(s) to ${p}${h}`),await Hr(p),a.push({ran:!0,provider:"cursor",added:d.length,skipped:m.length});break}case"zed":{let{added:p}=await En({folderPaths:i});l.info(`\u2705 Added ${p.length} folder(s) to Zed workspace`),a.push({ran:!0,provider:"zed",added:p.length,skipped:0});break}default:ve(c)}return a};var Cn=async e=>{let r=await O(),t=re(r),o=[];for(let s of t)switch(s.provider){case"cursor":{let n=await bn({...e,cursorConfig:s.config});o.push({...n,provider:"cursor"});break}case"zed":{let n=await xn(e);o.push({...n,provider:"zed"});break}default:ve(s)}return o};var Sn=e=>{switch(e){case"cursor":return"Cursor";case"zed":return"Zed";case void 0:return"IDE";default:return ve(e)}};var Yr=async e=>{let{projectRoot:r,worktreeDir:t,currentWorktrees:o,removedWorktrees:s,allowEditorRelaunch:n}=e;if(s.length===0)return[];let i=await O(),a=re(i),c=s.map(m=>`${t}/${m}`),p=o.filter(m=>!s.includes(m)),d=[];for(let m of a)switch(m.provider){case"cursor":{d.push(await sd({ide:m,projectRoot:r,folderPaths:c}));break}case"zed":{d.push(await id({projectRoot:r,worktreeDir:t,remainingBranches:p,allowEditorRelaunch:n}));break}default:ve(m)}return d},sd=async e=>{let{ide:r,projectRoot:t,folderPaths:o}=e;if(!r.config.workspaceConfigPath)return{provider:"cursor",supported:!0,removed:[]};let s=Ke(r.config.workspaceConfigPath,t);try{let{removed:n}=await Zr({workspacePath:s,folderPaths:o});return n.length>0&&l.info(`\u2705 Removed ${n.length} folder(s) from ${s}`),{provider:"cursor",supported:!0,removed:n}}catch(n){return l.warn({error:n},`\u26A0\uFE0F Failed to update Cursor workspace at ${s}`),{provider:"cursor",supported:!0,removed:[]}}},id=async e=>{let{projectRoot:r,worktreeDir:t,remainingBranches:o,allowEditorRelaunch:s}=e;return s?(await Pn({projectRoot:r,worktreeDir:t,remainingBranches:o}),{provider:"zed",supported:!0,removed:[]}):(l.info("\u2139\uFE0F Zed folder removal skipped (no interactive session); close removed worktree folders in Zed manually if needed."),{provider:"zed",supported:!0,removed:[]})};var Gt=["workspace","none"];var ad="feature",cd="release",na=async e=>{let{confirmedCommand:r,all:t,versions:o,githubDesktop:s,cmux:n}=e,i=e.ide??e.cursor;await M({operation:"create worktrees",requiredBranch:"dev"});try{let a=await V("release"),c=await w(),p=`${c}${te}`;await oa(`${p}/${cd}`),await oa(`${p}/${ad}`);let d=[];if(o)d=o.split(",").map(W=>ye(pe(W.trim())));else{let W=await x(),Q=W.map(Ge=>Ge.branch);if(Q.length===0)return l.info("\u2139\uFE0F No open release branches found"),u.print(),{content:g(JSON.stringify({createdWorktrees:[],count:0},null,2)),structuredContent:{createdWorktrees:[],count:0}};if(t)d=Q;else{u.setInteractive();let Ge=new Map(W.map(Fn=>[Fn.branch,E(Fn.title)])),et=await C();d=await fr(A({branches:Q,descriptions:et,types:Ge}),{required:!0})}}t?u.addOption("--all",!0):u.addOption("--versions",Be(d)),await D(r,"Are you sure you want to proceed with these worktree changes?"),r||u.addOption("--yes",!0);let m=await O(),h=i??(re(m).length>0?"workspace":"none");u.addOption("--ide",h);let y=s??m.worktrees?.openInGithubDesktop??await $(W=>ta({message:"Open created worktrees in GitHub Desktop?"},W));typeof s>"u"&&m.worktrees?.openInGithubDesktop===void 0&&u.setInteractive(),y?u.addOption("--github-desktop",!0):u.addOption("--no-github-desktop",!0);let b=n??m.worktrees?.openInCmux??await ta({message:"Open created worktrees in cmux?"});typeof n>"u"&&m.worktrees?.openInCmux===void 0&&u.setInteractive(),b?u.addOption("--cmux",!0):u.addOption("--no-cmux",!0);let{branchesToCreate:R}=ld({selectedReleaseBranches:d,currentWorktrees:a}),T=await pd(R,p);if(dd(T),h==="workspace"&&await Tn({projectRoot:c,worktreeDir:p,branches:T}),y)for(let W of T)await Xr`github ${p}/${W}`,await Xr`sleep 5`;if(b){let W=await ee(),Q=await mt();for(let Ge of T){let et=de({repoName:W,branch:Ge});Q.has(dt(et))||await ut({cwd:`${p}/${Ge}`,title:et})}}u.print();let Ue={createdWorktrees:T,count:T.length};return{content:g(JSON.stringify(Ue,null,2)),structuredContent:Ue}}catch(a){throw rr(a)?a:(l.error({error:a},"\u274C Error managing worktrees"),new f(a,{operation:"create worktrees",remediation:"verify branches don't already exist as worktrees: 'git worktree list'"}))}},oa=async e=>{await Xr`mkdir -p ${e}`},ld=e=>{let{selectedReleaseBranches:r,currentWorktrees:t}=e,o=t.filter(n=>tt(n));return{branchesToCreate:r.filter(n=>!o.includes(n))}},pd=async(e,r)=>{let t=await Promise.allSettled(e.map(async s=>{let n=`${r}/${s}`;return await Xr`git worktree add ${n} ${s}`,await Xr({cwd:n})`pnpm install`,s})),o=[];for(let[s,n]of t.entries())if(n.status==="fulfilled")o.push(n.value);else{let i=e[s],a=new f(n.reason,{operation:`git worktree add for ${i}`,remediation:"check the branch name and that the parent dir is writable"});l.error({error:n.reason,msg:a.message})}return o},dd=e=>{if(e.length>0){l.info("\u2705 Created git worktrees:");for(let r of e)l.info(r);l.info("")}else l.info("\u2139\uFE0F No new git worktrees to create")},$n=v({name:"worktrees-add",description:'Create local git worktrees for release branches under the worktrees directory and run "pnpm install" in each. Mutates the local filesystem. When invoked via MCP, pass either "versions" (comma-separated) or all=true \u2014 the branch picker and "open in Cursor / GitHub Desktop / cmux" follow-up prompts are unreachable without a TTY, and the CLI confirmation is auto-skipped for MCP calls.',inputSchema:{all:ke.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:ke.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:ke.enum(Gt).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:ke.enum(Gt).optional().describe('Deprecated alias for "ide". Prefer "ide". Ignored when "ide" is provided.'),githubDesktop:ke.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:ke.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:ke.array(ke.string()).describe("List of created git worktree branches"),count:ke.number().describe("Number of git worktrees created")},handler:na});import{z as yr}from"zod";var sa=async()=>{let e=await V("release");if(e.length===0)return l.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([x(),C()]),o=new Map(r.map(c=>[c.branch,E(c.title)])),s=e.flatMap(c=>{let p=_(c);if(!p)return[];let d=S(p),m=o.get(c)||"regular",h=t.get(G(p))||null;return[{version:d,type:m,description:h}]}),n=Math.max(...s.map(c=>c.version.length)),i=s.map(c=>{let p=Vr(c.version,c.type,n);return c.description?`${p} ${c.description}`:p});l.info(`\u{1F33F} Active worktrees:
|
|
228
228
|
|
|
229
229
|
${i.join(`
|
|
230
|
-
`)}`);let a={worktrees:s,count:s.length};return{content:g(JSON.stringify(a,null,2)),structuredContent:a}},_n=v({name:"worktrees-list",description:"List existing release-branch worktrees with version, release type (regular / hotfix), and Jira fix-version description. Read-only.",inputSchema:{},outputSchema:{worktrees:yr.array(yr.object({version:yr.string().describe("Release version"),type:yr.enum(["regular","hotfix"]).describe("Release type"),description:yr.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:yr.number().describe("Number of worktrees")},handler:na});import{z as Ae}from"zod";var sa=async()=>{try{let e=await w(),r=`${e}${te}`,t=await V("release"),o=await ee(),s=await pd({currentBranches:t,repoName:o}),[n,{opened:i}]=await Promise.all([Cn({projectRoot:e,worktreeDir:r,currentBranches:t}),dd({worktreeDir:r,currentBranches:t,repoName:o})]),a={closedCmux:s,openedCmux:i,ideProviders:n.filter(c=>c.ran).map(c=>c.provider),ideFoldersAdded:n.reduce((c,p)=>c+p.added,0),ideFoldersRemoved:n.reduce((c,p)=>c+p.removed,0)};return md(a,{ideRan:n.some(c=>c.ran)}),u.print(),{content:g(JSON.stringify(a,null,2)),structuredContent:{...a}}}catch(e){throw l.error({error:e},"\u274C Error reloading worktrees"),new f(e,{operation:"reload worktrees",remediation:"run `infra-kit worktrees list` to confirm the branches exist"})}},pd=async e=>{let{currentBranches:r,repoName:t}=e;if(r.length===0)return[];let o=await mt(),s=[];for(let n of r){let i=de({repoName:t,branch:n});o.has(dt(i))&&(await er(i),s.push(i))}return s},dd=async e=>{let{worktreeDir:r,currentBranches:t,repoName:o}=e,s=[];for(let n of t){let i=de({repoName:o,branch:n});try{await ut({cwd:`${r}/${n}`,title:i}),s.push(i)}catch(a){l.warn({error:a,title:i},`\u26A0\uFE0F Failed to reopen cmux workspace for ${n}`)}}return{opened:s}},md=(e,r)=>{if(e.closedCmux.length>0&&l.info(`\u{1F9F9} Closed ${e.closedCmux.length} cmux workspace(s)`),r.ideRan){let t=e.ideProviders.map(o=>Sn(o)).join(", ");e.ideFoldersAdded>0&&l.info(`\u2705 Added ${e.ideFoldersAdded} folder(s) to ${t} workspace(s)`),e.ideFoldersRemoved>0&&l.info(`\u{1F9F9} Removed ${e.ideFoldersRemoved} dangling folder(s) from ${t} workspace(s)`)}if(e.openedCmux.length>0){l.info("\u2705 Reopened cmux workspaces:");for(let t of e.openedCmux)l.info(t)}!r.ideRan&&e.closedCmux.length===0&&e.openedCmux.length===0&&e.ideFoldersAdded===0&&e.ideFoldersRemoved===0&&l.info("\u2139\uFE0F Nothing to reload")},An=v({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:Ae.array(Ae.string()).describe("Titles of cmux workspaces a close was attempted for (best-effort)"),openedCmux:Ae.array(Ae.string()).describe("Titles of cmux workspaces reopened during this run"),ideProviders:Ae.array(Ae.string()).describe("Configured IDE providers that were reloaded (cursor | zed); empty if none configured"),ideFoldersAdded:Ae.number().describe("Total worktree folders added across all configured editor workspaces"),ideFoldersRemoved:Ae.number().describe("Total dangling worktree folders removed across all configured editor workspaces")},handler:sa});import{z as Qr}from"zod";var ia=async e=>{let{confirmedCommand:r,all:t,versions:o}=e;await M({operation:"remove worktrees",requiredBranch:"dev"});try{let s=await V("release");if(s.length===0)return l.info("\u2139\uFE0F No active worktrees to remove"),u.print(),{content:g(JSON.stringify({removedWorktrees:[],count:0},null,2)),structuredContent:{removedWorktrees:[],count:0}};let n=await w(),i=`${n}${te}`,a=[];if(t)a=s;else if(o)a=o.split(",").map(h=>we(pe(h.trim())));else{u.setInteractive();let[h,y]=await Promise.all([C(),x()]),b=new Map(y.map(R=>[R.branch,E(R.title)]));a=await fr(A({branches:s,descriptions:h,types:b}),{required:!0})}let c=a.length===s.length;c?u.addOption("--all",!0):u.addOption("--versions",Je(a)),await D(r,"Are you sure you want to proceed with these worktree changes?"),r||u.addOption("--yes",!0);let p=await ee(),d=await Ur({branches:a,worktreeDir:i,repoName:p,pruneFolder:c});await Yr({projectRoot:n,worktreeDir:i,currentWorktrees:s,removedWorktrees:d,allowEditorRelaunch:!r}),ud(d),u.print();let m={removedWorktrees:d,count:d.length};return{content:g(JSON.stringify(m,null,2)),structuredContent:m}}catch(s){throw rr(s)?s:(l.error({error:s},"\u274C Error managing worktrees"),new f(s,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"}))}},ud=e=>{if(e.length>0){l.info("\u274C Removed worktrees:");for(let r of e)l.info(r);l.info("")}else l.info("\u2139\uFE0F No unused worktrees to remove")},In=v({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:Qr.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:Qr.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:Qr.array(Qr.string()).describe("List of removed git worktree branches"),count:Qr.number().describe("Number of git worktrees removed")},handler:ia});import{z as Nn}from"zod";import{$ as fd}from"zx";var aa=async e=>{let{confirmedCommand:r}=e;await M({operation:"sync worktrees",requiredBranch:"dev"});try{let t=await V("release"),o=await w(),s=`${o}${te}`,n=await Ct();await D(r,"Are you sure you want to proceed with these worktree changes?"),r||u.addOption("--yes",!0);let{branchesToRemove:i}=gd({releasePRsList:n,currentWorktrees:t}),a=await ee(),c=await hd({branches:i,worktreeDir:s,repoName:a});await Yr({projectRoot:o,worktreeDir:s,currentWorktrees:t,removedWorktrees:c,allowEditorRelaunch:!1}),vd(c),u.print();let p={removedWorktrees:c,count:c.length};return{content:g(JSON.stringify(p,null,2)),structuredContent:p}}catch(t){throw rr(t)?t:(l.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"}))}},gd=e=>{let{releasePRsList:r,currentWorktrees:t}=e;return{branchesToRemove:t.filter(n=>tt(n)).filter(n=>!r.includes(n))}},hd=async e=>{let{branches:r,worktreeDir:t,repoName:o}=e,s=[];for(let n of r)try{let i=`${t}/${n}`,a=de({repoName:o,branch:n});await er(a),await fd`git worktree remove ${i}`,s.push(n)}catch(i){let a=new f(i,{operation:`remove stale worktree for ${n}`,remediation:"inspect the worktree dir manually; rerun with the branch checked out elsewhere"});l.error({error:i,branch:n,msg:a.message})}return s},vd=e=>{if(e.length>0){l.info("\u274C Removed worktrees:");for(let r of e)l.info(r);l.info("")}else l.info("\u2139\uFE0F No unused worktrees to remove")},On=v({name:"worktrees-sync",description:"Remove worktrees whose release PR is no longer open (stale cleanup). Only removes \u2014 never creates; use worktrees-add to create worktrees for new releases. The CLI confirmation is auto-skipped for MCP calls, so the caller is responsible for gating.",inputSchema:{},outputSchema:{removedWorktrees:Nn.array(Nn.string()).describe("List of removed worktree branches"),count:Nn.number().describe("Number of worktrees removed during sync")},handler:aa});var kd=[{key:"develop",label:"Develop"},{key:"release",label:"Release Management"},{key:"worktrees",label:"Worktrees"},{key:"environment",label:"Environment"},{key:"configuration",label:"Configuration"},{key:"vendor",label:"Vendor"},{key:"setup",label:"Setup & Diagnostics"}],zt=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,groupPath:["dev"],longRunning:!0},{cliName:"merge-dev",menuGroup:"release",mcpTool:Lo,mcpExposed:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:Uo,mcpExposed:!0,groupPath:["release","list"]},{cliName:"release-create",menuGroup:"release",mcpTool:nn,mcpExposed:!0,groupPath:["release","create"]},{cliName:"release-desc-edit",menuGroup:"release",mcpTool:sn,mcpExposed:!0,groupPath:["release","desc-edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:Jo,mcpExposed:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:Ko,mcpExposed:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:Wo,mcpExposed:!1,groupPath:["release","deliver"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:$n,mcpExposed:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:_n,mcpExposed:!0,groupPath:["worktrees","list"]},{cliName:"worktrees-reload",menuGroup:"worktrees",mcpTool:An,mcpExposed:!0,groupPath:["worktrees","reload"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:In,mcpExposed:!1,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:On,mcpExposed:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:Ao,mcpExposed:!0,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:_o,mcpExposed:!0,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:ho,mcpExposed:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:$o,mcpExposed:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:No,mcpExposed:!0,groupPath:["env-token-list"]},{cliName:"config-path",menuGroup:"configuration",mcpTool:null,mcpExposed:!1,groupPath:["config","path"]},{cliName:"config-edit",menuGroup:"configuration",mcpTool:null,mcpExposed:!1,groupPath:["config","edit"],entersAltScreen:!0},{cliName:"vendor-check",menuGroup:"vendor",mcpTool:fn,mcpExposed:!0,groupPath:["vendor","check"]},{cliName:"vendor-diff",menuGroup:"vendor",mcpTool:vn,mcpExposed:!0,groupPath:["vendor","diff"]},{cliName:"vendor-config",menuGroup:"vendor",mcpTool:null,mcpExposed:!1,groupPath:["vendor","config"]},{cliName:"init",menuGroup:"setup",mcpTool:null,mcpExposed:!1,groupPath:["init"]},{cliName:"doctor",menuGroup:"setup",mcpTool:Co,mcpExposed:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:io,mcpExposed:!0,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:wn,mcpExposed:!0,groupPath:["version"]},{cliName:"vendor",menuGroup:null,mcpTool:null,mcpExposed:!1,groupPath:["vendor"]},{cliName:"config",menuGroup:null,mcpTool:null,mcpExposed:!1,groupPath:["config"]},{cliName:"env-autoload",menuGroup:null,mcpTool:null,mcpExposed:!1,groupPath:["env-autoload"]},{cliName:"env-token-set",menuGroup:null,mcpTool:null,mcpExposed:!1,groupPath:["env-token-set"]},{cliName:"env-token-remove",menuGroup:null,mcpTool:null,mcpExposed:!1,groupPath:["env-token-remove"]},{cliName:"self-update",menuGroup:null,mcpTool:null,mcpExposed:!1,groupPath:["self-update"]},{cliName:"mcp",menuGroup:null,mcpTool:null,mcpExposed:!1,groupPath:["mcp"]},{cliName:"vendor-manifest",menuGroup:null,mcpTool:kn,mcpExposed:!1,groupPath:["vendor","manifest"]},{cliName:"vendor-sync",menuGroup:null,mcpTool:yn,mcpExposed:!1,groupPath:["vendor","sync"]}],yd=()=>zt.flatMap(e=>e.mcpExposed&&e.mcpTool?[e.mcpTool]:[]),wd=e=>zt.filter(r=>r.menuGroup===e),Rd=e=>zt.some(r=>r.longRunning===!0&&r.groupPath.join(" ")===e);import Dn from"node:process";var bd="MODULE_TYPELESS_PACKAGE_JSON",Ed=(e,r)=>typeof e=="object"&&e!==null?e.code:r,ca=!1,xd=()=>{if(ca)return;ca=!0;let e=Dn.emitWarning.bind(Dn);Dn.emitWarning=((r,...t)=>{Ed(t[0],t[1])!==bd&&e(r,...t)})};export{g as a,ms as b,xr as c,Pr as d,Tr as e,De as f,Hm as g,qa as h,Ss as i,$s as j,ir as k,_s as l,As as m,wt as n,Rt as o,Ec as p,bo as q,Ws as r,cr as s,Yf as t,Eo as u,xo as v,ri as w,oi as x,si as y,ii as z,Io as A,pi as B,$t as C,xl as D,fi as E,hi as F,Ri as G,Ei as H,xi as I,Pi as J,ep as K,Ai as L,Ni as M,Li as N,Gi as O,zi as P,Zi as Q,Yi as R,Gt as S,oa as T,na as U,sa as V,ia as W,aa as X,kd as Y,zt as Z,yd as _,wd as $,Rd as aa,xd as ba};
|
|
231
|
-
//# sourceMappingURL=chunk-
|
|
230
|
+
`)}`);let a={worktrees:s,count:s.length};return{content:g(JSON.stringify(a,null,2)),structuredContent:a}},_n=v({name:"worktrees-list",description:"List existing release-branch worktrees with version, release type (regular / hotfix), and Jira fix-version description. Read-only.",inputSchema:{},outputSchema:{worktrees:yr.array(yr.object({version:yr.string().describe("Release version"),type:yr.enum(["regular","hotfix"]).describe("Release type"),description:yr.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:yr.number().describe("Number of worktrees")},handler:sa});import{z as Ae}from"zod";var ia=async()=>{try{let e=await w(),r=`${e}${te}`,t=await V("release"),o=await ee(),s=await md({currentBranches:t,repoName:o}),[n,{opened:i}]=await Promise.all([Cn({projectRoot:e,worktreeDir:r,currentBranches:t}),ud({worktreeDir:r,currentBranches:t,repoName:o})]),a={closedCmux:s,openedCmux:i,ideProviders:n.filter(c=>c.ran).map(c=>c.provider),ideFoldersAdded:n.reduce((c,p)=>c+p.added,0),ideFoldersRemoved:n.reduce((c,p)=>c+p.removed,0)};return fd(a,{ideRan:n.some(c=>c.ran)}),u.print(),{content:g(JSON.stringify(a,null,2)),structuredContent:{...a}}}catch(e){throw l.error({error:e},"\u274C Error reloading worktrees"),new f(e,{operation:"reload worktrees",remediation:"run `infra-kit worktrees list` to confirm the branches exist"})}},md=async e=>{let{currentBranches:r,repoName:t}=e;if(r.length===0)return[];let o=await mt(),s=[];for(let n of r){let i=de({repoName:t,branch:n});o.has(dt(i))&&(await er(i),s.push(i))}return s},ud=async e=>{let{worktreeDir:r,currentBranches:t,repoName:o}=e,s=[];for(let n of t){let i=de({repoName:o,branch:n});try{await ut({cwd:`${r}/${n}`,title:i}),s.push(i)}catch(a){l.warn({error:a,title:i},`\u26A0\uFE0F Failed to reopen cmux workspace for ${n}`)}}return{opened:s}},fd=(e,r)=>{if(e.closedCmux.length>0&&l.info(`\u{1F9F9} Closed ${e.closedCmux.length} cmux workspace(s)`),r.ideRan){let t=e.ideProviders.map(o=>Sn(o)).join(", ");e.ideFoldersAdded>0&&l.info(`\u2705 Added ${e.ideFoldersAdded} folder(s) to ${t} workspace(s)`),e.ideFoldersRemoved>0&&l.info(`\u{1F9F9} Removed ${e.ideFoldersRemoved} dangling folder(s) from ${t} workspace(s)`)}if(e.openedCmux.length>0){l.info("\u2705 Reopened cmux workspaces:");for(let t of e.openedCmux)l.info(t)}!r.ideRan&&e.closedCmux.length===0&&e.openedCmux.length===0&&e.ideFoldersAdded===0&&e.ideFoldersRemoved===0&&l.info("\u2139\uFE0F Nothing to reload")},An=v({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:Ae.array(Ae.string()).describe("Titles of cmux workspaces a close was attempted for (best-effort)"),openedCmux:Ae.array(Ae.string()).describe("Titles of cmux workspaces reopened during this run"),ideProviders:Ae.array(Ae.string()).describe("Configured IDE providers that were reloaded (cursor | zed); empty if none configured"),ideFoldersAdded:Ae.number().describe("Total worktree folders added across all configured editor workspaces"),ideFoldersRemoved:Ae.number().describe("Total dangling worktree folders removed across all configured editor workspaces")},handler:ia});import{z as Qr}from"zod";var aa=async e=>{let{confirmedCommand:r,all:t,versions:o}=e;await M({operation:"remove worktrees",requiredBranch:"dev"});try{let s=await V("release");if(s.length===0)return l.info("\u2139\uFE0F No active worktrees to remove"),u.print(),{content:g(JSON.stringify({removedWorktrees:[],count:0},null,2)),structuredContent:{removedWorktrees:[],count:0}};let n=await w(),i=`${n}${te}`,a=[];if(t)a=s;else if(o)a=o.split(",").map(h=>ye(pe(h.trim())));else{u.setInteractive();let[h,y]=await Promise.all([C(),x()]),b=new Map(y.map(R=>[R.branch,E(R.title)]));a=await fr(A({branches:s,descriptions:h,types:b}),{required:!0})}let c=a.length===s.length;c?u.addOption("--all",!0):u.addOption("--versions",Be(a)),await D(r,"Are you sure you want to proceed with these worktree changes?"),r||u.addOption("--yes",!0);let p=await ee(),d=await Ur({branches:a,worktreeDir:i,repoName:p,pruneFolder:c});await Yr({projectRoot:n,worktreeDir:i,currentWorktrees:s,removedWorktrees:d,allowEditorRelaunch:!r}),gd(d),u.print();let m={removedWorktrees:d,count:d.length};return{content:g(JSON.stringify(m,null,2)),structuredContent:m}}catch(s){throw rr(s)?s:(l.error({error:s},"\u274C Error managing worktrees"),new f(s,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"}))}},gd=e=>{if(e.length>0){l.info("\u274C Removed worktrees:");for(let r of e)l.info(r);l.info("")}else l.info("\u2139\uFE0F No unused worktrees to remove")},In=v({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:Qr.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:Qr.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:Qr.array(Qr.string()).describe("List of removed git worktree branches"),count:Qr.number().describe("Number of git worktrees removed")},handler:aa});import{z as Nn}from"zod";import{$ as hd}from"zx";var ca=async e=>{let{confirmedCommand:r}=e;await M({operation:"sync worktrees",requiredBranch:"dev"});try{let t=await V("release"),o=await w(),s=`${o}${te}`,n=await Ct();await D(r,"Are you sure you want to proceed with these worktree changes?"),r||u.addOption("--yes",!0);let{branchesToRemove:i}=vd({releasePRsList:n,currentWorktrees:t}),a=await ee(),c=await kd({branches:i,worktreeDir:s,repoName:a});await Yr({projectRoot:o,worktreeDir:s,currentWorktrees:t,removedWorktrees:c,allowEditorRelaunch:!1}),yd(c),u.print();let p={removedWorktrees:c,count:c.length};return{content:g(JSON.stringify(p,null,2)),structuredContent:p}}catch(t){throw rr(t)?t:(l.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"}))}},vd=e=>{let{releasePRsList:r,currentWorktrees:t}=e;return{branchesToRemove:t.filter(n=>tt(n)).filter(n=>!r.includes(n))}},kd=async e=>{let{branches:r,worktreeDir:t,repoName:o}=e,s=[];for(let n of r)try{let i=`${t}/${n}`,a=de({repoName:o,branch:n});await er(a),await hd`git worktree remove ${i}`,s.push(n)}catch(i){let a=new f(i,{operation:`remove stale worktree for ${n}`,remediation:"inspect the worktree dir manually; rerun with the branch checked out elsewhere"});l.error({error:i,branch:n,msg:a.message})}return s},yd=e=>{if(e.length>0){l.info("\u274C Removed worktrees:");for(let r of e)l.info(r);l.info("")}else l.info("\u2139\uFE0F No unused worktrees to remove")},On=v({name:"worktrees-sync",description:"Remove worktrees whose release PR is no longer open (stale cleanup). Only removes \u2014 never creates; use worktrees-add to create worktrees for new releases. The CLI confirmation is auto-skipped for MCP calls, so the caller is responsible for gating.",inputSchema:{},outputSchema:{removedWorktrees:Nn.array(Nn.string()).describe("List of removed worktree branches"),count:Nn.number().describe("Number of worktrees removed during sync")},handler:ca});var wd=[{key:"develop",label:"Develop"},{key:"release",label:"Release Management"},{key:"worktrees",label:"Worktrees"},{key:"environment",label:"Environment"},{key:"configuration",label:"Configuration"},{key:"vendor",label:"Vendor"},{key:"setup",label:"Setup & Diagnostics"}],zt=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,groupPath:["dev"],longRunning:!0},{cliName:"merge-dev",menuGroup:"release",mcpTool:Lo,mcpExposed:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:Uo,mcpExposed:!0,groupPath:["release","list"]},{cliName:"release-create",menuGroup:"release",mcpTool:nn,mcpExposed:!0,groupPath:["release","create"]},{cliName:"release-desc-edit",menuGroup:"release",mcpTool:sn,mcpExposed:!0,groupPath:["release","desc-edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:Bo,mcpExposed:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:Ko,mcpExposed:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:Wo,mcpExposed:!1,groupPath:["release","deliver"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:$n,mcpExposed:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:_n,mcpExposed:!0,groupPath:["worktrees","list"]},{cliName:"worktrees-reload",menuGroup:"worktrees",mcpTool:An,mcpExposed:!0,groupPath:["worktrees","reload"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:In,mcpExposed:!1,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:On,mcpExposed:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:Ao,mcpExposed:!0,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:_o,mcpExposed:!0,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:ho,mcpExposed:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:$o,mcpExposed:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:No,mcpExposed:!0,groupPath:["env-token-list"]},{cliName:"config-path",menuGroup:"configuration",mcpTool:null,mcpExposed:!1,groupPath:["config","path"]},{cliName:"config-edit",menuGroup:"configuration",mcpTool:null,mcpExposed:!1,groupPath:["config","edit"],entersAltScreen:!0},{cliName:"vendor-check",menuGroup:"vendor",mcpTool:fn,mcpExposed:!0,groupPath:["vendor","check"]},{cliName:"vendor-diff",menuGroup:"vendor",mcpTool:vn,mcpExposed:!0,groupPath:["vendor","diff"]},{cliName:"vendor-config",menuGroup:"vendor",mcpTool:null,mcpExposed:!1,groupPath:["vendor","config"]},{cliName:"init",menuGroup:"setup",mcpTool:null,mcpExposed:!1,groupPath:["init"]},{cliName:"doctor",menuGroup:"setup",mcpTool:Co,mcpExposed:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:io,mcpExposed:!0,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:wn,mcpExposed:!0,groupPath:["version"]},{cliName:"vendor",menuGroup:null,mcpTool:null,mcpExposed:!1,groupPath:["vendor"]},{cliName:"config",menuGroup:null,mcpTool:null,mcpExposed:!1,groupPath:["config"]},{cliName:"env-autoload",menuGroup:null,mcpTool:null,mcpExposed:!1,groupPath:["env-autoload"]},{cliName:"env-token-set",menuGroup:null,mcpTool:null,mcpExposed:!1,groupPath:["env-token-set"]},{cliName:"env-token-remove",menuGroup:null,mcpTool:null,mcpExposed:!1,groupPath:["env-token-remove"]},{cliName:"self-update",menuGroup:null,mcpTool:null,mcpExposed:!1,groupPath:["self-update"]},{cliName:"mcp",menuGroup:null,mcpTool:null,mcpExposed:!1,groupPath:["mcp"]},{cliName:"vendor-manifest",menuGroup:null,mcpTool:kn,mcpExposed:!1,groupPath:["vendor","manifest"]},{cliName:"vendor-sync",menuGroup:null,mcpTool:yn,mcpExposed:!1,groupPath:["vendor","sync"]}],Rd=()=>zt.flatMap(e=>e.mcpExposed&&e.mcpTool?[e.mcpTool]:[]),bd=e=>zt.filter(r=>r.menuGroup===e),Ed=e=>zt.some(r=>r.longRunning===!0&&r.groupPath.join(" ")===e);import Dn from"node:process";var xd="MODULE_TYPELESS_PACKAGE_JSON",Pd=(e,r)=>typeof e=="object"&&e!==null?e.code:r,la=!1,Td=()=>{if(la)return;la=!0;let e=Dn.emitWarning.bind(Dn);Dn.emitWarning=((r,...t)=>{Pd(t[0],t[1])!==xd&&e(r,...t)})};export{g as a,ms as b,xr as c,Pr as d,Tr as e,De as f,Ym as g,Ha as h,Ss as i,$s as j,ir as k,_s as l,As as m,wt as n,Rt as o,xc as p,bo as q,Ws as r,cr as s,Qf as t,Eo as u,xo as v,ri as w,oi as x,ii as y,ai as z,Io as A,di as B,$t as C,Tl as D,gi as E,vi as F,bi as G,xi as H,Pi as I,Ti as J,tp as K,Ii as L,Oi as M,Wi as N,zi as O,qi as P,Yi as Q,Xi as R,Gt as S,na as T,sa as U,ia as V,aa as W,ca as X,wd as Y,zt as Z,Rd as _,bd as $,Ed as aa,Td as ba};
|
|
231
|
+
//# sourceMappingURL=chunk-2C2U5ACS.js.map
|