infra-kit 0.3.6 → 0.3.8
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/boot-HP5ORQEX.js +2 -0
- package/dist/boot-HP5ORQEX.js.map +7 -0
- package/dist/{chunk-T74NOBEP.js → chunk-3LPUAYWA.js} +2 -2
- package/dist/{chunk-T74NOBEP.js.map → chunk-3LPUAYWA.js.map} +1 -1
- package/dist/chunk-7DL27USH.js +7 -0
- package/dist/{chunk-GZNE5CBQ.js.map → chunk-7DL27USH.js.map} +3 -3
- package/dist/chunk-KAWDTA5H.js +2 -0
- package/dist/chunk-KAWDTA5H.js.map +7 -0
- package/dist/{chunk-A7FAXZGI.js → chunk-LKKKDB6V.js} +1 -1
- package/dist/{chunk-A7FAXZGI.js.map → chunk-LKKKDB6V.js.map} +1 -1
- package/dist/chunk-PZU6BLQR.js +4 -0
- package/dist/{chunk-IVWPZEMC.js.map → chunk-PZU6BLQR.js.map} +3 -3
- package/dist/chunk-RDRJX6TT.js +232 -0
- package/dist/chunk-RDRJX6TT.js.map +7 -0
- package/dist/chunk-X46DP23W.js +2 -0
- package/dist/chunk-X46DP23W.js.map +7 -0
- package/dist/chunk-XTRPE4SX.js +2 -0
- package/dist/chunk-XTRPE4SX.js.map +7 -0
- package/dist/cli.js +8 -8
- package/dist/cli.js.map +3 -3
- package/dist/dev-server.js +3 -3
- package/dist/dev-server.js.map +2 -2
- package/dist/dev-wizard-run-KIOSJM4D.js +2 -0
- package/dist/dev-wizard-run-KIOSJM4D.js.map +7 -0
- package/dist/mcp.js +1 -1
- package/dist/mcp.js.map +1 -1
- package/dist/update-check.js +1 -1
- package/package.json +1 -1
- package/dist/boot-FHXCA53R.js +0 -2
- package/dist/boot-FHXCA53R.js.map +0 -7
- package/dist/chunk-3G6O7MCC.js +0 -231
- package/dist/chunk-3G6O7MCC.js.map +0 -7
- package/dist/chunk-EX66ZFV5.js +0 -2
- package/dist/chunk-EX66ZFV5.js.map +0 -7
- package/dist/chunk-GZNE5CBQ.js +0 -7
- package/dist/chunk-IVWPZEMC.js +0 -4
- package/dist/chunk-S45AAYXO.js +0 -4
- package/dist/chunk-S45AAYXO.js.map +0 -7
- package/dist/dev-wizard-run-5ST3BJ4L.js +0 -2
- package/dist/dev-wizard-run-5ST3BJ4L.js.map +0 -7
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
import{a as ms,b as ft,c as no,d as fs,e as gs,f as hs,g as vs,h as so,i as ks,j as Er,k as rr,l as tr,m as gt,n as ht,r as or,s as vt,t as nr}from"./chunk-XTRPE4SX.js";import{a as mt}from"./chunk-3LPUAYWA.js";import{a as it,c as H,d as y,e as dt,f as Z,i as m,k as ut,l as S,m as F}from"./chunk-7DL27USH.js";import{F as ss,G as is,I as as,J as cs,K as we,L as ls,M as oo,N as te,P as D,Q as j,R as ps,S as He,a as Hn,b as st,c as _,d as de,e as ye,f as Zn,g as to,h as q,i as $,j as Ne,k as Yn,l as Xn,m as re,n as R,o as qe,p as Qn,q as es,r as rs,s as ts,v as l,x as os,y as ns}from"./chunk-PZU6BLQR.js";import{a as J,b as at,c as xr,d as ds,e as ct,f as Ze,g as Ye,h as lt,i as Xe,j as De,k as Qe,l as pt,n as er,o as us,p as je,q as Fe,r as oe}from"./chunk-CHETBZ6M.js";import Cr from"node:path";import qa from"node:process";import{z as B}from"zod";var Re={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},io={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"]},ao=(e,r=Re)=>({requiredScripts:e.requiredScripts??[...r.requiredScripts],requiredFiles:e.requiredFiles??[...r.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...r.turboTasks]});import $a from"node:fs/promises";var ue=async e=>{try{return await $a.access(e),!0}catch{return!1}};import Ja from"node:path";import{packageConfigSchema as _a}from"@slip-stream-kit/config/internal";import ys from"node:fs/promises";import ws from"node:path";import{pathToFileURL as Aa}from"node:url";import{z as Ia}from"zod";var be="infra-kit.config.ts",co=async e=>{try{let r=await ys.readFile(ws.join(e,"package.json"),"utf-8");return JSON.parse(r)}catch{return{}}},Pr=async(e,r=Re)=>{let t=ws.join(e,be);if(!await ue(t))throw new Error(`${be} not found at ${t}`);let o=await ys.stat(t),i=(await import(`${Aa(t).href}?mtime=${Number(o.mtimeMs)}`)).default;if(i===void 0)throw new Error(`${be} at ${t} has no default export`);let a=typeof i=="function"?await i():i,c=_a.safeParse(a);if(!c.success)throw new Error(`Invalid ${be} at ${t}: ${Ia.prettifyError(c.error)}`);return ao(c.data,r)};import Rs from"node:fs/promises";import kt from"node:path";import Oa from"yaml";var Na="pnpm-workspace.yaml",Da=async e=>(await Rs.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(t=>t.isDirectory()).map(t=>kt.join(e,t.name)),ja=async(e,r)=>{let t=[];for(let o of e){if(r==="*"){t.push(...await Da(o));continue}let s=kt.join(o,r);await ue(s)&&t.push(s)}return t},Fa=async(e,r)=>{let t=[e];for(let o of r.split("/"))t=await ja(t,o);return t},Tr=async e=>{let r=await Rs.readFile(kt.join(e,Na),"utf-8"),o=((Oa.parse(r)??{}).packages??[]).filter(n=>!n.startsWith("!")&&!n.startsWith("vendor")),s=new Set;for(let n of o){let i=await Fa(e,n);for(let a of i)await ue(kt.join(a,"package.json"))&&s.add(a)}return[...s].sort()};var lo=async(e,r=Re)=>{try{let t=await Pr(e,r);return{check:{name:be,status:"pass",message:"present and valid"},rules:t}}catch(t){return{check:{name:be,status:"fail",message:t.message},rules:null}}};import Ma from"node:fs/promises";import La from"node:path";var po=async(e,r)=>Promise.all(r.map(async t=>{let o=await Ma.stat(La.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 uo=(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 Wa from"node:fs/promises";import Va from"node:path";var sr="turbo.json",mo=async(e,r)=>{if(r.length===0)return[];let t;try{let s=await Wa.readFile(Va.join(e,sr),"utf-8");t=JSON.parse(s)}catch(s){return[{name:sr,status:"fail",message:`cannot read/parse ${sr}: ${s.message}`}]}let o=t.tasks;return o===null||typeof o!="object"?[{name:sr,status:"fail",message:`no "tasks" object defined in ${sr}`}]: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 ${sr}`}})};var fo=async(e,r=Re)=>{let t=await co(e),o=t.name??Ja.basename(e),{check:s,rules:n}=await lo(e,r),i=[s];n&&(i.push(...uo(t.scripts??{},n.requiredScripts)),i.push(...await po(e,n.requiredFiles)),i.push(...await mo(e,n.turboTasks)));let a=i.every(c=>c.status==="pass");return{packageDir:e,packageName:o,checks:i,passed:a}};var h=e=>[{type:"text",text:e}],v=e=>e;import{loadDev as Ba}from"@slip-stream-kit/config/internal";import Ka from"node:path";var Ga=(e,r)=>{let t=new Set;for(let o of Object.values(e))for(let s of Object.keys(is(o,r).proxy))t.add(s);return[...t]},Ua=async(e,r)=>{let t={},o=[];return await Promise.all(r.map(async s=>{try{let i=(await Ba(Ka.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}},za=(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}))],bs=async e=>{let r=(await j()).devServersPresets;if(!r||Object.keys(r).length===0)return null;let t=ss(r);if(t.length>0){let u=t.map(g=>({name:`devServersPresets:${g.preset}`,status:"fail",message:g.message}));return{packageDir:e,packageName:"devServersPresets",checks:u,passed:!1}}let o=os(e),s=ns(e),n={api:o.map(u=>u.name),ui:s.map(u=>u.name)},{routePkg:i,loadErrors:a}=await Ua(e,Ga(r,n)),c={discovered:n,apiPkgByApp:Object.fromEntries(o.map(u=>[u.name,u.packageName])),routePkg:i},p=za(as(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 Ha=async e=>{let r=Cr.resolve(e);for(;r!==Cr.dirname(r);){if(await ue(Cr.join(r,"package.json")))return r;r=Cr.dirname(r)}if(await ue(Cr.join(r,"package.json")))return r;throw new Error(`No package.json found in or above ${e}`)},Za=async e=>e.root?[{dir:await R(),baseline:io}]:e.all?(await Tr(await R())).map(t=>({dir:t})):[{dir:await Ha(e.cwd??qa.cwd())}],Ya=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}`)}},xs=async(e={})=>{let r=await Za(e),t=[];for(let n of r)t.push(await fo(n.dir,n.baseline));if(e.root){let n=await bs(r[0].dir);n&&t.push(n)}for(let n of t)Ya(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:h(JSON.stringify(s,null,2)),structuredContent:s}},Xa={all:B.boolean().optional().describe("Audit every non-vendor workspace package"),root:B.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},Qa={allPassed:B.boolean().describe("Whether every audited package passed all checks"),packages:B.array(B.object({name:B.string(),passed:B.boolean(),checks:B.array(B.object({name:B.string(),status:B.enum(["pass","fail"]),message:B.string()}))})).describe("Per-package check results")},go=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:Xa,outputSchema:Qa,handler:e=>xs({all:e.all,root:e.root})});import L from"node:fs";import tl from"node:os";import se from"node:path";import{z as mr}from"zod";import{$ as No}from"zx";import{execFileSync as ec}from"node:child_process";var Es=(e,r)=>{let t=e.filter(o=>!o.live).map(o=>o.name);return r?{prunable:[],withheld:t}:{prunable:t,withheld:[]}},rc=[/\binfra-kit\s+dev\b/,/cli\.js\s+dev\b/,/dev-server\.(?:js|ts)\b/],tc=e=>rc.some(r=>r.test(e)),oc="/bin/ps",nc=()=>ec(oc,["-eo","command="],{encoding:"utf8",maxBuffer:8<<20}).split(`
|
|
4
|
+
`),Ps=(e=nc)=>{try{return e().some(tc)}catch{return!0}};import gc from"@inquirer/select";import{Buffer as hc}from"node:buffer";import vc from"node:fs";import kc from"node:path";import xo from"node:process";import{z as Nr}from"zod";import{$ as Rt}from"zx";var sc="Could not find requested project",ic="Could not find requested config",Ts="Invalid Auth token",Cs="does not have access to requested config",Sr=e=>e.includes(Ts)||e.includes(Cs)?"auth":e.includes(sc)?"project":e.includes(ic)?"config":"unknown",$r=e=>e.includes(Cs)?"mis-scoped":e.includes(Ts)?"revoked":null;var Ss=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
|
+
`),ir=class extends it{authKind;constructor(r,t=null,o){super(o??Ss(r),r),this.name="DopplerAuthError",this.authKind=t}};var ho=({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 yt}from"zx";var _r=e=>{if(e===null||typeof e!="object")return;let r=e.stderr;return typeof r=="string"&&r.length>0?r:void 0},ac=(e,r)=>{let t=r.stderrExcerpt??_r(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(ac(r,t),{cause:r}),this.name="OperationError",this.operation=t.operation,this.remediation=t.remediation}};var cc=5e3,lc="DOPPLER_CONFIG",Me=async()=>{let{envManagement:e}=await j();return e.config.name},Ar=async({childEnv:e,project:r,config:t})=>{let o=yt.quiet;yt.quiet=!0;try{let n=(await yt({env:e})`doppler secrets get ${lc} --plain --project ${r} --config ${t}`.timeout(cc)).stdout.trim();return n!==t?{outcome:"mis-scoped",scopedTo:n}:{outcome:"valid",scopedTo:n}}catch(s){return{outcome:pc(s)}}finally{yt.quiet=o}},pc=e=>{let r=_r(e)??(e instanceof Error?e.message:String(e));return Sr(r)!=="auth"?"unreachable":$r(r)??"unreachable"};import $s from"node:process";var Y="INFRA_KIT_ENV_TOKEN",ar=async e=>{let r=$s.env[Y];if(r)return{token:r,source:"env"};let o=(await Z())?.envs[e];if(o)return{token:o,source:"store"};throw new it(dc(e,await dt()),e)},af=async e=>$s.env[Y]?!0:!!(await Z())?.envs[e],dc=(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 ${y(r)} (mode 0600, never in the repo).`,`CI / agents: set ${Y} instead \u2014 it takes precedence and needs no home config.`].join(`
|
|
7
|
+
`);import _s from"node:fs/promises";import vo from"node:path";import uc from"yaml";var As=".github/workflows",Ir=async e=>{let r=await R();return Is(vo.resolve(r,As,e))},ko=async()=>{let e=await R(),r=vo.resolve(e,As),t;try{t=await _s.readdir(r)}catch{return[]}let o=t.filter(n=>n.endsWith(".yml")||n.endsWith(".yaml")).sort(),s=await Promise.all(o.map(n=>Is(vo.resolve(r,n))));return[...new Set(s.flat())]},Is=async e=>{let r;try{r=uc.parse(await _s.readFile(e,"utf-8"))}catch{return[]}let t=cr(r,"on")??cr(r,"true"),o=cr(cr(cr(cr(t,"workflow_dispatch"),"inputs"),"environment"),"options");return Array.isArray(o)?o.filter(s=>typeof s=="string"&&s.length>0):[]},cr=(e,r)=>{if(!(typeof e!="object"||e===null||Array.isArray(e)))return e[r]};var wt=async()=>{let e=await ko(),r=await Z(),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]},Le=async()=>(await wt()).map(r=>r.env);import Os from"node:fs";import{$ as mc}from"zx";import We from"node:fs";import Or from"node:path";var yo=({autoLoaded:e,projectDir:r,canonicalProjectRoot:t})=>!e||!r||!t?!1:t===r,me=e=>{if(!e)return"";try{return We.realpathSync(e)}catch{return""}},wo=(e,r)=>{try{let t=je(e);We.mkdirSync(t,{recursive:!0,mode:448}),Fe(Or.join(t,J),r,384)}catch(t){l.debug(`warm-cache write skipped: ${t.message}`)}},Ro=(e=Date.now(),r=xr)=>{let t=us(),o;try{o=We.readdirSync(t,{withFileTypes:!0})}catch{return}for(let s of o){if(!s.isDirectory())continue;let n=Or.join(t,s.name);try{let{mtimeMs:i}=We.statSync(Or.join(n,J));e-i>=r*1e3&&We.rmSync(n,{recursive:!0,force:!0})}catch{}}},bo=(e,r)=>{try{let t=je(e);if(r){We.rmSync(t,{recursive:!0,force:!0});return}if(!We.existsSync(Or.join(t,J)))return;Fe(Or.join(t,at),`# infra-kit warm cache cleared
|
|
8
|
+
`,384)}catch(t){l.debug(`warm-cache invalidate skipped: ${t.message}`)}};var Ns=e=>e.split(`
|
|
9
|
+
`).filter(r=>r.startsWith("worktree ")).map(r=>r.slice(9).trim()).filter(Boolean),fc=async()=>{let e;try{e=(await mc({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 Ns(e)){let o=me(t);if(!o)continue;let s=je(o);try{if(!Os.existsSync(s))continue;Os.rmSync(s,{recursive:!0,force:!0}),r.push(s)}catch(n){l.debug(`warm-cache purge skipped for ${s}: ${n.message}`)}}return r};var yc=e=>e?[`${De}=${Ve("1")}`]:[`unset ${De}`,`unset ${Qe}`],wc="DOPPLER_CONFIG",Ds=new Set(["DOPPLER_TOKEN",Y]),js=!1,Rc=e=>{e.length===0||js||(js=!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.`))},Ms=({pairs:e,config:r,project:t,projectRoot:o,loadedAt:s,autoLoaded:n})=>{let i=e.filter(([a])=>!Ds.has(a));return Rc(e.filter(([a])=>Ds.has(a)).map(([a])=>a)),["set -a",...i.map(([a,c])=>`${a}=${Ve(c)}`),`${ct}=${Ve(r)}`,`${Ze}=${Ve(r)}`,`${Ye}=${Ve(t)}`,`${lt}=${Ve(o)}`,`${Xe}=${Ve(s)}`,...yc(n),"set +a"]},bc=async()=>{try{return await R()}catch{return""}},Ls=async({config:e,autoLoaded:r=!1,beforeWrite:t,projectDir:o})=>{let s=await Me(),n=await bc(),i=await Pc(s,e),a=new Date().toISOString(),p=`${Ms({pairs:i,config:e,project:s,projectRoot:n,loadedAt:a,autoLoaded:r}).join(`
|
|
10
|
+
`)}
|
|
11
|
+
`,d=er(),u=kc.resolve(d,J);if(t&&!t())return null;vc.mkdirSync(d,{recursive:!0,mode:448}),Fe(u,p,384);let g=me(n);return yo({autoLoaded:r,projectDir:o,canonicalProjectRoot:g})&&(wo(o,p),Ro()),{filePath:u,variableCount:i.length,project:s,config:e}},Ws=async e=>{let{config:r}=e,t="";if(r)t=r;else{let n=await Le();m.setInteractive(),t=await S(i=>gc({message:"Select environment config",choices:n.map(a=>({name:a,value:a}))},i),{output:xo.stderr})}m.addOption("--config",t);let o=await Ls({config:t,autoLoaded:!1});if(!o)throw new Error("env-load: write was unexpectedly aborted");xo.stdout.write(`${o.filePath}
|
|
12
|
+
`),m.print();let s={filePath:o.filePath,variableCount:o.variableCount,project:o.project,config:o.config};return{content:h(JSON.stringify(s,null,2)),structuredContent:s}},Fs=1024*1024,xc=3e4,Ec=["DOPPLER_TOKEN","DOPPLER_PROJECT","DOPPLER_CONFIG"],lr=(e,r=xo.env)=>{let t={...r};for(let o of Ec)delete t[o];return t.DOPPLER_TOKEN=e,t},Pc=async(e,r)=>{let{token:t}=await ar(r),o=lr(t),s=Rt.quiet;Rt.quiet=!0;try{let n;try{n=await Rt({env:o})`doppler secrets download --no-file --format json --project ${e} --config ${r}`.timeout(xc)}catch(a){throw Tc(a,e,r)}Cc(n.stdout);let i=Js(n.stdout);return Vs(i,r),i}finally{Rt.quiet=s}},Vs=(e,r)=>{let t=e.find(([o])=>o===wc)?.[1];if(!(t===void 0||t===r))throw new ir(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}".`)},Tc=(e,r,t)=>{let o=_r(e)??(e instanceof Error?e.message:String(e)),s=Sr(o);return s==="auth"?new ir(t,$r(o)):s==="unknown"?e instanceof Error?e:new Error(String(e)):new Error(ho({kind:s,project:r,config:t,available:null}))},Cc=e=>{let r=hc.byteLength(e,"utf-8");if(r>Fs)throw new Error(`doppler returned unexpectedly large output (${r} bytes > ${Fs}) \u2014 refusing to write to disk`)},Ve=e=>`'${e.replaceAll("'","'\\''")}'`,Sc=/^[A-Z_]\w*$/i,Js=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(!Sc.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},Eo=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:Nr.string().describe('Doppler config / environment name to load (e.g. "dev", "arthur", "renana"). Required for MCP calls.')},outputSchema:{filePath:Nr.string().describe("Path to the file that must be sourced to apply variables"),variableCount:Nr.number().describe("Number of variables loaded"),project:Nr.string().describe("Doppler project name"),config:Nr.string().describe("Doppler config name")},handler:Ws});import M from"node:fs";import jr from"node:path";var pr=(e,r,t)=>{let o=e.indexOf(r),s=e.indexOf(t);return o!==-1&&s!==-1&&s>=o},xe=(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
|
+
${i}`:"")};var Bs=(e,r,t)=>`${e}
|
|
15
|
+
${r}
|
|
16
|
+
${t}`,Dr=({content:e,body:r,startMarker:t,endMarker:o,placement:s="replace-in-place"})=>{let n=Bs(t,r,o),i=pr(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?xe(e,t,o)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
|
|
17
|
+
${n}
|
|
18
|
+
`:`${n}
|
|
19
|
+
`};var Fr="<!-- infra-kit:begin -->",Mr="<!-- infra-kit:end -->",$c="<!-- infra-kit:version ",_c="<!-- infra-kit:import:begin -->",Ac="<!-- infra-kit:import:end -->",Ic="AGENTS.md",Oc="CLAUDE.md",Nc=e=>`${$c}${e} -->`,Dc=e=>[Nc(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` / `reopen` / `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
|
+
`),Ks=e=>{if(M.existsSync(e)&&M.lstatSync(e).isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},Gs=e=>{let r=new Date().toISOString().replace(/[:.]/g,"-");M.copyFileSync(e,`${e}.backup.${r}`)},Us=(e,r)=>{Ks(e);let t=M.existsSync(e);return(t?M.readFileSync(e,"utf-8"):null)===r?"unchanged":(t&&Gs(e),M.mkdirSync(jr.dirname(e),{recursive:!0}),M.writeFileSync(e,r,"utf-8"),t?"updated":"created")},jc=(e,r)=>M.existsSync(e)?M.readFileSync(e,"utf-8"):r,Fc=(e,r,t)=>{let o=M.readFileSync(e,"utf-8");if(!pr(o,r,t))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},Mc=e=>{if(!M.existsSync(e))return"unchanged";Ks(e);let r=M.readFileSync(e,"utf-8"),t=xe(r,Fr,Mr);return t===null?"unchanged":t.trim()===""?(Gs(e),M.rmSync(e),"removed"):Us(e,t)},zs=async()=>{let e;try{e=(await D()).main}catch{return l.info("Skipped agent-instruction files \u2014 not inside an infra-kit repo"),{skipped:!0,root:null,written:[]}}if(!M.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=jr.dirname(e),t=mt.version,o=Dc(t),s=jr.join(r,Ic),n=jr.join(r,Oc),i=jc(n,"");i=xe(i,_c,Ac)??i,i=Dr({content:i,body:o,startMarker:Fr,endMarker:Mr,placement:"replace-in-place"});let a=[{path:n,action:Us(n,i)},{path:s,action:Mc(s)}];Fc(n,Fr,Mr);for(let c of a)c.action==="unchanged"&&c.path!==n||l.info(` ${c.action.padEnd(9)} ${jr.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 ni from"node:os";import Lr from"node:path";import si from"node:process";import xt from"node:fs/promises";import Lc from"node:path";import Wc from"node:process";var qs=` // "envManagement": { // required in layer 1; provider-tagged
|
|
21
|
+
// "provider": "doppler",
|
|
22
|
+
// "config": { "name": "my-doppler-project" }
|
|
23
|
+
// },
|
|
24
|
+
//
|
|
25
|
+
// "ide": {
|
|
26
|
+
// "provider": "cursor",
|
|
27
|
+
// "config": { "workspaceConfigPath": "/path/to/your.code-workspace" }
|
|
28
|
+
// },
|
|
29
|
+
// // Or, for Zed (no workspace file \u2014 one window with all worktrees via "zed <root> <wt...>"):
|
|
30
|
+
// "ide": { "provider": "zed", "config": {} },
|
|
31
|
+
// // Or drive BOTH editors at once with an array (at most one entry per provider):
|
|
32
|
+
// "ide": [
|
|
33
|
+
// { "provider": "cursor", "config": { "workspaceConfigPath": "/path/to/your.code-workspace" } },
|
|
34
|
+
// { "provider": "zed", "config": {} }
|
|
35
|
+
// ],
|
|
36
|
+
//
|
|
37
|
+
// "taskManager": {
|
|
38
|
+
// "provider": "jira",
|
|
39
|
+
// "config": { "baseUrl": "https://acme.atlassian.net", "projectId": 123 }
|
|
40
|
+
// },
|
|
41
|
+
//
|
|
42
|
+
// "worktrees": {
|
|
43
|
+
// "openInGithubDesktop": false,
|
|
44
|
+
// "openInCmux": true,
|
|
45
|
+
// // cmux pane layout for opened worktrees: "two-columns" (default, left | right)
|
|
46
|
+
// // or "three-pane" (left split top/bottom + full-height right).
|
|
47
|
+
// "cmux": { "layout": "two-columns" }
|
|
48
|
+
// },
|
|
49
|
+
//
|
|
50
|
+
// // Auto-load Doppler env when working inside this project/worktree. Omit to
|
|
51
|
+
// // disable. "trigger" (pick one): "shell-startup" (new shells) | "cli-invocation"
|
|
52
|
+
// // (before each infra-kit command, primes subsequent commands). "config" is the
|
|
53
|
+
// // environment to load \u2014 must have a service token (infra-kit env-token-set) or
|
|
54
|
+
// // auto-load quietly disables. Requires the committed infra-kit.json at the git
|
|
55
|
+
// // repo root, and the zsh shell integration (infra-kit init + a new shell). zsh only.
|
|
56
|
+
// "envAutoLoad": { "trigger": "shell-startup", "config": "dev" },
|
|
57
|
+
//
|
|
58
|
+
// // Per-app local-dev overrides, keyed by APP FOLDER name (the directory under
|
|
59
|
+
// // apps/). Both fields optional: "port" pins the local listen port (otherwise
|
|
60
|
+
// // <APP>_PORT / PORT / a built-in default), "prefixUrl" pins the URL prefix the
|
|
61
|
+
// // app is served under. An unknown app name is ignored at resolve time, never a
|
|
62
|
+
// // parse error.
|
|
63
|
+
// "dev": {
|
|
64
|
+
// "client": { "port": 4001, "prefixUrl": "/api" }
|
|
65
|
+
// },
|
|
66
|
+
//
|
|
67
|
+
// // Named \`infra-kit dev <preset>\` sessions. The keys under "apps" are PACKAGES \u2014
|
|
68
|
+
// // "<app>/api" or "<app>/ui". A bare "<app>" is a FOLDER, not a package, and is
|
|
69
|
+
// // REJECTED. Per target: "watchDeps" (api targets) rebuilds the shared-package
|
|
70
|
+
// // dependency closure and restarts on change; "proxy" maps a route path to
|
|
71
|
+
// // "local" | "cloud" for this session only. "cmux": true runs each launched target
|
|
72
|
+
// // in its own cmux pane. Omit "apps" entirely to launch every discovered target.
|
|
73
|
+
// "devServersPresets": {
|
|
74
|
+
// "backend": {
|
|
75
|
+
// "apps": {
|
|
76
|
+
// "client/api": { "watchDeps": true, "proxy": { "/api": "local", "/auth": "cloud" } },
|
|
77
|
+
// "client/ui": {}
|
|
78
|
+
// },
|
|
79
|
+
// "cmux": true
|
|
80
|
+
// }
|
|
81
|
+
// },
|
|
82
|
+
//
|
|
83
|
+
// // DEPRECATED \u2014 accepted but IGNORED; safe to delete. Remove it and this note in a
|
|
84
|
+
// // future release.
|
|
85
|
+
// //
|
|
86
|
+
// // The proxy port is no longer configurable. Every dev URL is now
|
|
87
|
+
// // https://<release>.<package>.localhost with NO port, and the only port that can
|
|
88
|
+
// // serve a port-free HTTPS URL is 443 \u2014 so a setting here could only put the port
|
|
89
|
+
// // back into the URL. Set up the daemon once (the install is the only step needing
|
|
90
|
+
// // root; trusting its local CA does not). Run \`infra-kit doctor\`: it checks both and
|
|
91
|
+
// // prints each fix as a command you can paste, with the paths filled in for your
|
|
92
|
+
// // machine. Do not type a bare \`portless\` \u2014 it lives in node_modules, not on PATH.
|
|
93
|
+
// // infra-kit itself never elevates.
|
|
94
|
+
// "devProxy": { "port": 443 }
|
|
95
|
+
//
|
|
96
|
+
// // Doppler SERVICE TOKENS are not a config key and never belong in this file. They live in
|
|
97
|
+
// // tokens.json \u2014 a SIBLING of this file, at ~/.infra-kit/projects/<repo>/tokens.json (mode 0600) \u2014
|
|
98
|
+
// // shaped { "envs": { "<env>": "dp.st\u2026" } }. Write it with \`infra-kit env-token-set <env>\` (which
|
|
99
|
+
// // also fixes its modes), or by hand: both are supported, which is why the store carries no
|
|
100
|
+
// // repo-identity field and no mandatory version. Pasting a token into an
|
|
101
|
+
// // infra-kit.json (any layer) is REJECTED: the loader refuses to parse it and tells you to revoke
|
|
102
|
+
// // the token first, because a config file can be committed, backed up by your editor, or shared.`,Po=()=>`// infra-kit user-global config \u2014 ~/.infra-kit/infra-kit.json
|
|
103
|
+
//
|
|
104
|
+
// Merge chain (later layers override earlier ones at top-level keys):
|
|
105
|
+
// 1. <repo>/infra-kit.json \u2014 committed project config (required)
|
|
106
|
+
// 2. ~/.infra-kit/infra-kit.json \u2014 user-global (the sibling of this file)
|
|
107
|
+
// 3. ~/.infra-kit/projects/<repo-name>/infra-kit.json \u2014 user-scope per-project override
|
|
108
|
+
//
|
|
109
|
+
// Merge is shallow: setting a top-level key replaces that whole section from
|
|
110
|
+
// layer 1. Arrays do not concatenate. Top-level keys recognized:
|
|
111
|
+
// envManagement, ide, taskManager, worktrees, envAutoLoad, dev,
|
|
112
|
+
// devServersPresets, devProxy. The schema is strict \u2014 an unrecognized top-level
|
|
113
|
+
// key is a parse error, not a silently ignored one.
|
|
114
|
+
//
|
|
115
|
+
// This .example.jsonc is reference only \u2014 it is NOT loaded. Put real global
|
|
116
|
+
// overrides in the sibling infra-kit.json (strict JSON: no comments, double-quoted
|
|
117
|
+
// keys). Per-project tweaks belong in layer 3 \u2014 run \`infra-kit config edit\`.
|
|
118
|
+
//
|
|
119
|
+
// Every recognized key is documented below. NOTE: \`envManagement\` is REQUIRED in
|
|
120
|
+
// the committed project infra-kit.json (layer 1) and is usually NOT set in this
|
|
121
|
+
// user-global layer \u2014 it is shown here only to document the full, valid config shape.
|
|
122
|
+
{
|
|
123
|
+
${qs}
|
|
124
|
+
}
|
|
125
|
+
`,To=e=>`// infra-kit user override for ${e} \u2014 ~/.infra-kit/projects/${e}/infra-kit.json
|
|
126
|
+
//
|
|
127
|
+
// Layer 3 (highest precedence) of the config merge chain. Shallow-merged on top of
|
|
128
|
+
// <repo>/infra-kit.json (layer 1) and ~/.infra-kit/infra-kit.json (layer 2) \u2014 a
|
|
129
|
+
// top-level key set here replaces that whole section wholesale; arrays do not
|
|
130
|
+
// concatenate. Top-level keys recognized: envManagement, ide,
|
|
131
|
+
// taskManager, worktrees, envAutoLoad, dev, devServersPresets, devProxy. The schema
|
|
132
|
+
// is strict \u2014 an unrecognized top-level key is a parse error, not a silently ignored
|
|
133
|
+
// one.
|
|
134
|
+
//
|
|
135
|
+
// This .example.jsonc is reference only \u2014 it is NOT loaded. Put real overrides
|
|
136
|
+
// in the sibling infra-kit.json (strict JSON: no comments, double-quoted keys).
|
|
137
|
+
//
|
|
138
|
+
// Every recognized key is documented below. NOTE: \`envManagement\` is REQUIRED in
|
|
139
|
+
// the committed project infra-kit.json (layer 1) and is usually NOT set in this
|
|
140
|
+
// override layer \u2014 it is shown here only to document the full, valid config shape.
|
|
141
|
+
{
|
|
142
|
+
${qs}
|
|
143
|
+
}
|
|
144
|
+
`,Co=()=>`// infra-kit factory registry \u2014 ~/.infra-kit/vendor.json
|
|
145
|
+
//
|
|
146
|
+
// Machine-local registry the vendor commands (sync/manifest/diff) read to know
|
|
147
|
+
// where your project repos live and which ones to stamp. This .example.jsonc is
|
|
148
|
+
// reference only \u2014 it is NOT loaded. The real file is the strict-JSON sibling
|
|
149
|
+
// vendor.json (no comments, double-quoted keys); run \`infra-kit vendor config --init\`
|
|
150
|
+
// to scaffold it.
|
|
151
|
+
{
|
|
152
|
+
// "workspaceDir": "~/projects", // string (absolute or ~-prefixed) \u2014 where target repos are cloned
|
|
153
|
+
// "targets": ["my-repo-a", "my-repo-b"] // string[] (>=1) \u2014 repo dir names resolved under workspaceDir
|
|
154
|
+
}
|
|
155
|
+
`;var Hs=!1,Vc=e=>e.replace(/\.json$/,".example.jsonc"),Jc=async e=>{try{return await xt.readFile(e,"utf-8")}catch{return null}},Et=async e=>{let r=e.userProject,t=Vc(r);await xt.mkdir(Lc.dirname(r),{recursive:!0});let o=!await H(r);o&&await xt.writeFile(r,`{}
|
|
156
|
+
`,"utf-8");let s=To(e.projectName),n=await Jc(t)!==s;return n&&await xt.writeFile(t,s,"utf-8"),o&&ps(),{configPath:r,examplePath:t,createdConfig:o,refreshedExample:n}},Pt=e=>`Created ${y(e.configPath)} \u2014 see ${y(e.examplePath)} for the annotated reference.`,Bc=async()=>{if(Wc.env.INFRA_KIT_NO_SEED||Hs)return;Hs=!0;let e;try{e=await D()}catch{return}if(await H(e.main))try{let r=await Et(e);r.createdConfig?l.info(Pt(r)):r.refreshedExample&&l.debug(`Refreshed ${y(r.examplePath)} to match the current schema.`)}catch(r){l.debug({err:r,msg:`Skipped seeding ${y(e.userProject)} (config bootstrap failed).`})}};import K from"node:fs/promises";import ne from"node:path";import{pathToFileURL as Uc}from"node:url";import zc from"yaml";import{z as Qs}from"zod";import Kc from"node:fs/promises";import So from"node:os";import $o from"node:path";import{z as Gc}from"zod";import{z as Tt}from"zod";var Zs="vendor.json",Ct=Tt.object({workspaceDir:Tt.string().min(1),targets:Tt.array(Tt.string()).min(1)}).strict();var _o=()=>$o.join(So.homedir(),cs,Zs),Ys=e=>{if(e==="~")return So.homedir();if(e.startsWith("~/"))return $o.join(So.homedir(),e.slice(2));if($o.isAbsolute(e))return e;throw new Error(`workspaceDir must be absolute or ~-prefixed, got: ${e}`)},dr=async()=>{let e=_o(),r;try{r=await Kc.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
|
+
|
|
158
|
+
{
|
|
159
|
+
"workspaceDir": "~/projects",
|
|
160
|
+
"targets": ["my-repo"]
|
|
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=Ct.safeParse(t);if(!o.success)throw new Error(`Invalid factory config at ${e}: ${Gc.prettifyError(o.error)}`);return o.data};var Xs=e=>e.replace(/\.json$/,".yml"),ei=async()=>{let e;try{e=await D()}catch{return}let r=[{label:"infra-kit.json",yml:Xs(e.main),json:e.main,schema:ls},{label:"~/.infra-kit/infra-kit.json",yml:ne.join(ne.dirname(e.userGlobal),"config.yml"),json:e.userGlobal,schema:oo},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:Xs(e.userProject),json:e.userProject,schema:oo}],t=0;for(let o of r){let[s,n]=await Promise.all([H(o.yml),H(o.json)]);if(s){if(n){l.info(`\u26A0 Skipped ${y(o.yml)} \u2014 ${y(o.json)} already exists (remove the stale .yml manually)`);continue}try{let i=await K.readFile(o.yml,"utf-8"),a=zc.parse(i)??{},c=o.schema.safeParse(a);if(!c.success){l.info(`\u26A0 Skipped ${y(o.yml)} \u2014 invalid config: ${Qs.prettifyError(c.error)}`);continue}await K.mkdir(ne.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 ${y(o.yml)} \u2192 ${y(o.json)}`),t++}catch(i){l.info(`\u26A0 Skipped ${y(o.yml)} \u2014 ${i.message}`)}}}t>0&&He()},ri=async()=>{let e;try{e=await D()}catch{return}let r=ne.dirname(e.userGlobal),t=[{from:ne.join(r,"config.json"),to:e.userGlobal},{from:ne.join(r,"config.example.jsonc"),to:ne.join(r,"infra-kit.example.jsonc")}],o=0;for(let{from:s,to:n}of t){let[i,a]=await Promise.all([H(s),H(n)]);if(i){if(a){l.info(`\u26A0 Skipped ${y(s)} \u2014 ${y(n)} already exists (remove the stale file manually)`);continue}try{await K.mkdir(ne.dirname(n),{recursive:!0}),await K.rename(s,n),l.info(`\u2713 Renamed ${y(s)} \u2192 ${y(n)}`),o++}catch(c){l.info(`\u26A0 Skipped ${y(s)} \u2014 ${c.message}`)}}}o>0&&He()},ti=async()=>{let e=_o(),r=ne.dirname(e),t=ne.join(r,"vendor.config.ts"),[o,s]=await Promise.all([H(t),H(e)]);if(o){if(s){l.info(`\u26A0 Skipped ${y(t)} \u2014 ${y(e)} already exists (remove the stale vendor.config.ts manually)`);return}try{let n=await K.stat(t),c=(await import(`${Uc(t).href}?mtime=${Number(n.mtimeMs)}`)).default,p=typeof c=="function",d=p?await c():c,u=Ct.safeParse(d);if(!u.success){l.info(`\u26A0 Skipped ${y(t)} \u2014 invalid factory config: ${Qs.prettifyError(u.error)}`);return}await K.mkdir(r,{recursive:!0}),await K.writeFile(e,`${JSON.stringify(u.data,null,2)}
|
|
164
|
+
`,"utf-8"),await K.rm(t,{force:!0}),p?l.info(`\u26A0 Migrated ${y(t)} \u2192 ${y(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 ${y(e)} directly to change them.`):l.info(`\u2713 Migrated ${y(t)} \u2192 ${y(e)}`)}catch(n){l.info(`\u26A0 Skipped ${y(t)} \u2014 ${n.message}`)}}},qc=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}},oi=async()=>{let e;try{e=await D()}catch{return}let r=[e.main,e.userGlobal,e.userProject],t=0;for(let o of r)if(await H(o))try{let s=await K.readFile(o,"utf-8");if(s.trim()==="")continue;let n=JSON.parse(s),{changed:i,result:a}=qc(n);if(!i)continue;await K.writeFile(o,`${JSON.stringify(a,null,2)}
|
|
165
|
+
`,"utf-8"),l.info(`\u2713 Normalized ide config in ${y(o)} (removed legacy "mode")`),t++}catch(s){l.info(`\u26A0 Skipped normalizing ${y(o)} \u2014 ${s.message}`)}t>0&&He()};var Wr="# -- infra-kit:begin --",ur="# -- infra-kit:end --",Hc=[["# region infra-kit","# endregion infra-kit"]],Zc="# infra-kit shell functions",ch=async()=>{let e=Lr.join(ni.homedir(),".zshrc"),r=fe.existsSync(e)?el(fe.readFileSync(e,"utf-8")):"",t=Dr({content:r,body:ii(),startMarker:Wr,endMarker:ur,placement:"append-end"});fe.writeFileSync(e,t),l.info(`Added infra-kit shell functions to ${e}`),await ei(),await oi(),await ri(),await ti(),Yc(),await zs(),await Xc();let o=si.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.")},Yc=()=>{let e=Lr.join(ni.homedir(),".infra-kit"),r=Lr.join(e,"infra-kit.json");if(fe.mkdirSync(e,{recursive:!0}),fe.writeFileSync(Lr.join(e,"infra-kit.example.jsonc"),Po(),"utf-8"),fe.writeFileSync(Lr.join(e,"vendor.example.jsonc"),Co(),"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)`)},Xc=async()=>{if(!si.env.INFRA_KIT_NO_SEED)try{let e=await D();if(!fe.existsSync(e.main))return;let r=await Et(e);r.createdConfig&&l.info(Pt(r))}catch(e){l.debug({err:e,msg:"Skipped seeding the user-project config (init)."})}},Qc=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"),el=e=>{let r=xe(e,Wr,ur);if(r!==null)return r;for(let[a,c]of Hc){let p=xe(e,a,c);if(p!==null)return p}let t=e.indexOf(Zc);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&&Qc(s[n]);)n++;let i=s.slice(n).join(`
|
|
168
|
+
`);return o+(i?`
|
|
169
|
+
${i}`:"")},ii=()=>{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
|
+
`)},ai=()=>`${Wr}
|
|
171
|
+
${ii()}
|
|
172
|
+
${ur}`;import rl from"node:fs/promises";var Ao=async(e,r)=>{if(!r)return{hasOverrides:!1,overrideKeys:[],unreadable:!1};try{let t=await rl.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}}},Io=e=>e.unreadable?"(unreadable \u2014 invalid JSON)":e.overrideKeys.length===0?"(empty \u2014 no overrides)":`(${e.overrideKeys.length} override(s): ${e.overrideKeys.join(", ")})`;var Je=async(e,r,t,o)=>{try{return await No`${r}`,{name:e,status:"pass",message:t}}catch{return{name:e,status:"fail",message:o}}},ol=()=>{let e="zshrc init block",r=se.join(tl.homedir(),".zshrc");if(!L.existsSync(r))return{name:e,status:"fail",message:"~/.zshrc not found. Run: infra-kit init"};let t=L.readFileSync(r,"utf-8"),o=t.indexOf(Wr),s=t.indexOf(ur);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+ur.length).trim(),i=ai().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"}},nl=async()=>{let e="warm cache",r;try{r=await R()}catch{return{name:e,status:"pass",message:"warm cache: not a git project"}}let t=me(r);if(!t)return{name:e,status:"pass",message:"warm cache: unavailable"};let o=se.join(je(t),J);if(!L.existsSync(o))return{name:e,status:"pass",message:"warm cache: none yet (populated on next auto-load)"};let s=Math.floor((Date.now()-L.statSync(o).mtimeMs)/1e3),n=Math.floor(s/60),i=Math.floor(xr/60);return s>=xr?{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`}},sl=async()=>{let e="pnpm enableGlobalVirtualStore";try{let r=await R(),t=se.join(r,"pnpm-workspace.yaml");if(!L.existsSync(t))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${t}`};let o=L.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}`}}},il=async()=>{try{return He(),{config:await j(),error:null}}catch(e){return{config:null,error:e}}},al=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)"}},cl=384,Oo=448,ll=e=>e.map(r=>{let t=r.source===null?"no token":`token (${r.source})`;return`${r.env}: ${t}`}).join(", "),pl=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}}})),dl=async(e,r={})=>{let t="env tokens configured",o=r.readStore??Z,s=r.resolveToken??ar;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(u){return{name:t,status:"fail",message:`Token store unreadable \u2014 ${u.message}`}}let n=await Le(),i=e.config.envAutoLoad?.config,a=i&&!n.includes(i)?[...n,i]:n,c=await pl(a,s),p=ll(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(u=>u.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}`}},ul={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)"}},ml=async(e,r={})=>{let t="env token valid",o=r.resolveToken??ar,s=r.probe??Ar;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:lr(i),project:a,config:n}),p=ul[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}`}},Vr=(e,r)=>{let t=r(e);return t===null?null:t.mode&511},fl=async(e,r={})=>{let t="tokens.json perms",o=r.storePath??dt,s=r.statPath??gl,n=r.chmodPath??L.chmodSync,i;try{i=await o()}catch{return{name:t,status:"pass",message:"Skipped \u2014 the token store path could not be resolved"}}if(Vr(i,s)===null)return{name:t,status:"pass",message:`No token store yet at ${y(i)}`};let a=se.dirname(i),c=se.dirname(a),p=se.dirname(c),u=[{target:p,expected:Oo,actual:Vr(p,s)},{target:c,expected:Oo,actual:Vr(c,s)},{target:a,expected:Oo,actual:Vr(a,s)},{target:i,expected:cl,actual:Vr(i,s)}].filter(w=>w.actual!==null&&w.actual!==w.expected);if(u.length===0)return{name:t,status:"pass",message:`${y(i)} is 0600 (0700 dirs)`};let g=u.map(w=>`${y(w.target)} is ${ci(w.actual)}, expected ${ci(w.expected)}`).join("; ");if(!e)return{name:t,status:"fail",message:`${g}. Fix: run \`infra-kit doctor --fix\`, or chmod them by hand.`};for(let w of u)n(w.target,w.expected);return{name:t,status:"pass",message:`Tightened ${u.length} path(s): ${g}`}},ci=e=>`0${e.toString(8).padStart(3,"0")}`,gl=e=>{try{return L.statSync(e)}catch{return null}},hl=async()=>{let e="user override path";try{let r=await D(),t=L.existsSync(r.userProject),o=await Ao(r.userProject,t),s=t?Io(o):"(not created \u2014 seed failed?)";return{name:e,status:"pass",message:`${y(r.userProject)} ${s} \u2014 project: ${r.projectName}`}}catch(r){return{name:e,status:"fail",message:r.message}}},vl=async()=>{let e="legacy user-global config",r;try{r=await D()}catch{return{name:e,status:"pass",message:"Skipped \u2014 infra-kit config paths could not be resolved"}}let t=se.join(se.dirname(r.userGlobal),"config.json");return L.existsSync(t)?L.existsSync(r.userGlobal)?{name:e,status:"fail",message:`Stale legacy config.json found at ${y(t)} \u2014 ${y(r.userGlobal)} is active; remove the old file.`}:{name:e,status:"fail",message:`Legacy user-global config.json found at ${y(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"}},kl={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/"}},yl=async e=>{let r=kl[e];try{return await No`${r.command}`,{ok:!0,label:r.label,failMsg:r.failMsg}}catch{return{ok:!1,label:r.label,failMsg:r.failMsg}}},wl=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=te(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=>yl(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("; ")}},Rl=[1,2,3,5,7],bl=async()=>{let e="rtk configured";try{let t=(await No`rtk init --show`).stdout.split(`
|
|
173
|
+
`).map(s=>s.trim()).filter(s=>s.startsWith("[ok]")||s.startsWith("[--]")),o=[];for(let s of Rl){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}`}}},xl=async()=>{let e;try{e=(await D()).main}catch{return[]}if(!L.existsSync(e))return[];let r=se.join(se.dirname(e),"CLAUDE.md"),t=L.existsSync(r)?L.readFileSync(r,"utf-8"):"",o=pr(t,Fr,Mr);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"}]},pi=e=>ft(["service","install"],{sudo:!0,bin:e}),di=e=>ft(["trust"],{bin:e}),El=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),li="ERR_TLS_CERT_ALTNAME_INVALID",Pl=async(e,r)=>{let t=`portless serving TLS on :${we}`;return await e(we,!0)?{name:t,status:"pass",message:`portless is serving HTTPS on :${we}`}:{name:t,status:"fail",message:`No portless daemon is serving HTTPS on :${we}. Install it once (needs root): \`${pi(r)}\`.`}},Tl=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(we,p)})))).filter(p=>!p.result.ok);if(a.length===0)return{name:s,status:"pass",message:`Served certificate chains to ${y(t)} (${n.join(", ")})`};let c=a.map(p=>p.result.ok?"":p.result.code);return c.includes(li)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${li} 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=>El.has(p))?{name:s,status:"fail",message:`The daemon is serving a certificate that does not chain to ${y(t)}. Its CA was regenerated \u2014 run \`${di(o)}\`, or reinstall: \`${pi(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:`${y(r)} matches the recorded ca.trusted fingerprint`}:{name:o,status:"fail",message:`The portless CA is not trusted (or was regenerated). Run: \`${di(t)}\` (no sudo needed).`}},Sl=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 \`${ft(["alias","--remove","<name>"],{bin:t})}\`.`}},$l=async(e={})=>{let r=e.resolveBin??ms,t=e.isProxyServing??fs,o=e.handshake??vs,s=e.caTrusted??hs,n=e.routes??so,i=e.isListening??no,a=(e.caPath??gs)(),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(),u=await Pl(t,c),g=u.status==="fail"?{name:"portless CA chain valid",status:"pass",message:"Skipped \u2014 no daemon to handshake with"}:await Tl(o,d,a,c);return[p,u,g,Cl(s(),a,c),await Sl(d,i,c)]},_l=async(e={})=>{let r="portless routes",t=e.routes??so,o=e.isListening??no,s=e.devSessionRunning??Ps,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}=Es(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??ks().removeAlias;for(let d of a)await p(d);return{name:r,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},ui=async(e={})=>{let r=await il(),t=await Promise.all([Je("gh installed",["gh","--version"],"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/"),Je("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),Je("doppler installed",["doppler","--version"],"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli"),Je("aws installed",["aws","--version"],"AWS CLI is installed","AWS CLI is not installed. Install from: https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html"),Je("rtk installed",["rtk","--version"],"RTK is installed","RTK is not installed. Install from: https://github.com/rtk-ai/rtk"),Je("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"),Je("cmux installed",["cmux","--version"],"cmux is installed","cmux is not installed. Install from: https://cmux.com/"),bl(),Promise.resolve(ol()),nl(),sl(),Promise.resolve(al(r)),dl(r),ml(r),fl(e.fix??!1),hl(),vl(),wl(r)]),o=await $l();if(e.fix){let i=await _l(),a=o.findIndex(c=>c.name===i.name);a>=0?o[a]=i:o.push(i)}let s=[...t,...o,...await xl()],n={checks:s.map(i=>({name:i.name,status:i.status,message:i.message})),allPassed:s.every(i=>i.status==="pass")};return{content:h(JSON.stringify(n,null,2)),structuredContent:n}},Do=v({name:"doctor",description:"Check installation and authentication status of gh, doppler, aws, and rtk CLIs",inputSchema:{},outputSchema:{checks:mr.array(mr.object({name:mr.string().describe("Name of the check"),status:mr.enum(["pass","fail"]).describe("Check result"),message:mr.string().describe("Details about the check result")})).describe("List of all check results"),allPassed:mr.boolean().describe("Whether all checks passed")},handler:()=>ui()});import{Chalk as Al}from"chalk";import jo from"node:process";var Il="Tools & CLIs",Ol="Shell & integration",Nl="Project config",Dl="Doppler env tokens",jl="Dev proxy (portless)",Fl=`portless serving TLS on :${we}`,Fo=[[Il,["gh installed","gh authenticated","doppler installed","aws installed","rtk installed","typescript-language-server installed","cmux installed","ide installed"]],[Ol,["rtk configured","zshrc init block","warm cache","pnpm enableGlobalVirtualStore","CLAUDE.md block"]],[Nl,["infra-kit config valid","user override path","legacy user-global config"]],[Dl,["env tokens configured","env token valid","tokens.json perms"]],[jl,["portless installed",Fl,"portless CA chain valid","portless CA trusted","portless routes"]]],mi="Other",Ml=Fo.map(([e])=>e),Ll=new Map(Fo.flatMap(([e,r])=>r.map(t=>[t,e]))),Lh=Fo.flatMap(([,e])=>e),Wl=new Set(["portless routes","tokens.json perms"]),Vl=e=>{let r=new Map;for(let o of e){let s=Ll.get(o.name)??mi,n=r.get(s);n?n.push(o):r.set(s,[o])}return[...Ml,mi].flatMap(o=>{let s=r.get(o);return s&&s.length>0?[{label:o,checks:s}]:[]})},fi={unicode:{pass:"\u2713",fail:"\u2717",separator:"\xB7",rule:"\u2500"},ascii:{pass:"ok",fail:"!!",separator:"-",rule:"-"}},Jl=24,Bl=(e,r)=>{let t=e.split(/\s+/).filter(n=>n.length>0),o=[],s="";for(let n of t)s.length===0?s=n:`${s} ${n}`.length<=r?s=`${s} ${n}`:(o.push(s),s=n);return s.length>0&&o.push(s),o.length>0?o:[""]},hi=e=>{let r=e.filter(t=>t.status==="fail").length;return{passed:e.length-r,failed:r}},Kl=e=>{let r=new Al({level:e?1:0});return{header:t=>r.bold.cyan(t),pass:t=>r.green(t),fail:t=>r.red(t),dim:t=>r.dim(t),bold:t=>r.bold(t)}},Gl=(e,r,t,o)=>{if(e.failed===0){let i=`${r}/${r} ok`;return{text:t.pass(i),plainWidth:i.length}}let s=`${e.passed}/${r}`,n=`${e.failed} failed`;return{text:`${t.dim(s)} ${o.separator} ${t.fail(n)}`,plainWidth:s.length+n.length+3}},fr=" ",gi=" ",Ul=(e,r,t,o)=>{let s=hi(e.checks),n=Gl(s,e.checks.length,r,t),i=Math.max(1,o-fr.length-e.label.length-n.plainWidth);return`${fr}${r.header(e.label)}${" ".repeat(i)}${n.text}`},zl=(e,r,t,o,s)=>{let n=e.status==="fail",i=o.pass.length,a=n?o.fail:o.pass,c=e.name.padEnd(r),p=n?t.fail(a):t.pass(a),d=n?t.fail(c):c,u=gi.length+i+1+r+2,g=Math.max(Jl,s-u),[w,...b]=Bl(e.message,g),k=z=>n?z:t.dim(z);return[`${gi}${p} ${d} ${k(w??"")}`.trimEnd(),...b.map(z=>`${" ".repeat(u)}${k(z)}`)]},ql=(e,r,t,o)=>{let s=hi(e),n=t.rule.repeat(Math.max(12,Math.min(o-fr.length,56))),i=e.filter(g=>g.status==="fail"&&Wl.has(g.name)).length,a=r.pass(`${s.passed} passed`),c=r.fail(`${s.failed} failed`),p=s.failed===0?a:`${a} ${t.separator} ${c}`,d=r.dim(`${i} fixable \u2014 run \`infra-kit doctor --fix\``),u=i>0?` ${d}`:"";return[`${fr}${r.dim(n)}`,`${fr}${p}${u}`]},Hl=(e,r={})=>{let t=r.color??!1,o=r.unicode??!0,s=r.width??80,n=Kl(t),i=o?fi.unicode:fi.ascii;if(e.length===0)return[n.bold("infra-kit doctor"),"",`${fr}${n.dim("No checks ran.")}`];let a=Vl(e).flatMap(c=>{let p=Math.max(...c.checks.map(d=>d.name.length));return[Ul(c,n,i,s),...c.checks.flatMap(d=>zl(d,p,n,i,s)),""]});return[n.bold("infra-kit doctor"),"",...a,...ql(e,n,i,s)]},Zl=new Set(["","0","false","none"]),Yl=["LC_ALL","LC_CTYPE","LANG"],Xl=(e,r)=>e.NO_COLOR!==void 0&&e.NO_COLOR!==""?!1:e.FORCE_COLOR!==void 0?!Zl.has(e.FORCE_COLOR.toLowerCase()):!!r.isTTY,Ql=(e,r)=>{if(r)return!1;let t=Yl.map(o=>e[o]).find(o=>o!==void 0&&o!=="");return t===void 0?!0:/UTF-?8/i.test(t)},ep=(e={})=>{let r=e.env??jo.env,t=e.stream??jo.stderr;return{color:Xl(r,t),unicode:Ql(r,e.ascii??!1),width:t.columns??80}},rp=(e,r={})=>{(r.write??(o=>{jo.stderr.write(o)}))(`${Hl(e,ep(r)).join(`
|
|
174
|
+
`)}
|
|
175
|
+
`)};import Mo from"node:fs";import vi from"node:path";import tp from"node:process";import{z as Jr}from"zod";var op=async e=>{let r="";try{r=await R()}catch{return}let t=me(r);t&&bo(t,e)},np=e=>[...e.map(r=>`unset ${r}`),`unset ${ct}`,`unset ${Ze}`,`unset ${Ye}`,`unset ${lt}`,`unset ${Xe}`,`unset ${De}`,`export ${Qe}='1'`],ki=async({purge:e=!1}={})=>{let r=er(),t=vi.join(r,J),o=Mo.existsSync(t);if(!o&&!e)throw new Error("No loaded environment found. Run `env-load` first.");await op(e);let s=o?pt(t):[],n=np(s),i=vi.resolve(r,at);Mo.mkdirSync(r,{recursive:!0,mode:448}),Fe(i,`${n.join(`
|
|
176
|
+
`)}
|
|
177
|
+
`,384),tp.stdout.write(`${i}
|
|
178
|
+
`),o&&Mo.rmSync(t,{force:!0});let a={filePath:i,variableCount:s.length,unsetStatements:n,purged:e};return{content:h(JSON.stringify(a,null,2)),structuredContent:a}},Lo=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:Jr.string().describe("Path to the file that must be sourced to apply"),variableCount:Jr.number().describe("Number of variables cleared"),unsetStatements:Jr.array(Jr.string()).describe("Unset statements generated"),purged:Jr.boolean().describe("Whether the project warm cache was purged outright")},handler:()=>ki()});import sp from"node:process";import{z as Ee}from"zod";var ip=(e,r,t)=>e.map(({env:o,source:s})=>({env:o,source:s,hasToken:!!(t||r[o])})),yi=["Environment","Source","Token"],ap=e=>{let r=e.map(n=>[n.env,n.source,n.hasToken?"set":"not set"]),t=yi.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(yi),s,...r.map(o)]},Ri=async()=>{let e=await Me(),r=await wt(),t=await Z(),o=sp.env[Y],s=ip(r,t?.envs??{},o);if(l.info(`Doppler project: ${e}
|
|
179
|
+
`),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."),wi({project:e,envs:s});for(let n of ap(s))l.info(n);return wi({project:e,envs:s})},wi=({project:e,envs:r})=>{let t={project:e,configs:r.map(o=>o.env),tokens:r};return{content:h(JSON.stringify(t,null,2)),structuredContent:t}},Wo=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:Ri});import cp from"node:path";import Be from"node:process";import{z as Pe}from"zod";var bi=async()=>{l.info("Environment session status:");let e=er(),r=Be.env[ds],t=cp.join(e,J),o=0,s=0,n=Be.env[Ze]??null,i=Be.env[Ye]??null,a=Be.env[Xe]??null,c=Be.env[De]==="1",p=!!Be.env[Qe];if(n){let u=pt(t);u.length>0&&(s=u.length,o=u.filter(b=>b in Be.env).length);let g=a?.replace(/\.\d{3}Z$/,"")??null,w=c?"auto-loaded":"manually loaded";if(l.info(` ${n}: ${o} of ${s} vars loaded (${w}, project: ${i}, loadedAt: ${g}, session: ${r})
|
|
180
|
+
`),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 u=p?" (cleared \u2014 auto-load suppressed until a new shell or explicit env-load)":"";l.info(` Session ${r}: no env loaded${u}
|
|
181
|
+
`)}let d={sessionId:r,sessionLoadedCount:o,sessionTotalCount:s,sessionConfig:n,sessionProject:i,sessionLoadedAt:a,autoLoaded:c,cleared:p};return{content:h(JSON.stringify(d,null,2)),structuredContent:d}},Vo=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:Pe.string().describe("Current terminal session ID"),sessionLoadedCount:Pe.number().describe("Number of cached vars active in the current session"),sessionTotalCount:Pe.number().describe("Total number of cached var names"),sessionConfig:Pe.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:Pe.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:Pe.string().nullable().describe("ISO 8601 timestamp of when the env was loaded"),autoLoaded:Pe.boolean().describe("True when the loaded env was applied by env auto-load (not a manual env-load)"),cleared:Pe.boolean().describe("True when env-clear is currently suppressing auto-load in this shell")},handler:bi});import lp from"node:process";import{z as Te}from"zod";var xi="****",Jo=e=>typeof e!="string"||e.length<8?xi:`${xi}${e.slice(-4)}`;var Ei=(e,r,t)=>e.map(o=>{let s=t||r[o];return s?{env:o,source:t?`env:${Y}`:"store",redactedToken:Jo(s),present:!0}:{env:o,source:"-",redactedToken:"-",present:!1}}),pp=["ENV","SOURCE","TOKEN","PRESENT"],Pi=(e,r)=>{let t=[...pp,...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())},Ti=async({check:e}={})=>{let r=await Le(),t=await Z(),o=lp.env[Y],s=Ei(r,t?.envs??{},o);if(e){let a=await Me();for(let c of s){if(!c.present)continue;let p=o||t.envs[c.env],d=await Ar({childEnv:lr(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(`
|
|
182
|
+
No token for: ${n.map(a=>a.env).join(", ")}. Add one with \`infra-kit env-token-set <env>\`.`);let i={tokens:s};return{content:h(JSON.stringify(i,null,2)),structuredContent:i}},Bo=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:Te.boolean().optional().describe("Probe Doppler for each token\u2019s validity and scope (one cheap call per environment).")},outputSchema:{tokens:Te.array(Te.object({env:Te.string().describe("Environment / Doppler config name"),source:Te.string().describe('"store", "env:INFRA_KIT_ENV_TOKEN", or "-" when absent'),redactedToken:Te.string().describe("Redacted token \u2014 last 4 chars at most, never the raw value"),present:Te.boolean().describe("Whether a token is configured for this environment"),status:Te.string().optional().describe("Only with check=true: valid | revoked | mis-scoped | unreachable")})).describe("One row per declared environment")},handler:Ti});import{z as kr}from"zod";import{$ as G}from"zx";import{$ as Lv}from"zx";import{$ as N}from"zx";import{$ as Kr}from"zx";import Br from"node:process";var Ko=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}`)},Go=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 Ko(p,"Failed to create Jira version"),{success:!0,version:await p.json()}}catch(t){throw l.error({error:t},"Error creating Jira version"),t}},gr=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 Ko(a,"Failed to get Jira project versions"),await a.json()}catch(r){throw l.error({error:r},"Error getting Jira project versions"),r}},St=async(e,r)=>{try{return(await gr(r)).find(s=>s.name===e)||null}catch(t){throw l.error({error:t,versionName:e},"Error finding Jira version by name"),t}},$t=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 Ko(c,"Failed to update Jira version"),{success:!0,version:await c.json()}}catch(t){throw l.error({error:t},"Error updating Jira version"),t}},Uo=async(e,r)=>{try{let{versionName:t}=e,o=await St(t,r);if(!o)throw l.error({versionName:t},"Jira version not found"),new Error(`Version "${t}" not found in Jira project`);return await $t({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}},hr=async()=>{let e=Br.env.JIRA_BASE_URL,r=Br.env.JIRA_TOKEN||Br.env.JIRA_API_TOKEN,t=Br.env.JIRA_PROJECT_ID,o=Br.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(`
|
|
183
|
+
`);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}},Ke=async()=>{try{return await hr()}catch(e){return l.warn({error:e},"Jira configuration not available, skipping Jira integration"),null}};var Ci="dev",_t=e=>e==="hotfix"?"main":"dev",zo=async(e="regular")=>{let r=_t(e);Kr.quiet=!0,await Kr`git fetch origin`,await Kr`git switch ${r}`,await Kr`git pull origin ${r}`,Kr.quiet=!1},qo=async e=>{let{id:r,jiraConfig:t,description:o,type:s="regular"}=e,n=q(r),i=await Go({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 At({id:r,jiraVersionUrl:a,type:s,description:o});return{version:$(r),type:s,branchName:c.branchName,prUrl:c.prUrl,jiraVersionUrl:a}},C=async()=>{let e=new Map,r=await Ke();if(!r)return e;try{let t=await gr(r);for(let o of t)o.description&&e.set(o.name,o.description)}catch{}return e},Gr=(e,r,t)=>{let o=t?" ".repeat(t-e.length+3):" ",s=`[${r}]`.padEnd(11);return`${e}${o}${s}`},x=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",Si=e=>e.flatMap(r=>{let t=_(r);return t?[{branch:r,id:t,label:$(t)}]:[]}),ge=e=>{try{return ye(de(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")'})}},Ur=e=>{if(e===Ci)return Ci;let r=_(e);return r?$(r):e},Ge=e=>e.flatMap(r=>{let t=_(r);return t?[$(t)]:[]}),up=(e,r)=>r?r.get(e)||"regular":void 0,O=e=>{let{branches:r,descriptions:t,types:o}=e;return Si(r).map(({branch:s,id:n,label:i})=>({value:s,label:i,description:t.get(q(n)),type:up(s,o)}))};var mp=e=>e.map(r=>({pr:r,id:_(r.headRefName)})).filter(r=>r.id!==null).sort((r,t)=>Yn(r.id,t.id,{a:r.pr.createdAt,b:t.pr.createdAt})).map(r=>r.pr),fp=async()=>{let e=await N`gh pr list --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,r=await N`gh pr list --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName,createdAt`,t=[...JSON.parse(e.stdout),...JSON.parse(r.stdout)],o=new Set;return t.filter(s=>o.has(s.headRefName)?!1:(o.add(s.headRefName),!0))},$i=async()=>{try{let e=await fp();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 mp(e)}catch(e){throw e instanceof f?e:(l.error({error:e},"\u274C Error fetching release PRs"),new f(e,{operation:"fetch release PRs"}))}},It=async()=>(await $i()).map(r=>r.headRefName),E=async()=>(await $i()).map(r=>({branch:r.headRefName,title:r.title,createdAt:r.createdAt})),Ot=async e=>{let{branch:r,body:t}=e;try{N.quiet=!0,await N`gh pr edit ${r} --body ${t}`,N.quiet=!1}catch(o){throw l.error({error:o,branch:r},`Error updating release PR body for ${r}`),o}},At=async e=>{let{id:r,jiraVersionUrl:t,type:o,description:s}=e,n=Zn(r,o),i=_t(o),a=ye(r),c=s&&s.trim()!==""?`${t}
|
|
184
|
+
|
|
185
|
+
${s}`:`${t}
|
|
186
|
+
`;try{N.quiet=!0,await N`git switch ${i}`,await N`git pull origin ${i}`,await N`git checkout -b ${a}`,await N`git push -u origin ${a}`,await N`git commit --allow-empty-message --allow-empty --message ''`,await N`git push origin ${a}`;let d=(await N`gh pr create --title ${n} --body ${c} --base ${i} --head ${a}`).stdout.trim();return await N`git switch ${i}`,N.quiet=!1,{branchName:a,prUrl:d}}catch(p){throw l.error({error:p,branchName:a},`Error creating release branch ${a}`),p}};var W=async e=>{let{operation:r}=e;if(await es())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(!await Qn())throw new f(void 0,{operation:r,remediation:"commit or stash your changes, then retry",stderrExcerpt:"working tree has uncommitted changes"})};import vp from"node:process";var zr=class extends Error{name="PromptCancelledError";constructor(){super("Prompt cancelled")}};import gp from"node:process";var Nt={enabled:!1},hp=(e,r=t=>{gp.stdout.write(t)})=>(Nt.enabled&&e&&e.structuredContent!=null&&r(`${JSON.stringify(e.structuredContent,null,2)}
|
|
187
|
+
`),e),_i=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(_i)};var Ai=()=>{if(ut()||!vp.stdin.isTTY||Nt.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"})},Ce=async e=>{Ai();let{runBranchPicker:r}=await import("./boot-HP5ORQEX.js"),t=await r(e);if(t===null)throw new zr;return t},vr=async(e,r)=>{Ai();let{runBranchMultiPicker:t}=await import("./boot-HP5ORQEX.js"),o=await t(e,r);if(o===null)throw new zr;return o};var Ii=async e=>{let{all:r,confirmedCommand:t}=e;await W({operation:"merge dev into release branches"});let s=(await E()).filter(p=>x(p.title)==="regular").map(p=>p.branch);if(s.length===0)return l.info("\u2139\uFE0F No open release branches found"),m.print(),{content:h(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{m.setInteractive();let p=await C();n=await vr(O({branches:s,descriptions:p}),{required:!0})}n.length===s.length?m.addOption("--all",!0):m.addOption("--versions",Ge(n)),await F(t,`Are you sure you want to merge dev into these branches: ${n.join(", ")}?`),t||m.addOption("--yes",!0),G.quiet=!0;try{await G`git fetch origin`,await G`git switch dev`,await G`git pull origin dev`}catch(p){throw G.quiet=!1,new f(p,{operation:"switch to dev before merging",remediation:"dev may be checked out in another worktree \u2014 check `git worktree list`"})}let a=[];for(let p of n)await kp(p)||a.push(p);if(G.quiet=!1,a.length>0){l.info(`
|
|
188
|
+
\u26A0\uFE0F ${a.length} branch(es) failed to merge automatically.
|
|
189
|
+
`),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
|
|
190
|
+
|
|
191
|
+
git switch ${p} && git pull origin ${p} && git merge origin/dev
|
|
192
|
+
git push origin ${p} && git switch dev
|
|
193
|
+
`);l.info(`\u2705 ${n.length-a.length}/${n.length} merges completed successfully.`)}else l.info(`\u2705 All merges completed successfully!
|
|
194
|
+
`);m.print();let c={successfulMerges:n.length-a.length,failedMerges:a.length,failedBranches:a,totalBranches:n.length};return{content:h(JSON.stringify(c,null,2)),structuredContent:c}},kp=async e=>{try{return await G`git switch ${e}`,await G`git pull origin ${e}`,await G`git merge origin/dev --no-edit`,await G`git push origin ${e}`,await G`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 G`git reset --merge HEAD~1`,!1}},Ho=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:kr.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:kr.number().describe("Number of successful merges"),failedMerges:kr.number().describe("Number of failed merges"),failedBranches:kr.array(kr.string()).describe("List of branches that failed to merge"),totalBranches:kr.number().describe("Total number of branches processed")},handler:Ii});import{z as Zr}from"zod";import{$ as V}from"zx";var Oi=(e,r)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-r).trim()},qr=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=Oi(r.stderr,500);s&&(t.stderr=s);let n=Oi(r.stdout,200);return n&&(t.stdout=n),t};import{$ as Ni}from"zx";var Hr=async e=>{let{branches:r,worktreeDir:t,pruneFolder:o=!1}=e,s=await Promise.allSettled(r.map(async i=>{let a=`${t}/${i}`;return await tr(a),await Ni`git worktree remove ${a}`,i})),n=[];for(let[i,a]of s.entries())if(a.status==="fulfilled")n.push(a.value);else{let c=r[i],p=new f(a.reason,{operation:`remove worktree for ${c}`,remediation:"check 'git worktree list' for the path; uncommitted changes block removal"});l.error({error:a.reason,msg:p.message})}return o&&n.length===r.length&&await Ni`git worktree prune`,n};var yr=async(e,r,t)=>{try{return await t()}catch(o){throw l.error({err:qr(o)},`\u274C Failed to ${e}`),new f(o,{operation:e,remediation:r})}},ji=async e=>{let r=await V`gh pr list --head ${e} --state all --json number,state,title --limit 1`;return JSON.parse(r.stdout)[0]??null},yp=async e=>{let r=to(e),t=await V`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},Di=async()=>{let e=await V`gh pr list --head dev --base main --state open --json number,state,title --limit 5`;return JSON.parse(e.stdout)[0]??null},wp=async e=>{let r=ge(e),t=await ji(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}},Rp=async()=>{let e=await E(),r=e.map(i=>i.branch),t=new Map(e.map(i=>[i.branch,x(i.title)]));m.setInteractive();let o=await C(),s=await Ce(O({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}},bp=async e=>{if(!(await re("release")).includes(e))return;let o=`${await R()}${oe}`;if((await Hr({branches:[e],worktreeDir:o})).length===0)throw new f(void 0,{operation:`remove worktree for ${e} before merge`,remediation:`run manually: git worktree remove ${o}/${e} (use --force if uncommitted changes)`})},xp=async e=>{let{selectedReleaseBranch:r,releaseType:t}=e,o=t==="hotfix"?"main":"dev",s=await ji(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 yr(`merge release PR ${r} into ${o}`,`check 'gh pr view ${r}' for mergeability and required reviews`,async()=>{await V`gh pr merge ${r} --squash --admin --delete-branch`})},Ep=async e=>{let r=$(e),t=to(e),o=await Di();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 yr(`retitle dev \u2192 main PR #${n} to "${t}"`,`update manually: gh pr edit ${n} --title "${t}"`,async()=>{await V`gh pr edit ${n} --title ${t}`})),n}await yr(`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 V`gh pr create --base main --head dev --title ${t} --body ""`});let s=await Di();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},Pp=async e=>{let r=$(e);if(await yp(e)){l.info(`\u2713 RC PR for ${r} already merged into main \u2014 skipping`);return}let o=await Ep(e);await yr(`merge RC PR #${o} (dev \u2192 main) for ${r}`,`check 'gh pr view ${o}' for mergeability and required reviews`,async()=>{await V`gh pr merge ${o} --squash --admin`})},Tp=async()=>{V.quiet=!1,await yr("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await V`gh workflow run deploy-all.yml --ref main -f environment=prod`}),V.quiet=!0},Cp=async()=>{await yr("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 V`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},Sp=async e=>{try{await rs(e)}catch(r){l.warn({err:qr(r)},`Failed to delete local branch ${e} (non-blocking)`)}try{await ts(e)}catch(r){l.warn({err:qr(r)},`Failed to delete remote branch ${e} (non-blocking)`)}},$p=async e=>{let r=await Ke();if(!r){l.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let t=q(e);await Uo({versionName:t},r)}catch(t){l.error({err:qr(t)},"Failed to deliver Jira release (non-blocking)")}},Fi=async e=>{let{version:r,confirmedCommand:t}=e;await W({operation:"deliver release"});let{selectedReleaseBranch:o,releasePrTitle:s}=r?await wp(r):await Rp(),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=$(n);m.addOption("--version",i),l.info(`Delivering ${n.kind==="name"?"named release":"version"} ${o}`);let a=x(s);await F(t,`Are you sure you want to deliver version ${o} to production?`),m.addOption("--yes",!0),V.quiet=!0,await bp(o),await xp({selectedReleaseBranch:o,releaseType:a}),a!=="hotfix"&&await Pp(n),await Tp(),await Cp(),await Sp(o),V.quiet=!1,await $p(n),l.info(`Successfully delivered ${o} to production!`),m.print();let c={releaseBranch:o,version:i,type:a,success:!0};return{content:h(JSON.stringify(c,null,2)),structuredContent:c}},Zo=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:Zr.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:Zr.string().describe("The release branch that was delivered"),version:Zr.string().describe("The version that was delivered"),type:Zr.enum(["regular","hotfix"]).describe("Release type"),success:Zr.boolean().describe("Whether the delivery was successful")},handler:Fi});import Ip from"@inquirer/confirm";import{z as Se}from"zod";import{$ as Yo}from"zx";import _p from"@inquirer/select";var Dt=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 S(t=>_p({message:"\u{1F9EA} Select environment",choices:e.map(o=>({name:o,value:o}))},t))};var Ap=["prod"],Mi=e=>Ap.includes(e),jt=e=>e.filter(r=>!Mi(r)),Ft=(e,r)=>{if(Mi(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 Op="deploy-all.yml",Np=async e=>{let{confirmedCommand:r,branch:t,env:o}=e;if(r)return!0;m.setInteractive();let s=await S(n=>Ip({message:`Deploy ${t} \u2192 ${o}?`,default:!1},n));return s&&m.addOption("--yes",!0),s},Li=async e=>{let{version:r,env:t,skipTerraform:o,confirmedCommand:s}=e,n="";if(r)n=r==="dev"?"dev":ge(r);else{m.setInteractive();let d=await E(),u=d.map(b=>b.branch),g=new Map(d.map(b=>[b.branch,x(b.title)])),w=await C();n=await Ce([{value:"dev",label:"dev"},...O({branches:u,descriptions:w,types:g})])}let i=Ur(n);m.addOption("--version",i);let a=jt(await Ir(Op)),c="";t?c=t:(m.setInteractive(),c=await Dt(a,"launch deploy-all workflow")),m.addOption("--env",c),Ft(c,"launch deploy-all workflow");let p=o??!1;if(p&&m.addOption("--skip-terraform",!0),!await Np({confirmedCommand:s,branch:n,env:c})){l.info("Deployment cancelled");let d={releaseBranch:n,version:i,environment:c,skipTerraformDeploy:p,success:!1};return{content:h(JSON.stringify(d,null,2)),structuredContent:d}}try{Yo.quiet=!0,await Yo`gh workflow run deploy-all.yml --ref ${n} -f environment=${c} ${p?["-f","skip_terraform_deploy=true"]:[]}`,Yo.quiet=!1,l.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${n} and environment: ${c}`),m.print();let u={releaseBranch:n,version:i,environment:c,skipTerraformDeploy:p,success:!0};return{content:h(JSON.stringify(u,null,2)),structuredContent:u}}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"})}},Xo=v({name:"gh-release-deploy-all",description:'Dispatch the deploy-all.yml GitHub Actions workflow to deploy every service from a release branch to the given environment. Fire-and-forget \u2014 returns once GitHub accepts the workflow_dispatch, NOT when the deployment finishes; watch the workflow run for completion status. Use gh-release-deploy-selected for a subset of services. Pass version="dev" to deploy from the dev branch instead of a release branch. Both "version" and "env" are required when invoked via MCP (interactive pickers are unavailable without a TTY).',inputSchema:{version:Se.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign") \u2014 resolves to the release/vX.Y.Z or release/<name> branch. Pass "dev" to deploy from the dev branch instead. Required for MCP calls.'),env:Se.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),skipTerraform:Se.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:Se.string().describe("The release branch that was deployed"),version:Se.string().describe("The version that was deployed"),environment:Se.string().describe("The environment deployed to"),skipTerraformDeploy:Se.boolean().describe("Whether terraform deployment was skipped"),success:Se.boolean().describe("Whether the deployment was successful")},handler:Li});import Dp from"@inquirer/checkbox";import jp from"@inquirer/confirm";import Fp from"node:fs/promises";import{resolve as Mp}from"node:path";import Lp from"yaml";import{z as U}from"zod";import{$ as Qo}from"zx";var Mt="deploy-selected-services.yml",Wp="skip_terraform_deploy",Vp=async e=>{let{confirmedCommand:r,branch:t,env:o}=e;if(r)return!0;m.setInteractive();let s=await S(n=>jp({message:`Deploy ${t} \u2192 ${o}?`,default:!1},n));return s&&m.addOption("--yes",!0),s},Wi=async e=>{let{version:r,env:t,services:o,skipTerraform:s,confirmedCommand:n}=e,i="";if(r)i=r==="dev"?"dev":ge(r);else{m.setInteractive();let k=await E(),T=k.map(ee=>ee.branch),z=new Map(k.map(ee=>[ee.branch,x(ee.title)])),I=await C();i=await Ce([{value:"dev",label:"dev"},...O({branches:T,descriptions:I,types:z})])}let a=Ur(i);m.addOption("--version",a);let c=jt(await Ir(Mt)),p="";t?p=t:(m.setInteractive(),p=await Dt(c,"launch deploy-selected workflow")),m.addOption("--env",p),Ft(p,"launch deploy-selected workflow");let d=await Jp();if(d.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${Mt}`,stderrExcerpt:`no services found in .github/workflows/${Mt}`});let u=[];if(o&&o.length>0?u=o:(m.setInteractive(),u=await S(k=>Dp({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:d.map(T=>({name:T,value:T}))},k))),m.addOption("--services",u),u.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${d.join(", ")}`,stderrExcerpt:"no services selected"});let g=u.filter(k=>!d.includes(k));if(g.length>0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${d.join(", ")}`,stderrExcerpt:`invalid services: ${g.join(", ")}`});let w=s??!1;w&&m.addOption("--skip-terraform",!0);let b=k=>{let T={releaseBranch:i,version:a,environment:p,services:u,skipTerraformDeploy:w,success:k};return{content:h(JSON.stringify(T,null,2)),structuredContent:T}};if(!await Vp({confirmedCommand:n,branch:i,env:p}))return l.info("Deployment cancelled"),b(!1);try{Qo.quiet=!0;let k=u.flatMap(z=>["-f",`${z}=true`]);return await Qo`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${p} ${k} ${w?["-f","skip_terraform_deploy=true"]:[]}`,Qo.quiet=!1,l.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${p}, services: ${u.join(", ")}`),m.print(),b(!0)}catch(k){throw l.error({error:k},"\u274C Error launching workflow"),new f(k,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},Jp=async()=>{let e=await R(),r=Mp(e,".github/workflows",Mt),t;try{t=Lp.parse(await Fp.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!==Wp).map(([n])=>n)},en=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:Wi});import{z as wr}from"zod";var Vi=async()=>{let r=(await E()).flatMap(i=>{let a=_(i.branch);return a?[{version:$(a),jiraKey:q(a),type:x(i.title)}]:[]}),t=await C(),o=Math.max(...r.map(i=>i.version.length)),s=r.map(i=>{let a=Gr(i.version,i.type,o),c=t.get(i.jiraKey);return c?`${a} ${c}`:a});l.info(`All release branches:
|
|
195
|
+
`),l.info(`
|
|
196
|
+
${s.join(`
|
|
197
|
+
`)}
|
|
198
|
+
`);let n={releases:r.map(i=>({version:i.version,type:i.type,description:t.get(i.jiraKey)||null})),count:r.length};return{content:h(JSON.stringify(n,null,2)),structuredContent:n}},rn=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:wr.array(wr.object({version:wr.string().describe("Release version"),type:wr.enum(["regular","hotfix"]).describe("Release type"),description:wr.string().nullable().describe("Jira version description")})).describe("List of all release branches"),count:wr.number().describe("Number of release branches")},handler:Vi});import Yp from"@inquirer/confirm";import Gi from"@inquirer/select";import un from"node:process";import{z as P}from"zod";import{question as fn}from"zx";import{$ as Wt}from"zx";var $e=e=>e.slice(1).split(".").map(Number),tn=e=>[...e].sort((r,t)=>{let[o,s,n]=$e(r),[i,a,c]=$e(t);return o!==i?(o??0)-(i??0):s!==a?(s??0)-(a??0):(n??0)-(c??0)});var Bi="next",Bp=/^v?(\d+)\.(\d+)\.(\d+)$/,Kp=e=>e.replace(/^.*release\//,""),nn=e=>{let r=Kp(e.trim()),t=Bp.exec(r);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null},Ji=e=>`${e[0]}.${e[1]}.${e[2]}`,sn=e=>{let r=[...e.remoteBranches??[],...e.jiraVersions??[]],t=[],o=new Set;for(let s of r){let n=nn(s);if(!n)continue;let i=Ji(n);o.has(i)||(o.add(i),t.push(n))}return tn(t.map(s=>Ji(s))).map(s=>$e(`v${s}`))},Ue=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},Lt=(e,r)=>{if(e.length===0)throw new Ue;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`},an=e=>e.trim().toLowerCase()===Bi,Gp=e=>e==="regular"||e==="hotfix",Ki=e=>"name"in e,Up=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(!Gp(d))throw new Error(`Invalid release type "${p}". Expected "regular" or "hotfix".`);s=d}if(an(o)||nn(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},cn=e=>{let r=e.id.raw;return e.description!==void 0&&e.description!==""?`${r}:${e.type}:${e.description}`:e.type==="hotfix"?`${r}:hotfix`:r},on=(e,r)=>r!==void 0&&r!==""?{...e,description:r}:e,zp=e=>{let r=e.name.trim();return st(r),on({id:{kind:"name",name:r,raw:r},type:e.type},e.description)},ln=(e,r)=>{let t=[...r];return e.map(o=>{if(Ki(o))return zp(o);let s=o.version.trim();if(s==="")throw new Error("Release entry has an empty version");if(an(s)){let a=Lt(t,o.type);return t.push($e(`v${a}`)),on({id:de(a),type:o.type},o.description)}let n=nn(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),on({id:de(i),type:o.type},o.description)})},pn=e=>e.some(r=>!Ki(r)&&an(r.version));var qp=e=>e.split(`
|
|
199
|
+
`).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),Hp=async()=>{let e=Wt.quiet;try{Wt.quiet=!0;let r=await Wt`git ls-remote --heads origin 'release/v*'`;return qp(r.stdout)}finally{Wt.quiet=e}},Zp=async()=>{let e=await Ke();return e?(await gr(e)).map(t=>t.name):[]},dn=async()=>{let[e,r]=await Promise.allSettled([Hp(),Zp()]);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"),sn({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:r.status==="fulfilled"?r.value:[]})};var Xp='"1.2.5" or "next"',Qp=(e,r)=>{try{return Lt(e,r)}catch(t){if(t instanceof Ue)return null;throw t}},mn=(e,r)=>{try{return ln(e,r)}catch(t){throw t instanceof Ue?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 Hn?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}},ed=async(e,r)=>{let t=Qp(e,r),o=t?` [${t}]`:"",s=(await fn(` Version (e.g. ${Xp})${o}: `)).trim(),n=s===""?t??"":s;return n===""&&(l.error("No version provided. Exiting..."),un.exit(1)),n},rd=async()=>{let e=(await fn(' Name (kebab-case, e.g. "checkout-redesign"): ')).trim();e===""&&(l.error("No name provided. Exiting..."),un.exit(1));try{st(e)}catch(r){let t=r instanceof Error?r.message:String(r);l.error(`${t} Exiting...`),un.exit(1)}return e},td=async e=>{m.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 S(u=>Gi({message:`Release #${i} \u2014 version or name?`,choices:[{name:"version (semver / next)",value:"version"},{name:"name (free-form)",value:"name"}],default:"version"},u)),c=await S(u=>Gi({message:`Release #${i} \u2014 select type:`,choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"},u)),p;if(a==="name"){let u=await rd();p=mn([{name:u,type:c}],[])[0]}else{let u=await ed(await o(),c);p=mn([{version:u,type:c}],t)[0],p.id.kind==="version"&&t.push($e(`v${p.id.raw}`))}let d=(await fn(" Description (optional, press Enter to skip): ")).trim();s.push({...p,...d!==""?{description:d}:{}}),n=await S(u=>Yp({message:"Add another release?",default:!1},u))}return s},od=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 ")},Ui=e=>{for(let r of e)m.addOption("--release",cn(r))},nd=async(e,r)=>{if(e&&e.length>0){let o=pn(e)?await r():[],s=mn(e,o);return Ui(s),s}let t=await td(r);return Ui(t),t},sd=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"})},id=async(e,r)=>{let t=e.map(od).join(`
|
|
200
|
+
- `);await F(r,`Create the following ${e.length} release(s)?
|
|
201
|
+
- ${t}
|
|
202
|
+
`),m.addOption("--yes",!0)},ad=async e=>{let{entry:r,jiraConfig:t}=e,o=$(r.id),s=r.id.kind==="version"?`v${r.id.raw}`:r.id.name;try{await zo(r.type);let n=await qo({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}
|
|
203
|
+
`),{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}
|
|
204
|
+
`),{failure:{version:o,error:i.message}}}},cd=(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.`)},zi=async e=>{let{releases:r,confirmedCommand:t}=e,o=await hr(),s=null,i=await nd(r,async()=>(s===null&&(s=await dn()),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"});sd(i),await W({operation:"create release"}),await id(i,!!t);let a=[],c=[];for(let d of i){let{result:u,failure:g}=await ad({entry:d,jiraConfig:o});u&&a.push(u),g&&c.push(g)}cd(i.length,a.length,c.length),m.print();let p={createdBranches:a.map(d=>d.branchName),successCount:a.length,failureCount:c.length,releases:a,failedReleases:c};return{content:h(JSON.stringify(p,null,2)),structuredContent:p}},gn=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:zi});import{z as _e}from"zod";import{question as ld}from"zx";var qi=(e,r)=>`${e.baseUrl}/projects/${r.projectId}/versions/${r.id}/tab/release-report-all-issues`,pd=(e,r)=>r.trim()!==""?`${e}
|
|
205
|
+
|
|
206
|
+
${r}`:`${e}
|
|
207
|
+
`,dd=async()=>{let e=await E(),r=e.map(n=>n.branch),t=new Map(e.map(n=>[n.branch,x(n.title)])),o=await C(),s=await Ce(O({branches:r,descriptions:o,types:t}));return{branch:s,type:t.get(s)||"regular"}},ud=async e=>{let t=(await E()).find(o=>o.branch===e);if(!t)throw new f(void 0,{operation:`edit description for ${e}`,remediation:`confirm an open PR exists for ${e} ('gh pr list')`});return x(t.title)},md=async e=>{let r=e===""?"(no current description)":`current: "${e}"`,o=(await ld(` New description ${r}
|
|
208
|
+
(press Enter to keep current): `)).replace(/\n$/,"");return o===""?e:o},Hi=async e=>{let{version:r,description:t,confirmedCommand:o}=e,s=await hr(),n;r?(n=ge(r),await ud(n)):(m.setInteractive(),n=(await dd()).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=$(i);m.addOption("--version",a);let c=q(i),p=await St(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??"",u;t!==void 0?(u=t,m.addOption("--description",u)):(m.setInteractive(),u=await md(d));let g=k=>{let T={version:a,branch:n,jiraVersionUrl:qi(s,p),previousDescription:d,newDescription:u,changed:k};return{content:h(JSON.stringify(T,null,2)),structuredContent:T}};if(u===d)return l.info(`No change \u2014 description for ${c} is already: "${d}"`),m.print(),g(!1);await F(o,`Update description for ${c}?
|
|
209
|
+
from: "${d}"
|
|
210
|
+
to: "${u}"
|
|
211
|
+
`),m.addOption("--yes",!0),await $t({versionId:p.id,description:u},s);let w=qi(s,p),b=pd(w,u);return await Ot({branch:n,body:b}),l.info(`\u2705 Updated description for ${c}`),l.info(`\u{1F517} Jira Version: ${w}`),l.info(`\u{1F517} PR branch: ${n}
|
|
212
|
+
`),m.print(),g(!0)},hn=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:Hi});import{execFile as Pd}from"node:child_process";import ea from"node:path";import ra from"node:process";import{z as A}from"zod";import Zi from"node:fs/promises";import Vt from"node:path";var Yr=async e=>{let{workspacePath:r,folderPaths:t}=e,o=Vt.dirname(r),s;try{s=await Zi.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=>Vt.resolve(o,d.path))),c=[],p=[];for(let d of t){let u=Vt.resolve(d);if(a.has(u)){p.push(d);continue}let g=Vt.relative(o,u);i.push({path:g}),a.add(u),c.push(d)}return n.folders=i,await Zi.writeFile(r,`${JSON.stringify(n,null,2)}
|
|
213
|
+
`,"utf-8"),{added:c,skipped:p}};import{$ as fd}from"zx";var Xr=async e=>{await fd`cursor ${e}`};import gd from"node:fs/promises";import Bt from"node:path";import Yi 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 Yi.readFile(r,"utf-8")}catch(g){throw new Error(`Cursor workspace file not found at ${r}: ${g.message}`)}let n;try{n=JSON.parse(s)}catch(g){throw new Error(`Failed to parse ${r} as JSON. Comments (JSONC) are not supported. ${g.message}`)}let i=n.folders??[],a=new Set(t.map(g=>Jt.resolve(g))),c=new Set,p=i.filter(g=>{let w=Jt.resolve(o,g.path);return a.has(w)?(c.add(w),!1):!0});n.folders=p,await Yi.writeFile(r,`${JSON.stringify(n,null,2)}
|
|
214
|
+
`,"utf-8");let d=[],u=[];for(let g of t){let w=Jt.resolve(g);c.has(w)?d.push(g):u.push(g)}return{removed:d,notFound:u}};var vn=async e=>{let{workspacePath:r,worktreeDir:t,currentBranches:o}=e,s=Bt.dirname(r),n=Bt.resolve(`${t}/release`),i=await gd.readFile(r,"utf-8"),c=JSON.parse(i).folders??[],p=new Set(o.map(b=>Bt.resolve(`${t}/${b}`))),d=[];for(let b of c){let k=Bt.resolve(s,b.path);(k===n||k.startsWith(`${n}/`))&&!p.has(k)&&d.push(k)}let u=[];d.length>0&&(u=(await Qr({workspacePath:r,folderPaths:d})).removed);let g=o.map(b=>`${t}/${b}`),{added:w}=g.length>0?await Yr({workspacePath:r,folderPaths:g}):{added:[]};return{added:w,removed:u}};import Xi from"node:path";var ze=(e,r)=>Xi.isAbsolute(e)?e:Xi.resolve(r,e);var kn=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=ze(s.workspaceConfigPath,r);try{let{added:i,removed:a}=await vn({workspacePath:n,worktreeDir:t,currentBranches:o});return o.length>0&&await Xr(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 hd}from"zx";var yn=async e=>{let{folderPaths:r}=e;for(let t of r)await hd`zed --add ${t}`;return{added:r}};import{$ as vd}from"zx";var wn=async e=>{let{worktreePaths:r}=e;if(r.length===0)return{ran:!1,added:0,removed:0};try{return await vd`zed ${r}`,{ran:!0,added:r.length,removed:0}}catch(t){return l.warn({error:t},"\u26A0\uFE0F Failed to open Zed workspace"),{ran:!1,added:0,removed:0}}};import{$ as kd}from"zx";var Rn=async e=>{let{projectRoot:r,worktreeDir:t,remainingBranches:o}=e,s=[r,...o.map(n=>`${t}/${n}`)];try{return await kd`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 he=e=>{throw new Error(`Unexpected value: ${JSON.stringify(e)}`)};var bn=async e=>{let{projectRoot:r,worktreeDir:t,branches:o}=e,s=await j(),n=te(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=ze(c.config.workspaceConfigPath,r),{added:d,skipped:u}=await Yr({workspacePath:p,folderPaths:i}),g=u.length>0?` (${u.length} already present)`:"";l.info(`\u2705 Added ${d.length} folder(s) to ${p}${g}`),await Xr(p),a.push({ran:!0,provider:"cursor",added:d.length,skipped:u.length});break}case"zed":{let{added:p}=await yn({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:he(c)}return a};var xn=async e=>{let r=await j(),t=te(r),{projectRoot:o,worktreeDir:s,worktreePaths:n,currentBranches:i}=e,a=[];for(let c of t)switch(c.provider){case"cursor":{let p=await kn({projectRoot:o,worktreeDir:s,currentBranches:i,cursorConfig:c.config});a.push({...p,provider:"cursor"});break}case"zed":{let p=await wn({worktreePaths:n});a.push({...p,provider:"zed"});break}default:he(c)}return a};var En=e=>{switch(e){case"cursor":return"Cursor";case"zed":return"Zed";case void 0:return"IDE";default:return he(e)}};var et=async e=>{let{projectRoot:r,worktreeDir:t,currentWorktrees:o,removedWorktrees:s,allowEditorRelaunch:n}=e;if(s.length===0)return[];let i=await j(),a=te(i),c=s.map(u=>`${t}/${u}`),p=o.filter(u=>!s.includes(u)),d=[];for(let u of a)switch(u.provider){case"cursor":{d.push(await yd({ide:u,projectRoot:r,folderPaths:c}));break}case"zed":{d.push(await wd({projectRoot:r,worktreeDir:t,remainingBranches:p,allowEditorRelaunch:n}));break}default:he(u)}return d},yd=async e=>{let{ide:r,projectRoot:t,folderPaths:o}=e;if(!r.config.workspaceConfigPath)return{provider:"cursor",supported:!0,removed:[]};let s=ze(r.config.workspaceConfigPath,t);try{let{removed:n}=await Qr({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:[]}}},wd=async e=>{let{projectRoot:r,worktreeDir:t,remainingBranches:o,allowEditorRelaunch:s}=e;return s?(await Rn({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 Kt=["workspace","none"];import Pn from"node:fs/promises";import rt from"node:path";var Qi=async e=>{try{return await Pn.access(e),!0}catch{return!1}},Rd=async e=>{if(e&&e.length>0)return e;try{let r=await qe();return[rt.dirname(r)]}catch(r){throw new f(r,{operation:"discover infra-kit projects",remediation:"run inside an infra-kit repo, or pass --root <dir>"})}},bd=e=>e.isDirectory()||e.isSymbolicLink(),xd=async(e,r)=>{if(!bd(r))return null;let t=rt.join(e,r.name),[o,s]=await Promise.all([Qi(rt.join(t,".git")),Qi(rt.join(t,"infra-kit.json"))]);if(!o||!s)return null;try{let n=await Pn.realpath(t);return{name:rt.basename(t),repoRoot:n}}catch{return null}},Ed=async e=>{try{return await Pn.readdir(e,{withFileTypes:!0})}catch{return[]}},Tn=async(e={})=>{let r=await Rd(e.roots),t=new Map;for(let o of r){let s=await Ed(o);for(let n of s){let i=await xd(o,n);i&&!t.has(i.repoRoot)&&t.set(i.repoRoot,i)}}return[...t.values()].sort((o,s)=>o.name.localeCompare(s.name))};var Td=async(e={})=>e.all?Nd(e):ta(e),ta=async(e={})=>{let{releaseOnly:r=!1,force:t=!1,dryRun:o=!1}=e;try{let s=await R(),n=`${s}${oe}`,i=ea.basename(await qe(s)),a=await Xn(s),c=Cd(a,r),p=c.map(k=>k.path),d=c.map(k=>k.branch).filter(k=>Ne(k)),u=c.map(k=>({title:vt({branch:k.branch??ea.basename(k.path)}),cwd:k.path}));if(o){let k=await Ad({repo:i,releaseOnly:r,force:t,worktreePaths:p,targets:u});return Id(k,n),m.print(),{content:h(JSON.stringify(k,null,2)),structuredContent:k}}let[g,w]=await Promise.all([xn({projectRoot:s,worktreeDir:n,worktreePaths:p,currentBranches:d}),Sd({targets:u,force:t,repoName:i})]),b={repo:i,dryRun:!1,releaseOnly:r,worktreePaths:p,ideProviders:g.filter(k=>k.ran).map(k=>k.provider),cmuxOpened:w.opened,cmuxSkipped:w.skipped,cmuxClosed:w.closed};return Od(b,{ideRan:g.some(k=>k.ran)}),m.print(),{content:h(JSON.stringify(b,null,2)),structuredContent:b}}catch(s){throw s instanceof f?s:(l.error({error:s},"\u274C Error reopening worktree windows"),new f(s,{operation:"reopen worktrees",remediation:"run `infra-kit worktrees list` to confirm the worktrees exist"}))}},Cd=(e,r)=>e.filter(t=>t.bare||t.prunable?!1:r?Ne(t.branch):!0),Sd=async e=>{let{targets:r,force:t,repoName:o}=e,s=await gt(o),n=t?await $d({targets:r}):[],{opened:i,skipped:a}=await _d({targets:r,force:t,repoName:o,groupRef:s});return{opened:i,skipped:a,closed:n}},$d=async e=>{let{targets:r}=e;if(r.length===0)return[];let t=await rr(),o=[];for(let s of r)t.has(await Er(s.cwd))&&(await tr(s.cwd),o.push(s.title));return o},oa=async(e,r,t)=>{let o=[],s=[];for(let n of e)!t&&r.has(await Er(n.cwd))?s.push(n.title):o.push(n);return{toOpen:o,skipped:s}},_d=async e=>{let{targets:r,force:t,repoName:o,groupRef:s=null}=e,n=t?new Set:new Set((await rr()).keys()),{toOpen:i,skipped:a}=await oa(r,n,t),c=[],p=s,d=!1;for(let u of i)try{if(p)await or({cwd:u.cwd,title:u.title,group:p});else{let g=await or({cwd:u.cwd,title:u.title});d||(p=await ht(o,[g]),d=!0)}c.push(u.title)}catch(g){l.warn({error:g,title:u.title},`\u26A0\uFE0F Failed to reopen cmux workspace ${u.title}`)}return{opened:c,skipped:a}},Ad=async e=>{let{repo:r,releaseOnly:t,force:o,worktreePaths:s,targets:n}=e,i=o?new Set:new Set((await rr()).keys()),{toOpen:a,skipped:c}=await oa(n,i,o);return{repo:r,dryRun:!0,releaseOnly:t,worktreePaths:s,ideProviders:[],cmuxOpened:a.map(p=>p.title),cmuxSkipped:c,cmuxClosed:[]}},Id=(e,r)=>{l.info(`\u{1F50E} reopen --dry-run for ${e.repo} (worktrees dir: ${r})`),l.info(`\u{1F4C2} Would open ${e.worktreePaths.length} folder(s) in the editor:`);for(let t of e.worktreePaths)l.info(` ${t}`);if(e.cmuxOpened.length>0){l.info(`\u{1FA9F} Would open ${e.cmuxOpened.length} cmux workspace(s):`);for(let t of e.cmuxOpened)l.info(` ${t}`)}if(e.cmuxSkipped.length>0){l.info(`\u21A9\uFE0F Already open (would skip) ${e.cmuxSkipped.length} cmux workspace(s):`);for(let t of e.cmuxSkipped)l.info(` ${t}`)}},Od=(e,r)=>{if(e.cmuxClosed.length>0&&l.info(`\u{1F9F9} Closed ${e.cmuxClosed.length} cmux workspace(s)`),r.ideRan){let t=e.ideProviders.map(o=>En(o)).join(", ");l.info(`\u2705 Opened editor workspace(s): ${t}`)}if(e.cmuxOpened.length>0){l.info("\u2705 Opened cmux workspaces:");for(let t of e.cmuxOpened)l.info(t)}e.cmuxSkipped.length>0&&l.info(`\u21A9\uFE0F ${e.cmuxSkipped.length} cmux workspace(s) already open \u2014 skipped`),!r.ideRan&&e.cmuxOpened.length===0&&e.cmuxClosed.length===0&&l.info("\u2139\uFE0F Nothing to reopen")},Nd=async e=>{let{project:r=[],root:t=[],releaseOnly:o=!1,force:s=!1,dryRun:n=!1}=e,i=await Tn({roots:t}),a=Dd(i,r),c=jd({releaseOnly:o,force:s,dryRun:n}),p=[];for(let u of a)p.push(await Fd(u,c));let d={all:!0,dryRun:n,projects:a,results:p};return Ld(d),m.print(),{content:h(JSON.stringify(d,null,2)),structuredContent:d}},Dd=(e,r)=>{if(r.length===0)return e;let t=new Set(e.map(o=>o.name));for(let o of r)t.has(o)||l.warn(`\u26A0\uFE0F --project ${o} matched no discovered project \u2014 skipping`);return e.filter(o=>r.includes(o.name))},jd=e=>{let r=[];return e.dryRun&&r.push("--dry-run"),e.releaseOnly&&r.push("--release-only"),e.force&&r.push("--force"),r},Fd=async(e,r)=>{try{let t=await Md(e.repoRoot,r);return{...JSON.parse(t),repo:e.name,ok:!0}}catch(t){let o=t instanceof Error?t.message:String(t);return l.warn({error:t},`\u26A0\uFE0F reopen failed for ${e.name} \u2014 continuing`),{repo:e.name,ok:!1,error:o}}},Md=(e,r)=>{let t=ra.argv[1];return t===void 0?Promise.reject(new Error("cannot resolve the infra-kit CLI entry \u2014 process.argv[1] is undefined")):new Promise((o,s)=>{let n=[t,"reopen","--json",...r];Pd(ra.execPath,n,{cwd:e,maxBuffer:16*1024*1024},(i,a)=>{if(i){s(i);return}o(a)})})},Ld=e=>{let r=e.results.filter(n=>n.ok).length,t=e.results.length-r;l.info(`\u{1F310} reopen --all${e.dryRun?" --dry-run":""}: ${e.projects.length} project(s)`);let o=0,s=0;for(let n of e.results)n.ok?(o+=n.cmuxOpened.length,s+=n.cmuxSkipped.length,l.info(` \u2705 ${n.repo}: ${n.worktreePaths.length} folder(s), ${n.cmuxOpened.length} cmux ${e.dryRun?"planned":"opened"}, ${n.cmuxSkipped.length} skipped`)):l.info(` \u274C ${n.repo}: ${n.error}`);l.info(`\u{1F4CA} ${r} ok, ${t} failed \u2014 ${o} cmux ${e.dryRun?"planned":"opened"}, ${s} already open`)},Cn=v({name:"reopen",description:"Reopen editor + cmux windows for every active worktree in the current project \u2014 the main checkout plus every linked worktree (release, feature, detached). Additive and idempotent by default: cmux workspaces already open are skipped, so running twice does not double the windows. Zed opens the exact folder set; Cursor reconciles its release-branch-shaped workspace. Set releaseOnly to restrict to release worktrees (the legacy reload scope). Set force to close each cmux workspace first, then reopen (disruptive). Set dryRun to return the plan without spawning anything. Non-destructive to git \u2014 only cmux/editor view state is touched.",inputSchema:{releaseOnly:A.boolean().optional().describe("Restrict to release worktrees (reproduces the legacy worktrees-reload scope)"),force:A.boolean().optional().describe("Close each cmux workspace first, then reopen (disruptive)"),dryRun:A.boolean().optional().describe("Return the plan (paths + cmux titles) without spawning anything")},outputSchema:{repo:A.string().describe("Repository name the reopen ran for"),dryRun:A.boolean().describe("Whether this was a dry run (nothing was spawned)"),releaseOnly:A.boolean().describe("Whether the set was restricted to release worktrees"),worktreePaths:A.array(A.string()).describe("Absolute folder set handed to the editor (root-first)"),ideProviders:A.array(A.string()).describe("Configured IDE providers that opened (cursor | zed); empty in dry run"),cmuxOpened:A.array(A.string()).describe("Titles of cmux workspaces opened this run"),cmuxSkipped:A.array(A.string()).describe("Titles of cmux workspaces skipped because already open (additive mode)"),cmuxClosed:A.array(A.string()).describe("Titles of cmux workspaces closed first (force mode only)")},handler:ta});import{existsSync as aa}from"node:fs";import ca from"node:path";import Zd from"node:process";import{z as ve}from"zod";import{createHash as Wd}from"node:crypto";import{readFileSync as Vd}from"node:fs";var Gt=e=>Wd("sha256").update(Vd(e)).digest("hex");import{readFileSync as zd,writeFileSync as qd}from"node:fs";import qt from"node:path";import{z as ie}from"zod";import{readdirSync as Gd}from"node:fs";import Sn from"node:path";var X="vendor",Jd=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack"]),Bd=new Set([".sync-manifest.json",".eslintcache","log.txt"]),Kd=[".tsbuildinfo"],na=e=>Jd.has(e),sa=e=>Bd.has(e)?!0:Kd.some(r=>e.endsWith(r));var Ud=e=>e.split(Sn.sep).join("/"),Ut=e=>{let r=[],t=o=>{for(let s of Gd(o,{withFileTypes:!0})){let n=Sn.join(o,s.name);if(s.isDirectory()){if(na(s.name))continue;t(n);continue}sa(s.name)||r.push(Ud(Sn.relative(e,n)))}};return t(e),r.sort()};var ae=".sync-manifest.json",zt=1,Hd=ie.object({schemaVersion:ie.number().optional(),source:ie.string(),commit:ie.string(),syncedAt:ie.string(),fileCount:ie.number(),files:ie.record(ie.string(),ie.string())}),$n=e=>(e.schemaVersion??zt)>zt,ia=e=>{let r={};for(let t of Ut(e))try{r[t]=Gt(qt.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},_n=e=>{let r=qt.join(e,ae),t;try{t=zd(r,"utf8")}catch{throw new Error(`Missing ${ae} at ${r}`)}let o=Hd.safeParse(JSON.parse(t));if(!o.success)throw new Error(`Invalid ${ae} at ${r}: ${ie.prettifyError(o.error)}`);return o.data},An=(e,r)=>{let t=ia(e),o={schemaVersion:zt,source:r.source,commit:r.commit,syncedAt:new Date().toISOString(),fileCount:Object.keys(t).length,files:t};return qd(qt.join(e,ae),`${JSON.stringify(o,null,2)}
|
|
215
|
+
`),o},In=(e,r)=>{let t=r.files,o=Ut(e),s=[],n=[];for(let c of o){if(!(c in t)){n.push(c);continue}Gt(qt.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 On=30,Nn=(e,r)=>{if(r.length!==0){l.info(`
|
|
216
|
+
${e} (${r.length}):`);for(let t of r.slice(0,On))l.info(` ${t}`);r.length>On&&l.info(` \u2026and ${r.length-On} more`)}},la=async(e={})=>{let r=e.cwd??await R(),t=ca.join(r,X),o={modified:[],added:[],removed:[],fileCount:0};if(!aa(t)){l.info(`\u2139\uFE0F No ${X}/ folder found \u2014 nothing to check.`);let d={status:"skipped",ok:!0,...o};return{content:h(JSON.stringify(d,null,2)),structuredContent:d}}if(!aa(ca.join(t,ae))){l.error(`\u274C Missing ${X}/${ae}. Re-run the vendor sync to generate it.`);let d={status:"missing-manifest",ok:!1,...o};return{content:h(JSON.stringify(d,null,2)),structuredContent:d}}let s=_n(t);if($n(s)){l.error(`\u274C ${X}/${ae} has a newer schemaVersion (${String(s.schemaVersion)}) than this CLI supports. Upgrade infra-kit.`);let d={status:"unknown-schema",ok:!1,...o};return{content:h(JSON.stringify(d,null,2)),structuredContent:d}}let{modified:n,added:i,removed:a}=In(t,s),c=n.length>0||i.length>0||a.length>0;c?(l.error(`\u274C ${X}/ has drifted from ${X}/${ae}.`),l.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),Nn("Modified",n),Nn("Added (not in manifest)",i),Nn("Removed (in manifest, now missing)",a)):l.info(`\u2705 ${X}/ matches manifest (${s.fileCount} files).`);let p={status:c?"drift":"clean",ok:!c,fileCount:s.fileCount,modified:n,added:i,removed:a};return{content:h(JSON.stringify(p,null,2)),structuredContent:p}},Yd={status:ve.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:ve.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:ve.number(),modified:ve.array(ve.string()),added:ve.array(ve.string()),removed:ve.array(ve.string())},Dn=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:Yd,handler:()=>la({cwd:Zd.cwd()})});import{z as le}from"zod";import{VENDOR_CONFIG_FILE as Ht,vendorConfigSchema as Xd}from"@slip-stream-kit/config/internal";import Qd from"node:fs/promises";import eu from"node:path";import{pathToFileURL as ru}from"node:url";import{z as tu}from"zod";import{defineVendorConfig as _x}from"@slip-stream-kit/config/internal";var Zt=async e=>{let r=eu.join(e,Ht),t;try{t=await Qd.stat(r)}catch{throw new Error(`${Ht} not found at ${r}`)}let n=(await import(`${ru(r).href}?mtime=${Number(t.mtimeMs)}`)).default;if(n===void 0)throw new Error(`${Ht} at ${r} has no default export`);let i=typeof n=="function"?await n():n,a=Xd.safeParse(i);if(!a.success)throw new Error(`Invalid ${Ht} at ${r}: ${tu.prettifyError(a.error)}`);return a.data};import{existsSync as ce,mkdirSync as ou,writeFileSync as nu}from"node:fs";import Q from"node:path";import{$ as tt}from"zx";var su=["node_modules","dist","*.tsbuildinfo",".turbo",".eslintcache",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack","log.txt"],iu=`# vendor/ \u2014 mirrored from the source repo
|
|
217
|
+
|
|
218
|
+
**DO NOT EDIT files in this folder here.**
|
|
219
|
+
|
|
220
|
+
Everything under \`vendor/\` is the single source of truth maintained in the source
|
|
221
|
+
repo and copied into this repo by \`infra-kit vendor sync\`. Local edits are
|
|
222
|
+
overwritten on the next sync and will fail \`infra-kit vendor check\` in CI.
|
|
223
|
+
|
|
224
|
+
To change a vendored package, edit it in the source repo and re-run the sync.
|
|
225
|
+
|
|
226
|
+
See \`.sync-manifest.json\` for the source commit and per-file checksums.
|
|
227
|
+
`,da=()=>su.map(e=>`--exclude=${e}`),Yt=async e=>{try{return(await tt({cwd:e})`git rev-parse HEAD`).stdout.trim()}catch{return"unknown"}},au=async(e,r)=>{if(!ce(e))return!1;ce(r)&&await tt`rm -rf ${r}`;let t=`${e}/`,o=`${r}/`;return await tt`rsync -a ${da()} ${t} ${o}`,!0},cu=async(e,r)=>{if(!ce(e))return!1;let t=Q.dirname(r);return ce(t)||ou(t,{recursive:!0}),await tt`cp ${e} ${r}`,!0},lu=async(e,r)=>{if(!ce(e))return[];if(!ce(r))return[`missing target: ${r}`];let t=`${e}/`,o=`${r}/`;return(await tt`rsync -ai --dry-run --delete ${da()} ${t} ${o}`).stdout.split(`
|
|
228
|
+
`).map(n=>n.trim()).filter(Boolean)},ua=(e,r)=>{let t=Q.join(e,X);ce(t)&&(nu(Q.join(t,"README.md"),iu),An(t,r))},jn=(e,r)=>Q.join(Ys(e),r),Rr=(e,r)=>r?e.filter(t=>r.includes(t)):e,pa=(e,r,t,o,s)=>{let n=Q.resolve(e),i=Q.resolve(r);if(i!==n&&!i.startsWith(n+Q.sep))throw new f(void 0,{operation:`sync vendor item ${s}`,stderrExcerpt:`${t} escapes repo root: ${o}`})},ma=async(e,r,t,o,s)=>{let n=[];for(let i of o){let a=jn(t,i);if(!ce(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=Q.join(r,p.source),u=Q.join(a,p.target);pa(r,d,"source",p.source,p.name),pa(a,u,"target",p.target,p.name),(p.type==="directory"?await au(d,u):await cu(d,u))&&c++}ua(a,s),n.push({repo:i,copied:c,total:e.copy.length,skipped:!1})}return{source:s.source,commit:s.commit,repos:n}},fa=async(e,r,t)=>{let o=[];for(let s of r){let n=jn(e,s),i=!ce(n);i||ua(n,t),o.push({repo:s,skipped:i})}return o},ga=async(e,r,t,o)=>{let s=[],n=e.copy.filter(i=>i.vendored===!0);for(let i of o){let a=jn(t,i);if(ce(a))for(let c of n){let p=Q.join(r,c.source),d=Q.join(a,c.target),u=await lu(p,d);u.length>0&&s.push({repo:i,target:c.target,changes:u})}}return s};var Fn=20,ha=async(e={})=>{let r=e.cwd??await R(),t=await Zt(r),o=await dr(),s=Rr(o.targets,e.repos),n=await ga(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,Fn))l.info(` ${c}`);a.changes.length>Fn&&l.info(` \u2026and ${a.changes.length-Fn} more`)}let i={ok:n.length===0,drifted:n.length,entries:n};return{content:h(JSON.stringify(i,null,2)),structuredContent:i}},pu={ok:le.boolean().describe("Whether every target is in sync with the source"),drifted:le.number(),entries:le.array(le.object({repo:le.string(),target:le.string(),changes:le.array(le.string())}))},Mn=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:le.array(le.string()).optional().describe("Restrict to these target repo names")},outputSchema:pu,handler:e=>ha({repos:e.repos})});import du from"node:path";import{z as Ae}from"zod";var va=async e=>{let r=e.cwd??await R(),t=await dr(),o=Rr(t.targets,e.repos),s=await Yt(r),n=du.basename(r),i=await fa(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:h(JSON.stringify(a,null,2)),structuredContent:a}},uu={source:Ae.string(),commit:Ae.string(),repos:Ae.array(Ae.object({repo:Ae.string(),skipped:Ae.boolean()}))},Ln=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:Ae.array(Ae.string()).optional().describe("Restrict to these target repo names")},outputSchema:uu,handler:e=>va({repos:e.repos,confirmedCommand:e.confirmedCommand})});import mu from"@inquirer/confirm";import ka from"node:path";import ya from"node:process";import{z as pe}from"zod";var wa=async e=>{let r=e.cwd??await R(),t=await Zt(r),o=await dr(),s=Rr(o.targets,e.repos);e.confirmedCommand||await S(p=>mu({message:`Sync vendor files from ${ka.basename(r)} into ${s.length} repo(s)?`},p),{output:ya.stderr})||ya.exit(0);let n=await Yt(r),i=ka.basename(r),a=await ma(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:h(JSON.stringify(a,null,2)),structuredContent:a}},fu={source:pe.string(),commit:pe.string(),repos:pe.array(pe.object({repo:pe.string(),copied:pe.number(),total:pe.number(),skipped:pe.boolean()}))},Wn=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:pe.array(pe.string()).optional().describe("Restrict to these target repo names")},outputSchema:fu,handler:e=>wa({repos:e.repos,confirmedCommand:e.confirmedCommand})});import{z as gu}from"zod";var Ra=async()=>{let e=mt.version;l.info(e);let r={version:e};return{content:h(JSON.stringify(r,null,2)),structuredContent:r}},Vn=v({name:"version",description:"Print the installed infra-kit CLI version",inputSchema:{},outputSchema:{version:gu.string().describe("Installed infra-kit CLI version (from package.json)")},handler:Ra});import ba from"@inquirer/confirm";import hu from"node:path";import{z as ke}from"zod";import{$ as ot}from"zx";var vu="feature",ku="release",Ea=async e=>{let{confirmedCommand:r,all:t,versions:o,githubDesktop:s,cmux:n}=e,i=e.ide??e.cursor;await W({operation:"create worktrees"});try{let a=await re("release"),c=await R(),p=`${c}${oe}`;await xa(`${p}/${ku}`),await xa(`${p}/${vu}`);let d=[];if(o)d=o.split(",").map(I=>ye(de(I.trim())));else{let I=await E(),ee=I.map(Ie=>Ie.branch);if(ee.length===0)return l.info("\u2139\uFE0F No open release branches found"),m.print(),{content:h(JSON.stringify({createdWorktrees:[],count:0},null,2)),structuredContent:{createdWorktrees:[],count:0}};if(t)d=ee;else{m.setInteractive();let Ie=new Map(I.map(Oe=>[Oe.branch,x(Oe.title)])),nt=await C();d=await vr(O({branches:ee,descriptions:nt,types:Ie}),{required:!0})}}t?m.addOption("--all",!0):m.addOption("--versions",Ge(d)),await F(r,"Are you sure you want to proceed with these worktree changes?"),r||m.addOption("--yes",!0);let u=await j(),g=i??(te(u).length>0?"workspace":"none");m.addOption("--ide",g);let w=s??u.worktrees?.openInGithubDesktop??await S(I=>ba({message:"Open created worktrees in GitHub Desktop?"},I));typeof s>"u"&&u.worktrees?.openInGithubDesktop===void 0&&m.setInteractive(),w?m.addOption("--github-desktop",!0):m.addOption("--no-github-desktop",!0);let b=n??u.worktrees?.openInCmux??await S(I=>ba({message:"Open created worktrees in cmux?"},I));typeof n>"u"&&u.worktrees?.openInCmux===void 0&&m.setInteractive(),b?m.addOption("--cmux",!0):m.addOption("--no-cmux",!0);let{branchesToCreate:k}=yu({selectedReleaseBranches:d,currentWorktrees:a}),T=await wu(k,p);if(Ru(T),g==="workspace"&&await bn({projectRoot:c,worktreeDir:p,branches:T}),w)for(let I of T)await ot`github ${p}/${I}`,await ot`sleep 5`;if(b){let I=hu.basename(await qe(c)),ee=await rr(),Ie=await gt(I),nt=!1;for(let Oe of T){let eo=`${p}/${Oe}`;if(ee.has(await Er(eo)))continue;let qn=vt({branch:Oe});try{if(Ie)await or({cwd:eo,title:qn,group:Ie});else{let ro=await or({cwd:eo,title:qn});nt||(Ie=await ht(I,[ro]),nt=!0)}}catch(ro){l.warn({error:ro,branch:Oe},`\u26A0\uFE0F Failed to open cmux workspace for ${Oe}`)}}}m.print();let z={createdWorktrees:T,count:T.length};return{content:h(JSON.stringify(z,null,2)),structuredContent:z}}catch(a){throw nr(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'"}))}},xa=async e=>{await ot`mkdir -p ${e}`},yu=e=>{let{selectedReleaseBranches:r,currentWorktrees:t}=e,o=t.filter(n=>Ne(n));return{branchesToCreate:r.filter(n=>!o.includes(n))}},wu=async(e,r)=>{let t=await Promise.allSettled(e.map(async s=>{let n=`${r}/${s}`;return await ot`git worktree add ${n} ${s}`,await ot({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},Ru=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")},Jn=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(Kt).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(Kt).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:Ea});import{z as br}from"zod";var Pa=async()=>{let e=await re("release");if(e.length===0)return l.info("\u2139\uFE0F No active worktrees found"),{content:h(JSON.stringify({worktrees:[],count:0},null,2)),structuredContent:{worktrees:[],count:0}};let[r,t]=await Promise.all([E(),C()]),o=new Map(r.map(c=>[c.branch,x(c.title)])),s=e.flatMap(c=>{let p=_(c);if(!p)return[];let d=$(p),u=o.get(c)||"regular",g=t.get(q(p))||null;return[{version:d,type:u,description:g}]}),n=Math.max(...s.map(c=>c.version.length)),i=s.map(c=>{let p=Gr(c.version,c.type,n);return c.description?`${p} ${c.description}`:p});l.info(`\u{1F33F} Active worktrees:
|
|
229
|
+
|
|
230
|
+
${i.join(`
|
|
231
|
+
`)}`);let a={worktrees:s,count:s.length};return{content:h(JSON.stringify(a,null,2)),structuredContent:a}},Bn=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:br.array(br.object({version:br.string().describe("Release version"),type:br.enum(["regular","hotfix"]).describe("Release type"),description:br.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:br.number().describe("Number of worktrees")},handler:Pa});import{z as Xt}from"zod";var bu=e=>{if(ut()){if(e.all)throw new f(void 0,{operation:"remove worktrees",remediation:'name targets explicitly via "versions"; bulk all=true removal is disabled over MCP',stderrExcerpt:"all=true is not permitted for worktrees-remove over MCP"});if(!e.versions)throw new f(void 0,{operation:"remove worktrees",remediation:'pass "versions" (comma-separated release versions/names); the interactive picker needs a TTY',stderrExcerpt:'worktrees-remove over MCP requires "versions"'})}},xu=(e,r)=>{let t=e.filter(o=>!r.includes(o));if(t.length>0)throw new f(void 0,{operation:"remove worktrees",remediation:`no active worktree for: ${t.join(", ")}. Run 'infra-kit worktrees list' to see current worktrees`,stderrExcerpt:`unmatched worktree target(s): ${t.join(", ")}`})},Ta=async e=>{let{confirmedCommand:r,all:t,versions:o}=e;await W({operation:"remove worktrees"}),bu({all:t,versions:o});try{let s=await re("release");if(s.length===0)return l.info("\u2139\uFE0F No active worktrees to remove"),m.print(),{content:h(JSON.stringify({removedWorktrees:[],count:0},null,2)),structuredContent:{removedWorktrees:[],count:0}};let n=await R(),i=`${n}${oe}`,a=[];if(t)a=s;else if(o)a=o.split(",").map(u=>ye(de(u.trim())));else{m.setInteractive();let[u,g]=await Promise.all([C(),E()]),w=new Map(g.map(b=>[b.branch,x(b.title)]));a=await vr(O({branches:s,descriptions:u,types:w}),{required:!0})}xu(a,s);let c=a.length===s.length;c?m.addOption("--all",!0):m.addOption("--versions",Ge(a)),await F(r,"Are you sure you want to proceed with these worktree changes?"),r||m.addOption("--yes",!0);let p=await Hr({branches:a,worktreeDir:i,pruneFolder:c});await et({projectRoot:n,worktreeDir:i,currentWorktrees:s,removedWorktrees:p,allowEditorRelaunch:!r}),Eu(p),m.print();let d={removedWorktrees:p,count:p.length};return{content:h(JSON.stringify(d,null,2)),structuredContent:d}}catch(s){throw nr(s)||s instanceof f?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"}))}},Eu=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")},Kn=v({name:"worktrees-remove",description:'Remove local git worktrees for the named release branches. Over MCP you MUST pass "versions" (comma-separated); bulk all=true removal is disabled here (it is a one-shot, unconfirmed wipe of every worktree) \u2014 the branch picker and confirmation are unavailable without a TTY. Every named version must be an active worktree, or the call errors without removing anything. What survives: the release branches/commits themselves are never deleted, and the worktrees directory plus its release/feature subfolders are left in place (recreate a worktree with worktrees-add). What is lost: git refuses to remove a worktree with modified tracked files or untracked files, BUT it DOES delete the worktree directory including gitignored contents \u2014 a hydrated .env of Doppler secrets (re-fetch with env-load) and build output such as node_modules/dist (needs reinstall/rebuild). When every worktree is removed it also runs "git worktree prune".',inputSchema:{versions:Xt.string().describe('Comma-separated release versions or names to remove (e.g. "1.2.5, 1.2.6" or "checkout-redesign, 1.2.5"). Required: each must name an active worktree, or the call errors before removing anything.')},outputSchema:{removedWorktrees:Xt.array(Xt.string()).describe("List of removed git worktree branches"),count:Xt.number().describe("Number of git worktrees removed")},handler:Ta});import{z as Gn}from"zod";import{$ as Pu}from"zx";var Ca=async e=>{let{confirmedCommand:r}=e;await W({operation:"sync worktrees"});try{let t=await re("release"),o=await R(),s=`${o}${oe}`,n=await It();await F(r,"Are you sure you want to proceed with these worktree changes?"),r||m.addOption("--yes",!0);let{branchesToRemove:i}=Tu({releasePRsList:n,currentWorktrees:t}),a=await Cu({branches:i,worktreeDir:s});await et({projectRoot:o,worktreeDir:s,currentWorktrees:t,removedWorktrees:a,allowEditorRelaunch:!1}),Su(a),m.print();let c={removedWorktrees:a,count:a.length};return{content:h(JSON.stringify(c,null,2)),structuredContent:c}}catch(t){throw nr(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"}))}},Tu=e=>{let{releasePRsList:r,currentWorktrees:t}=e;return{branchesToRemove:t.filter(n=>Ne(n)).filter(n=>!r.includes(n))}},Cu=async e=>{let{branches:r,worktreeDir:t}=e,o=[];for(let s of r)try{let n=`${t}/${s}`;await tr(n),await Pu`git worktree remove ${n}`,o.push(s)}catch(n){let i=new f(n,{operation:`remove stale worktree for ${s}`,remediation:"inspect the worktree dir manually; rerun with the branch checked out elsewhere"});l.error({error:n,branch:s,msg:i.message})}return o},Su=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")},Un=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:Gn.array(Gn.string()).describe("List of removed worktree branches"),count:Gn.number().describe("Number of worktrees removed during sync")},handler:Ca});var $u=[{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"}],Qt=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,groupPath:["dev"],longRunning:!0},{cliName:"merge-dev",menuGroup:"release",mcpTool:Ho,mcpExposed:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:rn,mcpExposed:!0,groupPath:["release","list"]},{cliName:"release-create",menuGroup:"release",mcpTool:gn,mcpExposed:!0,groupPath:["release","create"]},{cliName:"release-desc-edit",menuGroup:"release",mcpTool:hn,mcpExposed:!0,groupPath:["release","desc-edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:Xo,mcpExposed:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:en,mcpExposed:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:Zo,mcpExposed:!1,groupPath:["release","deliver"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:Jn,mcpExposed:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:Bn,mcpExposed:!0,groupPath:["worktrees","list"]},{cliName:"reopen",menuGroup:"worktrees",mcpTool:Cn,mcpExposed:!0,groupPath:["reopen"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:Kn,mcpExposed:!0,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:Un,mcpExposed:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:Vo,mcpExposed:!0,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:Wo,mcpExposed:!0,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:Eo,mcpExposed:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:Lo,mcpExposed:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:Bo,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:Dn,mcpExposed:!0,groupPath:["vendor","check"]},{cliName:"vendor-diff",menuGroup:"vendor",mcpTool:Mn,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:Do,mcpExposed:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:go,mcpExposed:!0,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:Vn,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:Ln,mcpExposed:!1,groupPath:["vendor","manifest"]},{cliName:"vendor-sync",menuGroup:null,mcpTool:Wn,mcpExposed:!1,groupPath:["vendor","sync"]}],_u=()=>Qt.flatMap(e=>e.mcpExposed&&e.mcpTool?[e.mcpTool]:[]),Au=e=>Qt.filter(r=>r.menuGroup===e),Iu=e=>Qt.some(r=>r.longRunning===!0&&r.groupPath.join(" ")===e);import zn from"node:process";var Ou="MODULE_TYPELESS_PACKAGE_JSON",Nu=(e,r)=>typeof e=="object"&&e!==null?e.code:r,Sa=!1,Du=()=>{if(Sa)return;Sa=!0;let e=zn.emitWarning.bind(zn);zn.emitWarning=((r,...t)=>{Nu(t[0],t[1])!==Ou&&e(r,...t)})};export{h as a,xs as b,Sr as c,$r as d,_r as e,Me as f,af as g,fc as h,Ls as i,Ws as j,lr as k,Vs as l,Js as m,Et as n,Pt as o,Bc as p,_o as q,Ys as r,dr as s,ch as t,Ao as u,Io as v,ui as w,rp as x,ki as y,Ri as z,bi as A,Jo as B,Ti as C,Nt as D,hp as E,_i as F,Ii as G,Fi as H,Li as I,Wi as J,Vi as K,Up as L,zi as M,Hi as N,Kt as O,Td as P,la as Q,ha as R,va as S,wa as T,Ra as U,Ea as V,Pa as W,Ta as X,Ca as Y,$u as Z,Qt as _,_u as $,Au as aa,Iu as ba,Du as ca};
|
|
232
|
+
//# sourceMappingURL=chunk-RDRJX6TT.js.map
|