infra-kit 0.11.16 → 0.13.0

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/cli.js CHANGED
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
- import{a as $u,d as _u,f as bs,h as Ir,i as Rs,j as Fu,k as Lu,l as Vu,m as Bu,n as Wu,o as Ju,p as Uu,q as Gu,t as Ku,u as Hu,v as we}from"./chunk-TT7OQ4PI.js";import{a as Rt,b as Wp,c as va,d as Jp,e as Up,f as Gp,g as Kp,h as Dn,i as Hp,j as qp,k as zp,l as Yp,m as Xp,n as Nn,o as Zp,p as Qp,q as eu,r as tu,s as wa,t as cs,u as St,v as ru,w as ls,x as nu}from"./chunk-CMF7HEVU.js";import{a as ae,b as H,c as Et,d as hs,e as Sa,f as ys,g as Pa,h as Mn,i as qt,j as vs,k as hu,l as jn,m as Fn,n as xa,o as Ta,q as Ca}from"./chunk-BQPSXIH2.js";import{b as In,c as is,d as ya,e as jp,f as as,g as Fp,i as Lp,k as Vp,m as he,o as Bp}from"./chunk-AWFGP6GY.js";import{a as Nu}from"./chunk-TVG47UHG.js";import{a as h,b as ct,c as E,d as Au,e as Ou,f as I,g as ws,h as W,i as ks,j as lt,k as ue,l as Mu,m as ju}from"./chunk-UZTYMT6R.js";import{$ as Su,A as lu,B as du,C as pu,D as ms,E as fs,F as $e,G as _n,H as Or,I as gs,J as uu,K as mu,L as fu,M as ba,N as Ra,O as gu,P as p,Q as qe,R as X,S as w,T as yu,U as vu,V as ku,W as xt,X as bu,Y as Ea,Z as Tt,_ as Ru,a as at,aa as te,b as $,ba as D,c as ou,ca as Pu,d as A,da as Ct,e as ee,f as ie,fa as Eu,g as ds,h as $r,ha as xu,i as f,j as su,k as ps,l as K,m as ve,n as Te,o as iu,oa as Tu,p as ka,q as ne,r as Y,ra as Cu,s as us,t as au,u as Pt,v as Ce,w as x,x as Le,y as Ar,z as cu}from"./chunk-J7KIXQRB.js";import{a as wu}from"./chunk-MFAFQVTW.js";import{a as q}from"./chunk-6SLDCUNI.js";import{a as kt,b as rs,c as He,d as Dp,e as it,f as Er,g as xr,h as ns,i as Tr,j as os,k as Np,l as _p,m as Mp,n as bt,o as ss,p as ge,q as Cr}from"./chunk-QSTGO43H.js";import{a as Iu,b as Du}from"./chunk-QWVLAZ6N.js";import dI,{Separator as Rv}from"@inquirer/select";import{existsSync as pI,realpathSync as uI}from"node:fs";import{homedir as mI}from"node:os";import Ee from"node:process";import{fileURLToPath as Pv}from"node:url";import Am from"node:process";import{z as Ie}from"zod";import tm from"node:fs";import Nr from"node:path";import{packageConfigSchema as Yu}from"@slip-stream-kit/config/internal";import Xu from"node:fs/promises";import Ss from"node:path";import{pathToFileURL as Dv}from"node:url";import{z as Zu}from"zod";import qu from"node:path";var Ln=["frontend","backend","lib","e2e","mobile"],Tv={ui:"frontend",api:"backend",tests:"e2e"},Cv="mobile-app",$v=[{type:"e2e",packages:["@playwright/test"]},{type:"mobile",packages:["@capacitor/core","@capacitor/cli"]},{type:"backend",packages:["serverless"]}],Av=(e,t)=>{let r=qu.relative(t,e).split(qu.sep).filter(s=>s!==""&&s!=="."),[n,,o]=r;if(r.length===3&&n==="apps"&&o!==void 0){let s=Tv[o];if(s)return s}return r.at(-1)===Cv?"mobile":null},Ov=e=>{let t=new Set([...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{}),...Object.keys(e.peerDependencies??{})]);for(let n of $v)if(n.packages.some(o=>t.has(o)))return n.type;return t.has("vite")&&t.has("react")&&!!e.scripts?.dev?"frontend":null},Vn=({packageDir:e,repoRoot:t,pkgJson:r,declaredType:n})=>n??Av(e,t)??Ov(r)??"lib";var $t={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},zu=2e3,$a={"e2e-test":"pnpm exec playwright test","e2e-test-ui":"pnpm exec playwright test --ui","e2e-test-ui-demo":`E2E_SLOW_MO=\${E2E_SLOW_MO:-${zu}} pnpm exec playwright test --ui --headed --workers=1`,"e2e-test-chrome":"pnpm exec playwright test --project=chromium","e2e-test-debug":"pnpm exec playwright test --debug","e2e-test-codegen":"pnpm exec playwright codegen","playwright-install":"pnpm exec playwright install --with-deps"},Aa={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"]},Oa=(e,t=$t)=>({requiredScripts:e.requiredScripts??[...t.requiredScripts],requiredFiles:e.requiredFiles??[...t.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...t.turboTasks]});import Iv from"node:fs/promises";var Ve=async e=>{try{return await Iv.access(e),!0}catch{return!1}};var Be="infra-kit.config.ts",zt=async e=>{try{let t=await Xu.readFile(Ss.join(e,"package.json"),"utf-8");return JSON.parse(t)}catch{return{}}},Ia=async e=>{let t=await Xu.stat(e),o=(await import(`${Dv(e).href}?mtime=${Number(t.mtimeMs)}`)).default;if(o===void 0)throw new Error(`${Be} at ${e} has no default export`);return typeof o=="function"?await o():o},Yt=async e=>{let t=Ss.join(e,Be);if(await Ve(t))try{let n=(await Ia(t))?.type;return Ln.find(o=>o===n)}catch{return}},Bn=async(e,t=$t)=>{let r=Ss.join(e,Be);if(!await Ve(r))throw new Error(`${Be} not found at ${r}`);let n=await Ia(r),o=Yu.safeParse(n);if(!o.success)throw new Error(`Invalid ${Be} at ${r}: ${Zu.prettifyError(o.error)}`);return Oa(o.data,t)},Da=async e=>{let t=Ss.join(e,Be);if(!await Ve(t))return;let r=Yu.safeParse(await Ia(t));if(!r.success)throw new Error(`Invalid ${Be} at ${t}: ${Zu.prettifyError(r.error)}`);return r.data};import Qu from"node:fs/promises";import Ps from"node:path";import Nv from"yaml";var _v="pnpm-workspace.yaml",Mv=async e=>(await Qu.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(r=>r.isDirectory()).map(r=>Ps.join(e,r.name)),jv=async(e,t)=>{let r=[];for(let n of e){if(t==="*"){r.push(...await Mv(n));continue}let o=Ps.join(n,t);await Ve(o)&&r.push(o)}return r},Fv=async(e,t)=>{let r=[e];for(let n of t.split("/"))r=await jv(r,n);return r},ke=async e=>{let t=await Qu.readFile(Ps.join(e,_v),"utf-8"),n=((Nv.parse(t)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),o=new Set;for(let s of n){let i=await Fv(e,s);for(let a of i)await Ve(Ps.join(a,"package.json"))&&o.add(a)}return[...o].sort()};import Wn from"node:path";var Jn=async e=>{let t=Wn.resolve(e);for(;t!==Wn.dirname(t);){if(await Ve(Wn.join(t,"package.json")))return t;t=Wn.dirname(t)}if(await Ve(Wn.join(t,"package.json")))return t;throw new Error(`No package.json found in or above ${e} \u2014 cd into a package directory, or pass --root to audit a monorepo root`)};var ze=(e,t,r)=>{let n=e.indexOf(t),o=e.indexOf(r);return n!==-1&&o!==-1&&o>=n},At=(e,t,r)=>{let n=e.indexOf(t),o=e.indexOf(r);if(n===-1||o===-1||o<n)return null;let s=e.slice(0,n).replace(/\n+$/,""),i=e.slice(o+r.length).replace(/^\n+/,"");return s+(i?`
3
- ${i}`:"")},Na=(e,t)=>{let r=e.indexOf(t);if(r===-1)return null;let o=e.slice(r+t.length).match(/^([^\s>]+)/);return o?o[1]:null},em=(e,t,r)=>`${e}
2
+ import{a as up,d as yp,f as as,h as Rr,i as cs,j as Pp,k as Ep,l as xp,m as Tp,n as Cp,o as $p,p as Ap,q as Op,t as da,u as Dp,v as ve}from"./chunk-Z4ZY2G4O.js";import{b as ap,d as cp,k as lp,n as dp}from"./chunk-Y3RW74TE.js";import{a as mt,b as Ru,c as Qi,d as Su,e as Pu,f as Eu,g as xu,h as yn,i as Tu,j as Cu,k as $u,l as Au,m as Ou,n as vn,o as Iu,p as Du,q as Nu,r as _u,s as ea,t as Yo,u as ft,v as Mu,w as zo,x as ju}from"./chunk-CMF7HEVU.js";import{a as se,b as K,c as wt,d as ns,e as sa,f as os,g as ia,h as kn,i as Ft,j as ss,k as ip,l as bn,m as Rn,n as aa,o as ca,q as la}from"./chunk-BQPSXIH2.js";import{b as hn,c as Ho,d as Zi,e as yu,f as qo,g as vu,i as wu,k as ku,m as me,o as bu}from"./chunk-AWFGP6GY.js";import{a as hp}from"./chunk-TVG47UHG.js";import{D as ma,E as fa,a as k,b as S,c as vp,d as wp,e as br,f as kp,g as Vt,h as Sp,i as Ip,j as Sn,k as kt,l as Sr,m as We,n as ls,o as bt,p as ds,q as Np,r as _p,s as Ue,v as ua,x as Pn,z as pa}from"./chunk-LR57E6IP.js";import{a as h,b as nt,c as pp,d as mp,e as O,f as is,g as B,i as Lt,j as Bt,k as bp,l as Rp}from"./chunk-EU7LD5IV.js";import{$ as np,A as Ju,B as Gu,C as Ku,D as es,E as ts,F as Ce,G as wn,H as kr,I as rs,J as Hu,K as qu,L as Yu,M as ra,N as na,O as zu,P as u,Q as Ve,R as z,S as w,T as Xu,U as Zu,V as Qu,W as tp,X as ht,Y as rp,Z as oa,_ as yt,a as rt,aa as op,b as C,ba as Q,c as Fu,ca as M,d as I,da as sp,e as fe,ea as vt,f as ge,fa as x,g as Xo,h as Lu,i as f,j as Bu,k as Zo,l as J,m as ye,n as xe,o as Vu,p as ta,q as te,r as Y,s as Qo,t as Wu,u as gt,v as Te,w as E,x as je,y as wr,z as Uu}from"./chunk-D76UWTR5.js";import{a as ep}from"./chunk-MFAFQVTW.js";import{a as G}from"./chunk-FKA65HOC.js";import{a as gr,b as Wo,c as gn,d as uu,e as hr,f as Uo,g as Jo,h as pu,i as Go,j as Ko,k as mu,l as fu,m as gu,n as yr,o as hu,p as pe,q as vr}from"./chunk-QSTGO43H.js";import{a as fp,b as gp}from"./chunk-QWVLAZ6N.js";import TO,{Separator as tv}from"@inquirer/select";import{existsSync as CO,realpathSync as $O}from"node:fs";import{homedir as AO}from"node:os";import Ee from"node:process";import{fileURLToPath as nv}from"node:url";import Rm from"node:process";import{z as Oe}from"zod";import Up from"node:fs";import xr from"node:path";import{packageConfigSchema as Fp}from"@slip-stream-kit/config/internal";import Lp from"node:fs/promises";import us from"node:path";import{pathToFileURL as mv}from"node:url";import{z as Bp}from"zod";import Mp from"node:path";var En=["frontend","backend","lib","e2e","mobile"],av={ui:"frontend",api:"backend",tests:"e2e"},cv="mobile-app",lv=[{type:"e2e",packages:["@playwright/test"]},{type:"mobile",packages:["@capacitor/core","@capacitor/cli"]},{type:"backend",packages:["serverless"]}],dv=(e,t)=>{let r=Mp.relative(t,e).split(Mp.sep).filter(s=>s!==""&&s!=="."),[n,,o]=r;if(r.length===3&&n==="apps"&&o!==void 0){let s=av[o];if(s)return s}return r.at(-1)===cv?"mobile":null},uv=e=>{let t=new Set([...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{}),...Object.keys(e.peerDependencies??{})]);for(let n of lv)if(n.packages.some(o=>t.has(o)))return n.type;return t.has("vite")&&t.has("react")&&!!e.scripts?.dev?"frontend":null},xn=({packageDir:e,repoRoot:t,pkgJson:r,declaredType:n})=>n??dv(e,t)??uv(r)??"lib";var Rt={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},jp=2e3,ga={"e2e-test":"pnpm exec playwright test","e2e-test-ui":"pnpm exec playwright test --ui","e2e-test-ui-demo":`E2E_SLOW_MO=\${E2E_SLOW_MO:-${jp}} pnpm exec playwright test --ui --headed --workers=1`,"e2e-test-chrome":"pnpm exec playwright test --project=chromium","e2e-test-debug":"pnpm exec playwright test --debug","e2e-test-codegen":"pnpm exec playwright codegen","playwright-install":"pnpm exec playwright install --with-deps"},Tn={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"]},Cn=(e,t=Rt)=>({requiredScripts:e.requiredScripts??[...t.requiredScripts],requiredFiles:e.requiredFiles??[...t.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...t.turboTasks]});import pv from"node:fs/promises";var we=async e=>{try{return await pv.access(e),!0}catch{return!1}};var re="infra-kit.config.ts",Wt=async e=>{try{let t=await Lp.readFile(us.join(e,"package.json"),"utf-8");return JSON.parse(t)}catch{return{}}},ha=async e=>{let t=await Lp.stat(e),o=(await import(`${mv(e).href}?mtime=${Number(t.mtimeMs)}`)).default;if(o===void 0)throw new Error(`${re} at ${e} has no default export`);return typeof o=="function"?await o():o},Ut=async e=>{let t=us.join(e,re);if(await we(t))try{let n=(await ha(t))?.type;return En.find(o=>o===n)}catch{return}},$n=async(e,t=Rt)=>{let r=us.join(e,re);if(!await we(r))throw new Error(`${re} not found at ${r}`);let n=await ha(r),o=Fp.safeParse(n);if(!o.success)throw new Error(`Invalid ${re} at ${r}: ${Bp.prettifyError(o.error)}`);return Cn(o.data,t)},Pr=async e=>{let t=us.join(e,re);if(!await we(t))return;let r=Fp.safeParse(await ha(t));if(!r.success)throw new Error(`Invalid ${re} at ${t}: ${Bp.prettifyError(r.error)}`);return r.data};import Vp from"node:fs/promises";import ps from"node:path";import fv from"yaml";var gv="pnpm-workspace.yaml",hv=async e=>(await Vp.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(r=>r.isDirectory()).map(r=>ps.join(e,r.name)),yv=async(e,t)=>{let r=[];for(let n of e){if(t==="*"){r.push(...await hv(n));continue}let o=ps.join(n,t);await we(o)&&r.push(o)}return r},vv=async(e,t)=>{let r=[e];for(let n of t.split("/"))r=await yv(r,n);return r},ke=async e=>{let t=await Vp.readFile(ps.join(e,gv),"utf-8"),n=((fv.parse(t)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),o=new Set;for(let s of n){let i=await vv(e,s);for(let a of i)await we(ps.join(a,"package.json"))&&o.add(a)}return[...o].sort()};import An from"node:path";var On=async e=>{let t=An.resolve(e);for(;t!==An.dirname(t);){if(await we(An.join(t,"package.json")))return t;t=An.dirname(t)}if(await we(An.join(t,"package.json")))return t;throw new Error(`No package.json found in or above ${e} \u2014 cd into a package directory, or pass --root to audit a monorepo root`)};var Je=(e,t,r)=>{let n=e.indexOf(t),o=e.indexOf(r);return n!==-1&&o!==-1&&o>=n},St=(e,t,r)=>{let n=e.indexOf(t),o=e.indexOf(r);if(n===-1||o===-1||o<n)return null;let s=e.slice(0,n).replace(/\n+$/,""),i=e.slice(o+r.length).replace(/^\n+/,"");return s+(i?`
3
+ ${i}`:"")},ya=(e,t)=>{let r=e.indexOf(t);if(r===-1)return null;let o=e.slice(r+t.length).match(/^([^\s>]+)/);return o?o[1]:null},Wp=(e,t,r)=>`${e}
4
4
  ${t}
5
- ${r}`,Dr=({content:e,body:t,startMarker:r,endMarker:n,placement:o="replace-in-place"})=>{let s=em(r,t,n),i=ze(e,r,n);if(o==="replace-in-place"&&i){let l=e.indexOf(r),d=e.indexOf(n)+n.length;return e.slice(0,l)+s+e.slice(d)}let c=(i?At(e,r,n)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
5
+ ${r}`,Er=({content:e,body:t,startMarker:r,endMarker:n,placement:o="replace-in-place"})=>{let s=Wp(r,t,n),i=Je(e,r,n);if(o==="replace-in-place"&&i){let l=e.indexOf(r),d=e.indexOf(n)+n.length;return e.slice(0,l)+s+e.slice(d)}let c=(i?St(e,r,n)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
6
6
  ${s}
7
7
  `:`${s}
8
- `};var Ae="<!-- infra-kit:begin -->",Ye="<!-- infra-kit:end -->",_a="<!-- infra-kit:version ",Xe="<!-- infra-kit:package:begin -->",dt="<!-- infra-kit:package:end -->",Xt="<!-- infra-kit:package:version ";var Lv=e=>{let t=e.indexOf(Xe)+Xe.length;return e.slice(t,e.indexOf(dt))},Vv=e=>{let t=e.indexOf(Xt);if(t===-1)return null;let r=e.slice(t+Xt.length).match(/^\S+\s+([^\s>]+)/)?.[1];return Ln.find(n=>n===r)??null},Zt=e=>{if(e===null)return{state:"missing"};if(!ze(e,Xe,dt))return e.includes(Xe)||e.includes(dt)?{state:"malformed"}:ze(e,Ae,Ye)?{state:"foreign-block"}:{state:"no-block"};let t=Lv(e);if(t.trim()==="")return{state:"malformed"};let r={state:"ok"},n=Na(t,Xt),o=Vv(t);return n!==null&&(r.version=n),o!==null&&(r.type=o),r};import Bv from"node:fs";var Qt=e=>{try{return Bv.readFileSync(e,"utf-8")}catch{return null}};var rm="pnpm-workspace.yaml",Wv="CLAUDE.md",ja=e=>{let t=Nr.resolve(e);for(;t!==Nr.dirname(t);){if(tm.existsSync(Nr.join(t,rm)))return t;t=Nr.dirname(t)}return tm.existsSync(Nr.join(t,rm))?t:null},Ma=new Map,Es=()=>{Ma.clear()},Jv=async e=>{let t;try{t=await ke(e)}catch{return{adopted:!1,workspaceRoot:e}}for(let r of t){let n=Nr.join(r,Wv),o=Qt(n);if(o!==null&&Zt(o).state==="ok")return{adopted:!0,workspaceRoot:e,evidencePath:n}}return{adopted:!1,workspaceRoot:e}},_r=async e=>{if(e===null)return{adopted:!1,workspaceRoot:null};let t=Ma.get(e);if(t)return t;let r=await Jv(e);return Ma.set(e,r),r};import er from"node:fs";import Ot from"node:path";var nm=`---
8
+ `};var $e="<!-- infra-kit:begin -->",Ge="<!-- infra-kit:end -->",va="<!-- infra-kit:version ",Ke="<!-- infra-kit:package:begin -->",ot="<!-- infra-kit:package:end -->",Jt="<!-- infra-kit:package:version ";var wv=e=>{let t=e.indexOf(Ke)+Ke.length;return e.slice(t,e.indexOf(ot))},kv=e=>{let t=e.indexOf(Jt);if(t===-1)return null;let r=e.slice(t+Jt.length).match(/^\S+\s+([^\s>]+)/)?.[1];return En.find(n=>n===r)??null},Gt=e=>{if(e===null)return{state:"missing"};if(!Je(e,Ke,ot))return e.includes(Ke)||e.includes(ot)?{state:"malformed"}:Je(e,$e,Ge)?{state:"foreign-block"}:{state:"no-block"};let t=wv(e);if(t.trim()==="")return{state:"malformed"};let r={state:"ok"},n=ya(t,Jt),o=kv(t);return n!==null&&(r.version=n),o!==null&&(r.type=o),r};import bv from"node:fs";var Kt=e=>{try{return bv.readFileSync(e,"utf-8")}catch{return null}};var Jp="pnpm-workspace.yaml",Rv="CLAUDE.md",ka=e=>{let t=xr.resolve(e);for(;t!==xr.dirname(t);){if(Up.existsSync(xr.join(t,Jp)))return t;t=xr.dirname(t)}return Up.existsSync(xr.join(t,Jp))?t:null},wa=new Map,ms=()=>{wa.clear()},Sv=async e=>{let t;try{t=await ke(e)}catch{return{adopted:!1,workspaceRoot:e}}for(let r of t){let n=xr.join(r,Rv),o=Kt(n);if(o!==null&&Gt(o).state==="ok")return{adopted:!0,workspaceRoot:e,evidencePath:n}}return{adopted:!1,workspaceRoot:e}},Tr=async e=>{if(e===null)return{adopted:!1,workspaceRoot:null};let t=wa.get(e);if(t)return t;let r=await Sv(e);return wa.set(e,r),r};import Ht from"node:fs";import Pt from"node:path";var Gp=`---
9
9
  name: TODO
10
10
  description: TODO \u2014 one sentence describing the product surface this package renders.
11
11
  colors:
@@ -74,7 +74,7 @@ TODO \u2014 for each component in the front matter list: its variants, its state
74
74
  - Do TODO.
75
75
  - Don't TODO.
76
76
  - Don't TODO.
77
- `;var om=`# {{packageName}}
77
+ `;var Kp=`# {{packageName}}
78
78
 
79
79
  Workspace package at \`{{relDir}}\` \u2014 type: **{{type}}**.
80
80
  This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_ the markers, never inside.
@@ -95,7 +95,7 @@ This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_
95
95
  - Module-scope state belongs in the handler entry file \u2014 that is the file which re-evaluates on reload.
96
96
  - Env vars come from Doppler via \`ik env-load\`; never commit a secret.
97
97
  - The route prefix this service answers is declared in the consuming UI's \`dev.proxy\`, so changing a path is a two-package change.
98
- `;var sm="# {{packageName}}\n\nWorkspace package at `{{relDir}}` \u2014 type: **{{type}}**.\nThis block is generated by `infra-kit audit --fix` \u2014 edit text _outside_ the markers, never inside.\n\n## Read first\n\n- {{readmeBullet}}\n- `infra-kit.config.ts` \u2014 the audit rules this package must satisfy.\n\n## Checks\n\n- `infra-kit audit` \u2014 validate this package against its infra-kit rules.\n- `pnpm run ts-check && pnpm run eslint-check && pnpm run test` \u2014 this package only.\n- `pnpm run qa` at the repo root \u2014 the full gate; run it before claiming completion.\n\n## Rules\n\n- Specs run on Playwright. The `e2e-test*` scripts and the `E2E_SLOW_MO` / trace settings in `playwright.config.ts` are shared across repos and checked by `infra-kit audit` \u2014 never rename or fork them locally.\n- {{e2eDocBullet}}\n- `e2e-test-ui-demo` (visible browser, one worker) is for showing a flow to a person. It sets `E2E_SLOW_MO=2000` \u2014 2 s before every action \u2014 unless the variable is already set; debug with `e2e-test-ui` instead, and everywhere else `E2E_SLOW_MO` stays unset, which the config reads as 0.\n- Every spec cleans up what it creates, in teardown.\n- Selectors live in Page Objects, never inline in specs.\n- Run the suite with `infra-kit e2e`: it sets `e2e.baseUrlEnv` from `infra-kit.config.ts` to this worktree's dev server when one serves `e2e.target`, else to the deployed URL `infra-kit env-load` loaded (or `e2e.cloud` at `INFRA_KIT_ENV`). Never hand-set that variable to reach a local server.\n- Never point a run at a production environment.\n\n## Structure\n\n- Specs live in `src/tests/<domain>/`, one folder per business domain \u2014 never per page, browser, device, or environment (those are Playwright projects).\n- A domain folder's root holds only its `*.spec.ts` files. Everything else always goes in a subfolder, even a single file: `pages/` (`.page.ts`, `.component.ts`), `fixtures/` (`.fixture.ts`), `mocks/` (`.mock.ts`), `data/` (`.data.ts`), `lib/` (domain-private helpers).\n- Never nest specs in subfolders \u2014 when a domain has too many specs to scan, split it into two domains (`luggage/`, `luggage-pricing/`).\n- Anything two domains share moves up to `src/pages/`, `src/fixtures/`, `src/mocks/`, or `src/lib/`; a domain never imports from a sibling domain.\n- API and contract specs stay in their domain folder, told apart by suffix: `<flow>.api.spec.ts`, `<flow>.contract.spec.ts`. A suffix exists only when that suite runs in its own Playwright project.\n- Visual-regression specs live in `src/visual/<domain>/<flow>.visual.spec.ts`, so baseline screenshots stay out of the domain folders.\n- Auth and data preparation are `src/setup/*.setup.ts` / `*.teardown.ts`, wired as Playwright setup projects \u2014 never `globalSetup`. Saved auth state goes to the gitignored `.auth/`.\n\n## Naming\n\n- Every Playwright spec is `*.spec.ts`; `.test.ts` is never used in an e2e package.\n- Files and folders are kebab-case.\n- A spec file names a stable flow: `<feature-or-flow>.spec.ts`. No ticket ids, sequence numbers, or `common` / `main` / `smoke`.\n- Non-spec files never carry `.spec` / `.test`. A spec never imports another spec.\n- `describe` is a short domain context in Title Case (`Checkout`).\n- `test` is a lowercase behaviour phrase \u2014 action or condition plus the observable outcome (`rejects an expired coupon without changing the total`). No `should`, `test \u2026`, `works`, or case numbers.\n- `test.step` is a verb plus a business operation (`Pay with the saved card`), 3\u20136 per long flow \u2014 never one step per click or fill.\n- Screenshot baselines are named by UI state (`checkout-payment-error.png`), never `screenshot-1.png`.\n\n## Tags\n\nRun categories are tags (`{ tag: [...] }`), never file names. Only these four exist:\n\n- `@smoke` \u2014 the fast post-deploy check; every domain has at least one.\n- `@readonly` \u2014 creates and changes nothing, so it is safe against any shared environment.\n- `@mocked` \u2014 every backend call is mocked; runs without a live API.\n- `@slow` \u2014 excluded from local runs with `--grep-invert @slow`.\n\nNever tag a browser, device, or environment, and never add `@flaky`; fix the test or skip it with a linked issue.\n\nLint enforces the mechanical part: `@wl/e2e-file-layout` the Structure folders and the `.spec.ts` suffix, `@wl/e2e-test-tags` the tag list, `@wl/e2e-test-title` the missing `should`. The rest of Naming \u2014 `describe` in Title Case, no ticket ids, outcome-bearing titles, `test.step` wording \u2014 is on the author and the reviewer.\n";var im="# {{packageName}}\n\nWorkspace package at `{{relDir}}` \u2014 type: **{{type}}**.\nThis block is generated by `infra-kit audit --fix` \u2014 edit text _outside_ the markers, never inside.\n\n## Read first\n\n- {{readmeBullet}}\n- `DESIGN.md` \u2014 the visual language (colors, typography, spacing, components). It is the source of truth for UI decisions; if it is absent, ask before inventing one.\n- `infra-kit.config.ts` \u2014 the audit rules this package must satisfy.\n\n## Checks\n\n- `infra-kit audit` \u2014 validate this package against its infra-kit rules.\n- `pnpm run ts-check && pnpm run eslint-check && pnpm run test` \u2014 this package only.\n- `pnpm run qa` at the repo root \u2014 the full gate; run it before claiming completion.\n\n## Rules\n\n- Start the app with `infra-kit dev`, never a bare `vite` \u2014 dev URLs are proxied and port-free.\n- Backend calls go through the path prefixes declared in `dev.proxy` in `infra-kit.config.ts`. Never hardcode an API base URL or a port.\n- Use the tokens in `DESIGN.md` rather than ad-hoc colors, spacing, or type scales.\n";var am=`# {{packageName}}
98
+ `;var Hp="# {{packageName}}\n\nWorkspace package at `{{relDir}}` \u2014 type: **{{type}}**.\nThis block is generated by `infra-kit audit --fix` \u2014 edit text _outside_ the markers, never inside.\n\n## Read first\n\n- {{readmeBullet}}\n- `infra-kit.config.ts` \u2014 the audit rules this package must satisfy.\n\n## Checks\n\n- `infra-kit audit` \u2014 validate this package against its infra-kit rules.\n- `pnpm run ts-check && pnpm run eslint-check && pnpm run test` \u2014 this package only.\n- `pnpm run qa` at the repo root \u2014 the full gate; run it before claiming completion.\n\n## Rules\n\n- Specs run on Playwright. The `e2e-test*` scripts and the `E2E_SLOW_MO` / trace settings in `playwright.config.ts` are shared across repos and checked by `infra-kit audit` \u2014 never rename or fork them locally.\n- {{e2eDocBullet}}\n- `e2e-test-ui-demo` (visible browser, one worker) is for showing a flow to a person. It sets `E2E_SLOW_MO=2000` \u2014 2 s before every action \u2014 unless the variable is already set; debug with `e2e-test-ui` instead, and everywhere else `E2E_SLOW_MO` stays unset, which the config reads as 0.\n- Every spec cleans up what it creates, in teardown.\n- Selectors live in Page Objects, never inline in specs.\n- `playwright.config.ts` takes `baseURL`, `ignoreHTTPSErrors` and `webServer` from `infraKitE2e()` (`@slip-stream-kit/config/playwright`). Every run is local by default \u2014 this worktree's dev server, reused or started for the run \u2014 and cloud only with `INFRA_KIT_E2E=cloud` (`infra-kit e2e --cloud`) or on CI, against the URL the loaded env holds in the target app's `deployedUrlEnv` (`ik env-load -c <env>`). Read the base URL from Playwright's `baseURL`, never from that variable: locally it still holds the deployed URL.\n- Never point a run at a production environment.\n\n## Structure\n\n- Specs live in `src/tests/<domain>/`, one folder per business domain \u2014 never per page, browser, device, or environment (those are Playwright projects).\n- A domain folder's root holds only its `*.spec.ts` files. Everything else always goes in a subfolder, even a single file: `pages/` (`.page.ts`, `.component.ts`), `fixtures/` (`.fixture.ts`), `mocks/` (`.mock.ts`), `data/` (`.data.ts`), `lib/` (domain-private helpers).\n- Never nest specs in subfolders \u2014 when a domain has too many specs to scan, split it into two domains (`luggage/`, `luggage-pricing/`).\n- Anything two domains share moves up to `src/pages/`, `src/fixtures/`, `src/mocks/`, or `src/lib/`; a domain never imports from a sibling domain.\n- API and contract specs stay in their domain folder, told apart by suffix: `<flow>.api.spec.ts`, `<flow>.contract.spec.ts`. A suffix exists only when that suite runs in its own Playwright project.\n- Visual-regression specs live in `src/visual/<domain>/<flow>.visual.spec.ts`, so baseline screenshots stay out of the domain folders.\n- Auth and data preparation are `src/setup/*.setup.ts` / `*.teardown.ts`, wired as Playwright setup projects \u2014 never `globalSetup`. Saved auth state goes to the gitignored `.auth/`.\n\n## Naming\n\n- Every Playwright spec is `*.spec.ts`; `.test.ts` is never used in an e2e package.\n- Files and folders are kebab-case.\n- A spec file names a stable flow: `<feature-or-flow>.spec.ts`. No ticket ids, sequence numbers, or `common` / `main` / `smoke`.\n- Non-spec files never carry `.spec` / `.test`. A spec never imports another spec.\n- `describe` is a short domain context in Title Case (`Checkout`).\n- `test` is a lowercase behaviour phrase \u2014 action or condition plus the observable outcome (`rejects an expired coupon without changing the total`). No `should`, `test \u2026`, `works`, or case numbers.\n- `test.step` is a verb plus a business operation (`Pay with the saved card`), 3\u20136 per long flow \u2014 never one step per click or fill.\n- Screenshot baselines are named by UI state (`checkout-payment-error.png`), never `screenshot-1.png`.\n\n## Tags\n\nRun categories are tags (`{ tag: [...] }`), never file names. Only these four exist:\n\n- `@smoke` \u2014 the fast post-deploy check; every domain has at least one.\n- `@readonly` \u2014 creates and changes nothing, so it is safe against any shared environment.\n- `@mocked` \u2014 every backend call is mocked; runs without a live API.\n- `@slow` \u2014 excluded from local runs with `--grep-invert @slow`.\n\nNever tag a browser, device, or environment, and never add `@flaky`; fix the test or skip it with a linked issue.\n\nLint enforces the mechanical part: `@wl/e2e-file-layout` the Structure folders and the `.spec.ts` suffix, `@wl/e2e-test-tags` the tag list, `@wl/e2e-test-title` the missing `should`. The rest of Naming \u2014 `describe` in Title Case, no ticket ids, outcome-bearing titles, `test.step` wording \u2014 is on the author and the reviewer.\n";var qp="# {{packageName}}\n\nWorkspace package at `{{relDir}}` \u2014 type: **{{type}}**.\nThis block is generated by `infra-kit audit --fix` \u2014 edit text _outside_ the markers, never inside.\n\n## Read first\n\n- {{readmeBullet}}\n- `DESIGN.md` \u2014 the visual language (colors, typography, spacing, components). It is the source of truth for UI decisions; if it is absent, ask before inventing one.\n- `infra-kit.config.ts` \u2014 the audit rules this package must satisfy.\n\n## Checks\n\n- `infra-kit audit` \u2014 validate this package against its infra-kit rules.\n- `pnpm run ts-check && pnpm run eslint-check && pnpm run test` \u2014 this package only.\n- `pnpm run qa` at the repo root \u2014 the full gate; run it before claiming completion.\n\n## Rules\n\n- Start the app with `infra-kit dev`, never a bare `vite` \u2014 dev URLs are proxied and port-free.\n- Backend calls go through the path prefixes declared in `dev.proxy` in `infra-kit.config.ts`. Never hardcode an API base URL or a port.\n- Use the tokens in `DESIGN.md` rather than ad-hoc colors, spacing, or type scales.\n";var Yp=`# {{packageName}}
99
99
 
100
100
  Workspace package at \`{{relDir}}\` \u2014 type: **{{type}}**.
101
101
  This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_ the markers, never inside.
@@ -117,7 +117,7 @@ This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_
117
117
  - Changing that map is a breaking change for every dependent package.
118
118
  - Run \`pnpm run build\` before a dependent package can see a change.
119
119
  - No app-specific logic belongs here.
120
- `;var cm=`# {{packageName}}
120
+ `;var zp=`# {{packageName}}
121
121
 
122
122
  Workspace package at \`{{relDir}}\` \u2014 type: **{{type}}**.
123
123
  This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_ the markers, never inside.
@@ -139,39 +139,39 @@ This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_
139
139
  - The native shell is Capacitor; its settings live in \`capacitor.config.*\`.
140
140
  - The web build feeds the native shell, so a device run needs a rebuild first.
141
141
  - Use the tokens in \`DESIGN.md\` rather than ad-hoc colors, spacing, or type scales.
142
- `;var lm="# infra-kit\n\nThis repository uses the **infra-kit** CLI for environment, worktree, and release workflows.\nThis block is generated by `ik audit --fix --root` \u2014 edit text _outside_ the markers, never inside.\n\n## Commands (`ik` = `pnpm exec infra-kit`)\n\n- `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.\n- `ik dev [preset]` / `ik dev-status` \u2014 run this worktree's dev servers (a `devServersPresets` preset, or every app), or report what is running.\n- `ik e2e [--app <app>]` \u2014 run an app's Playwright suite against this worktree's dev server when one serves `e2e.target`, else against the deployed app at `INFRA_KIT_ENV` (the env-loaded `e2e.baseUrlEnv`, or `e2e.cloud`); `--dry-run` prints the target and proxy split. A cloud run previews and needs `--yes`.\n- `ik worktrees add` / `worktrees list` / `worktrees remove` / `worktrees sync` \u2014 manage release and feature git worktrees.\n- `ik release create` / `release remove` / `release list` / `release deploy-all` / `release deploy-selected` / `release deliver` / `release edit` \u2014 release-branch and deploy flow.\n- `ik release merge-dev` \u2014 merge the dev branch into every release branch; `--keep-conflicts` hands off any real conflict to a CLI-owned resolution worktree, `--continue`/`--abort` resume or drop that hand-off. The `/infra-kit:merge-dev` skill is the agent entry point for the whole flow.\n- `ik audit` \u2014 audit packages against `infra-kit.config.ts` rules.\n- `ik audit --fix` \u2014 regenerate this repo's infra-kit guidance blocks (`--all` for every package, `--root` for this file).\n- `ik doctor` \u2014 check gh / doppler / aws install + auth and repo setup.\n- `ik setup` \u2014 set up infra-kit on this machine: shell integration, the Claude Code skills plugin, and the external CLIs (brew, git, aws, gh, doppler, portless).\n\n## Conventions\n\n- 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.\n- Environment variables are managed through Doppler via `ik env-load` \u2014 never commit secrets.\n- Every workspace package has its own CLAUDE.md with package-scoped rules \u2014 read it before editing that package.\n- Launch Claude Code at the repository root: the infra-kit plugin (the `/infra-kit:*` skills) and this repo's `.claude/settings.json` hooks load only from there. If the `/infra-kit:*` skills are absent, this is a subdirectory session \u2014 restart Claude Code at the root.\n\n## Agents\n\n- Agents drive the same CLI over Bash: `infra-kit <command> --agent --json`. There is no MCP server; the `/infra-kit:*` skills are the entry points and they run the CLI on `PATH`.\n- A confirm-gated command (`release create|remove|edit|merge-dev|deploy-all|deploy-selected`, `release merge-dev --continue|--abort`, `worktrees add|remove|sync`) previews its plan and exits without acting; re-run the same argv with `--yes` to execute. Never put a mutating command behind a prefix allow \u2014 that makes the `--yes` re-run unprompted (`ik doctor` warns on such a pattern).\n- `env-load`, `env-clear` and `infra-kit setup` have no confirm step and run once: the host's prompt on the argv is the approval. `release deliver` and `vendor sync` are human-only and are refused under agent mode.\n- A command that needs a human choice returns a structured `argument_required` refusal naming the option; pass the value instead of retrying.\n\n## Writing code\n\n- Comment the **why**, never the **what**. If a comment would only restate what the code already says (a name, a type, an obvious assignment), delete it \u2014 and if code needs a comment to be _understood_, prefer renaming/refactoring until it reads on its own. Reserve comments for the genuinely non-obvious: external quirks, ordering constraints, fail-safe branches, workarounds, business-logic definitions. Keep them compact. When a comment explains a bug, outage, or upstream issue, link the source of truth instead of describing it.\n- Unit tests are `*.test.ts(x)` in a `__tests__/` folder beside the code they test (`src/foo/__tests__/foo.test.ts`), never next to the source file; inside a frontend feature, all of them go in the feature root's `features/<name>/__tests__/`. `*.spec.ts` is only for Playwright specs in an e2e package. The `@wl/test-location` lint rule enforces it.\n";var Mr={"root/body":lm.trimEnd(),"package/frontend":im.trimEnd(),"package/backend":om.trimEnd(),"package/lib":am.trimEnd(),"package/e2e":sm.trimEnd(),"package/mobile":cm.trimEnd(),"design/skeleton":nm.trimEnd()};var Fa=/\{\{(\w+)\}\}/g,Xv=/^- \{\{(\w+)\}\}$/,Zv=e=>new Set([...e.matchAll(Fa)].map(t=>t[1])),Qv=(e,t)=>{let r=Object.keys(t).filter(n=>!e.has(n));if(r.length>0)throw new Error(`renderTemplate: variable(s) never used by the template: ${r.join(", ")}`)},ew=(e,t)=>{let r=[...e].filter(n=>!(n in t));if(r.length>0)throw new Error(`renderTemplate: placeholder(s) with no variable: ${r.map(n=>`{{${n}}}`).join(", ")}`)},tw=(e,t)=>e.filter(r=>{let n=Xv.exec(r);return n===null||t[n[1]]!==""}),rw=(e,t)=>{for(let r of e)for(let n of r.matchAll(Fa)){let o=t[n[1]];if(o!==void 0&&o.includes(`
143
- `)&&n.index!==0)throw new Error(`renderTemplate: multi-line value for {{${n[1]}}} must start its line (found at column ${n.index})`)}},jr=(e,t)=>{let r=Zv(e);ew(r,t),Qv(r,t);let n=tw(e.split(`
144
- `),t);return rw(n,t),n.join(`
145
- `).replace(Fa,(o,s)=>t[s])};var nw="name: TODO",La=e=>{let t=jr(Mr["design/skeleton"],{packageName:e}),r=`name: ${e}`;return`${t.replace(nw,()=>r)}
146
- `};var ow=(e,t)=>`${Xt}${e} ${t} -->`,sw="`README.md` \u2014 what this package is and how to run it.",Va="docs/e2e-playwright.md",iw=`\`${Va}\` at the repo root \u2014 env setup, run modes, \`E2E_SLOW_MO\`, traces after a failure.`,Ba=e=>{let{version:t,type:r,packageName:n,relDir:o,hasReadme:s,hasE2eDoc:i}=e,a=jr(Mr[`package/${r}`],{packageName:n,relDir:o,type:r,readmeBullet:s?sw:"",...r==="e2e"?{e2eDocBullet:i?iw:""}:{}});return[ow(t,r),"",a].join(`
147
- `)};var aw=e=>`${_a}${e} -->`,Wa=e=>{let t=jr(Mr["root/body"],{});return[aw(e),"",t].join(`
148
- `)};import Fr from"node:fs";import cw from"node:path";var xs=e=>{let t;try{t=Fr.lstatSync(e)}catch{return}if(t.isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},Un=(e,t)=>{xs(e);let r=Fr.existsSync(e)?Fr.readFileSync(e,"utf-8"):null;return r===t?"unchanged":(Fr.mkdirSync(cw.dirname(e),{recursive:!0}),Fr.writeFileSync(e,t,"utf-8"),r===null?"created":"updated")},Ja=(e,t,r)=>{let n=Fr.readFileSync(e,"utf-8");if(!ze(n,t,r))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},dm=(e,t,r)=>ze(e,t,r)?{before:e.slice(0,e.indexOf(t)),after:e.slice(e.indexOf(r)+r.length)}:null,Ua=(e,t,r,n)=>{let o=dm(e,r,n),s=dm(t,r,n);if(!(o===null||s===null)&&(o.before!==s.before||o.after!==s.after))throw new Error("Post-write validation failed: content outside the managed markers changed")};var Cs="<!-- infra-kit:import:begin -->",$s="<!-- infra-kit:import:end -->",lw="AGENTS.md",pm="CLAUDE.md",dw="README.md",Ga="DESIGN.md",pw=["frontend","mobile"],uw=e=>er.existsSync(e)?er.readFileSync(e,"utf-8"):null,Ka=(e,t)=>{try{return er.readdirSync(e).includes(t)}catch{return!1}},Ts=(e,t,r)=>{let n=t instanceof Error?t.message:String(t),o={path:e,action:"failed",message:n};return r&&(o.type=r),o},um=({filePath:e,body:t,startMarker:r,endMarker:n,prepare:o})=>{let s=uw(e),i=s===null?"":o?.(s)??s,a=Dr({content:i,body:t,startMarker:r,endMarker:n,placement:"replace-in-place"}),c=Un(e,a);return Ja(e,r,n),s!==null&&Ua(i,a,r,n),c},mw=e=>{if(!er.existsSync(e))return"unchanged";xs(e);let t=er.readFileSync(e,"utf-8"),r=At(t,Ae,Ye);return r===null?"unchanged":r.trim()===""?(er.rmSync(e),"removed"):Un(e,r)},fw=(e,t)=>um({filePath:e,body:Wa(t),startMarker:Ae,endMarker:Ye,prepare:r=>At(r,Cs,$s)??r}),Gn=async(e,{version:t})=>{let r=Ot.join(e,pm),n=Ot.join(e,lw),o=[];try{o.push({path:r,action:fw(r,t)})}catch(s){o.push(Ts(r,s))}try{o.push({path:n,action:mw(n)})}catch(s){o.push(Ts(n,s))}return o},gw=(e,t,r)=>{if(!pw.includes(r)||Ka(e,Ga))return null;let n=Ot.join(e,Ga);try{return{path:n,action:Un(n,La(t)),type:r}}catch(o){return Ts(n,o,r)}},Kn=async(e,{repoRoot:t,version:r,design:n,declaredType:o})=>{let s=Ot.join(e,pm),i=await zt(e),a=i.name??Ot.basename(e),c=Vn({packageDir:e,repoRoot:t,pkgJson:i,declaredType:o}),l=Ba({version:r,type:c,packageName:a,relDir:Ot.relative(t,e).split(Ot.sep).join("/"),hasReadme:Ka(e,dw),hasDesign:Ka(e,Ga),hasE2eDoc:er.existsSync(Ot.join(t,Va))}),d=[];try{d.push({path:s,action:um({filePath:s,body:l,startMarker:Xe,endMarker:dt}),type:c})}catch(u){d.push(Ts(s,u,c))}if(n){let u=gw(e,a,c);u&&d.push(u)}return d};import xw from"node:path";import mm from"node:path";var Ha="agent-guidance",Hn="CLAUDE.md",hw="\u2014 run: infra-kit audit --fix",yw={missing:`${Hn} missing`,"no-block":`${Hn} has no infra-kit block (expected ${Xe} \u2026 ${dt})`,malformed:`${Hn} block is malformed (end marker precedes start, or body is empty)`,"foreign-block":`${Hn} carries the ROOT infra-kit block (${Ae}); a package needs the package block`},vw=e=>e.adopted?` (workspace adopted: ${mm.relative(e.workspaceRoot,e.evidencePath)} carries a package block)`:"",qa=(e,t)=>{let r=Zt(Qt(mm.join(e,Hn)));if(r.state==="ok"){let s=r.version??"unknown",i=r.type??"unknown";return{name:Ha,status:"pass",message:`present (block from infra-kit ${s}, type ${i})`}}let n=`${yw[r.state]} ${hw}`,o=r.state==="missing"?`${n}${vw(t)}`:n;return t.adopted?{name:Ha,status:"fail",message:o}:{name:Ha,status:"pass",message:`not yet adopted \u2014 ${o}`}};var za=async(e,t=$t)=>{try{let r=await Bn(e,t);return{check:{name:Be,status:"pass",message:"present and valid"},rules:r}}catch(r){return{check:{name:Be,status:"fail",message:r.message},rules:null}}};import ww from"node:fs/promises";import kw from"node:path";var As="playwright.config.ts",bw=[{name:"slow-mo",pattern:/process\.env\.E2E_SLOW_MO/u,expected:"const SLOW_MO = Number(process.env.E2E_SLOW_MO ?? 0)"},{name:"launch-options",pattern:/launchOptions:\s*\{[^}]*\bslowMo\b/u,expected:"use.launchOptions: { slowMo: SLOW_MO }"},{name:"timeout-headroom",pattern:/\btimeout:[^\n]*\bSLOW_MO\b/u,expected:"timeout: <base> + SLOW_MO * 100"},{name:"trace",pattern:/trace:\s*process\.env\.CI\s*\?\s*'on-first-retry'\s*:\s*'retain-on-failure'/u,expected:"use.trace: process.env.CI ? 'on-first-retry' : 'retain-on-failure'"}],fm=e=>Object.entries($a).map(([t,r])=>{let n=`e2e-script:${t}`,o=e[t];return typeof o!="string"||o.trim().length===0?{name:n,status:"fail",message:`missing "${t}" in package.json scripts \u2014 expected: ${r}`}:o.trim()!==r?{name:n,status:"fail",message:`"${t}" drifts from the shared e2e scripts \u2014 expected: ${r}`}:{name:n,status:"pass",message:"matches the shared e2e scripts"}}),gm=async e=>{let t=kw.join(e,As),r=await ww.readFile(t,"utf-8").catch(()=>null);return r===null?[{name:`e2e-config:${As}`,status:"fail",message:`missing ${As}`}]:bw.map(n=>{let o=`e2e-config:${n.name}`;return n.pattern.test(r)?{name:o,status:"pass",message:"present"}:{name:o,status:"fail",message:`${As} lacks the shared e2e convention \u2014 expected: ${n.expected}`}})},Ya=async(e,t)=>[...fm(t),...await gm(e)];import Rw from"node:fs/promises";import Sw from"node:path";var Xa=async(e,t)=>Promise.all(t.map(async r=>{let n=await Rw.stat(Sw.join(e,r)).catch(()=>null);return n?n.isFile()?{name:`file:${r}`,status:"pass",message:"exists"}:{name:`file:${r}`,status:"fail",message:`not a file: ${r} (found a directory)`}:{name:`file:${r}`,status:"fail",message:`missing file: ${r}`}}));var Za=(e,t)=>t.map(r=>{let n=e[r];return typeof n!="string"?{name:`script:${r}`,status:"fail",message:`missing "${r}" in package.json scripts`}:n.trim().length===0?{name:`script:${r}`,status:"fail",message:`"${r}" is empty in package.json scripts`}:{name:`script:${r}`,status:"pass",message:"defined"}});import Pw from"node:fs/promises";import Ew from"node:path";var Lr="turbo.json",Qa=async(e,t)=>{if(t.length===0)return[];let r;try{let o=await Pw.readFile(Ew.join(e,Lr),"utf-8");r=JSON.parse(o)}catch(o){return[{name:Lr,status:"fail",message:`cannot read/parse ${Lr}: ${o.message}`}]}let n=r.tasks;return n===null||typeof n!="object"?[{name:Lr,status:"fail",message:`no "tasks" object defined in ${Lr}`}]:t.map(o=>{let s=o in n||`//#${o}`in n;return{name:`turbo:${o}`,status:s?"pass":"fail",message:s?"defined":`missing turbo task "${o}" in ${Lr}`}})};var Tw={adopted:!1,workspaceRoot:null},Cw=async(e,t,r)=>Vn({packageDir:e,repoRoot:r??e,pkgJson:t,declaredType:await Yt(e)}),ec=async(e,t=$t,r={})=>{let n=await zt(e),o=n.name??xw.basename(e),{check:s,rules:i}=await za(e,t),a=[s];r.isRoot||a.push(qa(e,r.adoption??Tw)),i&&(a.push(...Za(n.scripts??{},i.requiredScripts)),a.push(...await Xa(e,i.requiredFiles)),a.push(...await Qa(e,i.turboTasks))),!r.isRoot&&await Cw(e,n,r.repoRoot)==="e2e"&&a.push(...await Ya(e,n.scripts??{}));let c=a.every(l=>l.status==="pass");return{packageDir:e,packageName:o,checks:a,passed:c}};var tc=["plugin","marketplace","add",Et],rc=["plugin","install",H,"--scope","project"],hm=(e,t)=>qt({projectPath:e,home:t}).kind==="installed",nc=e=>((e??"").split(`
149
- `).find(r=>r.trim().length>0)??"").trim(),$w=(e,t)=>{if(Mn(t))return null;p.debug({msg:`Running: ${hs} ${tc.join(" ")}`});let r=e({args:tc});return r.ok?null:{step:"marketplace",error:nc(r.output)}},Aw=(e,t)=>{p.debug({msg:`Running: ${hs} ${ys.join(" ")}`});let r=e({args:ys,cwd:t});return r.ok?{status:"updated"}:{status:"update-failed",error:nc(r.output)}},oc=e=>{let{projectRoot:t,home:r}=e,n=e.run??Pa;if(!n({args:Sa}).ok)return{status:"claude-missing"};if(hm(t,r))return e.cliIsStale?.()===!0?{status:"skipped-cli-stale"}:Aw(n,t);let o=$w(n,r);if(o!==null)return{status:"failed",...o};p.debug({msg:`Running: ${hs} ${rc.join(" ")}`});let s=n({args:rc,cwd:t});return s.ok?hm(t,r)?{status:"installed"}:{status:"unverified"}:{status:"failed",step:"install",error:nc(s.output)}};import Ow from"node:fs";import Iw from"node:path";var Oe=".mcp.json",Ze="mcpServers",Dw="infra-kit",Nw=["mcp"],_w="/infra-kit/dist/mcp.js",sc=" ",tr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ym=e=>{if(!tr(e))return!1;let{command:t,args:r}=e;return Array.isArray(r)?t===Dw&&r[0]===Nw[0]?!0:r.some(n=>typeof n=="string"&&n.endsWith(_w)):!1},vm=e=>/\n([ \t]+)"/.exec(e)?.[1]??sc,ic=e=>{try{return{kind:"raw",raw:Ow.readFileSync(e,"utf-8")}}catch(t){return t.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable",error:t}}},ac=e=>{try{return JSON.parse(e)}catch{return}},cc=e=>e instanceof Error?e.message:String(e),qn=e=>{let t=ic(Iw.join(e,Oe));if(t.kind==="absent")return{kind:"missing-file"};if(t.kind==="unreadable")return{kind:"unparseable"};let r=ac(t.raw);if(!tr(r)||!tr(r[Ze]))return{kind:"unparseable"};let n=r[Ze];if(ae in n)return{kind:"stale"};let o=Object.keys(n).find(s=>ym(n[s]));return o===void 0?{kind:"absent"}:{kind:"wrong-key",key:o}};import Os from"node:fs";import Mw from"node:path";var pt=`claude plugin install ${H} --scope project`,Vr=`claude plugin update ${H} --scope project`,lc=`claude plugin marketplace add ${Et}`,km=" ",bm=()=>({source:{source:"github",repo:Et}}),jw=()=>({extraKnownMarketplaces:{[ae]:bm()},enabledPlugins:{[H]:!0}}),Rm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Fw=e=>/\n([ \t]+)"/.exec(e)?.[1]??km,wm=(e,t,r,n)=>{let o=e[t];return o===void 0?(e[t]={[r]:n},`${t}.${r}`):!Rm(o)||r in o?null:(o[r]=n,`${t}.${r}`)},Lw=e=>[wm(e,"extraKnownMarketplaces",ae,bm()),wm(e,"enabledPlugins",H,!0)].filter(r=>r!==null),Vw=e=>{try{return Os.readFileSync(e,"utf-8")}catch{return null}},Bw=e=>(Os.mkdirSync(Mw.dirname(e),{recursive:!0}),Os.writeFileSync(e,`${JSON.stringify(jw(),null,km)}
150
- `,"utf-8"),{status:"created",path:e,added:[`extraKnownMarketplaces.${ae}`,`enabledPlugins.${H}`]}),dc=e=>{let t=Vw(e);if(t===null)return Bw(e);let r;try{r=JSON.parse(t)}catch{r=void 0}if(!Rm(r))return p.warn(`Could not parse ${e} \u2014 left it untouched. Add "${H}" to enabledPlugins by hand, or fix the JSON and re-run: infra-kit setup --skip-tools`),{status:"unparseable",path:e,added:[]};let n=Lw(r);if(n.length===0)return{status:"unchanged",path:e,added:[]};let o=Fw(t),s=t.endsWith(`
142
+ `;var Xp="# infra-kit\n\nThis repository uses the **infra-kit** CLI for environment, worktree, and release workflows.\nThis block is generated by `ik audit --fix --root` \u2014 edit text _outside_ the markers, never inside.\n\n## Commands (`ik` = `pnpm exec infra-kit`)\n\n- `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.\n- `ik dev [preset|app]` / `ik dev-status` \u2014 run this worktree's dev servers, or report what is running. An app (`ik dev client`) runs its api and ui plus every backend its proxy routes can run locally; a `devServersPresets` name runs that preset; no name runs every app. Names are per-repo: an unknown one is refused with the presets and apps as choices, never guess one.\n- `ik e2e [--app <app>]` \u2014 run an app's Playwright suite locally: against this worktree's dev server when it runs, otherwise the package's `infraKitE2e()` Playwright config starts `ik dev <app> --reuse` for the run and stops it after. Plain `playwright test` / `pnpm e2e-test` behave the same way. `--cloud` runs against the deployed app instead \u2014 the URL the loaded env (`ik env-load -c <env>`) holds in the target app's `deployedUrlEnv` \u2014 previews, and needs `--yes`; `--dry-run` prints the target.\n- `ik worktrees add` / `worktrees list` / `worktrees remove` / `worktrees sync` \u2014 manage release and feature git worktrees.\n- `ik release create` / `release remove` / `release list` / `release deploy-all` / `release deploy-selected` / `release deliver` / `release edit` \u2014 release-branch and deploy flow.\n- `ik release merge-dev` \u2014 merge the dev branch into every release branch; `--keep-conflicts` hands off any real conflict to a CLI-owned resolution worktree, `--continue`/`--abort` resume or drop that hand-off. The `/infra-kit:merge-dev` skill is the agent entry point for the whole flow.\n- `ik audit` \u2014 audit packages against their `infra-kit.config.ts` rules (`--root`: the repo root against the `audit` block in `infra-kit.json`).\n- `ik audit --fix` \u2014 regenerate this repo's infra-kit guidance blocks (`--all` for every package, `--root` for this file).\n- `ik doctor` \u2014 check gh / doppler / aws install + auth and repo setup.\n- `ik setup` \u2014 set up infra-kit on this machine: shell integration, the Claude Code skills plugin, and the external CLIs (brew, git, aws, gh, doppler, portless).\n\n## Conventions\n\n- 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.\n- Config is split by level: repo-wide settings live in the root `infra-kit.json` (personal overrides in `~/.infra-kit/`), per-package settings in that package's `infra-kit.config.ts`. The root has no `infra-kit.config.ts`.\n- Environment variables are managed through Doppler via `ik env-load` \u2014 never commit secrets.\n- Every workspace package has its own CLAUDE.md with package-scoped rules \u2014 read it before editing that package.\n- Launch Claude Code at the repository root: the infra-kit plugin (the `/infra-kit:*` skills) and this repo's `.claude/settings.json` hooks load only from there. If the `/infra-kit:*` skills are absent, this is a subdirectory session \u2014 restart Claude Code at the root.\n\n## Agents\n\n- Agents drive the same CLI over Bash: `infra-kit <command> --agent --json`. There is no MCP server; the `/infra-kit:*` skills are the entry points and they run the CLI on `PATH`.\n- A confirm-gated command (`release create|remove|edit|merge-dev|deploy-all|deploy-selected`, `release merge-dev --continue|--abort`, `worktrees add|remove|sync`) previews its plan and exits without acting; re-run the same argv with `--yes` to execute. Never put a mutating command behind a prefix allow \u2014 that makes the `--yes` re-run unprompted (`ik doctor` warns on such a pattern).\n- `env-load`, `env-clear` and `infra-kit setup` have no confirm step and run once: the host's prompt on the argv is the approval. `release deliver` and `vendor sync` are human-only and are refused under agent mode.\n- A command that needs a human choice returns a structured `argument_required` refusal naming the option; pass the value instead of retrying.\n\n## Writing code\n\n- Comment the **why**, never the **what**. If a comment would only restate what the code already says (a name, a type, an obvious assignment), delete it \u2014 and if code needs a comment to be _understood_, prefer renaming/refactoring until it reads on its own. Reserve comments for the genuinely non-obvious: external quirks, ordering constraints, fail-safe branches, workarounds, business-logic definitions. Keep them compact. When a comment explains a bug, outage, or upstream issue, link the source of truth instead of describing it.\n- Unit tests are `*.test.ts(x)` in a `__tests__/` folder beside the code they test (`src/foo/__tests__/foo.test.ts`), never next to the source file; inside a frontend feature, all of them go in the feature root's `features/<name>/__tests__/`. `*.spec.ts` is only for Playwright specs in an e2e package. The `@wl/test-location` lint rule enforces it.\n";var Cr={"root/body":Xp.trimEnd(),"package/frontend":qp.trimEnd(),"package/backend":Kp.trimEnd(),"package/lib":Yp.trimEnd(),"package/e2e":Hp.trimEnd(),"package/mobile":zp.trimEnd(),"design/skeleton":Gp.trimEnd()};var ba=/\{\{(\w+)\}\}/g,Ov=/^- \{\{(\w+)\}\}$/,Iv=e=>new Set([...e.matchAll(ba)].map(t=>t[1])),Dv=(e,t)=>{let r=Object.keys(t).filter(n=>!e.has(n));if(r.length>0)throw new Error(`renderTemplate: variable(s) never used by the template: ${r.join(", ")}`)},Nv=(e,t)=>{let r=[...e].filter(n=>!(n in t));if(r.length>0)throw new Error(`renderTemplate: placeholder(s) with no variable: ${r.map(n=>`{{${n}}}`).join(", ")}`)},_v=(e,t)=>e.filter(r=>{let n=Ov.exec(r);return n===null||t[n[1]]!==""}),Mv=(e,t)=>{for(let r of e)for(let n of r.matchAll(ba)){let o=t[n[1]];if(o!==void 0&&o.includes(`
143
+ `)&&n.index!==0)throw new Error(`renderTemplate: multi-line value for {{${n[1]}}} must start its line (found at column ${n.index})`)}},$r=(e,t)=>{let r=Iv(e);Nv(r,t),Dv(r,t);let n=_v(e.split(`
144
+ `),t);return Mv(n,t),n.join(`
145
+ `).replace(ba,(o,s)=>t[s])};var jv="name: TODO",Ra=e=>{let t=$r(Cr["design/skeleton"],{packageName:e}),r=`name: ${e}`;return`${t.replace(jv,()=>r)}
146
+ `};var Fv=(e,t)=>`${Jt}${e} ${t} -->`,Lv="`README.md` \u2014 what this package is and how to run it.",Sa="docs/e2e-playwright.md",Bv=`\`${Sa}\` at the repo root \u2014 env setup, run modes, \`E2E_SLOW_MO\`, traces after a failure.`,Pa=e=>{let{version:t,type:r,packageName:n,relDir:o,hasReadme:s,hasE2eDoc:i}=e,a=$r(Cr[`package/${r}`],{packageName:n,relDir:o,type:r,readmeBullet:s?Lv:"",...r==="e2e"?{e2eDocBullet:i?Bv:""}:{}});return[Fv(t,r),"",a].join(`
147
+ `)};var Vv=e=>`${va}${e} -->`,Ea=e=>{let t=$r(Cr["root/body"],{});return[Vv(e),"",t].join(`
148
+ `)};import Ar from"node:fs";import Wv from"node:path";var fs=e=>{let t;try{t=Ar.lstatSync(e)}catch{return}if(t.isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},In=(e,t)=>{fs(e);let r=Ar.existsSync(e)?Ar.readFileSync(e,"utf-8"):null;return r===t?"unchanged":(Ar.mkdirSync(Wv.dirname(e),{recursive:!0}),Ar.writeFileSync(e,t,"utf-8"),r===null?"created":"updated")},xa=(e,t,r)=>{let n=Ar.readFileSync(e,"utf-8");if(!Je(n,t,r))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},Zp=(e,t,r)=>Je(e,t,r)?{before:e.slice(0,e.indexOf(t)),after:e.slice(e.indexOf(r)+r.length)}:null,Ta=(e,t,r,n)=>{let o=Zp(e,r,n),s=Zp(t,r,n);if(!(o===null||s===null)&&(o.before!==s.before||o.after!==s.after))throw new Error("Post-write validation failed: content outside the managed markers changed")};var hs="<!-- infra-kit:import:begin -->",ys="<!-- infra-kit:import:end -->",Uv="AGENTS.md",Qp="CLAUDE.md",Jv="README.md",Ca="DESIGN.md",Gv=["frontend","mobile"],Kv=e=>Ht.existsSync(e)?Ht.readFileSync(e,"utf-8"):null,$a=(e,t)=>{try{return Ht.readdirSync(e).includes(t)}catch{return!1}},gs=(e,t,r)=>{let n=t instanceof Error?t.message:String(t),o={path:e,action:"failed",message:n};return r&&(o.type=r),o},em=({filePath:e,body:t,startMarker:r,endMarker:n,prepare:o})=>{let s=Kv(e),i=s===null?"":o?.(s)??s,a=Er({content:i,body:t,startMarker:r,endMarker:n,placement:"replace-in-place"}),c=In(e,a);return xa(e,r,n),s!==null&&Ta(i,a,r,n),c},Hv=e=>{if(!Ht.existsSync(e))return"unchanged";fs(e);let t=Ht.readFileSync(e,"utf-8"),r=St(t,$e,Ge);return r===null?"unchanged":r.trim()===""?(Ht.rmSync(e),"removed"):In(e,r)},qv=(e,t)=>em({filePath:e,body:Ea(t),startMarker:$e,endMarker:Ge,prepare:r=>St(r,hs,ys)??r}),Dn=async(e,{version:t})=>{let r=Pt.join(e,Qp),n=Pt.join(e,Uv),o=[];try{o.push({path:r,action:qv(r,t)})}catch(s){o.push(gs(r,s))}try{o.push({path:n,action:Hv(n)})}catch(s){o.push(gs(n,s))}return o},Yv=(e,t,r)=>{if(!Gv.includes(r)||$a(e,Ca))return null;let n=Pt.join(e,Ca);try{return{path:n,action:In(n,Ra(t)),type:r}}catch(o){return gs(n,o,r)}},Nn=async(e,{repoRoot:t,version:r,design:n,declaredType:o})=>{let s=Pt.join(e,Qp),i=await Wt(e),a=i.name??Pt.basename(e),c=xn({packageDir:e,repoRoot:t,pkgJson:i,declaredType:o}),l=Pa({version:r,type:c,packageName:a,relDir:Pt.relative(t,e).split(Pt.sep).join("/"),hasReadme:$a(e,Jv),hasDesign:$a(e,Ca),hasE2eDoc:Ht.existsSync(Pt.join(t,Sa))}),d=[];try{d.push({path:s,action:em({filePath:s,body:l,startMarker:Ke,endMarker:ot}),type:c})}catch(p){d.push(gs(s,p,c))}if(n){let p=Yv(e,a,c);p&&d.push(p)}return d};import cw from"node:path";import tm from"node:path";var Aa="agent-guidance",_n="CLAUDE.md",zv="\u2014 run: infra-kit audit --fix",Xv={missing:`${_n} missing`,"no-block":`${_n} has no infra-kit block (expected ${Ke} \u2026 ${ot})`,malformed:`${_n} block is malformed (end marker precedes start, or body is empty)`,"foreign-block":`${_n} carries the ROOT infra-kit block (${$e}); a package needs the package block`},Zv=e=>e.adopted?` (workspace adopted: ${tm.relative(e.workspaceRoot,e.evidencePath)} carries a package block)`:"",Oa=(e,t)=>{let r=Gt(Kt(tm.join(e,_n)));if(r.state==="ok"){let s=r.version??"unknown",i=r.type??"unknown";return{name:Aa,status:"pass",message:`present (block from infra-kit ${s}, type ${i})`}}let n=`${Xv[r.state]} ${zv}`,o=r.state==="missing"?`${n}${Zv(t)}`:n;return t.adopted?{name:Aa,status:"fail",message:o}:{name:Aa,status:"pass",message:`not yet adopted \u2014 ${o}`}};import Qv from"node:path";var Ia=async(e,t=Rt)=>{try{let r=await $n(e,t);return{check:{name:re,status:"pass",message:"present and valid"},rules:r}}catch(r){return{check:{name:re,status:"fail",message:r.message},rules:null}}},rm="infra-kit.json",ew=async e=>await we(Qv.join(e,re))?{name:re,status:"fail",message:'retired at the repo root \u2014 root audit rules live in infra-kit.json "audit". Run `infra-kit audit --fix --root` to move them and delete the file'}:null,Da=async(e,t=Tn)=>{let r=await ew(e),n=r?[r]:[];try{let{audit:o={}}=await M();return{checks:[{name:rm,status:"pass",message:"present and valid"},...n],rules:Cn(o,t)}}catch(o){return{checks:[{name:rm,status:"fail",message:o.message},...n],rules:null}}};import tw from"node:fs/promises";import rw from"node:path";var vs="playwright.config.ts",nw=[{name:"slow-mo",pattern:/process\.env\.E2E_SLOW_MO/u,expected:"const SLOW_MO = Number(process.env.E2E_SLOW_MO ?? 0)"},{name:"launch-options",pattern:/launchOptions:\s*\{[^}]*\bslowMo\b/u,expected:"use.launchOptions: { slowMo: SLOW_MO }"},{name:"timeout-headroom",pattern:/\btimeout:[^\n]*\bSLOW_MO\b/u,expected:"timeout: <base> + SLOW_MO * 100"},{name:"trace",pattern:/trace:\s*process\.env\.CI\s*\?\s*'on-first-retry'\s*:\s*'retain-on-failure'/u,expected:"use.trace: process.env.CI ? 'on-first-retry' : 'retain-on-failure'"}],nm=e=>Object.entries(ga).map(([t,r])=>{let n=`e2e-script:${t}`,o=e[t];return typeof o!="string"||o.trim().length===0?{name:n,status:"fail",message:`missing "${t}" in package.json scripts \u2014 expected: ${r}`}:o.trim()!==r?{name:n,status:"fail",message:`"${t}" drifts from the shared e2e scripts \u2014 expected: ${r}`}:{name:n,status:"pass",message:"matches the shared e2e scripts"}}),om=async e=>{let t=rw.join(e,vs),r=await tw.readFile(t,"utf-8").catch(()=>null);return r===null?[{name:`e2e-config:${vs}`,status:"fail",message:`missing ${vs}`}]:nw.map(n=>{let o=`e2e-config:${n.name}`;return n.pattern.test(r)?{name:o,status:"pass",message:"present"}:{name:o,status:"fail",message:`${vs} lacks the shared e2e convention \u2014 expected: ${n.expected}`}})},Na=async(e,t)=>[...nm(t),...await om(e)];import ow from"node:fs/promises";import sw from"node:path";var _a=async(e,t)=>Promise.all(t.map(async r=>{let n=await ow.stat(sw.join(e,r)).catch(()=>null);return n?n.isFile()?{name:`file:${r}`,status:"pass",message:"exists"}:{name:`file:${r}`,status:"fail",message:`not a file: ${r} (found a directory)`}:{name:`file:${r}`,status:"fail",message:`missing file: ${r}`}}));var Ma=(e,t)=>t.map(r=>{let n=e[r];return typeof n!="string"?{name:`script:${r}`,status:"fail",message:`missing "${r}" in package.json scripts`}:n.trim().length===0?{name:`script:${r}`,status:"fail",message:`"${r}" is empty in package.json scripts`}:{name:`script:${r}`,status:"pass",message:"defined"}});import iw from"node:fs/promises";import aw from"node:path";var Or="turbo.json",ja=async(e,t)=>{if(t.length===0)return[];let r;try{let o=await iw.readFile(aw.join(e,Or),"utf-8");r=JSON.parse(o)}catch(o){return[{name:Or,status:"fail",message:`cannot read/parse ${Or}: ${o.message}`}]}let n=r.tasks;return n===null||typeof n!="object"?[{name:Or,status:"fail",message:`no "tasks" object defined in ${Or}`}]:t.map(o=>{let s=o in n||`//#${o}`in n;return{name:`turbo:${o}`,status:s?"pass":"fail",message:s?"defined":`missing turbo task "${o}" in ${Or}`}})};var lw=async(e,t)=>{let{check:r,rules:n}=await Ia(e,t);return{checks:[r],rules:n}},dw={adopted:!1,workspaceRoot:null},uw=async(e,t,r)=>xn({packageDir:e,repoRoot:r??e,pkgJson:t,declaredType:await Ut(e)}),Fa=async(e,t=Rt,r={})=>{let n=await Wt(e),o=n.name??cw.basename(e),{checks:s,rules:i}=r.isRoot?await Da(e,t):await lw(e,t);r.isRoot||s.push(Oa(e,r.adoption??dw)),i&&(s.push(...Ma(n.scripts??{},i.requiredScripts)),s.push(...await _a(e,i.requiredFiles)),s.push(...await ja(e,i.turboTasks))),!r.isRoot&&await uw(e,n,r.repoRoot)==="e2e"&&s.push(...await Na(e,n.scripts??{}));let a=s.every(c=>c.status==="pass");return{packageDir:e,packageName:o,checks:s,passed:a}};var La=["plugin","marketplace","add",wt],Ba=["plugin","install",K,"--scope","project"],sm=(e,t)=>Ft({projectPath:e,home:t}).kind==="installed",Va=e=>((e??"").split(`
149
+ `).find(r=>r.trim().length>0)??"").trim(),pw=(e,t)=>{if(kn(t))return null;u.debug({msg:`Running: ${ns} ${La.join(" ")}`});let r=e({args:La});return r.ok?null:{step:"marketplace",error:Va(r.output)}},mw=(e,t)=>{u.debug({msg:`Running: ${ns} ${os.join(" ")}`});let r=e({args:os,cwd:t});return r.ok?{status:"updated"}:{status:"update-failed",error:Va(r.output)}},Wa=e=>{let{projectRoot:t,home:r}=e,n=e.run??ia;if(!n({args:sa}).ok)return{status:"claude-missing"};if(sm(t,r))return e.cliIsStale?.()===!0?{status:"skipped-cli-stale"}:mw(n,t);let o=pw(n,r);if(o!==null)return{status:"failed",...o};u.debug({msg:`Running: ${ns} ${Ba.join(" ")}`});let s=n({args:Ba,cwd:t});return s.ok?sm(t,r)?{status:"installed"}:{status:"unverified"}:{status:"failed",step:"install",error:Va(s.output)}};import fw from"node:fs";import gw from"node:path";var Ae=".mcp.json",He="mcpServers",hw="infra-kit",yw=["mcp"],vw="/infra-kit/dist/mcp.js",Ua=" ",qt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),im=e=>{if(!qt(e))return!1;let{command:t,args:r}=e;return Array.isArray(r)?t===hw&&r[0]===yw[0]?!0:r.some(n=>typeof n=="string"&&n.endsWith(vw)):!1},am=e=>/\n([ \t]+)"/.exec(e)?.[1]??Ua,Ja=e=>{try{return{kind:"raw",raw:fw.readFileSync(e,"utf-8")}}catch(t){return t.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable",error:t}}},Ga=e=>{try{return JSON.parse(e)}catch{return}},Ka=e=>e instanceof Error?e.message:String(e),Mn=e=>{let t=Ja(gw.join(e,Ae));if(t.kind==="absent")return{kind:"missing-file"};if(t.kind==="unreadable")return{kind:"unparseable"};let r=Ga(t.raw);if(!qt(r)||!qt(r[He]))return{kind:"unparseable"};let n=r[He];if(se in n)return{kind:"stale"};let o=Object.keys(n).find(s=>im(n[s]));return o===void 0?{kind:"absent"}:{kind:"wrong-key",key:o}};import ws from"node:fs";import ww from"node:path";var st=`claude plugin install ${K} --scope project`,Ir=`claude plugin update ${K} --scope project`,Ha=`claude plugin marketplace add ${wt}`,lm=" ",dm=()=>({source:{source:"github",repo:wt}}),kw=()=>({extraKnownMarketplaces:{[se]:dm()},enabledPlugins:{[K]:!0}}),um=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),bw=e=>/\n([ \t]+)"/.exec(e)?.[1]??lm,cm=(e,t,r,n)=>{let o=e[t];return o===void 0?(e[t]={[r]:n},`${t}.${r}`):!um(o)||r in o?null:(o[r]=n,`${t}.${r}`)},Rw=e=>[cm(e,"extraKnownMarketplaces",se,dm()),cm(e,"enabledPlugins",K,!0)].filter(r=>r!==null),Sw=e=>{try{return ws.readFileSync(e,"utf-8")}catch{return null}},Pw=e=>(ws.mkdirSync(ww.dirname(e),{recursive:!0}),ws.writeFileSync(e,`${JSON.stringify(kw(),null,lm)}
150
+ `,"utf-8"),{status:"created",path:e,added:[`extraKnownMarketplaces.${se}`,`enabledPlugins.${K}`]}),qa=e=>{let t=Sw(e);if(t===null)return Pw(e);let r;try{r=JSON.parse(t)}catch{r=void 0}if(!um(r))return u.warn(`Could not parse ${e} \u2014 left it untouched. Add "${K}" to enabledPlugins by hand, or fix the JSON and re-run: infra-kit setup --skip-tools`),{status:"unparseable",path:e,added:[]};let n=Rw(r);if(n.length===0)return{status:"unchanged",path:e,added:[]};let o=bw(t),s=t.endsWith(`
151
151
  `)?`
152
- `:"";return Os.writeFileSync(e,`${JSON.stringify(r,null,o)}${s}`,"utf-8"),{status:"added",path:e,added:n}};var k=e=>[{type:"text",text:e}],R=e=>e;import Ww from"node:path";import Jw from"node:process";var Uw=["unchanged","created"],Gw=["unchanged","created","updated","removed","failed"],Sm=async(e,t,r)=>{let n=await Yt(e);return Kn(e,{repoRoot:t,version:q.version,design:r,declaredType:n})},Kw=async(e,t)=>{if(e.root)return Gn(t,{version:q.version});if(e.all){let n=[];for(let o of await ke(t))n.push(...await Sm(o,t,e.design));return n}let r=await Jn(e.cwd??Jw.cwd());return Sm(r,t,e.design)},Hw=e=>{let t=new Map;for(let n of e)t.set(n.action,(t.get(n.action)??0)+1);return`Agent guidance synced \u2014 ${Gw.filter(n=>Uw.includes(n)||(t.get(n)??0)>0).map(n=>`${t.get(n)??0} ${n}`).join(", ")} (infra-kit ${q.version})`},qw=(e,t)=>{for(let r of e){if(r.action==="unchanged")continue;let n=Ww.relative(t,r.path),o=r.type?` (${r.type})`:"",s=r.action==="failed"&&r.message?` \u2014 ${r.message}`:"";p.info(` ${r.action.padEnd(9)} ${n}${o}${s}`)}p.info(Hw(e))},zw=e=>{let t={path:e.path,action:e.action};return e.type&&(t.type=e.type),t},Pm=async(e,t)=>{let r=await x();Es();let n=await _r(t),o=await Kw(e,r);qw(o,r),Es();let s=await _r(t),i=!e.all&&!e.root;return{fixed:o.map(zw),adoptionFlipped:i&&!n.adopted&&s.adopted}};import xm from"node:fs";import Tm from"node:path";var pc="ik-mcp",Em=(e,t)=>{let r=["--name",e];for(let n of t.env)r.push("--env",n);for(let n of t.unset)r.push("--unset",n);return r.push("--",t.command,...t.args),{type:"stdio",command:pc,args:r}};var Is="run `infra-kit setup` (or `infra-kit audit --root --fix`)",Yw=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((r,n)=>r===t[n]),uc=e=>tr(e)&&e.command===pc,Xw=(e,t)=>({...e??{},type:t.type,command:t.command,args:t.args}),Zw=(e,t,r)=>{let n=[],o={...e},s=!1;for(let[i,a]of Object.entries(t)){let c=Em(i,a),l=e[i];if(l!==void 0&&!uc(l)){n.push({name:i,status:"conflict",message:`"${i}" is configured under mcp but .mcp.json already has a hand-written "${i}" server that is not ik-mcp \u2014 left it untouched. Remove that entry (or rename it) and ${Is}, or drop mcp.${i} from infra-kit.json`});continue}if(uc(l)&&l.type===c.type&&Yw(l.args,c.args)){n.push({name:i,status:"unchanged",message:""});continue}if(r){o[i]=Xw(l,c),s=!0,n.push({name:i,status:"written",message:""});continue}n.push({name:i,status:"drifted",message:l===void 0?`"${i}" is configured under mcp in infra-kit.json but has no .mcp.json entry \u2014 the entry is generated from that config: ${Is}`:`"${i}" in .mcp.json does not match its mcp.${i} config in infra-kit.json \u2014 infra-kit.json is the source and the .mcp.json entry is generated from it, so edit the config and regenerate: ${Is}`})}for(let[i,a]of Object.entries(e))Object.hasOwn(t,i)||!uc(a)||n.push({name:i,status:"stale",message:`"${i}" runs ik-mcp but there is no mcp.${i} in infra-kit.json \u2014 add it, or remove the entry: claude mcp remove ${i} --scope project`});return{entries:n,servers:o,changed:s}},Qw=(e,t,r)=>{let n=r===null?sc:vm(r),o=r===null||r.endsWith(`
152
+ `:"";return ws.writeFileSync(e,`${JSON.stringify(r,null,o)}${s}`,"utf-8"),{status:"added",path:e,added:n}};import Tw from"node:path";import Cw from"node:process";import Ya from"node:fs/promises";import pm from"node:path";var Ew="infra-kit.json",mm=["requiredScripts","requiredFiles","turbo"],jn=(e,t)=>[{path:e,action:"failed",message:t}],xw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),fm=async e=>{let t=pm.join(e,re),r=pm.join(e,Ew),n;try{n=await Pr(e)}catch(c){return jn(t,c.message)}if(!n)return[];let o={...n},s=Object.keys(o).filter(c=>!mm.includes(c));if(s.length>0)return jn(t,`declares ${s.join(", ")}, which mean nothing at the repo root \u2014 remove them, then re-run`);let i=Object.fromEntries(mm.filter(c=>o[c]!==void 0).map(c=>[c,o[c]])),a=[];if(Object.keys(i).length>0)try{let c=await Ya.stat(r),l=await Ya.readFile(r,"utf8"),d=JSON.parse(l);if(!xw(d))return jn(r,"is not a JSON object");if("audit"in d)return jn(r,`already has an "audit" block \u2014 merge ${re}'s rules into it by hand, then delete ${re}`);await Zu({path:r,raw:l,migrated:{...d,audit:i},expectedMtimeMs:c.mtimeMs}),a.push({path:r,action:"updated"})}catch(c){return jn(r,c.message)}try{await Ya.rm(t),a.push({path:t,action:"removed"})}catch(c){a.push({path:t,action:"failed",message:c.message})}return a};var $w=["unchanged","created"],Aw=["unchanged","created","updated","removed","failed"],gm=async(e,t,r)=>{let n=await Ut(e);return Nn(e,{repoRoot:t,version:G.version,design:r,declaredType:n})},Ow=async(e,t)=>{if(e.root)return[...await fm(t),...await Dn(t,{version:G.version})];if(e.all){let n=[];for(let o of await ke(t))n.push(...await gm(o,t,e.design));return n}let r=await On(e.cwd??Cw.cwd());return gm(r,t,e.design)},Iw=e=>{let t=new Map;for(let n of e)t.set(n.action,(t.get(n.action)??0)+1);return`Agent guidance synced \u2014 ${Aw.filter(n=>$w.includes(n)||(t.get(n)??0)>0).map(n=>`${t.get(n)??0} ${n}`).join(", ")} (infra-kit ${G.version})`},Dw=(e,t)=>{for(let r of e){if(r.action==="unchanged")continue;let n=Tw.relative(t,r.path),o=r.type?` (${r.type})`:"",s=r.action==="failed"&&r.message?` \u2014 ${r.message}`:"";u.info(` ${r.action.padEnd(9)} ${n}${o}${s}`)}u.info(Iw(e))},Nw=e=>{let t={path:e.path,action:e.action};return e.type&&(t.type=e.type),t},hm=async(e,t)=>{let r=await E();ms();let n=await Tr(t),o=await Ow(e,r);Dw(o,r),ms();let s=await Tr(t),i=!e.all&&!e.root;return{fixed:o.map(Nw),adoptionFlipped:i&&!n.adopted&&s.adopted}};import vm from"node:fs";import wm from"node:path";var za="ik-mcp",ym=(e,t)=>{let r=["--name",e];for(let n of t.env)r.push("--env",n);for(let n of t.unset)r.push("--unset",n);return r.push("--",t.command,...t.args),{type:"stdio",command:za,args:r}};var ks="run `infra-kit setup` (or `infra-kit audit --root --fix`)",_w=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((r,n)=>r===t[n]),Xa=e=>qt(e)&&e.command===za,Mw=(e,t)=>({...e??{},type:t.type,command:t.command,args:t.args}),jw=(e,t,r)=>{let n=[],o={...e},s=!1;for(let[i,a]of Object.entries(t)){let c=ym(i,a),l=e[i];if(l!==void 0&&!Xa(l)){n.push({name:i,status:"conflict",message:`"${i}" is configured under mcp but .mcp.json already has a hand-written "${i}" server that is not ik-mcp \u2014 left it untouched. Remove that entry (or rename it) and ${ks}, or drop mcp.${i} from infra-kit.json`});continue}if(Xa(l)&&l.type===c.type&&_w(l.args,c.args)){n.push({name:i,status:"unchanged",message:""});continue}if(r){o[i]=Mw(l,c),s=!0,n.push({name:i,status:"written",message:""});continue}n.push({name:i,status:"drifted",message:l===void 0?`"${i}" is configured under mcp in infra-kit.json but has no .mcp.json entry \u2014 the entry is generated from that config: ${ks}`:`"${i}" in .mcp.json does not match its mcp.${i} config in infra-kit.json \u2014 infra-kit.json is the source and the .mcp.json entry is generated from it, so edit the config and regenerate: ${ks}`})}for(let[i,a]of Object.entries(e))Object.hasOwn(t,i)||!Xa(a)||n.push({name:i,status:"stale",message:`"${i}" runs ik-mcp but there is no mcp.${i} in infra-kit.json \u2014 add it, or remove the entry: claude mcp remove ${i} --scope project`});return{entries:n,servers:o,changed:s}},Fw=(e,t,r)=>{let n=r===null?Ua:am(r),o=r===null||r.endsWith(`
153
153
  `)?`
154
- `:"";try{return xm.mkdirSync(Tm.dirname(e),{recursive:!0}),xm.writeFileSync(e,`${JSON.stringify(t,null,n)}${o}`,"utf-8"),!0}catch(s){return p.warn(`Could not write ${e} (${cc(s)}) \u2014 the ik-mcp entries were not updated.`),!1}},Ds=({projectRoot:e,proxies:t,write:r})=>{let n=Tm.join(e,Oe),o=ic(n);if(o.kind==="unreadable")return p.warn(`Could not read ${n} (${cc(o.error)}) \u2014 left it untouched.`),{status:"unreadable",path:n,entries:[],wrote:!1};let s=o.kind==="raw"?o.raw:null,i=s===null?{}:ac(s);if(!tr(i))return p.warn(`Could not parse ${n} \u2014 left it untouched. Fix the JSON, then ${Is}.`),{status:"unparseable",path:n,entries:[],wrote:!1};let a=i[Ze];if(a!==void 0&&!tr(a))return p.warn(`${n} has a "${Ze}" that is not an object \u2014 left it untouched.`),{status:"unparseable",path:n,entries:[],wrote:!1};let c=Zw(a??{},t,r);if(!c.changed)return{status:"ok",path:n,entries:c.entries,wrote:!1};let l=Qw(n,{...i,[Ze]:c.servers},s);return{status:l?"ok":"failed",path:n,entries:c.entries,wrote:l}};var Cm=async(e,t)=>{let r;try{r=(await D()).mcp}catch{return null}if(!r||Object.keys(r).length===0)return null;let n=Ds({projectRoot:e,proxies:r,write:t});if(n.status!=="ok"&&n.status!=="failed")return{packageDir:e,packageName:"mcp",checks:[{name:"mcp:.mcp.json",status:"fail",message:`${n.path} could not be read as JSON \u2014 fix it and re-run`}],passed:!1};let o=n.entries.filter(i=>i.status!=="unchanged"&&i.status!=="written"),s=o.length===0?[{name:"mcp:.mcp.json",status:"pass",message:"every mcp.<name> has a matching ik-mcp entry in .mcp.json"}]:o.map(i=>({name:`mcp:${i.name}`,status:"fail",message:i.message}));return{packageDir:e,packageName:"mcp",checks:s,passed:o.length===0}};var ek=(e,t)=>[...t.map(r=>({name:`devServersPresets:config:${r.app}`,status:"fail",message:`could not load apps/${r.app}/ui/infra-kit.config.ts (referenced by a preset proxy override): ${r.message}`})),...e.map(r=>({name:`devServersPresets:${r.preset}`,status:"fail",message:r.message}))],$m=async e=>{let t=(await D()).devServersPresets;if(!t||Object.keys(t).length===0)return null;let r=Tu(t);if(r.length>0){let d=r.map(u=>({name:`devServersPresets:${u.preset}`,status:"fail",message:u.message}));return{packageDir:e,packageName:"devServersPresets",checks:d,passed:!1}}let n=Eu(e),o=xu(e),s={api:n.map(d=>d.name),ui:o.map(d=>d.name)},{ctx:i,loadErrors:a}=await $u(e,t,s,n),c=ek(Cu(t,i),a),l=c.length===0?[{name:"devServersPresets:proxy-locality",status:"pass",message:"every local proxy override resolves to a backend the preset launches"}]:c;return{packageDir:e,packageName:"devServersPresets",checks:l,passed:c.length===0}};var tk="workspace adopted \u2014 every other package now needs a CLAUDE.md: run infra-kit audit --fix --all",rk=async e=>e.root?[{dir:await x(),baseline:Aa,isRoot:!0}]:e.all?(await ke(await x())).map(r=>({dir:r})):[{dir:await Jn(e.cwd??Am.cwd())}],nk=async e=>e.root||e.all?await x():e.cwd??Am.cwd(),ok=async()=>{try{return await x()}catch{return}},sk=e=>{let t=0,r=0;for(let i of e)for(let a of i.checks)t+=1,a.status!=="pass"&&(r+=1,p.info(`[FAIL] ${i.packageName} ${a.name}: ${a.message}`));let n=e.every(i=>i.passed),o=(i,a)=>`${i} ${a}${i===1?"":"s"}`,s=`${o(t,"check")}, ${o(e.length,"target")}`;return p.info(n?`\u2705 audit passed \u2014 ${s}`:`\u274C audit failed \u2014 ${r}/${s}`),n},ik=async(e,t)=>{let{fixed:r,adoptionFlipped:n}=await Pm(e,t);return n&&p.info(tk),r},ak=e=>{if(qn(e).kind!=="stale")return null;let t=`${Oe} still registers "${ae}" \u2014 delete this key: the plugin no longer serves an MCP server and the entry spawns a retired subcommand that exits immediately (Claude Code lists it as failed). Delete the "${ae}" entry by hand in a PR, keeping its siblings`;return p.info(`[INFO] mcp mcp:legacy-key: ${t}`),{packageDir:e,packageName:"mcp",checks:[{name:"mcp:legacy-key",status:"pass",message:t}],passed:!0}},Ns=async(e={})=>{let t=ja(await nk(e)),r=e.fix?await ik(e,t):void 0,n=await rk(e),o=await _r(t),s=await ok(),i=[];for(let l of n)i.push(await ec(l.dir,l.baseline,{adoption:o,isRoot:l.isRoot,repoRoot:s}));if(e.root){let l=await $m(n[0].dir);l&&i.push(l);let d=await Cm(n[0].dir,e.fix===!0);d&&i.push(d);let u=ak(n[0].dir);u&&i.push(u)}let c={allPassed:sk(i),packages:i.map(l=>({name:l.packageName,passed:l.passed,checks:l.checks}))};return r&&(c.fixed=r),{content:k(JSON.stringify(c,null,2)),structuredContent:c}},ck={all:Ie.boolean().optional().describe("Audit every non-vendor workspace package"),root:Ie.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},lk={allPassed:Ie.boolean().describe("Whether every audited package passed all checks"),packages:Ie.array(Ie.object({name:Ie.string(),passed:Ie.boolean(),checks:Ie.array(Ie.object({name:Ie.string(),status:Ie.enum(["pass","fail"]),message:Ie.string()}))})).describe("Per-package check results")},mc=R({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:ck,outputSchema:lk,handler:e=>Ns({all:e.all,root:e.root})});import{z as zn}from"zod";var _s=async()=>{let[e,t]=await Promise.all([D(),te()]),r=Object.keys(e).sort();p.info(`Merged config for ${t.projectName} \u2014 ${r.length} section(s): ${r.join(", ")}`),p.info(` source: ${t.main}`);let n={config:e,configPath:t.main,projectName:t.projectName};return{content:k(JSON.stringify(n,null,2)),structuredContent:n}},dk={config:zn.record(zn.string(),zn.unknown()).describe("The fully resolved infra-kit configuration \u2014 the same object every command sees at runtime, after the project infra-kit.json, the user-global, and the user-scope per-project override layers are merged (later layers win). Top-level sections include envManagement, ide, worktrees, dev, devServersPresets, and protectedEnvs."),configPath:zn.string().describe("Absolute path to the project-level infra-kit.json (the base layer / committed source of truth)."),projectName:zn.string().describe("Repository name the config is keyed to (the main-repo basename; shared across all worktrees of the repo).")},fc=R({name:"config-get",description:"Return the fully merged infra-kit configuration (project + user-global + per-project override layers) as it is resolved at runtime. Read-only introspection \u2014 makes no changes; use `config edit` (CLI-only) to modify the per-machine override file (every key except `mcp`, which is project-layer only and refused there). Fails with the loader error when run outside a configured infra-kit repo, or when an override layer carries a refused key.",inputSchema:{},outputSchema:dk,handler:()=>_s()});import hk from"node:fs";import{z as ce}from"zod";import Yn from"node:fs";import Br from"node:path";import pk from"node:process";var uk=Br.join(".infra-kit","dev-context"),mk=".infra-kit",Om=(e,t)=>{let r=Br.resolve(e);for(;;){let n=Br.join(r,t);if(Yn.existsSync(n))return n;let o=Br.dirname(r);if(o===r)return;r=o}},fk=e=>{let t=Om(e,uk);if(t)return t;let r=Om(e,mk);return r?Br.join(r,"dev-context"):void 0},gc=e=>typeof e=="number"&&Number.isFinite(e)?e:0,Ms=e=>typeof e=="string"?e:"",gk=(e,t,r)=>{let n=Br.join(e,t);try{let o=Yn.statSync(n),s=JSON.parse(Yn.readFileSync(n,"utf-8"));if(typeof s!="object"||s===null)return null;let i=s;return{app:t.replace(/\.json$/,""),package:Ms(i.package),port:gc(i.port),alias:Ms(i.alias),origin:Ms(i.origin),release:Ms(i.release),pid:gc(i.pid),writtenAt:gc(i.writtenAt),mtimeMs:Math.round(o.mtimeMs),ageMs:Math.max(0,Math.round(r-o.mtimeMs))}}catch{return null}},hc=(e=pk.cwd())=>{let t=Date.now(),r=fk(e);if(!r||!Yn.existsSync(r))return{session:"none",fragmentDir:r,readAt:t,apps:[]};let n;try{n=Yn.readdirSync(r).filter(s=>s.endsWith(".json"))}catch{return{session:"none",fragmentDir:r,readAt:t,apps:[]}}let o=n.map(s=>gk(r,s,t)).filter(s=>s!==null).sort((s,i)=>s.app.localeCompare(i.app));return{session:o.length>0?"active":"none",fragmentDir:r,readAt:t,apps:o}};var js=async(e={})=>{let t=e.now??Date.now,r=e.isListening??Dn,n=hc(e.cwd),o=t(),s=await Promise.all(n.apps.map(async u=>{let m=Math.max(0,Math.round((o-u.mtimeMs)/1e3)),g=await r(u.port);return{app:u.app,package:u.package,port:u.port,pid:u.pid,alias:u.alias,origin:u.origin,release:u.release,writtenAt:u.writtenAt>0?new Date(u.writtenAt).toISOString():null,fragmentMtime:new Date(u.mtimeMs).toISOString(),ageSeconds:m,live:g}})),i=s.length>0,a=n.fragmentDir??null,c=a!==null&&(hk.statSync(a,{throwIfNoEntry:!1})?.isDirectory()??!1),l=a===null?"nothing (no .infra-kit anchor exists up-tree)":a;if(i){p.info(`infra-kit dev: ${s.length} app(s) with a dev-context fragment in ${l}:`);for(let u of s){let m=u.live?"live":"NOT responding",g=`written ${u.ageSeconds}s ago`;p.info(` ${u.app} (${u.package}) \u2192 ${u.origin} on :${u.port} \u2014 ${m}, ${g}`)}}else{let u=c?"no readable fragment found there":"that directory does not exist";p.info(`No active infra-kit dev session \u2014 searched ${l} (${u}).`)}let d={active:i,apps:s,contextDir:a,contextDirExists:c};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}},yk={active:ce.boolean().describe("True when at least one dev-context fragment exists on disk (an infra-kit dev session has apps registered). False means no active dev session was found \u2014 this is a clean result, NOT an error."),contextDir:ce.string().nullable().describe("The RESOLVED dev-context fragment directory \u2014 found by searching UPWARD from the working directory. This is where the read looked, NOT proof anything is there: when no fragment directory exists the resolver derives one from an up-tree `.infra-kit`, so this can name a path (even under $HOME) that was never written to. Check contextDirExists before drawing any conclusion from it. Null when no `.infra-kit` anchor exists up-tree at all."),contextDirExists:ce.boolean().describe('Whether contextDir actually exists on disk. False with a non-null contextDir means the path was DERIVED, not read \u2014 the usual state in a repo where `infra-kit dev` has never run. Distinguishes "looked and found nothing" from "had nowhere to look".'),apps:ce.array(ce.object({app:ce.string().describe("App folder name (the fragment filename without .json)."),package:ce.string().describe("The app package name the vite helper reads to decide a local route."),port:ce.number().describe("The actual bound port the dev server is listening on."),pid:ce.number().describe("PID of the dev-server process that wrote the fragment (ownership / staleness metadata)."),alias:ce.string().describe("Registered portless hostname for the app."),origin:ce.string().describe("Authoritative local origin the vite helper proxies to for this app."),release:ce.string().describe("Release slug the runner recorded for this worktree."),writtenAt:ce.string().nullable().describe("ISO 8601 time the runner self-reported writing the fragment (writer clock \u2014 may be wrong; prefer fragmentMtime). Null when the fragment did not record it."),fragmentMtime:ce.string().describe("ISO 8601 filesystem mtime of the fragment file \u2014 the AUTHORITATIVE freshness signal."),ageSeconds:ce.number().describe("Seconds since the fragment was last written on disk. A large value with live:false means a stale/abandoned fragment."),live:ce.boolean().describe("Whether a TCP connection to the app port succeeds RIGHT NOW (a real engine liveness probe, not an inference). A fresh fragment with live:false is a crashed or killed dev server whose fragment was not cleaned up.")})).describe("One entry per dev-context fragment on disk, sorted by app name. Empty when no dev session is active.")},yc=R({name:"dev-status",description:"Report what `infra-kit dev` currently has running by READING the on-disk dev-context fragments (never starts a server). Advisory + read-only: surfaces each app\u2019s package, bound port, portless alias, local origin, fragment freshness (mtime / ageSeconds), and a live TCP liveness probe of the port. The fragment directory is found by searching UPWARD from the working directory, so this agrees with the `infra-kit://dev-context` resource and with the vite helper\u2019s routing decision; `contextDir` / `contextDirExists` report where it looked and whether that directory is real. Returns { active: false, apps: [] } when no dev session is active.",inputSchema:{},outputSchema:yk,handler:()=>js()});import{spawnSync as Sg}from"node:child_process";import re from"node:fs";import Pg from"node:os";import pe from"node:path";import ot from"node:process";import{z as fe}from"zod";import{execFileSync as vk}from"node:child_process";var Im=(e,t)=>{let r=e.filter(n=>!n.live).map(n=>n.name);return t?{prunable:[],withheld:r}:{prunable:r,withheld:[]}},wk=[/\binfra-kit\s+dev\b/,/cli\.js\s+dev\b/,/dev-server\.(?:js|ts)\b/],kk=e=>wk.some(t=>t.test(e)),bk="/bin/ps",Rk=()=>vk(bk,["-eo","command="],{encoding:"utf8",maxBuffer:8<<20}).split(`
155
- `),Dm=(e=Rk)=>{try{return e().some(kk)}catch{return!0}};import{Chalk as Sk}from"chalk";import vc from"node:process";var wc={unicode:{ok:"\u2713",changed:"+",skipped:"-",manual:">",warn:"!",fail:"\u2717",separator:"\xB7",rule:"\u2500"},ascii:{ok:"ok",changed:"++",skipped:"--",manual:">>",warn:"!?",fail:"!!",separator:"-",rule:"-"}},Pk=new Set(["warn","fail"]),Ek=24,Wr=" ",Nm=" ",xk=(e,t)=>{let r=e.split(/\s+/).filter(s=>s.length>0),n=[],o="";for(let s of r)o.length===0?o=s:`${o} ${s}`.length<=t?o=`${o} ${s}`:(n.push(o),o=s);return o.length>0&&n.push(o),n.length>0?n:[""]},_m=e=>{let t={ok:0,changed:0,skipped:0,manual:0,warn:0,fail:0};for(let r of e)t[r.status]+=1;return t},Tk=e=>{let t=new Sk({level:e?1:0});return{header:r=>t.bold.cyan(r),ok:r=>t.green(r),changed:r=>t.green(r),skipped:r=>t.gray(r),manual:r=>t.cyan(r),fail:r=>t.red(r),warn:r=>t.yellow(r),dim:r=>t.dim(r),bold:r=>t.bold(r)}},Mm=(e,t)=>[{status:"changed",plain:`${e.changed} changed`},{status:"skipped",plain:`${e.skipped} skipped`},{status:"manual",plain:`${e.manual} to run yourself`},{status:"fail",plain:`${e.fail} failed`},{status:"warn",plain:`${e.warn} ${t(e.warn)}`}].filter(n=>e[n.status]>0),Ck=(e,t,r,n)=>{if(e.ok===t){let c=`${t}/${t} ok`;return{text:r.ok(c),plainWidth:c.length}}let o=`${e.ok+e.changed}/${t}`,s=Mm(e,c=>`warning${c===1?"":"s"}`),i=[r.dim(o),...s.map(c=>r[c.status](c.plain))].join(` ${n.separator} `),a=s.reduce((c,l)=>c+l.plain.length+3,o.length);return{text:i,plainWidth:a}},$k=(e,t,r,n)=>{let o=Ck(_m(e.rows),e.rows.length,t,r),s=Math.max(1,n-Wr.length-e.label.length-o.plainWidth);return`${Wr}${t.header(e.label)}${" ".repeat(s)}${o.text}`},Ak=(e,t,r,n,o)=>{let s=Pk.has(e.status),i=n.ok.length,a=e.name.padEnd(t),c=r[e.status],l=s?c(a):a,d=Nm.length+i+1+t+2,u=Math.max(Ek,o-d),[m,...g]=xk(e.message,u),y=" ".repeat(d),S=C=>s?C:r.dim(C);return[`${Nm}${c(n[e.status])} ${l} ${S(m??"")}`.trimEnd(),...g.map(C=>`${y}${S(C)}`),...(e.notes??[]).map(C=>`${y}${C}`.trimEnd())]},Ok=(e,t,r,n,o)=>{let s=_m(t),i=n.rule.repeat(Math.max(12,Math.min(o-Wr.length,56))),a=Mm(s,()=>"warned"),c=[r.ok(`${s.ok} passed`),...a.map(d=>r[d.status](d.plain))].join(` ${n.separator} `),l=(e.hints??[]).map(d=>` ${r.dim(d)}`);return[`${Wr}${r.dim(i)}`,`${Wr}${c}${l.join("")}`]},kc=(e,t={})=>{let r=t.width??80,n=Tk(t.color??!1),o=t.unicode??!0?wc.unicode:wc.ascii,s=e.sections.filter(d=>d.rows.length>0),i=s.flatMap(d=>d.rows),a=n.bold(e.title);if(i.length===0)return[a,"",`${Wr}${n.dim(e.emptyMessage??"Nothing ran.")}`];let c=Math.max(...i.map(d=>d.name.length)),l=s.flatMap(d=>[$k(d,n,o,r),...d.rows.flatMap(u=>Ak(u,c,n,o,r)),""]);return[a,"",...l,...Ok(e,i,n,o,r)]},Ik=new Set(["","0","false","none"]),Dk=["LC_ALL","LC_CTYPE","LANG"],Nk=(e,t)=>e.NO_COLOR!==void 0&&e.NO_COLOR!==""?!1:e.FORCE_COLOR!==void 0?!Ik.has(e.FORCE_COLOR.toLowerCase()):!!t.isTTY,_k=(e,t)=>{if(t)return!1;let r=Dk.map(n=>e[n]).find(n=>n!==void 0&&n!=="");return r===void 0?!0:/UTF-?8/i.test(r)},bc=(e={})=>{let t=e.env??vc.env,r=e.stream??vc.stderr;return{color:Nk(t,r),unicode:_k(t,e.ascii??!1),width:r.columns??80}},It=(e,t={})=>{(t.write??(n=>{vc.stderr.write(n)}))(`${kc(e,bc(t)).join(`
154
+ `:"";try{return vm.mkdirSync(wm.dirname(e),{recursive:!0}),vm.writeFileSync(e,`${JSON.stringify(t,null,n)}${o}`,"utf-8"),!0}catch(s){return u.warn(`Could not write ${e} (${Ka(s)}) \u2014 the ik-mcp entries were not updated.`),!1}},bs=({projectRoot:e,proxies:t,write:r})=>{let n=wm.join(e,Ae),o=Ja(n);if(o.kind==="unreadable")return u.warn(`Could not read ${n} (${Ka(o.error)}) \u2014 left it untouched.`),{status:"unreadable",path:n,entries:[],wrote:!1};let s=o.kind==="raw"?o.raw:null,i=s===null?{}:Ga(s);if(!qt(i))return u.warn(`Could not parse ${n} \u2014 left it untouched. Fix the JSON, then ${ks}.`),{status:"unparseable",path:n,entries:[],wrote:!1};let a=i[He];if(a!==void 0&&!qt(a))return u.warn(`${n} has a "${He}" that is not an object \u2014 left it untouched.`),{status:"unparseable",path:n,entries:[],wrote:!1};let c=jw(a??{},t,r);if(!c.changed)return{status:"ok",path:n,entries:c.entries,wrote:!1};let l=Fw(n,{...i,[He]:c.servers},s);return{status:l?"ok":"failed",path:n,entries:c.entries,wrote:l}};var km=async(e,t)=>{let r;try{r=(await M()).mcp}catch{return null}if(!r||Object.keys(r).length===0)return null;let n=bs({projectRoot:e,proxies:r,write:t});if(n.status!=="ok"&&n.status!=="failed")return{packageDir:e,packageName:"mcp",checks:[{name:"mcp:.mcp.json",status:"fail",message:`${n.path} could not be read as JSON \u2014 fix it and re-run`}],passed:!1};let o=n.entries.filter(i=>i.status!=="unchanged"&&i.status!=="written"),s=o.length===0?[{name:"mcp:.mcp.json",status:"pass",message:"every mcp.<name> has a matching ik-mcp entry in .mcp.json"}]:o.map(i=>({name:`mcp:${i.name}`,status:"fail",message:i.message}));return{packageDir:e,packageName:"mcp",checks:s,passed:o.length===0}};var Lw=(e,t)=>[...t.map(r=>({name:`devServersPresets:config:${r.app}`,status:"fail",message:`could not load apps/${r.app}/ui/infra-kit.config.ts (referenced by a preset proxy override): ${r.message}`})),...e.map(r=>({name:`devServersPresets:${r.preset}`,status:"fail",message:r.message}))],bm=async e=>{let t=(await M()).devServersPresets;if(!t||Object.keys(t).length===0)return null;let r=lp(t);if(r.length>0){let d=r.map(p=>({name:`devServersPresets:${p.preset}`,status:"fail",message:p.message}));return{packageDir:e,packageName:"devServersPresets",checks:d,passed:!1}}let n=ap(e),o=cp(e),s={api:n.map(d=>d.name),ui:o.map(d=>d.name)},{ctx:i,loadErrors:a}=await up(e,t,s,n),c=Lw(dp(t,i),a),l=c.length===0?[{name:"devServersPresets:proxy-locality",status:"pass",message:"every local proxy override resolves to a backend the preset launches"}]:c;return{packageDir:e,packageName:"devServersPresets",checks:l,passed:c.length===0}};var Bw="workspace adopted \u2014 every other package now needs a CLAUDE.md: run infra-kit audit --fix --all",Vw=async e=>e.root?[{dir:await E(),baseline:Tn,isRoot:!0}]:e.all?(await ke(await E())).map(r=>({dir:r})):[{dir:await On(e.cwd??Rm.cwd())}],Ww=async e=>e.root||e.all?await E():e.cwd??Rm.cwd(),Uw=async()=>{try{return await E()}catch{return}},Jw=e=>{let t=0,r=0;for(let i of e)for(let a of i.checks)t+=1,a.status!=="pass"&&(r+=1,u.info(`[FAIL] ${i.packageName} ${a.name}: ${a.message}`));let n=e.every(i=>i.passed),o=(i,a)=>`${i} ${a}${i===1?"":"s"}`,s=`${o(t,"check")}, ${o(e.length,"target")}`;return u.info(n?`\u2705 audit passed \u2014 ${s}`:`\u274C audit failed \u2014 ${r}/${s}`),n},Gw=async(e,t)=>{let{fixed:r,adoptionFlipped:n}=await hm(e,t);return n&&u.info(Bw),r},Kw=e=>{if(Mn(e).kind!=="stale")return null;let t=`${Ae} still registers "${se}" \u2014 delete this key: the plugin no longer serves an MCP server and the entry spawns a retired subcommand that exits immediately (Claude Code lists it as failed). Delete the "${se}" entry by hand in a PR, keeping its siblings`;return u.info(`[INFO] mcp mcp:legacy-key: ${t}`),{packageDir:e,packageName:"mcp",checks:[{name:"mcp:legacy-key",status:"pass",message:t}],passed:!0}},Rs=async(e={})=>{let t=ka(await Ww(e)),r=e.fix?await Gw(e,t):void 0,n=await Vw(e),o=await Tr(t),s=await Uw(),i=[];for(let l of n)i.push(await Fa(l.dir,l.baseline,{adoption:o,isRoot:l.isRoot,repoRoot:s}));if(e.root){let l=await bm(n[0].dir);l&&i.push(l);let d=await km(n[0].dir,e.fix===!0);d&&i.push(d);let p=Kw(n[0].dir);p&&i.push(p)}let c={allPassed:Jw(i),packages:i.map(l=>({name:l.packageName,passed:l.passed,checks:l.checks}))};return r&&(c.fixed=r),{content:k(JSON.stringify(c,null,2)),structuredContent:c}},Hw={all:Oe.boolean().optional().describe("Audit every non-vendor workspace package"),root:Oe.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},qw={allPassed:Oe.boolean().describe("Whether every audited package passed all checks"),packages:Oe.array(Oe.object({name:Oe.string(),passed:Oe.boolean(),checks:Oe.array(Oe.object({name:Oe.string(),status:Oe.enum(["pass","fail"]),message:Oe.string()}))})).describe("Per-package check results")},Za=S({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:Hw,outputSchema:qw,handler:e=>Rs({all:e.all,root:e.root})});import{z as Fn}from"zod";var Ss=async()=>{let[e,t]=await Promise.all([M(),Q()]),r=Object.keys(e).sort();u.info(`Merged config for ${t.projectName} \u2014 ${r.length} section(s): ${r.join(", ")}`),u.info(` source: ${t.main}`);let n={config:e,configPath:t.main,projectName:t.projectName};return{content:k(JSON.stringify(n,null,2)),structuredContent:n}},Yw={config:Fn.record(Fn.string(),Fn.unknown()).describe("The fully resolved infra-kit configuration \u2014 the same object every command sees at runtime, after the project infra-kit.json, the user-global, and the user-scope per-project override layers are merged (later layers win). Top-level sections include envManagement, ide, worktrees, dev, devServersPresets, and protectedEnvs."),configPath:Fn.string().describe("Absolute path to the project-level infra-kit.json (the base layer / committed source of truth)."),projectName:Fn.string().describe("Repository name the config is keyed to (the main-repo basename; shared across all worktrees of the repo).")},Qa=S({name:"config-get",description:"Return the fully merged infra-kit configuration (project + user-global + per-project override layers) as it is resolved at runtime. Read-only introspection \u2014 makes no changes; use `config edit` (CLI-only) to modify the per-machine override file (every key except `mcp`, which is project-layer only and refused there). Fails with the loader error when run outside a configured infra-kit repo, or when an override layer carries a refused key.",inputSchema:{},outputSchema:Yw,handler:()=>Ss()});import tk from"node:fs";import{z as ie}from"zod";import Ln from"node:fs";import Dr from"node:path";import zw from"node:process";var Xw=Dr.join(".infra-kit","dev-context"),Zw=".infra-kit",Sm=(e,t)=>{let r=Dr.resolve(e);for(;;){let n=Dr.join(r,t);if(Ln.existsSync(n))return n;let o=Dr.dirname(r);if(o===r)return;r=o}},Qw=e=>{let t=Sm(e,Xw);if(t)return t;let r=Sm(e,Zw);return r?Dr.join(r,"dev-context"):void 0},ec=e=>typeof e=="number"&&Number.isFinite(e)?e:0,Ps=e=>typeof e=="string"?e:"",ek=(e,t,r)=>{let n=Dr.join(e,t);try{let o=Ln.statSync(n),s=JSON.parse(Ln.readFileSync(n,"utf-8"));if(typeof s!="object"||s===null)return null;let i=s;return{app:t.replace(/\.json$/,""),package:Ps(i.package),port:ec(i.port),alias:Ps(i.alias),origin:Ps(i.origin),release:Ps(i.release),pid:ec(i.pid),writtenAt:ec(i.writtenAt),mtimeMs:Math.round(o.mtimeMs),ageMs:Math.max(0,Math.round(r-o.mtimeMs))}}catch{return null}},tc=(e=zw.cwd())=>{let t=Date.now(),r=Qw(e);if(!r||!Ln.existsSync(r))return{session:"none",fragmentDir:r,readAt:t,apps:[]};let n;try{n=Ln.readdirSync(r).filter(s=>s.endsWith(".json"))}catch{return{session:"none",fragmentDir:r,readAt:t,apps:[]}}let o=n.map(s=>ek(r,s,t)).filter(s=>s!==null).sort((s,i)=>s.app.localeCompare(i.app));return{session:o.length>0?"active":"none",fragmentDir:r,readAt:t,apps:o}};var Es=async(e={})=>{let t=e.now??Date.now,r=e.isListening??yn,n=tc(e.cwd),o=t(),s=await Promise.all(n.apps.map(async p=>{let m=Math.max(0,Math.round((o-p.mtimeMs)/1e3)),g=await r(p.port);return{app:p.app,package:p.package,port:p.port,pid:p.pid,alias:p.alias,origin:p.origin,release:p.release,writtenAt:p.writtenAt>0?new Date(p.writtenAt).toISOString():null,fragmentMtime:new Date(p.mtimeMs).toISOString(),ageSeconds:m,live:g}})),i=s.length>0,a=n.fragmentDir??null,c=a!==null&&(tk.statSync(a,{throwIfNoEntry:!1})?.isDirectory()??!1),l=a===null?"nothing (no .infra-kit anchor exists up-tree)":a;if(i){u.info(`infra-kit dev: ${s.length} app(s) with a dev-context fragment in ${l}:`);for(let p of s){let m=p.live?"live":"NOT responding",g=`written ${p.ageSeconds}s ago`;u.info(` ${p.app} (${p.package}) \u2192 ${p.origin} on :${p.port} \u2014 ${m}, ${g}`)}}else{let p=c?"no readable fragment found there":"that directory does not exist";u.info(`No active infra-kit dev session \u2014 searched ${l} (${p}).`)}let d={active:i,apps:s,contextDir:a,contextDirExists:c};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}},rk={active:ie.boolean().describe("True when at least one dev-context fragment exists on disk (an infra-kit dev session has apps registered). False means no active dev session was found \u2014 this is a clean result, NOT an error."),contextDir:ie.string().nullable().describe("The RESOLVED dev-context fragment directory \u2014 found by searching UPWARD from the working directory. This is where the read looked, NOT proof anything is there: when no fragment directory exists the resolver derives one from an up-tree `.infra-kit`, so this can name a path (even under $HOME) that was never written to. Check contextDirExists before drawing any conclusion from it. Null when no `.infra-kit` anchor exists up-tree at all."),contextDirExists:ie.boolean().describe('Whether contextDir actually exists on disk. False with a non-null contextDir means the path was DERIVED, not read \u2014 the usual state in a repo where `infra-kit dev` has never run. Distinguishes "looked and found nothing" from "had nowhere to look".'),apps:ie.array(ie.object({app:ie.string().describe("App folder name (the fragment filename without .json)."),package:ie.string().describe("The app package name the vite helper reads to decide a local route."),port:ie.number().describe("The actual bound port the dev server is listening on."),pid:ie.number().describe("PID of the dev-server process that wrote the fragment (ownership / staleness metadata)."),alias:ie.string().describe("Registered portless hostname for the app."),origin:ie.string().describe("Authoritative local origin the vite helper proxies to for this app."),release:ie.string().describe("Release slug the runner recorded for this worktree."),writtenAt:ie.string().nullable().describe("ISO 8601 time the runner self-reported writing the fragment (writer clock \u2014 may be wrong; prefer fragmentMtime). Null when the fragment did not record it."),fragmentMtime:ie.string().describe("ISO 8601 filesystem mtime of the fragment file \u2014 the AUTHORITATIVE freshness signal."),ageSeconds:ie.number().describe("Seconds since the fragment was last written on disk. A large value with live:false means a stale/abandoned fragment."),live:ie.boolean().describe("Whether a TCP connection to the app port succeeds RIGHT NOW (a real engine liveness probe, not an inference). A fresh fragment with live:false is a crashed or killed dev server whose fragment was not cleaned up.")})).describe("One entry per dev-context fragment on disk, sorted by app name. Empty when no dev session is active.")},rc=S({name:"dev-status",description:"Report what `infra-kit dev` currently has running by READING the on-disk dev-context fragments (never starts a server). Advisory + read-only: surfaces each app\u2019s package, bound port, portless alias, local origin, fragment freshness (mtime / ageSeconds), and a live TCP liveness probe of the port. The fragment directory is found by searching UPWARD from the working directory, so this agrees with the `infra-kit://dev-context` resource and with the vite helper\u2019s routing decision; `contextDir` / `contextDirExists` report where it looked and whether that directory is real. Returns { active: false, apps: [] } when no dev session is active.",inputSchema:{},outputSchema:rk,handler:()=>Es()});import{spawnSync as cg}from"node:child_process";import ee from"node:fs";import lg from"node:os";import ce from"node:path";import et from"node:process";import{z as de}from"zod";import{execFileSync as nk}from"node:child_process";var Pm=(e,t)=>{let r=e.filter(n=>!n.live).map(n=>n.name);return t?{prunable:[],withheld:r}:{prunable:r,withheld:[]}},ok=[/\binfra-kit\s+dev\b/,/cli\.js\s+dev\b/,/dev-server\.(?:js|ts)\b/],sk=e=>ok.some(t=>t.test(e)),ik="/bin/ps",ak=()=>nk(ik,["-eo","command="],{encoding:"utf8",maxBuffer:8<<20}).split(`
155
+ `),Em=(e=ak)=>{try{return e().some(sk)}catch{return!0}};import{Chalk as ck}from"chalk";import nc from"node:process";var oc={unicode:{ok:"\u2713",changed:"+",skipped:"-",manual:">",warn:"!",fail:"\u2717",separator:"\xB7",rule:"\u2500"},ascii:{ok:"ok",changed:"++",skipped:"--",manual:">>",warn:"!?",fail:"!!",separator:"-",rule:"-"}},lk=new Set(["warn","fail"]),dk=24,Nr=" ",xm=" ",uk=(e,t)=>{let r=e.split(/\s+/).filter(s=>s.length>0),n=[],o="";for(let s of r)o.length===0?o=s:`${o} ${s}`.length<=t?o=`${o} ${s}`:(n.push(o),o=s);return o.length>0&&n.push(o),n.length>0?n:[""]},Tm=e=>{let t={ok:0,changed:0,skipped:0,manual:0,warn:0,fail:0};for(let r of e)t[r.status]+=1;return t},pk=e=>{let t=new ck({level:e?1:0});return{header:r=>t.bold.cyan(r),ok:r=>t.green(r),changed:r=>t.green(r),skipped:r=>t.gray(r),manual:r=>t.cyan(r),fail:r=>t.red(r),warn:r=>t.yellow(r),dim:r=>t.dim(r),bold:r=>t.bold(r)}},Cm=(e,t)=>[{status:"changed",plain:`${e.changed} changed`},{status:"skipped",plain:`${e.skipped} skipped`},{status:"manual",plain:`${e.manual} to run yourself`},{status:"fail",plain:`${e.fail} failed`},{status:"warn",plain:`${e.warn} ${t(e.warn)}`}].filter(n=>e[n.status]>0),mk=(e,t,r,n)=>{if(e.ok===t){let c=`${t}/${t} ok`;return{text:r.ok(c),plainWidth:c.length}}let o=`${e.ok+e.changed}/${t}`,s=Cm(e,c=>`warning${c===1?"":"s"}`),i=[r.dim(o),...s.map(c=>r[c.status](c.plain))].join(` ${n.separator} `),a=s.reduce((c,l)=>c+l.plain.length+3,o.length);return{text:i,plainWidth:a}},fk=(e,t,r,n)=>{let o=mk(Tm(e.rows),e.rows.length,t,r),s=Math.max(1,n-Nr.length-e.label.length-o.plainWidth);return`${Nr}${t.header(e.label)}${" ".repeat(s)}${o.text}`},gk=(e,t,r,n,o)=>{let s=lk.has(e.status),i=n.ok.length,a=e.name.padEnd(t),c=r[e.status],l=s?c(a):a,d=xm.length+i+1+t+2,p=Math.max(dk,o-d),[m,...g]=uk(e.message,p),y=" ".repeat(d),R=$=>s?$:r.dim($);return[`${xm}${c(n[e.status])} ${l} ${R(m??"")}`.trimEnd(),...g.map($=>`${y}${R($)}`),...(e.notes??[]).map($=>`${y}${$}`.trimEnd())]},hk=(e,t,r,n,o)=>{let s=Tm(t),i=n.rule.repeat(Math.max(12,Math.min(o-Nr.length,56))),a=Cm(s,()=>"warned"),c=[r.ok(`${s.ok} passed`),...a.map(d=>r[d.status](d.plain))].join(` ${n.separator} `),l=(e.hints??[]).map(d=>` ${r.dim(d)}`);return[`${Nr}${r.dim(i)}`,`${Nr}${c}${l.join("")}`]},sc=(e,t={})=>{let r=t.width??80,n=pk(t.color??!1),o=t.unicode??!0?oc.unicode:oc.ascii,s=e.sections.filter(d=>d.rows.length>0),i=s.flatMap(d=>d.rows),a=n.bold(e.title);if(i.length===0)return[a,"",`${Nr}${n.dim(e.emptyMessage??"Nothing ran.")}`];let c=Math.max(...i.map(d=>d.name.length)),l=s.flatMap(d=>[fk(d,n,o,r),...d.rows.flatMap(p=>gk(p,c,n,o,r)),""]);return[a,"",...l,...hk(e,i,n,o,r)]},yk=new Set(["","0","false","none"]),vk=["LC_ALL","LC_CTYPE","LANG"],wk=(e,t)=>e.NO_COLOR!==void 0&&e.NO_COLOR!==""?!1:e.FORCE_COLOR!==void 0?!yk.has(e.FORCE_COLOR.toLowerCase()):!!t.isTTY,kk=(e,t)=>{if(t)return!1;let r=vk.map(n=>e[n]).find(n=>n!==void 0&&n!=="");return r===void 0?!0:/UTF-?8/i.test(r)},ic=(e={})=>{let t=e.env??nc.env,r=e.stream??nc.stderr;return{color:wk(t,r),unicode:kk(t,e.ascii??!1),width:r.columns??80}},qe=(e,t={})=>{(t.write??(n=>{nc.stderr.write(n)}))(`${sc(e,ic(t)).join(`
156
156
  `)}
157
- `)};var Mk="Tools & CLIs",jk="Shell & integration",Fk="Project config",Lk="Doppler env tokens",Vk="Dev proxy (portless)",Bk="Claude Code plugin",Wk=`portless serving TLS on :${xt}`,Rc=[[Mk,["brew installed","git installed","gh installed","gh authenticated","doppler installed","aws installed","package manager installed","typescript-language-server installed","orca installed","ide installed"]],[jk,["zshrc init block","zshenv session block","pnpm enableGlobalVirtualStore","CLAUDE.md block"]],[Fk,["infra-kit config valid","user override path","legacy user-global config","merge-dev resolutions"]],[Lk,["tokens.json present","env tokens configured","tokens.json perms"]],[Vk,["portless installed","portless node","portless service target",Wk,"portless CA chain valid","portless CA trusted","portless routes"]],[Bk,["claude CLI","marketplace registered","plugin installed","plugin version","plugin MCP server","CLI version","Agent mode","Agent allowlist"]]],jm="Other",Jk=Rc.map(([e])=>e),Uk=new Map(Rc.flatMap(([e,t])=>t.map(r=>[r,e]))),TM=Rc.flatMap(([,e])=>e),Sc=new Set(["portless routes","tokens.json perms"]),Gk=e=>{let t=new Map;for(let n of e){let o=Uk.get(n.name)??jm,s=t.get(o);s?s.push(n):t.set(o,[n])}return[...Jk,jm].flatMap(n=>{let o=t.get(n);return o&&o.length>0?[{label:n,checks:o}]:[]})};var Kk=e=>{switch(e){case"pass":return"ok";case"fail":return"fail";case"warn":return"warn";case"skip":return"skipped";default:return qe(e)}},Hk=e=>{let t=e.filter(r=>r.status==="fail"&&Sc.has(r.name)).length;return{title:"infra-kit doctor",emptyMessage:"No checks ran.",sections:Gk(e).map(r=>({label:r.label,rows:r.checks.map(n=>({name:n.name,status:Kk(n.status),message:n.message}))})),hints:t>0?[`${t} fixable \u2014 run \`infra-kit doctor --fix\``]:[]}};var Pc=(e,t={})=>{It(Hk(e),t)};var qk=e=>e.replace(/&apos;/g,"'").replace(/&quot;/g,'"').replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&amp;/g,"&"),zk=e=>[...e.matchAll(/<string>([\s\S]*?)<\/string>/g)].map(t=>qk(t[1])),Yk=e=>{let t=e.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/);return t===null?null:zk(t[1])},Xk=e=>{let t=[],r="",n=!1,o=!1,s=!1,i=[...e];for(let[a,c]of i.entries()){if(s){s=!1;continue}if(c==='"'){n=!n,o=!0;continue}let l=i[a+1];if(c==="\\"&&(l==='"'||l==="\\")){r+=l,o=!0,s=!0;continue}if(/\s/.test(c)&&!n){o&&(t.push(r),r="",o=!1);continue}r+=c,o=!0}return o&&t.push(r),t},Zk=e=>{let t=e.split(`
158
- `).find(r=>r.startsWith("ExecStart="));return t===void 0?null:Xk(t.slice(10))},Fm=(e,t)=>{try{return e==="darwin"?Yk(t):e==="linux"?Zk(t):null}catch{return null}};import{Buffer as of}from"node:buffer";import Re from"node:fs/promises";import et from"node:path";import sf from"node:process";import{$ as qs}from"zx";import Qk from"node:process";var Xn=class extends Error{name="PromptCancelledError";constructor(){super("Prompt cancelled")}};var Lm=e=>{let t={operation:"interactive branch selection",remediation:"pass the branch selection explicitly (`--version`/`--versions`/`--all`) for non-interactive, --json, or --agent runs"};if(ie())throw new E({status:"argument_required",argument:e,agentMode:A.source},2,t);if(!Qk.stdin.isTTY)throw new f(void 0,t)},Dt=async e=>{Lm("version");let{runBranchPicker:t}=await import("./boot-XLDVLQEG.js"),r=await t(e);if(r===null)throw new Xn;return r},Nt=async(e,t)=>{Lm("versions");let{runBranchMultiPicker:r}=await import("./boot-XLDVLQEG.js"),n=await r(e,t);if(n===null)throw new Xn;return n};import{$ as Km}from"zx";import{$ as FM}from"zx";import{$ as Ur}from"zx";import{$ as Vm}from"zx";var Ec=async e=>{let{operation:t}=e;try{await Vm({quiet:!0})`git rev-parse --git-dir`}catch(r){throw new f(r,{operation:t,remediation:"run this from inside a git repository"})}try{await Vm({quiet:!0})`git remote get-url origin`}catch(r){throw new f(r,{operation:t,remediation:"this repository has no `origin` remote to fetch from or push to"})}},tb=4,Jr=async e=>{let{operation:t}=e,r=await cu();if(r.length===0)return;p.error(`working tree has uncommitted changes:
157
+ `)};var bk="Tools & CLIs",Rk="Shell & integration",Sk="Project config",Pk="Doppler env tokens",Ek="Dev proxy (portless)",xk="Claude Code plugin",Tk=`portless serving TLS on :${ht}`,ac=[[bk,["brew installed","git installed","gh installed","gh authenticated","doppler installed","aws installed","package manager installed","typescript-language-server installed","orca installed","ide installed"]],[Rk,["zshrc init block","zshenv session block","pnpm enableGlobalVirtualStore","CLAUDE.md block"]],[Sk,["infra-kit config valid","user override path","legacy user-global config","merge-dev resolutions"]],[Pk,["tokens.json present","env tokens configured","tokens.json perms"]],[Ek,["portless installed","portless node","portless service target",Tk,"portless CA chain valid","portless CA trusted","portless routes"]],[xk,["claude CLI","marketplace registered","plugin installed","plugin version","plugin MCP server","CLI version","Agent mode","Agent allowlist"]]],$m="Other",Ck=ac.map(([e])=>e),$k=new Map(ac.flatMap(([e,t])=>t.map(r=>[r,e]))),Z_=ac.flatMap(([,e])=>e),cc=new Set(["portless routes","tokens.json perms"]),Ak=e=>{let t=new Map;for(let n of e){let o=$k.get(n.name)??$m,s=t.get(o);s?s.push(n):t.set(o,[n])}return[...Ck,$m].flatMap(n=>{let o=t.get(n);return o&&o.length>0?[{label:n,checks:o}]:[]})};var Ok=e=>{switch(e){case"pass":return"ok";case"fail":return"fail";case"warn":return"warn";case"skip":return"skipped";default:return Ve(e)}},Ik=e=>{let t=e.filter(r=>r.status==="fail"&&cc.has(r.name)).length;return{title:"infra-kit doctor",emptyMessage:"No checks ran.",sections:Ak(e).map(r=>({label:r.label,rows:r.checks.map(n=>({name:n.name,status:Ok(n.status),message:n.message}))})),hints:t>0?[`${t} fixable \u2014 run \`infra-kit doctor --fix\``]:[]}};var lc=(e,t={})=>{qe(Ik(e),t)};var Dk=e=>e.replace(/&apos;/g,"'").replace(/&quot;/g,'"').replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&amp;/g,"&"),Nk=e=>[...e.matchAll(/<string>([\s\S]*?)<\/string>/g)].map(t=>Dk(t[1])),_k=e=>{let t=e.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/);return t===null?null:Nk(t[1])},Mk=e=>{let t=[],r="",n=!1,o=!1,s=!1,i=[...e];for(let[a,c]of i.entries()){if(s){s=!1;continue}if(c==='"'){n=!n,o=!0;continue}let l=i[a+1];if(c==="\\"&&(l==='"'||l==="\\")){r+=l,o=!0,s=!0;continue}if(/\s/.test(c)&&!n){o&&(t.push(r),r="",o=!1);continue}r+=c,o=!0}return o&&t.push(r),t},jk=e=>{let t=e.split(`
158
+ `).find(r=>r.startsWith("ExecStart="));return t===void 0?null:Mk(t.slice(10))},Am=(e,t)=>{try{return e==="darwin"?_k(t):e==="linux"?jk(t):null}catch{return null}};import{Buffer as zm}from"node:buffer";import Re from"node:fs/promises";import ze from"node:path";import Xm from"node:process";import{$ as Ms}from"zx";import Fk from"node:process";var Bn=class extends Error{name="PromptCancelledError";constructor(){super("Prompt cancelled")}};var Om=e=>{let t={operation:"interactive branch selection",remediation:"pass the branch selection explicitly (`--version`/`--versions`/`--all`) for non-interactive, --json, or --agent runs"};if(ge())throw new x({status:"argument_required",argument:e,agentMode:I.source},2,t);if(!Fk.stdin.isTTY)throw new f(void 0,t)},Et=async e=>{Om("version");let{runBranchPicker:t}=await import("./boot-LC2ESPY6.js"),r=await t(e);if(r===null)throw new Bn;return r},xt=async(e,t)=>{Om("versions");let{runBranchMultiPicker:r}=await import("./boot-LC2ESPY6.js"),n=await r(e,t);if(n===null)throw new Bn;return n};import{$ as Fm}from"zx";import{$ as lM}from"zx";import{$ as Mr}from"zx";import{$ as Im}from"zx";var dc=async e=>{let{operation:t}=e;try{await Im({quiet:!0})`git rev-parse --git-dir`}catch(r){throw new f(r,{operation:t,remediation:"run this from inside a git repository"})}try{await Im({quiet:!0})`git remote get-url origin`}catch(r){throw new f(r,{operation:t,remediation:"this repository has no `origin` remote to fetch from or push to"})}},Bk=4,_r=async e=>{let{operation:t}=e,r=await Uu();if(r.length===0)return;u.error(`working tree has uncommitted changes:
159
159
  ${r.join(`
160
- `)}`);let n=r.slice(0,tb),o=r.length-n.length,s=o>0?`${n.join(", ")} (+${o} more)`:n.join(", ");throw new f(void 0,{operation:t,remediation:"commit or stash your changes (`git stash -u`), then retry",stderrExcerpt:`working tree has uncommitted changes: ${s}`})},Zn=async e=>{let{operation:t,base:r}=e;if(await Ar()===r)return;let n=(await Pt(await x())).find(o=>o.branch===r);if(n)throw new f(void 0,{operation:t,remediation:"close or remove that worktree, or run the release from it",stderrExcerpt:`base branch "${r}" is checked out in the worktree at ${n.path}`})},be=async e=>{let{operation:t}=e;if(await du())throw new f(void 0,{operation:t,remediation:"run this from the main repository checkout, not a linked git worktree",stderrExcerpt:"command run from inside a linked worktree"});await Jr({operation:t})};var rb=e=>e.map(t=>({pr:t,id:K(t.headRefName)})).filter(t=>t.id!==null).sort((t,r)=>au(t.id,r.id,{a:t.pr.createdAt,b:r.pr.createdAt})).map(t=>t.pr),Qn=200,Bm=(e,t)=>{e.length<Qn||p.warn({source:t,limit:Qn},`\u26A0\uFE0F ${t} returned ${Qn} PRs \u2014 the page is full, so older release PRs may be missing`)},nb=async()=>{let[e,t]=await Promise.all([Ur`gh pr list --limit ${Qn} --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,Ur`gh pr list --limit ${Qn} --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName,createdAt`]),r=JSON.parse(e.stdout),n=JSON.parse(t.stdout);Bm(r,"release PR discovery (base dev)"),Bm(n,"hotfix PR discovery (base main)");let o=new Set(r.map(c=>c.headRefName)),s=new Set(n.filter(c=>o.has(c.headRefName)).map(c=>c.headRefName)),i=[...n,...r],a=new Set;return i.filter(c=>a.has(c.headRefName)?!1:(a.add(c.headRefName),!0)).map(c=>({...c,dualBase:s.has(c.headRefName)}))},eo="find open release PRs",Wm=async()=>{try{let e=await nb();if(e.length===0)throw new f(void 0,{operation:eo,remediation:"open a release PR first, or check you are in the right repo"});return rb(e)}catch(e){throw e instanceof f?e:(p.debug({err:e},"Error fetching release PRs"),new f(e,{operation:"fetch release PRs"}))}},Fs=async()=>(await Wm()).map(t=>t.headRefName),ob=e=>{let t=to(e.baseRefName);if(t===null)throw new f(void 0,{operation:"classify release PRs",remediation:"discovery returned a PR outside the dev/main base set \u2014 this is an infra-kit bug, please report it",stderrExcerpt:`${e.headRefName} (#${e.number}) targets ${e.baseRefName}`});let r=xc(e.title)!==t;return(r||e.dualBase)&&p.warn({branch:e.headRefName,title:e.title,baseRefName:e.baseRefName},e.dualBase?`\u26A0\uFE0F ${e.headRefName} has open PRs to both dev and main \u2014 treated as a hotfix (base main)`:`\u26A0\uFE0F ${e.headRefName} is titled "${e.title}" but targets ${e.baseRefName} \u2014 treated as ${t} by its base`),{branch:e.headRefName,number:e.number,title:e.title,createdAt:e.createdAt,baseRefName:e.baseRefName,type:t,titleMismatch:r,dualBase:e.dualBase}},F=async()=>(await Wm()).map(ob),Ls=async e=>{let{branch:t,body:r}=e;try{await Ur({quiet:!0})`gh pr edit ${t} --body ${r}`}catch(n){throw p.error({error:n,branch:t},`Error updating release PR body for ${t}`),n}},sb=async(e,t)=>{let r=Ur({quiet:!0,nothrow:!0}),n=await r`git ls-remote --heads origin ${e}`,o=n.exitCode!==0,s=n.stdout.trim().length>0;if(o||s){p.error({branchName:e},o?`could not reach origin to check whether ${e} was pushed \u2014 the branch is left in place; check with \`git ls-remote --heads origin ${e}\` before deleting anything`:`release branch ${e} exists on origin without a PR \u2014 left in place; delete it with \`git push origin --delete ${e}\` once you are sure`);return}await r`git switch ${t}`,(await r`git branch -D ${e}`).exitCode!==0&&p.error({branchName:e},`could not remove the local branch ${e} after a failed release \u2014 delete it with \`git branch -D ${e}\` before retrying`)},Vs=async e=>{let{id:t,jiraVersionUrl:r,type:n,description:o,baseSha:s}=e,i=iu(t,n),a=Qe(n),c=Ur({quiet:!0}),l=Te(t),d=ro(r,o);try{await Jr({operation:`create release branch ${l}`});let u=(await c`git rev-parse HEAD`).stdout.trim();if(u!==s)throw new f(void 0,{operation:`create release branch ${l}`,remediation:"something moved the checkout mid-run \u2014 re-run the release",stderrExcerpt:`expected to be on ${s.slice(0,8)} (${a}) but HEAD is ${u.slice(0,8)}`});await c`git checkout -b ${l}`;try{await c`git commit --allow-empty-message --allow-empty --message ''`,await c`git push -u origin ${l}`;let m=await c`gh pr create --title ${i} --body ${d} --base ${a} --head ${l}`;return{branchName:l,prUrl:m.stdout.trim()}}catch(m){throw await sb(l,a),m}}catch(u){throw p.error({error:u,branchName:l},`Error creating release branch ${l}`),u}finally{await Ur({quiet:!0,nothrow:!0})`git switch ${a}`}};import{$ as Tc}from"zx";var Gr=async e=>{let t=await Tc`gh pr list --head ${e} --state all --json number,state,title,baseRefName,headRefName --limit 1`;return JSON.parse(t.stdout)[0]??null},Cc=async e=>{let t=await Tc`gh pr list --head ${e} --state open --limit 5 --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)},$c=async e=>{try{let t=await Tc`gh pr view ${e} --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)}catch(t){throw new f(t,{operation:`fetch PR #${e}`,remediation:`check it exists with \`gh pr view ${e}\``})}};import oo from"node:process";var ib="x-seraph-loginreason",ab="AUTHENTICATED_FAILED",cb=(e,t=160)=>{let r=e.split(`
161
- `,1)[0].trim();return r.length>t?`${r.slice(0,t)}\u2026`:r},Um=(e,t)=>t===ab||e===401?"auth":e===403?"forbidden":e===404?"not-found-or-forbidden":"other",Jm=(e,t)=>e==="auth"?`Jira rejected the credentials (HTTP ${t}) \u2014 check JIRA_EMAIL and JIRA_TOKEN; Atlassian API tokens expire`:e==="forbidden"?`Jira authenticated the account but refused the operation (HTTP ${t}) \u2014 the account lacks permission on this project`:e==="not-found-or-forbidden"?`Jira returned HTTP ${t}: either JIRA_PROJECT_ID does not exist, or these credentials cannot browse it, or the Authorization header was malformed and the request went out anonymous`:`Jira returned HTTP ${t}`,Kr=class extends Error{status;kind;body;context;constructor(t){let r=Um(t.status,t.seraphLoginReason),n=cb(t.body);super(n===""?`${t.context}: ${Jm(r,t.status)}`:`${t.context}: ${Jm(r,t.status)}. Jira said: ${n}`),this.name="JiraApiError",this.status=t.status,this.kind=r,this.body=t.body,this.context=t.context}},no=e=>e instanceof Kr,Gm=e=>e.headers.get(ib);var Hr=async(e,t)=>{if(e.ok)return;let r=await e.text(),n=new Kr({status:e.status,seraphLoginReason:Gm(e),body:r,context:t});throw p.debug({status:e.status,kind:n.kind,body:r},t),n},rr=(e,t)=>`${e.baseUrl}/projects/${t.projectId}/versions/${t.id}/tab/release-report-all-issues`,Ac=async(e,t)=>{let{baseUrl:r,token:n,email:o,projectId:s}=t,i={name:e.name,projectId:e.projectId||s,description:e.description||"",released:e.released||!1,archived:e.archived||!1,...e.releaseDate===void 0?{}:{releaseDate:e.releaseDate}},a=`${r}/rest/api/3/version`,c=btoa(`${o}:${n}`),l=await fetch(a,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${c}`},body:JSON.stringify(i)});return await Hr(l,"Failed to create Jira version"),{success:!0,version:await l.json()}},qr=async e=>{let{baseUrl:t,token:r,email:n,projectId:o}=e,s=`${t}/rest/api/3/project/${o}/versions`,i=btoa(`${n}:${r}`),a=await fetch(s,{method:"GET",headers:{Accept:"application/json",Authorization:`Basic ${i}`}});return await Hr(a,"Failed to get Jira project versions"),await a.json()},ut=async(e,t)=>(await qr(t)).find(o=>o.name===e)||null,zr=async(e,t)=>{let{baseUrl:r,token:n,email:o}=t,s={};e.released!==void 0&&(s.released=e.released),e.archived!==void 0&&(s.archived=e.archived),e.releaseDate!==void 0&&(s.releaseDate=e.releaseDate),e.description!==void 0&&(s.description=e.description);let i=`${r}/rest/api/3/version/${e.versionId}`,a=btoa(`${o}:${n}`),c=await fetch(i,{method:"PUT",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${a}`},body:JSON.stringify(s)});await Hr(c,"Failed to update Jira version");let l=await c.json();if(e.releaseDate===null&&(l.releaseDate||null)!==null)throw new Error(`Jira accepted the update (the write happened) but still reports releaseDate=${l.releaseDate}; the clear payload in updateJiraVersion needs revisiting`);return{success:!0,version:l}},Oc=async(e,t)=>{let{versionName:r}=e,n=await ut(r,t);if(!n)throw new Error(`Version "${r}" not found in Jira project`);return await zr({versionId:n.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},t)},Yr=async()=>{let e=oo.env.JIRA_BASE_URL,t=oo.env.JIRA_TOKEN||oo.env.JIRA_API_TOKEN,r=oo.env.JIRA_PROJECT_ID,n=oo.env.JIRA_EMAIL,o=[];if(e||o.push("JIRA_BASE_URL (e.g., https://your-domain.atlassian.net)"),t||o.push("JIRA_TOKEN or JIRA_API_TOKEN (your Jira API token)"),r||o.push("JIRA_PROJECT_ID (numeric project ID)"),n||o.push("JIRA_EMAIL (your Jira email address)"),o.length>0){let i=["Jira configuration is required but incomplete.","Please configure the following environment variables:",...o.map(a=>` - ${a}`),"","You can set these in your .env file or as environment variables."].join(`
162
- `);throw new Error(i)}let s=Number.parseInt(r,10);if(Number.isNaN(s))throw new TypeError(`Invalid JIRA_PROJECT_ID: "${r}" must be a numeric value (e.g., 10001)`);return{baseUrl:e.replace(/\/$/,""),token:t,projectId:s,email:n}},mt=async()=>{try{return await Yr()}catch(e){return p.warn({err:e},"Jira configuration not available, skipping Jira integration"),null}};var Bs=async(e,t)=>{let{baseUrl:r,token:n,email:o}=t,s=`${r}/rest/api/3/version/${e}/relatedIssueCounts`,i=btoa(`${o}:${n}`),a=await fetch(s,{method:"GET",headers:{Accept:"application/json",Authorization:`Basic ${i}`}});await Hr(a,"Failed to get Jira version issue counts");let c=await a.json();return{issuesFixedCount:c.issuesFixedCount,issuesAffectedCount:c.issuesAffectedCount}},Ic=async(e,t)=>{let{baseUrl:r,token:n,email:o}=t,s={};e.moveFixIssuesTo!==void 0&&(s.moveFixIssuesTo=e.moveFixIssuesTo),e.moveAffectedIssuesTo!==void 0&&(s.moveAffectedIssuesTo=e.moveAffectedIssuesTo);let i=`${r}/rest/api/3/version/${e.versionId}/removeAndSwap`,a=btoa(`${o}:${n}`),c=await fetch(i,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${a}`},body:JSON.stringify(s)});await Hr(c,"Failed to remove Jira version")};var Hm="dev",qm={regular:"dev",hotfix:"main"},Qe=e=>qm[e],to=e=>{let t=Object.entries(qm).find(([,r])=>r===e);return t?t[0]:null},ro=(e,t)=>(t??"").trim()!==""?`${e}
160
+ `)}`);let n=r.slice(0,Bk),o=r.length-n.length,s=o>0?`${n.join(", ")} (+${o} more)`:n.join(", ");throw new f(void 0,{operation:t,remediation:"commit or stash your changes (`git stash -u`), then retry",stderrExcerpt:`working tree has uncommitted changes: ${s}`})},Vn=async e=>{let{operation:t,base:r}=e;if(await wr()===r)return;let n=(await gt(await E())).find(o=>o.branch===r);if(n)throw new f(void 0,{operation:t,remediation:"close or remove that worktree, or run the release from it",stderrExcerpt:`base branch "${r}" is checked out in the worktree at ${n.path}`})},be=async e=>{let{operation:t}=e;if(await Gu())throw new f(void 0,{operation:t,remediation:"run this from the main repository checkout, not a linked git worktree",stderrExcerpt:"command run from inside a linked worktree"});await _r({operation:t})};var Vk=e=>e.map(t=>({pr:t,id:J(t.headRefName)})).filter(t=>t.id!==null).sort((t,r)=>Wu(t.id,r.id,{a:t.pr.createdAt,b:r.pr.createdAt})).map(t=>t.pr),Wn=200,Dm=(e,t)=>{e.length<Wn||u.warn({source:t,limit:Wn},`\u26A0\uFE0F ${t} returned ${Wn} PRs \u2014 the page is full, so older release PRs may be missing`)},Wk=async()=>{let[e,t]=await Promise.all([Mr`gh pr list --limit ${Wn} --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,Mr`gh pr list --limit ${Wn} --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName,createdAt`]),r=JSON.parse(e.stdout),n=JSON.parse(t.stdout);Dm(r,"release PR discovery (base dev)"),Dm(n,"hotfix PR discovery (base main)");let o=new Set(r.map(c=>c.headRefName)),s=new Set(n.filter(c=>o.has(c.headRefName)).map(c=>c.headRefName)),i=[...n,...r],a=new Set;return i.filter(c=>a.has(c.headRefName)?!1:(a.add(c.headRefName),!0)).map(c=>({...c,dualBase:s.has(c.headRefName)}))},Un="find open release PRs",Nm=async()=>{try{let e=await Wk();if(e.length===0)throw new f(void 0,{operation:Un,remediation:"open a release PR first, or check you are in the right repo"});return Vk(e)}catch(e){throw e instanceof f?e:(u.debug({err:e},"Error fetching release PRs"),new f(e,{operation:"fetch release PRs"}))}},xs=async()=>(await Nm()).map(t=>t.headRefName),Uk=e=>{let t=Jn(e.baseRefName);if(t===null)throw new f(void 0,{operation:"classify release PRs",remediation:"discovery returned a PR outside the dev/main base set \u2014 this is an infra-kit bug, please report it",stderrExcerpt:`${e.headRefName} (#${e.number}) targets ${e.baseRefName}`});let r=uc(e.title)!==t;return(r||e.dualBase)&&u.warn({branch:e.headRefName,title:e.title,baseRefName:e.baseRefName},e.dualBase?`\u26A0\uFE0F ${e.headRefName} has open PRs to both dev and main \u2014 treated as a hotfix (base main)`:`\u26A0\uFE0F ${e.headRefName} is titled "${e.title}" but targets ${e.baseRefName} \u2014 treated as ${t} by its base`),{branch:e.headRefName,number:e.number,title:e.title,createdAt:e.createdAt,baseRefName:e.baseRefName,type:t,titleMismatch:r,dualBase:e.dualBase}},F=async()=>(await Nm()).map(Uk),Ts=async e=>{let{branch:t,body:r}=e;try{await Mr({quiet:!0})`gh pr edit ${t} --body ${r}`}catch(n){throw u.error({error:n,branch:t},`Error updating release PR body for ${t}`),n}},Jk=async(e,t)=>{let r=Mr({quiet:!0,nothrow:!0}),n=await r`git ls-remote --heads origin ${e}`,o=n.exitCode!==0,s=n.stdout.trim().length>0;if(o||s){u.error({branchName:e},o?`could not reach origin to check whether ${e} was pushed \u2014 the branch is left in place; check with \`git ls-remote --heads origin ${e}\` before deleting anything`:`release branch ${e} exists on origin without a PR \u2014 left in place; delete it with \`git push origin --delete ${e}\` once you are sure`);return}await r`git switch ${t}`,(await r`git branch -D ${e}`).exitCode!==0&&u.error({branchName:e},`could not remove the local branch ${e} after a failed release \u2014 delete it with \`git branch -D ${e}\` before retrying`)},Cs=async e=>{let{id:t,jiraVersionUrl:r,type:n,description:o,baseSha:s}=e,i=Vu(t,n),a=Ye(n),c=Mr({quiet:!0}),l=xe(t),d=Gn(r,o);try{await _r({operation:`create release branch ${l}`});let p=(await c`git rev-parse HEAD`).stdout.trim();if(p!==s)throw new f(void 0,{operation:`create release branch ${l}`,remediation:"something moved the checkout mid-run \u2014 re-run the release",stderrExcerpt:`expected to be on ${s.slice(0,8)} (${a}) but HEAD is ${p.slice(0,8)}`});await c`git checkout -b ${l}`;try{await c`git commit --allow-empty-message --allow-empty --message ''`,await c`git push -u origin ${l}`;let m=await c`gh pr create --title ${i} --body ${d} --base ${a} --head ${l}`;return{branchName:l,prUrl:m.stdout.trim()}}catch(m){throw await Jk(l,a),m}}catch(p){throw u.error({error:p,branchName:l},`Error creating release branch ${l}`),p}finally{await Mr({quiet:!0,nothrow:!0})`git switch ${a}`}};import{$ as pc}from"zx";var jr=async e=>{let t=await pc`gh pr list --head ${e} --state all --json number,state,title,baseRefName,headRefName --limit 1`;return JSON.parse(t.stdout)[0]??null},mc=async e=>{let t=await pc`gh pr list --head ${e} --state open --limit 5 --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)},fc=async e=>{try{let t=await pc`gh pr view ${e} --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)}catch(t){throw new f(t,{operation:`fetch PR #${e}`,remediation:`check it exists with \`gh pr view ${e}\``})}};import Hn from"node:process";var Gk="x-seraph-loginreason",Kk="AUTHENTICATED_FAILED",Hk=(e,t=160)=>{let r=e.split(`
161
+ `,1)[0].trim();return r.length>t?`${r.slice(0,t)}\u2026`:r},Mm=(e,t)=>t===Kk||e===401?"auth":e===403?"forbidden":e===404?"not-found-or-forbidden":"other",_m=(e,t)=>e==="auth"?`Jira rejected the credentials (HTTP ${t}) \u2014 check JIRA_EMAIL and JIRA_TOKEN; Atlassian API tokens expire`:e==="forbidden"?`Jira authenticated the account but refused the operation (HTTP ${t}) \u2014 the account lacks permission on this project`:e==="not-found-or-forbidden"?`Jira returned HTTP ${t}: either JIRA_PROJECT_ID does not exist, or these credentials cannot browse it, or the Authorization header was malformed and the request went out anonymous`:`Jira returned HTTP ${t}`,Fr=class extends Error{status;kind;body;context;constructor(t){let r=Mm(t.status,t.seraphLoginReason),n=Hk(t.body);super(n===""?`${t.context}: ${_m(r,t.status)}`:`${t.context}: ${_m(r,t.status)}. Jira said: ${n}`),this.name="JiraApiError",this.status=t.status,this.kind=r,this.body=t.body,this.context=t.context}},Kn=e=>e instanceof Fr,jm=e=>e.headers.get(Gk);var Lr=async(e,t)=>{if(e.ok)return;let r=await e.text(),n=new Fr({status:e.status,seraphLoginReason:jm(e),body:r,context:t});throw u.debug({status:e.status,kind:n.kind,body:r},t),n},Yt=(e,t)=>`${e.baseUrl}/projects/${t.projectId}/versions/${t.id}/tab/release-report-all-issues`,gc=async(e,t)=>{let{baseUrl:r,token:n,email:o,projectId:s}=t,i={name:e.name,projectId:e.projectId||s,description:e.description||"",released:e.released||!1,archived:e.archived||!1,...e.releaseDate===void 0?{}:{releaseDate:e.releaseDate}},a=`${r}/rest/api/3/version`,c=btoa(`${o}:${n}`),l=await fetch(a,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${c}`},body:JSON.stringify(i)});return await Lr(l,"Failed to create Jira version"),{success:!0,version:await l.json()}},Br=async e=>{let{baseUrl:t,token:r,email:n,projectId:o}=e,s=`${t}/rest/api/3/project/${o}/versions`,i=btoa(`${n}:${r}`),a=await fetch(s,{method:"GET",headers:{Accept:"application/json",Authorization:`Basic ${i}`}});return await Lr(a,"Failed to get Jira project versions"),await a.json()},it=async(e,t)=>(await Br(t)).find(o=>o.name===e)||null,Vr=async(e,t)=>{let{baseUrl:r,token:n,email:o}=t,s={};e.released!==void 0&&(s.released=e.released),e.archived!==void 0&&(s.archived=e.archived),e.releaseDate!==void 0&&(s.releaseDate=e.releaseDate),e.description!==void 0&&(s.description=e.description);let i=`${r}/rest/api/3/version/${e.versionId}`,a=btoa(`${o}:${n}`),c=await fetch(i,{method:"PUT",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${a}`},body:JSON.stringify(s)});await Lr(c,"Failed to update Jira version");let l=await c.json();if(e.releaseDate===null&&(l.releaseDate||null)!==null)throw new Error(`Jira accepted the update (the write happened) but still reports releaseDate=${l.releaseDate}; the clear payload in updateJiraVersion needs revisiting`);return{success:!0,version:l}},hc=async(e,t)=>{let{versionName:r}=e,n=await it(r,t);if(!n)throw new Error(`Version "${r}" not found in Jira project`);return await Vr({versionId:n.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},t)},Wr=async()=>{let e=Hn.env.JIRA_BASE_URL,t=Hn.env.JIRA_TOKEN||Hn.env.JIRA_API_TOKEN,r=Hn.env.JIRA_PROJECT_ID,n=Hn.env.JIRA_EMAIL,o=[];if(e||o.push("JIRA_BASE_URL (e.g., https://your-domain.atlassian.net)"),t||o.push("JIRA_TOKEN or JIRA_API_TOKEN (your Jira API token)"),r||o.push("JIRA_PROJECT_ID (numeric project ID)"),n||o.push("JIRA_EMAIL (your Jira email address)"),o.length>0){let i=["Jira configuration is required but incomplete.","Please configure the following environment variables:",...o.map(a=>` - ${a}`),"","You can set these in your .env file or as environment variables."].join(`
162
+ `);throw new Error(i)}let s=Number.parseInt(r,10);if(Number.isNaN(s))throw new TypeError(`Invalid JIRA_PROJECT_ID: "${r}" must be a numeric value (e.g., 10001)`);return{baseUrl:e.replace(/\/$/,""),token:t,projectId:s,email:n}},at=async()=>{try{return await Wr()}catch(e){return u.warn({err:e},"Jira configuration not available, skipping Jira integration"),null}};var $s=async(e,t)=>{let{baseUrl:r,token:n,email:o}=t,s=`${r}/rest/api/3/version/${e}/relatedIssueCounts`,i=btoa(`${o}:${n}`),a=await fetch(s,{method:"GET",headers:{Accept:"application/json",Authorization:`Basic ${i}`}});await Lr(a,"Failed to get Jira version issue counts");let c=await a.json();return{issuesFixedCount:c.issuesFixedCount,issuesAffectedCount:c.issuesAffectedCount}},yc=async(e,t)=>{let{baseUrl:r,token:n,email:o}=t,s={};e.moveFixIssuesTo!==void 0&&(s.moveFixIssuesTo=e.moveFixIssuesTo),e.moveAffectedIssuesTo!==void 0&&(s.moveAffectedIssuesTo=e.moveAffectedIssuesTo);let i=`${r}/rest/api/3/version/${e.versionId}/removeAndSwap`,a=btoa(`${o}:${n}`),c=await fetch(i,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${a}`},body:JSON.stringify(s)});await Lr(c,"Failed to remove Jira version")};var Lm="dev",Bm={regular:"dev",hotfix:"main"},Ye=e=>Bm[e],Jn=e=>{let t=Object.entries(Bm).find(([,r])=>r===e);return t?t[0]:null},Gn=(e,t)=>(t??"").trim()!==""?`${e}
163
163
 
164
164
  ${t}`:`${e}
165
- `,Dc=async(e="regular")=>{let t=Qe(e),r=Km({quiet:!0});await r`git fetch origin`,await r`git switch ${t}`;try{await r`git pull --ff-only origin ${t}`}catch(n){let o=await Km({quiet:!0,nothrow:!0})`git rev-list --left-right --count origin/${t}...${t}`,[s="?",i="?"]=o.exitCode===0?o.stdout.trim().split(/\s+/):[],a=i!=="0"||s!=="0";throw new f(n,{operation:`fast-forward ${t} onto origin/${t}`,remediation:a?`your local ${t} has diverged \u2014 rebase or reset it to origin/${t}, then retry`:`check your access to origin and that ${t} tracks it, then retry`,...a?{stderrExcerpt:`local ${t} is ${i} commit(s) ahead and ${s} behind origin/${t}`}:{}})}return(await r`git rev-parse HEAD`).stdout.trim()},lb=async e=>{let{versionName:t,jiraConfig:r,description:n,releaseDate:o}=e,s=await ut(t,r);if(!s)return(await Ac({name:t,projectId:r.projectId,description:n||"",released:!1,archived:!1,...o===void 0?{}:{releaseDate:o}},r)).version;if(s.released||s.archived)throw new f(void 0,{operation:`reuse Jira fix version "${t}"`,remediation:"pick a different version, or un-release it in Jira first",stderrExcerpt:`fix version "${t}" is already ${s.released?"released":"archived"}`});let i=n||"",a={...i!==""&&i!==(s.description??"")?{description:i}:{},...o!==void 0&&o!==(s.releaseDate??"")?{releaseDate:o}:{}};if(Object.keys(a).length===0)return s;let c=await zr({versionId:s.id,...a},r);return{...s,...a,...a.releaseDate===void 0?{}:{releaseDate:c.version.releaseDate}}},Nc=async e=>{let{id:t,jiraConfig:r,description:n,releaseDate:o,type:s="regular",baseSha:i}=e,a=ne(t),c=await lb({versionName:a,jiraConfig:r,description:n,...o===void 0?{}:{releaseDate:o}}),l=rr(r,c),d=await Vs({id:t,jiraVersionUrl:l,type:s,description:n,baseSha:i});return{version:Y(t),type:s,branchName:d.branchName,prUrl:d.prUrl,jiraVersionUrl:l,releaseDate:c.releaseDate||null}},Ws=async()=>{let e=new Map,t=await mt();if(!t)return e;try{let r=await qr(t);for(let n of r)e.set(n.name,{description:n.description||null,releaseDate:n.releaseDate||null})}catch(r){p.warn({err:r},"Jira descriptions unavailable \u2014 the release list will render without them. If this persists, check JIRA_EMAIL / JIRA_TOKEN.")}return e},oe=async()=>{let e=await Ws();return new Map([...e].flatMap(([t,{description:r}])=>r?[[t,r]]:[]))},so=(e,t,r)=>{let n=r?" ".repeat(r-e.length+3):" ",o=`[${t}]`.padEnd(11);return`${e}${n}${o}`},xc=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",Js=e=>e.flatMap(t=>{let r=K(t);return r?[{branch:t,id:r,label:Y(r)}]:[]}),ft=e=>{try{return Te(ve(e))}catch(t){throw new f(t,{operation:`resolve release ref "${e}"`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")',stderrExcerpt:t instanceof Error?t.message:String(t)})}},io=e=>{if(e===Hm)return Hm;let t=K(e);return t?Y(t):e},nr=e=>e.flatMap(t=>{let r=K(t);return r?[Y(r)]:[]}),db=(e,t)=>t?t.get(e)||"regular":void 0,se=e=>{let{branches:t,descriptions:r,types:n}=e;return Js(t).map(({branch:o,id:s,label:i})=>({value:o,label:i,description:r.get(ne(s)),type:db(o,n)}))};import zm from"node:fs/promises";import pb from"node:path";import{$ as _c}from"zx";var L="pnpm-lock.yaml",ub=/^(?:<{7}|={7}|>{7})(?:\s|$)/m,Xm=async(e,t)=>{let r=pb.join(e,L),n=`${t}:${L}`;try{let o=await _c({cwd:e,quiet:!0})`git show ${n}`;await zm.writeFile(r,o.stdout)}catch(o){return{ok:!1,reason:`dev has no ${L} to start from: ${Ym(o)}`}}try{await _c({cwd:e,quiet:!0})`pnpm install --lockfile-only --ignore-scripts --no-frozen-lockfile`}catch(o){return{ok:!1,reason:`pnpm could not merge ${L}: ${Ym(o)}`}}return ub.test(await zm.readFile(r,"utf8"))?{ok:!1,reason:`${L} still carries conflict markers after pnpm ran`}:(await _c({cwd:e,quiet:!0})`git add -- ${L}`,{ok:!0})},Ym=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim()};import{$ as or}from"zx";var Mc="Merge remote-tracking branch 'origin/dev' into ",Zm=e=>String(e.stderr??e.message??e).trim(),mb=async e=>{try{return(await or({cwd:e,quiet:!0})`git diff --name-only --diff-filter=U`).stdout.split(`
166
- `).map(r=>r.trim()).filter(r=>r.length>0)}catch{return[]}},fb=async(e,t)=>{let r=Zm(t),n=await mb(e);return n.length>0?{status:"conflict",conflictPaths:n,reason:r}:await fu(e)?{status:"hook-failed",reason:r}:{status:"error",reason:r}},Qm=async e=>{let{cwd:t,worktreePath:r,branches:n}=e,o=[],s=await $e(t,"origin/dev");if(!s)return n.map(i=>({branch:i,status:"error",reason:"origin/dev does not resolve"}));for(let i of n){let a=Date.now(),c=await gb({cwd:t,worktreePath:r,branch:i,devSha:s});o.push({...c,durationMs:Date.now()-a})}return o},gb=async e=>{let{cwd:t,worktreePath:r,branch:n,devSha:o}=e,s=`origin/${n}`;if(!await $e(t,s))return{branch:n,status:"error",reason:`${s} does not exist on origin`};if(await _n(t,"origin/dev",s))return{branch:n,status:"up-to-date"};try{await ba(r),await or({cwd:r,quiet:!0})`git checkout --detach ${s}`;let i=`${Mc}${n}`;await or({cwd:r,quiet:!0})`git merge origin/dev --no-edit -m ${i}`;let a=(await or({cwd:r,quiet:!0})`git rev-parse HEAD`).stdout.trim();return{branch:n,status:a===o?"fast-forward":"merged",mergeSha:a}}catch(i){return{branch:n,...await fb(r,i)}}finally{await Ra(r)}},ef=e=>e.flatMap(t=>t.mergeSha?[{branch:t.branch,sha:t.mergeSha}]:[]),tf="pnpm install --frozen-lockfile",rf=async e=>{let{worktreePath:t,refs:r,command:n}=e,o=[],s=new Map;for(let i of r)try{await ba(t),await or({cwd:t,quiet:!0})`git checkout --detach ${i.sha}`,await or({cwd:t,quiet:!0})`sh -c ${n}`,o.push(i)}catch(a){s.set(i.branch,Zm(a))}finally{await Ra(t)}return{kept:o,failed:s}},ao=async(e,t,r="origin/dev")=>{await or({cwd:e,quiet:!0})`git fetch origin --prune`;let n=[],o=[];for(let s of t)await _n(e,r,`origin/${s.branch}`)?o.push(s.branch):n.push(s);return{kept:n,nowUpToDate:o}};import jc from"node:process";var Us=new Set,Gs=e=>(Us.add(e),()=>{Us.delete(e)}),hb=async()=>{for(let e of[...Us])try{await e()}catch(t){p.warn({error:t,msg:"cleanup failed during shutdown"})}Us.clear()},yb=["SIGINT","SIGTERM"],nf=async(e,t={})=>{let{register:r=(i,a)=>{jc.on(i,a)},unregister:n=(i,a)=>{jc.off(i,a)},exit:o=i=>{jc.exit(i)}}=t,s=new Map;for(let i of yb){let a=()=>{hb().then(()=>{o(_u(i))})};s.set(i,a),r(i,a)}try{return await e()}finally{for(let[i,a]of s)n(i,a)}};var vb="pnpm install --frozen-lockfile --ignore-scripts",wb="pnpm install --frozen-lockfile",af=64*1024,uf=4096,lo=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim().slice(-uf)},N=async(e,t)=>(await qs({cwd:e,quiet:!0})`git ${t}`).stdout,Fc=e=>e.split(`
167
- `).map(t=>t.trim()).filter(t=>t.length>0),zs=e=>e.split("\0").filter(t=>t.length>0),Ks=async(e,t)=>{try{return(await N(e,["rev-parse","-q","--verify",t])).trim()||null}catch{return null}},mf=async e=>et.resolve(e,(await N(e,["rev-parse","--git-common-dir"])).trim()),Lc=e=>e.then(()=>!0,()=>!1),co=()=>({results:[],atomicPush:{attempted:!1,aborted:!1},declined:!1}),Vc=e=>e?.length===1&&e[0]===L,ff=async e=>et.join(await mf(e),"infra-kit","merge-dev-resolutions"),Bc=async(e,t)=>et.join(await ff(e),`${uu(t)}.json`),gf=async e=>{try{return JSON.parse(await Re.readFile(e,"utf8"))}catch{return null}},Zr=async(e,t)=>{let r=await Bc(e,t.branch);await Re.mkdir(et.dirname(r),{recursive:!0}),await Re.writeFile(r,`${JSON.stringify(t,null,2)}
168
- `)},hf=async e=>{let t=await ff(e),r=await Re.readdir(t).catch(()=>[]);return(await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(o=>gf(et.join(t,o))))).filter(o=>o!==null)},yf=async e=>Promise.all((await hf(e)).map(async t=>({branch:t.branch,worktreePath:t.worktreePath,createdAt:t.createdAt,worktreeExists:await Lc(Re.stat(t.worktreePath))}))),cf=(e,t)=>({worktreePath:e.worktreePath,baseSha:e.baseSha,devSha:e.devSha,conflictPaths:e.conflictPaths,lockfileOnly:e.lockfileOnly,rererePreResolved:e.rererePreResolved,state:t}),Wc=async(e,t,r)=>{await N(e,["worktree","remove","--force",r]).catch(()=>Re.rm(r,{recursive:!0,force:!0})),await Re.rm(await Bc(e,t),{force:!0}).catch(()=>{}),await N(e,["worktree","prune"]).catch(()=>{})},vf=async e=>zs(await N(e,["diff","--name-only","-z","--diff-filter=U"])),Hs=async e=>zs(await N(e,["status","--porcelain","-z","--untracked-files=all","--ignored=matching"])).filter(r=>r.startsWith("!! ")).map(r=>r.slice(3)),kb=async(e,t)=>{let r=(await N(e,["config","--type=bool","--get","rerere.enabled"]).catch(()=>"")).trim(),n=await Lc(Re.stat(et.join(await mf(e),"rr-cache")));if(r==="false"||r===""&&!n)return[];let o=new Set(Fc(await N(e,["rerere","remaining"])));return t.filter(s=>!o.has(s))},wf=e=>e.split("/").includes("node_modules"),Ys=async(e,t)=>{let r=new Set(t.conflictPaths),n=new Set([...t.ignoredAtHandoff,...t.ignoredByVerify??[]]),o=zs(await N(e,["diff","--cached","--name-only","-z","--no-renames",t.autoMergeTree])),s=[...await bb(e),...o].filter(a=>!r.has(a)),i=(await Hs(e)).filter(a=>!n.has(a)&&!wf(a));return[...new Set([...s,...i,...await Rb(e)])].sort()},bb=async e=>{let t=zs(await N(e,["status","--porcelain","-z","--untracked-files=all"])),r=[],n=!1;for(let o of t){if(n){n=!1;continue}let[s,i]=o;i!==" "&&r.push(o.slice(3)),n=s==="R"||s==="C"}return r},Rb=async e=>(await N(e,["ls-files","-v"])).split(`
169
- `).filter(t=>{let r=t.charAt(0);return r==="S"||r!==""&&r!==r.toUpperCase()}).map(t=>t.slice(2)),Sb=async e=>{let t=`:(exclude)${L}`;try{return await N(e,["diff","--cached","--check","HEAD","--",".",t]),[]}catch(r){let{stdout:n="",stderr:o="",exitCode:s}=r;if(o.trim().length>0||n.trim().length===0||s!==1&&s!==2)throw new f(r,{operation:"check the staged resolution for conflict markers"});let i=new Set;for(let a of n.split(`
170
- `)){let c=/^(.*):\d+: leftover conflict marker/.exec(a);c?.[1]&&i.add(c[1])}return[...i].sort()}},Pb=async(e,t)=>{let r=[];for(let n of t)(await Lc(Re.lstat(et.join(e,n)))||(await N(e,["--literal-pathspecs","ls-files","--",n])).length>0)&&r.push(n);r.length>0&&await N(e,["--literal-pathspecs","add","-A","--",...r])},lf=async e=>(await N(e,["write-tree"])).trim(),kf=async e=>(await N(e,["rev-list","--parents","-n","1","HEAD"])).trim().split(" ").slice(1),Eb=e=>e?`${wb} && ${e}`:vb,xb=async(e,t)=>{try{return await qs({cwd:e,quiet:!0})`sh -c ${t}`,{command:t,ok:!0}}catch(r){return{command:t,ok:!1,reason:lo(r)}}},bf=async(e,t)=>{let r=(await N(e,["diff","--cached","--stat",t.autoMergeTree])).trim(),n=async l=>(await N(e,["diff","--cached","--stat",l,"--",L])).trim(),o=t.conflictPaths.includes(L)?{vsDev:await n(t.devSha),vsBase:await n(t.baseSha)}:void 0,s=await N(e,["diff","--cached",t.autoMergeTree,"--",".",`:(exclude)${L}`]),i=new Set(t.rererePreResolved),a=s.split(/^(?=diff --git )/m).map(l=>{let d=/^diff --git a\/(.*) b\//.exec(l)?.[1];return d&&i.has(d)?`# rerere (recorded resolution)
171
- ${l}`:l}).join(""),c=of.byteLength(a)>af;return{diffStat:r,...o?{lockfileDiffStat:o}:{},resolutionDiff:c?of.from(a).subarray(0,af).toString():a,resolutionDiffTruncated:c}},Rf=async e=>{let{cwd:t,branches:r,devSha:n}=e,o=new Map;for(let s of r)o.set(s,await Tb(t,s,n));return o},Tb=async(e,t,r)=>{let n=await gf(await Bc(e,t));if(n)return{resolution:cf(n,"exists"),reason:`resolution-exists: ${n.worktreePath} \u2014 finish it with --continue or drop it with --abort`};let o=await $e(e,`origin/${t}`);if(!o)return{reason:`origin/${t} does not exist on origin`};let s=mu(e,t),i=()=>Wc(e,t,s),a=Gs(i);try{await N(e,["worktree","prune"]),await Re.mkdir(et.dirname(s),{recursive:!0}),await N(e,["worktree","add","--detach",s,o]),await qs({cwd:s,quiet:!0})`git merge --no-commit ${r} -m ${Mc+t}`.catch(()=>{});let c=await vf(s);if(c.length===0)return await i(),{reason:"the merge no longer conflicts \u2014 re-run release merge-dev"};let l=await Ks(s,"AUTO_MERGE");if(!l)return await i(),{reason:`git-too-old: the scope check needs AUTO_MERGE, written by git \u2265 2.42 (found ${(await N(e,["--version"])).trim()})`};let d=await kb(s,c),u=Vc(c),m={branch:t,worktreePath:s,baseSha:o,devSha:r,conflictPaths:c,autoMergeTree:l,rererePreResolved:d,ignoredAtHandoff:await Hs(s),lockfileOnly:u,cliVersion:q.version,createdAt:new Date().toISOString()};return await Zr(e,m),{resolution:cf(m,u?"lockfile-only":"needs-agent")}}catch(c){return await i(),{reason:lo(c)}}finally{a()}},Sf=async e=>{let{cwd:t,versions:r,all:n}=e,o=await hf(t),s=o.map(a=>a.branch);if(r!==void 0)return(Array.isArray(r)?r:r.split(",")).map(c=>c.trim()).filter(c=>c.length>0).map(c=>{let l=Te(ve(c)),d=o.find(u=>u.branch===l);if(!d)throw new f(void 0,{operation:`select the resolution for "${c}"`,stderrExcerpt:`${l} has no resolution in progress`,remediation:s.length>0?`pass one of: ${s.join(", ")}`:"start one with release merge-dev --keep-conflicts"});return d});if(n||o.length===0)return o;let i=await Nt(se({branches:s,descriptions:new Map}),{required:!0});return o.filter(a=>i.includes(a.branch))},Cb=async(e,t)=>{let r=await Re.realpath(t).catch(()=>null);if(!r)return!1;let n=await Pt(e);for(let o of n)if(await Re.realpath(o.path).catch(()=>o.path)===r)return!0;return!1},Xr=(e,t,r,n)=>({...e,blocked:{code:t,detail:r,...n&&n.length>0?{paths:n}:{}}}),Pf=async(e,t,r)=>{let n=t.worktreePath,o={branch:t.branch,worktreePath:n,baseSha:t.baseSha,devSha:t.devSha,conflictPaths:t.conflictPaths,lockfileMerged:!1,rerereFiles:t.rererePreResolved};if(!await Cb(e,n))return Xr(o,"parents-mismatch",`the resolution worktree ${n} is gone \u2014 run --abort, then start again`);let s=await Ks(n,"HEAD"),i=await Ks(n,"MERGE_HEAD");return s===t.baseSha&&i===t.devSha?Db(e,t,o,r):$b(t,o,s,i)},$b=async(e,t,r,n)=>{let o=e.worktreePath;if(r!==null&&r===e.unapprovedCommit)return Xr(t,"tree-changed",`commit ${r} carries a tree a commit hook rewrote after approval \u2014 run --abort, then hand off again`);let s=n?[]:await kf(o),i=n?null:await Ks(o,"HEAD^{tree}");if(!(s.length===2&&s[0]===e.baseSha&&s[1]===e.devSha&&i!==null&&i===e.previewedTree)||!r||!i){let l=n?`HEAD ${r??"none"} merging ${n}`:`HEAD ${r??"none"}`;return Xr(t,"parents-mismatch",`expected HEAD ${e.baseSha} merging ${e.devSha}, or an approved merge commit of the two; found ${l}`)}let c=await Ys(o,e);return c.length>0?Xr(t,"out-of-scope-edit","only the conflicted paths may change",c):{...t,committed:!0,mergeSha:r,treeSha:i,lockfileMerged:e.conflictPaths.includes(L),...await bf(o,e)}},df=async(e,t)=>{let r=Fc(await N(e,["--literal-pathspecs","ls-files","-s","--",t])),[n,o,s]=r.length===1?(r[0]??"").split(/\s+/):[];return n&&s==="0"?o??null:null},Ab=async(e,t)=>{let r=t.worktreePath,n=await df(r,L),o=t.lockfileBlob,s=await Xm(r,t.devSha);if(!s.ok)return{code:"verify-failed",detail:s.reason,paths:[L]};let i=await df(r,L);if(i!==null&&i!==o&&(t.lockfileBlob=i,await Zr(e,t)),n!==null&&n!==i)return n===o?{code:"tree-changed",detail:`rebuilding ${L} from dev resolved differently than the last preview (the registry moved) \u2014 preview again`,paths:[L]}:{code:"out-of-scope-edit",detail:`${L} was staged by something other than the CLI; it has been rebuilt from dev \u2014 preview again`,paths:[L]};let a=await Ys(r,t);return a.length>0?{code:"out-of-scope-edit",detail:"merging the lockfile changed other paths",paths:a}:null},Ob=async(e,t)=>{let r=t.worktreePath;await Pb(r,t.conflictPaths.filter(i=>i!==L));let n=await Ys(r,t);if(n.length>0)return{code:"out-of-scope-edit",detail:"only the conflicted paths may change",paths:n};let o=(await vf(r)).filter(i=>i!==L);if(o.length>0)return{code:"unmerged-paths",detail:"these paths are still unmerged",paths:o};let s;try{s=await Sb(r)}catch(i){return{code:"markers-remaining",detail:`the marker check could not run: ${lo(i)}`}}return s.length>0?{code:"markers-remaining",detail:"conflict markers are still staged",paths:s}:t.conflictPaths.includes(L)?Ab(e,t):null},Ib=async(e,t,r,n)=>{if(t.verified?.treeSha===r&&t.verified.command===n)return{command:n,ok:!0,reused:!0};let o=t.worktreePath,s=new Set(await Hs(o)),i=await xb(o,n);if(!i.ok)return i;let a=(await Hs(o)).filter(c=>!s.has(c)&&!wf(c)&&et.posix.basename(c)!==".gitignore");return t.ignoredByVerify=[...new Set([...t.ignoredByVerify??[],...a])],await Zr(e,t),i},Db=async(e,t,r,n)=>{let o=t.worktreePath,s=await Ob(e,t);if(s)return{...r,blocked:s};let i=t.conflictPaths.includes(L),a=await lf(o),c=await Ib(e,t,a,Eb(n)),l={...r,treeSha:a,lockfileMerged:i,verify:c};if(!c.ok)return Xr(l,"verify-failed",c.reason??"the verify command failed");let d=await Ys(o,t),u=Fc(await N(o,["diff","--name-only"]));return d.length>0||u.length>0||await lf(o)!==a?Xr(l,"verify-mutated-tree","the verify step changed the tree",[...new Set([...d,...u])]):(c.reused||(t.verified={treeSha:a,command:c.command},await Zr(e,t)),{...l,...await bf(o,t)})},Nb=12e4,_b=async(e,t=Nb)=>{let r=qs({cwd:e,quiet:!0,detached:!0,stdio:["ignore","pipe","pipe"],env:{...sf.env,GIT_TERMINAL_PROMPT:"0"}})`git commit --no-edit --cleanup=strip`,n=!1,o=setTimeout(()=>{n=!0;let s=r.child?.pid;try{s&&sf.kill(-s,"SIGKILL")}catch{}},t);try{return await r,{ok:!0}}catch(s){if(!n)return{ok:!1,reason:lo(s)};let i=(await N(e,["rev-parse","--git-path","index.lock"])).trim();return await Re.rm(et.resolve(e,i),{force:!0}),{ok:!1,reason:`git commit timed out after ${t}ms`}}finally{clearTimeout(o)}},Mb={"verify-failed":"verify-failed","tree-changed":"tree-changed"},jb=e=>{let t=e.blocked;return{branch:e.branch,status:Mb[t.code]??"blocked",conflictPaths:e.conflictPaths,pushed:!1,reason:[`${t.code}: ${t.detail}`,...t.paths?[`(${t.paths.join(", ")})`]:[]].join(" "),blocked:t}},Fb=async(e,t,r,n)=>{let o=r.worktreePath,s=(d,u,m={})=>({branch:t.branch,status:d,conflictPaths:t.conflictPaths,pushed:!1,reason:u,...m});if(!n)return s("tree-changed",`not approved: the preview this --yes came from had no ready tree for ${t.branch} \u2014 preview again`);if(t.treeSha!==n)return s("tree-changed",`the resolution is tree ${t.treeSha} but the approved tree is ${n} \u2014 preview again`);if(t.committed&&t.mergeSha)return{sha:t.mergeSha};let i=await _b(o);if(!i.ok)return s("hook-failed",i.reason);let a=(await N(o,["rev-parse","HEAD"])).trim(),c=(await N(o,["rev-parse","HEAD^{tree}"])).trim();if(c!==t.treeSha)return r.unapprovedCommit=a,await Zr(e,r),s("tree-changed",`a commit hook rewrote the tree (${c}, approved ${t.treeSha}) \u2014 run --abort, then hand off again`,{mergeSha:a});let l=await kf(o);if(l.length!==2||l[0]!==r.baseSha||l[1]!==r.devSha){let d={code:"parents-mismatch",detail:`commit parents are ${l.join(" ")}, expected ${r.baseSha} ${r.devSha}`};return s("blocked",`parents-mismatch: ${d.detail}`,{mergeSha:a,blocked:d})}return{sha:a}},Lb=async(e,t,r)=>{let n=(c,l,d)=>({branch:t.branch,status:c,mergeSha:r,conflictPaths:t.conflictPaths,pushed:!1,...l?{reason:l}:{},...d?{blocked:d}:{}}),o;try{o=(await ao(e,[{branch:t.branch,sha:r}],t.devSha)).nowUpToDate}catch(c){let l={code:"parents-mismatch",detail:`origin/${t.branch}: ${lo(c)}`};return n("blocked",`parents-mismatch: ${l.detail}`,l)}if(o.includes(t.branch))return n("up-to-date",`origin/${t.branch} already carries ${t.devSha}`);let s=await $e(e,`origin/${t.branch}`);if(s===t.baseSha)return"keep";let i=s!==null&&await _n(e,s,t.baseSha),a={code:"parents-mismatch",detail:`origin/${t.branch} ${i?"was rewound":"moved"} to ${s??"nothing"} since the hand-off at ${t.baseSha}`};return n("blocked",`parents-mismatch: ${a.detail}`,a)},Vb=e=>{p.info(`
172
- \u{1F4CB} Resolution preview:`);for(let t of e)t.blocked?p.info(` ${t.branch} \u2014 BLOCKED ${t.blocked.code}: ${t.blocked.detail}`):p.info(` ${t.branch} \u2014 ready${t.committed?" (already committed)":""}: tree ${t.treeSha}`)},Ef=async e=>{let{cwd:t,versions:r,all:n,verify:o,trees:s=new Map,confirmedCommand:i}=e,a=await Sf({cwd:t,versions:r,all:n});if(a.length===0)return p.info("\u2139\uFE0F No merge-dev resolutions in progress"),co();if(i)return pf(t,a,o,s);let c=[];for(let m of a){let g=await Pf(t,m,o);!g.blocked&&!g.committed&&g.treeSha&&(m.previewedTree=g.treeSha,await Zr(t,m)),c.push(g)}Vb(c);let l={branches:c},d=c.filter(m=>!m.blocked&&m.treeSha!==void 0);if(d.length===0)throw new E({status:"refused",plan:l,agentMode:A.source},2,{operation:"continue the merge-dev resolutions",stderrExcerpt:"every selected resolution is blocked",remediation:"fix the paths each row names, then preview again \u2014 or drop it with --abort"});let u=new Map(d.map(m=>[m.branch,m.treeSha]));try{await W(i,`Commit and push the resolved merges for: ${[...u.keys()].join(", ")}?`,{plan:l,throwOnDecline:!0,rerun:Bb(u)})}catch(m){if(!ct(m))throw m;return{...co(),declined:!0}}return pf(t,a,o,u)},xf=e=>{let t=new Map,r=(Array.isArray(e)?e:[e??""]).flatMap(n=>n.split(","));for(let n of r.map(o=>o.trim())){if(n.length===0)continue;let o=/^(.+)=([0-9a-f]{40,64})$/.exec(n);if(!o?.[1]||!o[2])throw new f(void 0,{operation:"read --tree",stderrExcerpt:`"${n}" is not <branch>=<tree sha>`,remediation:"run the rerun a --continue preview printed, unchanged"});t.set(o[1],o[2])}return t},Bb=e=>{let t=[],r=!1;for(let o of Ou())r?r=!1:o==="--tree"?r=!0:o!=="--yes"&&o!=="-y"&&!o.startsWith("--tree=")&&t.push(o);let n=[...e].map(([o,s])=>`${o}=${s}`);return[...t,"--tree",n.join(","),"--yes"]},Wb=async(e,t,r,n)=>{let o=await Pf(e,t,r);if(o.blocked)return jb(o);let s=await Fb(e,o,t,n);if(!("sha"in s))return s;let i=await Lb(e,t,s.sha);return i==="keep"?s:i},Jb=async(e,t)=>{if(t.length===0)return{results:[],atomicPush:{attempted:!1,aborted:!1}};let r=t.map(s=>({branch:s.record.branch,sha:s.sha}));p.info(`
173
- \u2B06\uFE0F Pushing atomically: ${r.map(s=>s.branch).join(", ")}`);let n=await gs(e,r),o=[];for(let s of t){let i=n.pushed||await Or(e,s.record.branch)===s.sha;o.push({branch:s.record.branch,status:i?"merged":"push-aborted",mergeSha:s.sha,conflictPaths:s.record.conflictPaths,pushed:i,...i?{}:{reason:n.stderr?.trim().slice(-uf)}})}return{results:o,atomicPush:{attempted:!0,aborted:!n.pushed,abortedBy:n.stderr?.split(`
174
- `)[0]}}},pf=async(e,t,r,n)=>{let o=[],s=[];for(let d of t){let u=await Wb(e,d,r,n.get(d.branch));"sha"in u?s.push({record:d,sha:u.sha}):o.push(u)}let i=await Jb(e,s),a=[...o,...i.results],c=t.filter(d=>a.some(u=>u.branch===d.branch&&(u.pushed||u.status==="up-to-date")));for(let d of c)await Wc(e,d.branch,d.worktreePath);let l=t.map(d=>d.branch);return a.sort((d,u)=>l.indexOf(d.branch)-l.indexOf(u.branch)),{results:a,atomicPush:i.atomicPush,declined:!1}},Tf=async e=>{let{cwd:t,versions:r,all:n,confirmedCommand:o}=e,s=await Sf({cwd:t,versions:r,all:n});if(s.length===0)return p.info("\u2139\uFE0F No merge-dev resolutions in progress"),co();let i={branches:s.map(a=>({branch:a.branch,worktreePath:a.worktreePath}))};try{await W(o,`Discard the resolution worktrees for: ${s.map(a=>a.branch).join(", ")}?`,{plan:i,throwOnDecline:!0})}catch(a){if(!ct(a))throw a;return{...co(),declined:!0}}for(let a of s)await Wc(t,a.branch,a.worktreePath),p.info(`\u{1F5D1}\uFE0F Discarded the resolution for ${a.branch}`);return{...co(),results:s.map(a=>({branch:a.branch,status:"aborted",conflictPaths:a.conflictPaths,pushed:!1}))}};import Ub from"node:fs";import Gb from"node:os";import Kb from"node:path";var Hb="infra-kit.json",qb="Skipped agent-instruction files, the plugin pointer, the plugin install and .mcp.json \u2014 no usable git repo root here (not a git repo, or the root is your home directory)",zb="Skipped agent-instruction files \u2014 no infra-kit.json at the repo root (the plugin pointer, the plugin install and .mcp.json are unaffected)",po=async()=>{let e;try{e=await x()}catch{return null}let t=e.trim();return t===""||t===Gb.homedir()?null:t},Cf=async()=>{let e=await po();return e===null&&p.info(qb),e},Yb=async()=>{let e=await po();return e===null?null:Ub.existsSync(Kb.join(e,Hb))?e:(p.info(zb),null)};var Xb=async e=>{try{return await ke(e)}catch(t){return p.debug({err:t,msg:"Skipped per-package agent guidance \u2014 no workspace packages could be discovered."}),[]}},$f=async()=>{let e=await Yb(),t=q.version;if(e===null)return{skipped:!0,root:null,version:t,written:[]};let r=[...await Gn(e,{version:t})];for(let n of await Xb(e)){let o=await Yt(n);r.push(...await Kn(n,{repoRoot:e,version:t,declaredType:o}))}return{skipped:!1,root:e,version:t,written:r}};import le from"node:fs";import Xc from"node:os";import me from"node:path";import Zc from"node:process";import Zs from"node:fs/promises";import Zb from"node:path";import Qb from"node:process";var Af=` // "envManagement": { // required in layer 1; provider-tagged
165
+ `,vc=async(e="regular")=>{let t=Ye(e),r=Fm({quiet:!0});await r`git fetch origin`,await r`git switch ${t}`;try{await r`git pull --ff-only origin ${t}`}catch(n){let o=await Fm({quiet:!0,nothrow:!0})`git rev-list --left-right --count origin/${t}...${t}`,[s="?",i="?"]=o.exitCode===0?o.stdout.trim().split(/\s+/):[],a=i!=="0"||s!=="0";throw new f(n,{operation:`fast-forward ${t} onto origin/${t}`,remediation:a?`your local ${t} has diverged \u2014 rebase or reset it to origin/${t}, then retry`:`check your access to origin and that ${t} tracks it, then retry`,...a?{stderrExcerpt:`local ${t} is ${i} commit(s) ahead and ${s} behind origin/${t}`}:{}})}return(await r`git rev-parse HEAD`).stdout.trim()},qk=async e=>{let{versionName:t,jiraConfig:r,description:n,releaseDate:o}=e,s=await it(t,r);if(!s)return(await gc({name:t,projectId:r.projectId,description:n||"",released:!1,archived:!1,...o===void 0?{}:{releaseDate:o}},r)).version;if(s.released||s.archived)throw new f(void 0,{operation:`reuse Jira fix version "${t}"`,remediation:"pick a different version, or un-release it in Jira first",stderrExcerpt:`fix version "${t}" is already ${s.released?"released":"archived"}`});let i=n||"",a={...i!==""&&i!==(s.description??"")?{description:i}:{},...o!==void 0&&o!==(s.releaseDate??"")?{releaseDate:o}:{}};if(Object.keys(a).length===0)return s;let c=await Vr({versionId:s.id,...a},r);return{...s,...a,...a.releaseDate===void 0?{}:{releaseDate:c.version.releaseDate}}},wc=async e=>{let{id:t,jiraConfig:r,description:n,releaseDate:o,type:s="regular",baseSha:i}=e,a=te(t),c=await qk({versionName:a,jiraConfig:r,description:n,...o===void 0?{}:{releaseDate:o}}),l=Yt(r,c),d=await Cs({id:t,jiraVersionUrl:l,type:s,description:n,baseSha:i});return{version:Y(t),type:s,branchName:d.branchName,prUrl:d.prUrl,jiraVersionUrl:l,releaseDate:c.releaseDate||null}},As=async()=>{let e=new Map,t=await at();if(!t)return e;try{let r=await Br(t);for(let n of r)e.set(n.name,{description:n.description||null,releaseDate:n.releaseDate||null})}catch(r){u.warn({err:r},"Jira descriptions unavailable \u2014 the release list will render without them. If this persists, check JIRA_EMAIL / JIRA_TOKEN.")}return e},ne=async()=>{let e=await As();return new Map([...e].flatMap(([t,{description:r}])=>r?[[t,r]]:[]))},qn=(e,t,r)=>{let n=r?" ".repeat(r-e.length+3):" ",o=`[${t}]`.padEnd(11);return`${e}${n}${o}`},uc=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",Os=e=>e.flatMap(t=>{let r=J(t);return r?[{branch:t,id:r,label:Y(r)}]:[]}),ct=e=>{try{return xe(ye(e))}catch(t){throw new f(t,{operation:`resolve release ref "${e}"`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")',stderrExcerpt:t instanceof Error?t.message:String(t)})}},Yn=e=>{if(e===Lm)return Lm;let t=J(e);return t?Y(t):e},zt=e=>e.flatMap(t=>{let r=J(t);return r?[Y(r)]:[]}),Yk=(e,t)=>t?t.get(e)||"regular":void 0,oe=e=>{let{branches:t,descriptions:r,types:n}=e;return Os(t).map(({branch:o,id:s,label:i})=>({value:o,label:i,description:r.get(te(s)),type:Yk(o,n)}))};import Vm from"node:fs/promises";import zk from"node:path";import{$ as kc}from"zx";var L="pnpm-lock.yaml",Xk=/^(?:<{7}|={7}|>{7})(?:\s|$)/m,Um=async(e,t)=>{let r=zk.join(e,L),n=`${t}:${L}`;try{let o=await kc({cwd:e,quiet:!0})`git show ${n}`;await Vm.writeFile(r,o.stdout)}catch(o){return{ok:!1,reason:`dev has no ${L} to start from: ${Wm(o)}`}}try{await kc({cwd:e,quiet:!0})`pnpm install --lockfile-only --ignore-scripts --no-frozen-lockfile`}catch(o){return{ok:!1,reason:`pnpm could not merge ${L}: ${Wm(o)}`}}return Xk.test(await Vm.readFile(r,"utf8"))?{ok:!1,reason:`${L} still carries conflict markers after pnpm ran`}:(await kc({cwd:e,quiet:!0})`git add -- ${L}`,{ok:!0})},Wm=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim()};import{$ as Xt}from"zx";var bc="Merge remote-tracking branch 'origin/dev' into ",Jm=e=>String(e.stderr??e.message??e).trim(),Zk=async e=>{try{return(await Xt({cwd:e,quiet:!0})`git diff --name-only --diff-filter=U`).stdout.split(`
166
+ `).map(r=>r.trim()).filter(r=>r.length>0)}catch{return[]}},Qk=async(e,t)=>{let r=Jm(t),n=await Zk(e);return n.length>0?{status:"conflict",conflictPaths:n,reason:r}:await Yu(e)?{status:"hook-failed",reason:r}:{status:"error",reason:r}},Gm=async e=>{let{cwd:t,worktreePath:r,branches:n}=e,o=[],s=await Ce(t,"origin/dev");if(!s)return n.map(i=>({branch:i,status:"error",reason:"origin/dev does not resolve"}));for(let i of n){let a=Date.now(),c=await eb({cwd:t,worktreePath:r,branch:i,devSha:s});o.push({...c,durationMs:Date.now()-a})}return o},eb=async e=>{let{cwd:t,worktreePath:r,branch:n,devSha:o}=e,s=`origin/${n}`;if(!await Ce(t,s))return{branch:n,status:"error",reason:`${s} does not exist on origin`};if(await wn(t,"origin/dev",s))return{branch:n,status:"up-to-date"};try{await ra(r),await Xt({cwd:r,quiet:!0})`git checkout --detach ${s}`;let i=`${bc}${n}`;await Xt({cwd:r,quiet:!0})`git merge origin/dev --no-edit -m ${i}`;let a=(await Xt({cwd:r,quiet:!0})`git rev-parse HEAD`).stdout.trim();return{branch:n,status:a===o?"fast-forward":"merged",mergeSha:a}}catch(i){return{branch:n,...await Qk(r,i)}}finally{await na(r)}},Km=e=>e.flatMap(t=>t.mergeSha?[{branch:t.branch,sha:t.mergeSha}]:[]),Hm="pnpm install --frozen-lockfile",qm=async e=>{let{worktreePath:t,refs:r,command:n}=e,o=[],s=new Map;for(let i of r)try{await ra(t),await Xt({cwd:t,quiet:!0})`git checkout --detach ${i.sha}`,await Xt({cwd:t,quiet:!0})`sh -c ${n}`,o.push(i)}catch(a){s.set(i.branch,Jm(a))}finally{await na(t)}return{kept:o,failed:s}},zn=async(e,t,r="origin/dev")=>{await Xt({cwd:e,quiet:!0})`git fetch origin --prune`;let n=[],o=[];for(let s of t)await wn(e,r,`origin/${s.branch}`)?o.push(s.branch):n.push(s);return{kept:n,nowUpToDate:o}};import Rc from"node:process";var Is=new Set,Ds=e=>(Is.add(e),()=>{Is.delete(e)}),tb=async()=>{for(let e of[...Is])try{await e()}catch(t){u.warn({error:t,msg:"cleanup failed during shutdown"})}Is.clear()},rb=["SIGINT","SIGTERM"],Ym=async(e,t={})=>{let{register:r=(i,a)=>{Rc.on(i,a)},unregister:n=(i,a)=>{Rc.off(i,a)},exit:o=i=>{Rc.exit(i)}}=t,s=new Map;for(let i of rb){let a=()=>{tb().then(()=>{o(yp(i))})};s.set(i,a),r(i,a)}try{return await e()}finally{for(let[i,a]of s)n(i,a)}};var nb="pnpm install --frozen-lockfile --ignore-scripts",ob="pnpm install --frozen-lockfile",Zm=64*1024,nf=4096,Zn=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim().slice(-nf)},N=async(e,t)=>(await Ms({cwd:e,quiet:!0})`git ${t}`).stdout,Sc=e=>e.split(`
167
+ `).map(t=>t.trim()).filter(t=>t.length>0),js=e=>e.split("\0").filter(t=>t.length>0),Ns=async(e,t)=>{try{return(await N(e,["rev-parse","-q","--verify",t])).trim()||null}catch{return null}},of=async e=>ze.resolve(e,(await N(e,["rev-parse","--git-common-dir"])).trim()),Pc=e=>e.then(()=>!0,()=>!1),Xn=()=>({results:[],atomicPush:{attempted:!1,aborted:!1},declined:!1}),Ec=e=>e?.length===1&&e[0]===L,sf=async e=>ze.join(await of(e),"infra-kit","merge-dev-resolutions"),xc=async(e,t)=>ze.join(await sf(e),`${Hu(t)}.json`),af=async e=>{try{return JSON.parse(await Re.readFile(e,"utf8"))}catch{return null}},Jr=async(e,t)=>{let r=await xc(e,t.branch);await Re.mkdir(ze.dirname(r),{recursive:!0}),await Re.writeFile(r,`${JSON.stringify(t,null,2)}
168
+ `)},cf=async e=>{let t=await sf(e),r=await Re.readdir(t).catch(()=>[]);return(await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(o=>af(ze.join(t,o))))).filter(o=>o!==null)},lf=async e=>Promise.all((await cf(e)).map(async t=>({branch:t.branch,worktreePath:t.worktreePath,createdAt:t.createdAt,worktreeExists:await Pc(Re.stat(t.worktreePath))}))),Qm=(e,t)=>({worktreePath:e.worktreePath,baseSha:e.baseSha,devSha:e.devSha,conflictPaths:e.conflictPaths,lockfileOnly:e.lockfileOnly,rererePreResolved:e.rererePreResolved,state:t}),Tc=async(e,t,r)=>{await N(e,["worktree","remove","--force",r]).catch(()=>Re.rm(r,{recursive:!0,force:!0})),await Re.rm(await xc(e,t),{force:!0}).catch(()=>{}),await N(e,["worktree","prune"]).catch(()=>{})},df=async e=>js(await N(e,["diff","--name-only","-z","--diff-filter=U"])),_s=async e=>js(await N(e,["status","--porcelain","-z","--untracked-files=all","--ignored=matching"])).filter(r=>r.startsWith("!! ")).map(r=>r.slice(3)),sb=async(e,t)=>{let r=(await N(e,["config","--type=bool","--get","rerere.enabled"]).catch(()=>"")).trim(),n=await Pc(Re.stat(ze.join(await of(e),"rr-cache")));if(r==="false"||r===""&&!n)return[];let o=new Set(Sc(await N(e,["rerere","remaining"])));return t.filter(s=>!o.has(s))},uf=e=>e.split("/").includes("node_modules"),Fs=async(e,t)=>{let r=new Set(t.conflictPaths),n=new Set([...t.ignoredAtHandoff,...t.ignoredByVerify??[]]),o=js(await N(e,["diff","--cached","--name-only","-z","--no-renames",t.autoMergeTree])),s=[...await ib(e),...o].filter(a=>!r.has(a)),i=(await _s(e)).filter(a=>!n.has(a)&&!uf(a));return[...new Set([...s,...i,...await ab(e)])].sort()},ib=async e=>{let t=js(await N(e,["status","--porcelain","-z","--untracked-files=all"])),r=[],n=!1;for(let o of t){if(n){n=!1;continue}let[s,i]=o;i!==" "&&r.push(o.slice(3)),n=s==="R"||s==="C"}return r},ab=async e=>(await N(e,["ls-files","-v"])).split(`
169
+ `).filter(t=>{let r=t.charAt(0);return r==="S"||r!==""&&r!==r.toUpperCase()}).map(t=>t.slice(2)),cb=async e=>{let t=`:(exclude)${L}`;try{return await N(e,["diff","--cached","--check","HEAD","--",".",t]),[]}catch(r){let{stdout:n="",stderr:o="",exitCode:s}=r;if(o.trim().length>0||n.trim().length===0||s!==1&&s!==2)throw new f(r,{operation:"check the staged resolution for conflict markers"});let i=new Set;for(let a of n.split(`
170
+ `)){let c=/^(.*):\d+: leftover conflict marker/.exec(a);c?.[1]&&i.add(c[1])}return[...i].sort()}},lb=async(e,t)=>{let r=[];for(let n of t)(await Pc(Re.lstat(ze.join(e,n)))||(await N(e,["--literal-pathspecs","ls-files","--",n])).length>0)&&r.push(n);r.length>0&&await N(e,["--literal-pathspecs","add","-A","--",...r])},ef=async e=>(await N(e,["write-tree"])).trim(),pf=async e=>(await N(e,["rev-list","--parents","-n","1","HEAD"])).trim().split(" ").slice(1),db=e=>e?`${ob} && ${e}`:nb,ub=async(e,t)=>{try{return await Ms({cwd:e,quiet:!0})`sh -c ${t}`,{command:t,ok:!0}}catch(r){return{command:t,ok:!1,reason:Zn(r)}}},mf=async(e,t)=>{let r=(await N(e,["diff","--cached","--stat",t.autoMergeTree])).trim(),n=async l=>(await N(e,["diff","--cached","--stat",l,"--",L])).trim(),o=t.conflictPaths.includes(L)?{vsDev:await n(t.devSha),vsBase:await n(t.baseSha)}:void 0,s=await N(e,["diff","--cached",t.autoMergeTree,"--",".",`:(exclude)${L}`]),i=new Set(t.rererePreResolved),a=s.split(/^(?=diff --git )/m).map(l=>{let d=/^diff --git a\/(.*) b\//.exec(l)?.[1];return d&&i.has(d)?`# rerere (recorded resolution)
171
+ ${l}`:l}).join(""),c=zm.byteLength(a)>Zm;return{diffStat:r,...o?{lockfileDiffStat:o}:{},resolutionDiff:c?zm.from(a).subarray(0,Zm).toString():a,resolutionDiffTruncated:c}},ff=async e=>{let{cwd:t,branches:r,devSha:n}=e,o=new Map;for(let s of r)o.set(s,await pb(t,s,n));return o},pb=async(e,t,r)=>{let n=await af(await xc(e,t));if(n)return{resolution:Qm(n,"exists"),reason:`resolution-exists: ${n.worktreePath} \u2014 finish it with --continue or drop it with --abort`};let o=await Ce(e,`origin/${t}`);if(!o)return{reason:`origin/${t} does not exist on origin`};let s=qu(e,t),i=()=>Tc(e,t,s),a=Ds(i);try{await N(e,["worktree","prune"]),await Re.mkdir(ze.dirname(s),{recursive:!0}),await N(e,["worktree","add","--detach",s,o]),await Ms({cwd:s,quiet:!0})`git merge --no-commit ${r} -m ${bc+t}`.catch(()=>{});let c=await df(s);if(c.length===0)return await i(),{reason:"the merge no longer conflicts \u2014 re-run release merge-dev"};let l=await Ns(s,"AUTO_MERGE");if(!l)return await i(),{reason:`git-too-old: the scope check needs AUTO_MERGE, written by git \u2265 2.42 (found ${(await N(e,["--version"])).trim()})`};let d=await sb(s,c),p=Ec(c),m={branch:t,worktreePath:s,baseSha:o,devSha:r,conflictPaths:c,autoMergeTree:l,rererePreResolved:d,ignoredAtHandoff:await _s(s),lockfileOnly:p,cliVersion:G.version,createdAt:new Date().toISOString()};return await Jr(e,m),{resolution:Qm(m,p?"lockfile-only":"needs-agent")}}catch(c){return await i(),{reason:Zn(c)}}finally{a()}},gf=async e=>{let{cwd:t,versions:r,all:n}=e,o=await cf(t),s=o.map(a=>a.branch);if(r!==void 0)return(Array.isArray(r)?r:r.split(",")).map(c=>c.trim()).filter(c=>c.length>0).map(c=>{let l=xe(ye(c)),d=o.find(p=>p.branch===l);if(!d)throw new f(void 0,{operation:`select the resolution for "${c}"`,stderrExcerpt:`${l} has no resolution in progress`,remediation:s.length>0?`pass one of: ${s.join(", ")}`:"start one with release merge-dev --keep-conflicts"});return d});if(n||o.length===0)return o;let i=await xt(oe({branches:s,descriptions:new Map}),{required:!0});return o.filter(a=>i.includes(a.branch))},mb=async(e,t)=>{let r=await Re.realpath(t).catch(()=>null);if(!r)return!1;let n=await gt(e);for(let o of n)if(await Re.realpath(o.path).catch(()=>o.path)===r)return!0;return!1},Ur=(e,t,r,n)=>({...e,blocked:{code:t,detail:r,...n&&n.length>0?{paths:n}:{}}}),hf=async(e,t,r)=>{let n=t.worktreePath,o={branch:t.branch,worktreePath:n,baseSha:t.baseSha,devSha:t.devSha,conflictPaths:t.conflictPaths,lockfileMerged:!1,rerereFiles:t.rererePreResolved};if(!await mb(e,n))return Ur(o,"parents-mismatch",`the resolution worktree ${n} is gone \u2014 run --abort, then start again`);let s=await Ns(n,"HEAD"),i=await Ns(n,"MERGE_HEAD");return s===t.baseSha&&i===t.devSha?vb(e,t,o,r):fb(t,o,s,i)},fb=async(e,t,r,n)=>{let o=e.worktreePath;if(r!==null&&r===e.unapprovedCommit)return Ur(t,"tree-changed",`commit ${r} carries a tree a commit hook rewrote after approval \u2014 run --abort, then hand off again`);let s=n?[]:await pf(o),i=n?null:await Ns(o,"HEAD^{tree}");if(!(s.length===2&&s[0]===e.baseSha&&s[1]===e.devSha&&i!==null&&i===e.previewedTree)||!r||!i){let l=n?`HEAD ${r??"none"} merging ${n}`:`HEAD ${r??"none"}`;return Ur(t,"parents-mismatch",`expected HEAD ${e.baseSha} merging ${e.devSha}, or an approved merge commit of the two; found ${l}`)}let c=await Fs(o,e);return c.length>0?Ur(t,"out-of-scope-edit","only the conflicted paths may change",c):{...t,committed:!0,mergeSha:r,treeSha:i,lockfileMerged:e.conflictPaths.includes(L),...await mf(o,e)}},tf=async(e,t)=>{let r=Sc(await N(e,["--literal-pathspecs","ls-files","-s","--",t])),[n,o,s]=r.length===1?(r[0]??"").split(/\s+/):[];return n&&s==="0"?o??null:null},gb=async(e,t)=>{let r=t.worktreePath,n=await tf(r,L),o=t.lockfileBlob,s=await Um(r,t.devSha);if(!s.ok)return{code:"verify-failed",detail:s.reason,paths:[L]};let i=await tf(r,L);if(i!==null&&i!==o&&(t.lockfileBlob=i,await Jr(e,t)),n!==null&&n!==i)return n===o?{code:"tree-changed",detail:`rebuilding ${L} from dev resolved differently than the last preview (the registry moved) \u2014 preview again`,paths:[L]}:{code:"out-of-scope-edit",detail:`${L} was staged by something other than the CLI; it has been rebuilt from dev \u2014 preview again`,paths:[L]};let a=await Fs(r,t);return a.length>0?{code:"out-of-scope-edit",detail:"merging the lockfile changed other paths",paths:a}:null},hb=async(e,t)=>{let r=t.worktreePath;await lb(r,t.conflictPaths.filter(i=>i!==L));let n=await Fs(r,t);if(n.length>0)return{code:"out-of-scope-edit",detail:"only the conflicted paths may change",paths:n};let o=(await df(r)).filter(i=>i!==L);if(o.length>0)return{code:"unmerged-paths",detail:"these paths are still unmerged",paths:o};let s;try{s=await cb(r)}catch(i){return{code:"markers-remaining",detail:`the marker check could not run: ${Zn(i)}`}}return s.length>0?{code:"markers-remaining",detail:"conflict markers are still staged",paths:s}:t.conflictPaths.includes(L)?gb(e,t):null},yb=async(e,t,r,n)=>{if(t.verified?.treeSha===r&&t.verified.command===n)return{command:n,ok:!0,reused:!0};let o=t.worktreePath,s=new Set(await _s(o)),i=await ub(o,n);if(!i.ok)return i;let a=(await _s(o)).filter(c=>!s.has(c)&&!uf(c)&&ze.posix.basename(c)!==".gitignore");return t.ignoredByVerify=[...new Set([...t.ignoredByVerify??[],...a])],await Jr(e,t),i},vb=async(e,t,r,n)=>{let o=t.worktreePath,s=await hb(e,t);if(s)return{...r,blocked:s};let i=t.conflictPaths.includes(L),a=await ef(o),c=await yb(e,t,a,db(n)),l={...r,treeSha:a,lockfileMerged:i,verify:c};if(!c.ok)return Ur(l,"verify-failed",c.reason??"the verify command failed");let d=await Fs(o,t),p=Sc(await N(o,["diff","--name-only"]));return d.length>0||p.length>0||await ef(o)!==a?Ur(l,"verify-mutated-tree","the verify step changed the tree",[...new Set([...d,...p])]):(c.reused||(t.verified={treeSha:a,command:c.command},await Jr(e,t)),{...l,...await mf(o,t)})},wb=12e4,kb=async(e,t=wb)=>{let r=Ms({cwd:e,quiet:!0,detached:!0,stdio:["ignore","pipe","pipe"],env:{...Xm.env,GIT_TERMINAL_PROMPT:"0"}})`git commit --no-edit --cleanup=strip`,n=!1,o=setTimeout(()=>{n=!0;let s=r.child?.pid;try{s&&Xm.kill(-s,"SIGKILL")}catch{}},t);try{return await r,{ok:!0}}catch(s){if(!n)return{ok:!1,reason:Zn(s)};let i=(await N(e,["rev-parse","--git-path","index.lock"])).trim();return await Re.rm(ze.resolve(e,i),{force:!0}),{ok:!1,reason:`git commit timed out after ${t}ms`}}finally{clearTimeout(o)}},bb={"verify-failed":"verify-failed","tree-changed":"tree-changed"},Rb=e=>{let t=e.blocked;return{branch:e.branch,status:bb[t.code]??"blocked",conflictPaths:e.conflictPaths,pushed:!1,reason:[`${t.code}: ${t.detail}`,...t.paths?[`(${t.paths.join(", ")})`]:[]].join(" "),blocked:t}},Sb=async(e,t,r,n)=>{let o=r.worktreePath,s=(d,p,m={})=>({branch:t.branch,status:d,conflictPaths:t.conflictPaths,pushed:!1,reason:p,...m});if(!n)return s("tree-changed",`not approved: the preview this --yes came from had no ready tree for ${t.branch} \u2014 preview again`);if(t.treeSha!==n)return s("tree-changed",`the resolution is tree ${t.treeSha} but the approved tree is ${n} \u2014 preview again`);if(t.committed&&t.mergeSha)return{sha:t.mergeSha};let i=await kb(o);if(!i.ok)return s("hook-failed",i.reason);let a=(await N(o,["rev-parse","HEAD"])).trim(),c=(await N(o,["rev-parse","HEAD^{tree}"])).trim();if(c!==t.treeSha)return r.unapprovedCommit=a,await Jr(e,r),s("tree-changed",`a commit hook rewrote the tree (${c}, approved ${t.treeSha}) \u2014 run --abort, then hand off again`,{mergeSha:a});let l=await pf(o);if(l.length!==2||l[0]!==r.baseSha||l[1]!==r.devSha){let d={code:"parents-mismatch",detail:`commit parents are ${l.join(" ")}, expected ${r.baseSha} ${r.devSha}`};return s("blocked",`parents-mismatch: ${d.detail}`,{mergeSha:a,blocked:d})}return{sha:a}},Pb=async(e,t,r)=>{let n=(c,l,d)=>({branch:t.branch,status:c,mergeSha:r,conflictPaths:t.conflictPaths,pushed:!1,...l?{reason:l}:{},...d?{blocked:d}:{}}),o;try{o=(await zn(e,[{branch:t.branch,sha:r}],t.devSha)).nowUpToDate}catch(c){let l={code:"parents-mismatch",detail:`origin/${t.branch}: ${Zn(c)}`};return n("blocked",`parents-mismatch: ${l.detail}`,l)}if(o.includes(t.branch))return n("up-to-date",`origin/${t.branch} already carries ${t.devSha}`);let s=await Ce(e,`origin/${t.branch}`);if(s===t.baseSha)return"keep";let i=s!==null&&await wn(e,s,t.baseSha),a={code:"parents-mismatch",detail:`origin/${t.branch} ${i?"was rewound":"moved"} to ${s??"nothing"} since the hand-off at ${t.baseSha}`};return n("blocked",`parents-mismatch: ${a.detail}`,a)},Eb=e=>{u.info(`
172
+ \u{1F4CB} Resolution preview:`);for(let t of e)t.blocked?u.info(` ${t.branch} \u2014 BLOCKED ${t.blocked.code}: ${t.blocked.detail}`):u.info(` ${t.branch} \u2014 ready${t.committed?" (already committed)":""}: tree ${t.treeSha}`)},yf=async e=>{let{cwd:t,versions:r,all:n,verify:o,trees:s=new Map,confirmedCommand:i}=e,a=await gf({cwd:t,versions:r,all:n});if(a.length===0)return u.info("\u2139\uFE0F No merge-dev resolutions in progress"),Xn();if(i)return rf(t,a,o,s);let c=[];for(let m of a){let g=await hf(t,m,o);!g.blocked&&!g.committed&&g.treeSha&&(m.previewedTree=g.treeSha,await Jr(t,m)),c.push(g)}Eb(c);let l={branches:c},d=c.filter(m=>!m.blocked&&m.treeSha!==void 0);if(d.length===0)throw new x({status:"refused",plan:l,agentMode:I.source},2,{operation:"continue the merge-dev resolutions",stderrExcerpt:"every selected resolution is blocked",remediation:"fix the paths each row names, then preview again \u2014 or drop it with --abort"});let p=new Map(d.map(m=>[m.branch,m.treeSha]));try{await B(i,`Commit and push the resolved merges for: ${[...p.keys()].join(", ")}?`,{plan:l,throwOnDecline:!0,rerun:xb(p)})}catch(m){if(!nt(m))throw m;return{...Xn(),declined:!0}}return rf(t,a,o,p)},vf=e=>{let t=new Map,r=(Array.isArray(e)?e:[e??""]).flatMap(n=>n.split(","));for(let n of r.map(o=>o.trim())){if(n.length===0)continue;let o=/^(.+)=([0-9a-f]{40,64})$/.exec(n);if(!o?.[1]||!o[2])throw new f(void 0,{operation:"read --tree",stderrExcerpt:`"${n}" is not <branch>=<tree sha>`,remediation:"run the rerun a --continue preview printed, unchanged"});t.set(o[1],o[2])}return t},xb=e=>{let t=[],r=!1;for(let o of mp())r?r=!1:o==="--tree"?r=!0:o!=="--yes"&&o!=="-y"&&!o.startsWith("--tree=")&&t.push(o);let n=[...e].map(([o,s])=>`${o}=${s}`);return[...t,"--tree",n.join(","),"--yes"]},Tb=async(e,t,r,n)=>{let o=await hf(e,t,r);if(o.blocked)return Rb(o);let s=await Sb(e,o,t,n);if(!("sha"in s))return s;let i=await Pb(e,t,s.sha);return i==="keep"?s:i},Cb=async(e,t)=>{if(t.length===0)return{results:[],atomicPush:{attempted:!1,aborted:!1}};let r=t.map(s=>({branch:s.record.branch,sha:s.sha}));u.info(`
173
+ \u2B06\uFE0F Pushing atomically: ${r.map(s=>s.branch).join(", ")}`);let n=await rs(e,r),o=[];for(let s of t){let i=n.pushed||await kr(e,s.record.branch)===s.sha;o.push({branch:s.record.branch,status:i?"merged":"push-aborted",mergeSha:s.sha,conflictPaths:s.record.conflictPaths,pushed:i,...i?{}:{reason:n.stderr?.trim().slice(-nf)}})}return{results:o,atomicPush:{attempted:!0,aborted:!n.pushed,abortedBy:n.stderr?.split(`
174
+ `)[0]}}},rf=async(e,t,r,n)=>{let o=[],s=[];for(let d of t){let p=await Tb(e,d,r,n.get(d.branch));"sha"in p?s.push({record:d,sha:p.sha}):o.push(p)}let i=await Cb(e,s),a=[...o,...i.results],c=t.filter(d=>a.some(p=>p.branch===d.branch&&(p.pushed||p.status==="up-to-date")));for(let d of c)await Tc(e,d.branch,d.worktreePath);let l=t.map(d=>d.branch);return a.sort((d,p)=>l.indexOf(d.branch)-l.indexOf(p.branch)),{results:a,atomicPush:i.atomicPush,declined:!1}},wf=async e=>{let{cwd:t,versions:r,all:n,confirmedCommand:o}=e,s=await gf({cwd:t,versions:r,all:n});if(s.length===0)return u.info("\u2139\uFE0F No merge-dev resolutions in progress"),Xn();let i={branches:s.map(a=>({branch:a.branch,worktreePath:a.worktreePath}))};try{await B(o,`Discard the resolution worktrees for: ${s.map(a=>a.branch).join(", ")}?`,{plan:i,throwOnDecline:!0})}catch(a){if(!nt(a))throw a;return{...Xn(),declined:!0}}for(let a of s)await Tc(t,a.branch,a.worktreePath),u.info(`\u{1F5D1}\uFE0F Discarded the resolution for ${a.branch}`);return{...Xn(),results:s.map(a=>({branch:a.branch,status:"aborted",conflictPaths:a.conflictPaths,pushed:!1}))}};import $b from"node:fs";import Ab from"node:os";import Ob from"node:path";var Ib="infra-kit.json",Db="Skipped agent-instruction files, the plugin pointer, the plugin install and .mcp.json \u2014 no usable git repo root here (not a git repo, or the root is your home directory)",Nb="Skipped agent-instruction files \u2014 no infra-kit.json at the repo root (the plugin pointer, the plugin install and .mcp.json are unaffected)",Qn=async()=>{let e;try{e=await E()}catch{return null}let t=e.trim();return t===""||t===Ab.homedir()?null:t},kf=async()=>{let e=await Qn();return e===null&&u.info(Db),e},_b=async()=>{let e=await Qn();return e===null?null:$b.existsSync(Ob.join(e,Ib))?e:(u.info(Nb),null)};var Mb=async e=>{try{return await ke(e)}catch(t){return u.debug({err:t,msg:"Skipped per-package agent guidance \u2014 no workspace packages could be discovered."}),[]}},bf=async()=>{let e=await _b(),t=G.version;if(e===null)return{skipped:!0,root:null,version:t,written:[]};let r=[...await Dn(e,{version:t})];for(let n of await Mb(e)){let o=await Ut(n);r.push(...await Nn(n,{repoRoot:e,version:t,declaredType:o}))}return{skipped:!1,root:e,version:t,written:r}};import ae from"node:fs";import Mc from"node:os";import le from"node:path";import jc from"node:process";import Bs from"node:fs/promises";import jb from"node:path";import Fb from"node:process";var Rf=` // "envManagement": { // required in layer 1; provider-tagged
175
175
  // "provider": "doppler",
176
176
  // "config": { "name": "my-doppler-project" }
177
177
  // },
@@ -272,13 +272,24 @@ ${l}`:l}).join(""),c=of.byteLength(a)>af;return{diffStat:r,...o?{lockfileDiffSta
272
272
  // "exclude": ["serverless-config"]
273
273
  // }
274
274
  //
275
+ // // Rules \`ik audit --root\` checks the repo root against; each key replaces its built-in
276
+ // // baseline. Packages keep theirs in their own infra-kit.config.ts.
277
+ // //
278
+ // // PROJECT LAYER ONLY. REFUSED here and in the per-project override \u2014 the root audit gates CI,
279
+ // // so a per-machine copy would pass or fail a different check list than CI does.
280
+ // "audit": {
281
+ // "requiredScripts": ["build", "test", "qa"],
282
+ // "requiredFiles": ["turbo.json"],
283
+ // "turbo": { "requiredTasks": ["build", "test"] }
284
+ // }
285
+ //
275
286
  // // Doppler SERVICE TOKENS are not a config key and never belong in this file. They live in
276
287
  // // tokens.json \u2014 a SIBLING of this file, at ~/.infra-kit/projects/<repo>/tokens.json (mode 0600) \u2014
277
288
  // // shaped { "envs": { "<env>": "dp.st\u2026" } }. Write it with \`infra-kit env-token-set <env>\` (which
278
289
  // // also fixes its modes), or by hand: both are supported, which is why the store carries no
279
290
  // // repo-identity field and no mandatory version. Pasting a token into an
280
291
  // // infra-kit.json (any layer) is REJECTED: the loader refuses to parse it and tells you to revoke
281
- // // the token first, because a config file can be committed, backed up by your editor, or shared.`,Jc=()=>`// infra-kit user-global config \u2014 ~/.infra-kit/infra-kit.json
292
+ // // the token first, because a config file can be committed, backed up by your editor, or shared.`,Cc=()=>`// infra-kit user-global config \u2014 ~/.infra-kit/infra-kit.json
282
293
  //
283
294
  // Merge chain (later layers override earlier ones at top-level keys):
284
295
  // 1. <repo>/infra-kit.json \u2014 committed project config (required)
@@ -288,7 +299,7 @@ ${l}`:l}).join(""),c=of.byteLength(a)>af;return{diffStat:r,...o?{lockfileDiffSta
288
299
  // Merge is shallow: setting a top-level key replaces that whole section from
289
300
  // layer 1. Arrays do not concatenate. Top-level keys recognized:
290
301
  // envManagement, ide, taskManager, worktrees, dev, devServersPresets,
291
- // protectedEnvs, mcp, vendorSource (both project layer only). The schema is strict \u2014 an
302
+ // protectedEnvs, mcp, vendorSource, audit (the last three project layer only). The schema is strict \u2014 an
292
303
  // unrecognized top-level key is a parse error, not a silently ignored one.
293
304
  //
294
305
  // This .example.jsonc is reference only \u2014 it is NOT loaded. Put real global
@@ -299,15 +310,15 @@ ${l}`:l}).join(""),c=of.byteLength(a)>af;return{diffStat:r,...o?{lockfileDiffSta
299
310
  // the committed project infra-kit.json (layer 1) and is usually NOT set in this
300
311
  // user-global layer \u2014 it is shown here only to document the full, valid config shape.
301
312
  {
302
- ${Af}
313
+ ${Rf}
303
314
  }
304
- `,Uc=e=>`// infra-kit user override for ${e} \u2014 ~/.infra-kit/projects/${e}/infra-kit.json
315
+ `,$c=e=>`// infra-kit user override for ${e} \u2014 ~/.infra-kit/projects/${e}/infra-kit.json
305
316
  //
306
317
  // Layer 3 (highest precedence) of the config merge chain. Shallow-merged on top of
307
318
  // <repo>/infra-kit.json (layer 1) and ~/.infra-kit/infra-kit.json (layer 2) \u2014 a
308
319
  // top-level key set here replaces that whole section wholesale; arrays do not
309
320
  // concatenate. Top-level keys recognized: envManagement, ide, taskManager,
310
- // worktrees, dev, devServersPresets, protectedEnvs, mcp, vendorSource (project layer only \u2014
321
+ // worktrees, dev, devServersPresets, protectedEnvs, mcp, vendorSource, audit (the last three project layer only \u2014
311
322
  // refused here). The schema is strict \u2014 an unrecognized top-level key is a parse
312
323
  // error, not a silently ignored one.
313
324
  //
@@ -318,9 +329,9 @@ ${Af}
318
329
  // the committed project infra-kit.json (layer 1) and is usually NOT set in this
319
330
  // override layer \u2014 it is shown here only to document the full, valid config shape.
320
331
  {
321
- ${Af}
332
+ ${Rf}
322
333
  }
323
- `,Gc=()=>`// infra-kit factory registry \u2014 ~/.infra-kit/vendor.json
334
+ `,Ac=()=>`// infra-kit factory registry \u2014 ~/.infra-kit/vendor.json
324
335
  //
325
336
  // Machine-local registry the vendor commands (sync/manifest/diff) read to know
326
337
  // where your project repos live, which one is the source and which ones to stamp. This .example.jsonc is
@@ -332,94 +343,86 @@ ${Af}
332
343
  // "source": "starter-workspace", // string \u2014 the one repo \`vendor sync\` copies from (its infra-kit.json holds vendorSource)
333
344
  // "targets": ["my-repo-a", "my-repo-b"] // string[] (>=1) \u2014 repo dir names resolved under workspaceDir
334
345
  }
335
- `;var Of=!1,eR=e=>e.replace(/\.json$/,".example.jsonc"),tR=async e=>{try{return await Zs.readFile(e,"utf-8")}catch{return null}},Qr=async e=>{let t=e.userProject,r=eR(t);await Zs.mkdir(Zb.dirname(t),{recursive:!0});let n=!await X(t);n&&await Zs.writeFile(t,`{}
336
- `,"utf-8");let o=Uc(e.projectName),s=await tR(r)!==o;return s&&await Zs.writeFile(r,o,"utf-8"),n&&Pu(),{configPath:t,examplePath:r,createdConfig:n,refreshedExample:s}},en=e=>`Created ${w(e.configPath)} \u2014 see ${w(e.examplePath)} for the annotated reference.`,Kc=async()=>{if(Qb.env.INFRA_KIT_NO_SEED||Of)return;Of=!0;let e;try{e=await te()}catch{return}if(await X(e.main))try{let t=await Qr(e);t.createdConfig?p.info(en(t)):t.refreshedExample&&p.debug(`Refreshed ${w(t.examplePath)} to match the current schema.`)}catch(t){p.debug({err:t,msg:`Skipped seeding ${w(e.userProject)} (config bootstrap failed).`})}};import{spawn as rR}from"node:child_process";import Df from"node:fs";import tn from"node:process";import{fileURLToPath as Nf}from"node:url";var If=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],Hc=e=>{let{argv:t,env:r,isTty:n,selfRealPath:o,cwd:s,realpath:i}=e;return If.some(c=>{let l=r[c];return l!=null&&l!==""})?"opt-out":t.includes("--json")?"json":n?Lp(o,s,i)?"local-install":null:"not-a-tty"};var nR=e=>{rR(tn.execPath,[e,"--parent-pid",String(tn.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},oR=()=>Nf(new URL("./update-check.js",import.meta.url)),sR=()=>Df.realpathSync(Nf(new URL("./cli.js",import.meta.url))),iR=/^[\w@./+ -]+$/i,aR=e=>iR.test(e),cR=(e,t,r)=>{!e?.latestVersion||!e.updateCommand||jn(e.latestVersion,t)&&e.updateCommand.every(aR)&&r(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${as(e.updateCommand)}`)},qc=(e,t={})=>{try{let r=t.argv??tn.argv,n=t.env??tn.env,o=t.isTty??!!tn.stdout.isTTY,s=t.cwd??tn.cwd(),i=t.nowMs??Date.now(),a=t.selfRealPath??sR(),c=t.readCache??Fn,l=t.spawnChild??nR,d=t.fileExists??(y=>Df.existsSync(y)),u=t.notify??(y=>{p.info(y)});if(Hc({argv:r,env:n,isTty:o,selfRealPath:a,cwd:s,realpath:he})!==null)return;let m=c();if(cR(m,e,u),!xa(m,i))return;let g=t.childPath??oR();if(!d(g))return;l(g)}catch{}};import rt from"node:fs/promises";import tt from"node:path";import{pathToFileURL as pR}from"node:url";import uR from"yaml";import{z as on}from"zod";import lR from"node:fs/promises";import zc from"node:os";import Yc from"node:path";import{z as dR}from"zod";import{z as uo}from"zod";var _f="vendor.json",Mf=uo.object({workspaceDir:uo.string().min(1),source:uo.string().min(1),targets:uo.array(uo.string()).min(1)}).strict().refine(e=>!e.targets.includes(e.source),{message:'the source repo must not also be listed in "targets"',path:["targets"]});var rn=()=>Yc.join(zc.homedir(),Dp,_f),nn=e=>{if(e==="~")return zc.homedir();if(e.startsWith("~/"))return Yc.join(zc.homedir(),e.slice(2));if(Yc.isAbsolute(e))return e;throw new Error(`workspaceDir must be absolute or ~-prefixed, got: ${e}`)},Qs=async()=>{let e=rn(),t;try{t=await lR.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, which one is the source and which to stamp. Run \`infra-kit vendor config --init\` to scaffold it, or create it manually as JSON:
346
+ `;var Sf=!1,Lb=e=>e.replace(/\.json$/,".example.jsonc"),Bb=async e=>{try{return await Bs.readFile(e,"utf-8")}catch{return null}},Gr=async e=>{let t=e.userProject,r=Lb(t);await Bs.mkdir(jb.dirname(t),{recursive:!0});let n=!await z(t);n&&await Bs.writeFile(t,`{}
347
+ `,"utf-8");let o=$c(e.projectName),s=await Bb(r)!==o;return s&&await Bs.writeFile(r,o,"utf-8"),n&&sp(),{configPath:t,examplePath:r,createdConfig:n,refreshedExample:s}},Kr=e=>`Created ${w(e.configPath)} \u2014 see ${w(e.examplePath)} for the annotated reference.`,Oc=async()=>{if(Fb.env.INFRA_KIT_NO_SEED||Sf)return;Sf=!0;let e;try{e=await Q()}catch{return}if(await z(e.main))try{let t=await Gr(e);t.createdConfig?u.info(Kr(t)):t.refreshedExample&&u.debug(`Refreshed ${w(t.examplePath)} to match the current schema.`)}catch(t){u.debug({err:t,msg:`Skipped seeding ${w(e.userProject)} (config bootstrap failed).`})}};import{spawn as Vb}from"node:child_process";import Ef from"node:fs";import Hr from"node:process";import{fileURLToPath as xf}from"node:url";var Pf=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],Ic=e=>{let{argv:t,env:r,isTty:n,selfRealPath:o,cwd:s,realpath:i}=e;return Pf.some(c=>{let l=r[c];return l!=null&&l!==""})?"opt-out":t.includes("--json")?"json":n?wu(o,s,i)?"local-install":null:"not-a-tty"};var Wb=e=>{Vb(Hr.execPath,[e,"--parent-pid",String(Hr.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},Ub=()=>xf(new URL("./update-check.js",import.meta.url)),Jb=()=>Ef.realpathSync(xf(new URL("./cli.js",import.meta.url))),Gb=/^[\w@./+ -]+$/i,Kb=e=>Gb.test(e),Hb=(e,t,r)=>{!e?.latestVersion||!e.updateCommand||bn(e.latestVersion,t)&&e.updateCommand.every(Kb)&&r(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${qo(e.updateCommand)}`)},Dc=(e,t={})=>{try{let r=t.argv??Hr.argv,n=t.env??Hr.env,o=t.isTty??!!Hr.stdout.isTTY,s=t.cwd??Hr.cwd(),i=t.nowMs??Date.now(),a=t.selfRealPath??Jb(),c=t.readCache??Rn,l=t.spawnChild??Wb,d=t.fileExists??(y=>Ef.existsSync(y)),p=t.notify??(y=>{u.info(y)});if(Ic({argv:r,env:n,isTty:o,selfRealPath:a,cwd:s,realpath:me})!==null)return;let m=c();if(Hb(m,e,p),!aa(m,i))return;let g=t.childPath??Ub();if(!d(g))return;l(g)}catch{}};import Ze from"node:fs/promises";import Xe from"node:path";import{pathToFileURL as zb}from"node:url";import Xb from"yaml";import{z as zr}from"zod";import qb from"node:fs/promises";import Nc from"node:os";import _c from"node:path";import{z as Yb}from"zod";import{z as eo}from"zod";var Tf="vendor.json",Cf=eo.object({workspaceDir:eo.string().min(1),source:eo.string().min(1),targets:eo.array(eo.string()).min(1)}).strict().refine(e=>!e.targets.includes(e.source),{message:'the source repo must not also be listed in "targets"',path:["targets"]});var qr=()=>_c.join(Nc.homedir(),uu,Tf),Yr=e=>{if(e==="~")return Nc.homedir();if(e.startsWith("~/"))return _c.join(Nc.homedir(),e.slice(2));if(_c.isAbsolute(e))return e;throw new Error(`workspaceDir must be absolute or ~-prefixed, got: ${e}`)},Vs=async()=>{let e=qr(),t;try{t=await qb.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, which one is the source and which to stamp. Run \`infra-kit vendor config --init\` to scaffold it, or create it manually as JSON:
337
348
 
338
349
  {
339
350
  "workspaceDir": "~/projects",
340
351
  "source": "my-starter",
341
352
  "targets": ["my-repo"]
342
353
  }
343
- `)}let r;try{r=t.trim()===""?{}:JSON.parse(t)}catch(o){throw new Error(`Invalid JSON in vendor.json at ${e}: ${o.message}`)}let n=Mf.safeParse(r);if(!n.success)throw new Error(`Invalid factory config at ${e}: ${dR.prettifyError(n.error)}`);return n.data};var jf=e=>e.replace(/\.json$/,".yml"),Ff=async()=>{let e;try{e=await te()}catch{return}let t=[{label:"infra-kit.json",yml:jf(e.main),json:e.main,schema:bu},{label:"~/.infra-kit/infra-kit.json",yml:tt.join(tt.dirname(e.userGlobal),"config.yml"),json:e.userGlobal,schema:Ea},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:jf(e.userProject),json:e.userProject,schema:Ea}],r=0;for(let n of t){let[o,s]=await Promise.all([X(n.yml),X(n.json)]);if(o){if(s){p.info(`\u26A0 Skipped ${w(n.yml)} \u2014 ${w(n.json)} already exists (remove the stale .yml manually)`);continue}try{let i=await rt.readFile(n.yml,"utf-8"),a=uR.parse(i)??{},c=n.schema.safeParse(a);if(!c.success){p.info(`\u26A0 Skipped ${w(n.yml)} \u2014 invalid config: ${on.prettifyError(c.error)}`);continue}await rt.mkdir(tt.dirname(n.json),{recursive:!0}),await rt.writeFile(n.json,`${JSON.stringify(c.data,null,2)}
344
- `,"utf-8"),await rt.rm(n.yml,{force:!0}),p.info(`\u2713 Migrated ${w(n.yml)} \u2192 ${w(n.json)}`),r++}catch(i){p.info(`\u26A0 Skipped ${w(n.yml)} \u2014 ${i.message}`)}}}r>0&&Ct()},Lf=async()=>{let e;try{e=await te()}catch{return}let t=tt.dirname(e.userGlobal),r=[{from:tt.join(t,"config.json"),to:e.userGlobal},{from:tt.join(t,"config.example.jsonc"),to:tt.join(t,"infra-kit.example.jsonc")}],n=0;for(let{from:o,to:s}of r){let[i,a]=await Promise.all([X(o),X(s)]);if(i){if(a){p.info(`\u26A0 Skipped ${w(o)} \u2014 ${w(s)} already exists (remove the stale file manually)`);continue}try{await rt.mkdir(tt.dirname(s),{recursive:!0}),await rt.rename(o,s),p.info(`\u2713 Renamed ${w(o)} \u2192 ${w(s)}`),n++}catch(c){p.info(`\u26A0 Skipped ${w(o)} \u2014 ${c.message}`)}}}n>0&&Ct()},mR=on.object({workspaceDir:on.string().min(1),targets:on.array(on.string()).min(1)}).strict(),Vf=async()=>{let e=rn(),t=tt.dirname(e),r=tt.join(t,"vendor.config.ts"),[n,o]=await Promise.all([X(r),X(e)]);if(n){if(o){p.info(`\u26A0 Skipped ${w(r)} \u2014 ${w(e)} already exists (remove the stale vendor.config.ts manually)`);return}try{let s=await rt.stat(r),c=(await import(`${pR(r).href}?mtime=${Number(s.mtimeMs)}`)).default,l=typeof c=="function",d=l?await c():c,u=mR.safeParse(d);if(!u.success){p.info(`\u26A0 Skipped ${w(r)} \u2014 invalid factory config: ${on.prettifyError(u.error)}`);return}await rt.mkdir(t,{recursive:!0}),await rt.writeFile(e,`${JSON.stringify(u.data,null,2)}
345
- `,"utf-8"),await rt.rm(r,{force:!0}),l?p.info(`\u26A0 Migrated ${w(r)} \u2192 ${w(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 ${w(e)} directly to change them.`):p.info(`\u2713 Migrated ${w(r)} \u2192 ${w(e)}`)}catch(s){p.info(`\u26A0 Skipped ${w(r)} \u2014 ${s.message}`)}}},Bf=async()=>{let e=await fR(),t=0;for(let r of e)if(await X(r))try{let n=await vu(r);if(!n.changed)continue;p.info(`\u2713 Migrated ${w(r)} (removed ${n.notes.join(" and ")})`),t++}catch(n){let o=n instanceof yu?"changed while migrating":n.message;p.info(`\u26A0 Skipped ${w(r)} \u2014 ${o}`)}t>0&&Ct()},fR=async()=>{try{let e=await te();return[e.main,e.userGlobal,e.userProject]}catch{return[Su()]}};var sr="# -- infra-kit:begin --",_t="# -- infra-kit:end --",gR=[["# region infra-kit","# endregion infra-kit"]],hR="# infra-kit shell functions",sn=class extends Error{constructor(r,n){super(n instanceof Error?n.message:String(n),{cause:n});this.step=r;this.reason=n;this.name="InitStepError"}step;reason},an="Run `source ~/.zshrc` or open a new terminal to activate.",yR={step:"migrations",outcome:"unchanged",message:"Config migrations checked (legacy yml layers, user-global filename, ide structure, factory config, retired project cache)",level:"silent"},nt=async(e,t)=>{try{return await t()}catch(r){throw new sn(e,r)}},Qc=async e=>{let t=[],r=(...s)=>{for(let i of s)t.push(i),e?.(i)};await nt("zshrc",()=>{r(vR())}),await nt("zshenv",()=>{r(wR())}),await nt("migrations",async()=>{await bR(),kR(),r(yR)}),await nt("user-config",()=>{r(SR())});let n=await nt("guidance",async()=>{let{entries:s,root:i}=await xR();return r(...s),i}),o=await nt("plugin-pointer",async()=>Cf());return r(...$R(o,n)),await nt("worktrees",async()=>{r(...await NR(o))}),await nt("plugin-pointer",async()=>{await _R(o,r)}),await nt("mcp-proxies",async()=>{r(...await jR(o))}),await nt("project-config",async()=>{r(...await PR())}),r(...RR()),t};var vR=()=>{let e=me.join(Xc.homedir(),".zshrc"),t=le.existsSync(e)?LR(le.readFileSync(e,"utf-8")):"",r=Dr({content:t,body:Jf(),startMarker:sr,endMarker:_t,placement:"append-end"});return le.writeFileSync(e,r),{step:"zshrc",outcome:"written",message:`Added infra-kit shell functions to ${e}`,level:"info"}},wR=()=>{let e=me.join(Xc.homedir(),".zshenv"),t=le.existsSync(e)?le.readFileSync(e,"utf-8"):"",r=Dr({content:t,body:el(),startMarker:sr,endMarker:_t});return le.writeFileSync(e,r),{step:"zshenv",outcome:"written",message:`Added infra-kit session-env block to ${e}`,level:"info"}},kR=()=>{le.rmSync(me.join(Mp(),"projects"),{recursive:!0,force:!0})},bR=async()=>{await Ff(),await Lf(),await Bf(),await Vf()},RR=()=>{let e=Zc.env.SHELL??"",t=[];return e.includes("zsh")||t.push({step:"shell",outcome:"warned",message:`Your login shell ($SHELL=${e||"unset"}) is not zsh. The infra-kit shell integration (env-load/env-clear) is zsh-only and won't activate in bash/fish.`,level:"warn"}),t.push({step:"shell",outcome:"unchanged",message:an,level:"info"}),t},SR=()=>{let e=me.join(Xc.homedir(),".infra-kit"),t=me.join(e,"infra-kit.json");return le.mkdirSync(e,{recursive:!0}),le.writeFileSync(me.join(e,"infra-kit.example.jsonc"),Jc(),"utf-8"),le.writeFileSync(me.join(e,"vendor.example.jsonc"),Gc(),"utf-8"),le.existsSync(t)?{step:"user-config",outcome:"unchanged",message:`User-global config already present at ${t} (refreshed reference examples)`,level:"info"}:(le.writeFileSync(t,`{}
346
- `,"utf-8"),{step:"user-config",outcome:"written",message:`Wrote user-global config to ${t} (see the sibling .example.jsonc files for reference)`,level:"info"})},PR=async()=>{if(Zc.env.INFRA_KIT_NO_SEED)return[ei("skipped","INFRA_KIT_NO_SEED is set")];try{let e=await te();if(!le.existsSync(e.main))return[ei("skipped",`no project config at ${e.main}`)];let t=await Qr(e);return t.createdConfig?[{step:"project-config",outcome:"written",message:en(t),level:"info"}]:[ei("unchanged","the user-project config was already present")]}catch(e){return p.debug({err:e,msg:"Skipped seeding the user-project config (init)."}),[ei("warned",e instanceof Error?e.message:String(e))]}},ei=(e,t)=>({step:"project-config",outcome:e,message:`Skipped seeding the user-project config \u2014 ${t}`,level:"silent"}),ER=(e,t,r)=>{let n=[];for(let s of r){if(s.action==="unchanged")continue;let i=s.type===void 0?"":` (${s.type})`;n.push({step:"guidance",outcome:s.action==="failed"?"warned":"written",message:` ${s.action.padEnd(9)} ${me.relative(e,s.path)}${i}`,level:"info"})}n.push({step:"guidance",outcome:"written",message:`Agent-instruction files synced (infra-kit ${t})`,level:"info"});let o=r.filter(s=>s.action==="failed");return o.length===0||n.push({step:"guidance",outcome:"warned",message:`${o.length} package guidance files could not be written \u2014 run: infra-kit audit --fix --all`,level:"warn"}),n},xR=async()=>{let{skipped:e,root:t,version:r,written:n}=await $f();return e||t===null?{root:null,entries:[{step:"guidance",outcome:"skipped",message:"Agent-instruction files skipped \u2014 not an infra-kit repo",level:"silent"}]}:{root:t,entries:ER(t,r,n)}},TR=(e,t)=>{let r=me.relative(e,t.path);return t.status==="created"?{step:"plugin-pointer",outcome:"written",message:` created ${r} (Claude Code plugin pointer)`,level:"info"}:t.status==="added"?{step:"plugin-pointer",outcome:"written",message:` updated ${r} \u2014 added ${t.added.join(", ")}`,level:"info"}:{step:"plugin-pointer",outcome:t.status==="unchanged"?"unchanged":"warned",message:`${r} \u2014 ${t.status}`,level:"silent"}},CR=(e,t)=>{let r=Oe;if(t.kind==="stale"||t.kind==="wrong-key"){let o=t.kind==="stale"?ae:t.key;return{step:"mcp-server",outcome:"unchanged",message:` ${r} still registers the infra-kit MCP server under "${o}" \u2014 the plugin no longer serves one, so this entry only spawns a failed server row. Delete the "${o}" entry from ${r} by hand in a PR, keeping its siblings`,level:"info"}}return t.kind==="unparseable"?{step:"mcp-server",outcome:"warned",message:`Could not read ${Ze} from ${me.join(e,Oe)} \u2014 fix the JSON and re-run: infra-kit setup --skip-tools`,level:"warn"}:{step:"mcp-server",outcome:"unchanged",message:` infra-kit MCP server: none wanted \u2014 the plugin is skills-only (${t.kind==="absent"?`${r} carries no "${ae}" key`:`no ${r}`})`,level:"info"}},$R=(e,t)=>e===null||t!==null?[]:[{step:"plugin-pointer",outcome:"warned",message:`No infra-kit.json at ${e} \u2014 setting up Claude Code there anyway: writing .claude/settings.json and installing the ${H} plugin for that project. If that is not the repo you meant to set up, revert that file and uninstall the plugin.`,level:"warn"}],AR=()=>[lc,pt].map(e=>({step:"plugin-pointer",outcome:"manual",message:e,level:"info"})),OR=e=>{let r={step:"plugin-pointer",outcome:"warned",message:`Claude Code plugin not updated \u2014 ${e.stale?`CLI ${q.version} is behind ${e.latestVersion}, update it first with the command below`:`CLI ${q.version} is behind the published version, update it first`}. The plugin follows on the next update check after that.`,level:"warn"};return e.stale?[r,{step:"plugin-pointer",outcome:"manual",message:as(e.updateCommand),level:"info"}]:[r]},IR=(e,t)=>e.status==="skipped-cli-stale"?OR(t):e.status==="updated"?[{step:"plugin-pointer",outcome:"unchanged",message:`Claude Code plugin ${H} up to date (project scope)`,level:"info"}]:e.status==="update-failed"?[{step:"plugin-pointer",outcome:"warned",message:`Could not update the Claude Code plugin \u2014 ${e.error}. Run by hand: ${Vr}`,level:"warn"}]:e.status==="installed"?[{step:"plugin-pointer",outcome:"written",message:`installed Claude Code plugin ${H} (project scope)`,level:"info"}]:e.status==="claude-missing"?[{step:"plugin-pointer",outcome:"skipped",message:"No `claude` on PATH, so the Claude Code plugin was not installed. Install Claude Code, then run:",level:"info"},...AR()]:[{step:"plugin-pointer",outcome:"warned",message:`Could not install the Claude Code plugin \u2014 ${e.status==="unverified"?"the install reported success but Claude Code recorded no installation":`the ${e.step} step failed: ${e.error}`}. Run by hand: ${pt}`,level:"warn"}],Wf={stale:!1},DR=async()=>{let e=Fn(),t=e===null?await Ta(Zc.env):e.latestVersion;return t===null||!Ca(t,q.version)?Wf:{stale:!0,latestVersion:t,updateCommand:e?.updateCommand??Fp(t)}},NR=async e=>{if(e===null)return[];let r=`${await Le(e)}${ge}`,n=Object.values(Cr).filter(o=>!le.existsSync(me.join(r,o)));for(let o of Object.values(Cr))le.mkdirSync(me.join(r,o),{recursive:!0});return n.length===0?[{step:"worktrees",outcome:"unchanged",message:`Worktree directories already present at ${r}`,level:"info"}]:[{step:"worktrees",outcome:"written",message:`Created worktree directories at ${r} (${n.join(", ")})`,level:"info"}]},_R=async(e,t)=>{if(e===null){t({step:"plugin-pointer",outcome:"skipped",message:"Claude Code plugin steps skipped \u2014 no git root safe to write into",level:"silent"});return}try{t(TR(e,dc(me.join(e,".claude","settings.json"))));let n=qt({projectPath:e}).kind==="installed"?await DR():Wf;t(...IR(oc({projectRoot:e,cliIsStale:()=>n.stale}),n)),t(CR(e,qn(e)))}catch(r){let n=r instanceof Error?r.message:String(r);t({step:"plugin-pointer",outcome:"warned",message:`Could not finish the Claude Code plugin step for ${e} (${n}). Run by hand: ${pt}`,level:"warn"})}},MR=(e,t)=>{let r=me.relative(e,t.path);if(t.status!=="ok"&&t.status!=="failed")return[{step:"mcp-proxies",outcome:"warned",message:` ${r} could not be read as JSON \u2014 ik-mcp entries not synced`,level:"warn"}];if(t.status==="failed")return[{step:"mcp-proxies",outcome:"warned",message:` ${r} could not be written \u2014 ik-mcp entries not synced`,level:"warn"}];let n=[];for(let o of t.entries)o.status==="written"?n.push({step:"mcp-proxies",outcome:"written",message:` updated ${r} \u2014 ik-mcp "${o.name}"`,level:"info"}):(o.status==="conflict"||o.status==="stale")&&n.push({step:"mcp-proxies",outcome:"warned",message:` ${o.message}`,level:"warn"});return n},jR=async e=>{if(e===null)return[];if(!le.existsSync(me.join(e,"infra-kit.json")))return[{step:"mcp-proxies",outcome:"skipped",message:"no infra-kit.json \u2014 no ik-mcp entries to derive",level:"silent"}];let t;try{t=(await D()).mcp}catch(r){let n=r instanceof Error?r.message:String(r);return[{step:"mcp-proxies",outcome:"warned",message:` ik-mcp entries not synced \u2014 infra-kit.json could not be loaded (${n.split(`
347
- `)[0]??n})`,level:"warn"}]}return!t||Object.keys(t).length===0?[]:MR(e,Ds({projectRoot:e,proxies:t,write:!0}))},FR=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("fi"),LR=e=>{let t=At(e,sr,_t);if(t!==null)return t;for(let[a,c]of gR){let l=At(e,a,c);if(l!==null)return l}let r=e.indexOf(hR);if(r===-1)return e;let n=e.slice(0,r).replace(/\n+$/,""),o=e.slice(r).split(`
348
- `),s=0;for(;s<o.length&&FR(o[s]);)s++;let i=o.slice(s).join(`
354
+ `)}let r;try{r=t.trim()===""?{}:JSON.parse(t)}catch(o){throw new Error(`Invalid JSON in vendor.json at ${e}: ${o.message}`)}let n=Cf.safeParse(r);if(!n.success)throw new Error(`Invalid factory config at ${e}: ${Yb.prettifyError(n.error)}`);return n.data};var $f=e=>e.replace(/\.json$/,".yml"),Af=async()=>{let e;try{e=await Q()}catch{return}let t=[{label:"infra-kit.json",yml:$f(e.main),json:e.main,schema:rp},{label:"~/.infra-kit/infra-kit.json",yml:Xe.join(Xe.dirname(e.userGlobal),"config.yml"),json:e.userGlobal,schema:oa},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:$f(e.userProject),json:e.userProject,schema:oa}],r=0;for(let n of t){let[o,s]=await Promise.all([z(n.yml),z(n.json)]);if(o){if(s){u.info(`\u26A0 Skipped ${w(n.yml)} \u2014 ${w(n.json)} already exists (remove the stale .yml manually)`);continue}try{let i=await Ze.readFile(n.yml,"utf-8"),a=Xb.parse(i)??{},c=n.schema.safeParse(a);if(!c.success){u.info(`\u26A0 Skipped ${w(n.yml)} \u2014 invalid config: ${zr.prettifyError(c.error)}`);continue}await Ze.mkdir(Xe.dirname(n.json),{recursive:!0}),await Ze.writeFile(n.json,`${JSON.stringify(c.data,null,2)}
355
+ `,"utf-8"),await Ze.rm(n.yml,{force:!0}),u.info(`\u2713 Migrated ${w(n.yml)} \u2192 ${w(n.json)}`),r++}catch(i){u.info(`\u26A0 Skipped ${w(n.yml)} \u2014 ${i.message}`)}}}r>0&&vt()},Of=async()=>{let e;try{e=await Q()}catch{return}let t=Xe.dirname(e.userGlobal),r=[{from:Xe.join(t,"config.json"),to:e.userGlobal},{from:Xe.join(t,"config.example.jsonc"),to:Xe.join(t,"infra-kit.example.jsonc")}],n=0;for(let{from:o,to:s}of r){let[i,a]=await Promise.all([z(o),z(s)]);if(i){if(a){u.info(`\u26A0 Skipped ${w(o)} \u2014 ${w(s)} already exists (remove the stale file manually)`);continue}try{await Ze.mkdir(Xe.dirname(s),{recursive:!0}),await Ze.rename(o,s),u.info(`\u2713 Renamed ${w(o)} \u2192 ${w(s)}`),n++}catch(c){u.info(`\u26A0 Skipped ${w(o)} \u2014 ${c.message}`)}}}n>0&&vt()},Zb=zr.object({workspaceDir:zr.string().min(1),targets:zr.array(zr.string()).min(1)}).strict(),If=async()=>{let e=qr(),t=Xe.dirname(e),r=Xe.join(t,"vendor.config.ts"),[n,o]=await Promise.all([z(r),z(e)]);if(n){if(o){u.info(`\u26A0 Skipped ${w(r)} \u2014 ${w(e)} already exists (remove the stale vendor.config.ts manually)`);return}try{let s=await Ze.stat(r),c=(await import(`${zb(r).href}?mtime=${Number(s.mtimeMs)}`)).default,l=typeof c=="function",d=l?await c():c,p=Zb.safeParse(d);if(!p.success){u.info(`\u26A0 Skipped ${w(r)} \u2014 invalid factory config: ${zr.prettifyError(p.error)}`);return}await Ze.mkdir(t,{recursive:!0}),await Ze.writeFile(e,`${JSON.stringify(p.data,null,2)}
356
+ `,"utf-8"),await Ze.rm(r,{force:!0}),l?u.info(`\u26A0 Migrated ${w(r)} \u2192 ${w(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 ${w(e)} directly to change them.`):u.info(`\u2713 Migrated ${w(r)} \u2192 ${w(e)}`)}catch(s){u.info(`\u26A0 Skipped ${w(r)} \u2014 ${s.message}`)}}},Df=async()=>{let e=await Qb(),t=0;for(let r of e)if(await z(r))try{let n=await Qu(r);if(!n.changed)continue;u.info(`\u2713 Migrated ${w(r)} (removed ${n.notes.join(" and ")})`),t++}catch(n){let o=n instanceof Xu?"changed while migrating":n.message;u.info(`\u26A0 Skipped ${w(r)} \u2014 ${o}`)}t>0&&vt()},Qb=async()=>{try{let e=await Q();return[e.main,e.userGlobal,e.userProject]}catch{return[op()]}};var Zt="# -- infra-kit:begin --",Tt="# -- infra-kit:end --",eR=[["# region infra-kit","# endregion infra-kit"]],tR="# infra-kit shell functions",Xr=class extends Error{constructor(r,n){super(n instanceof Error?n.message:String(n),{cause:n});this.step=r;this.reason=n;this.name="InitStepError"}step;reason},Zr="Run `source ~/.zshrc` or open a new terminal to activate.",rR={step:"migrations",outcome:"unchanged",message:"Config migrations checked (legacy yml layers, user-global filename, ide structure, factory config, retired project cache)",level:"silent"},Qe=async(e,t)=>{try{return await t()}catch(r){throw new Xr(e,r)}},Fc=async e=>{let t=[],r=(...s)=>{for(let i of s)t.push(i),e?.(i)};await Qe("zshrc",()=>{r(nR())}),await Qe("zshenv",()=>{r(oR())}),await Qe("migrations",async()=>{await iR(),sR(),r(rR)}),await Qe("user-config",()=>{r(cR())});let n=await Qe("guidance",async()=>{let{entries:s,root:i}=await uR();return r(...s),i}),o=await Qe("plugin-pointer",async()=>kf());return r(...fR(o,n)),await Qe("worktrees",async()=>{r(...await wR(o))}),await Qe("plugin-pointer",async()=>{await kR(o,r)}),await Qe("mcp-proxies",async()=>{r(...await RR(o))}),await Qe("project-config",async()=>{r(...await lR())}),r(...aR()),t};var nR=()=>{let e=le.join(Mc.homedir(),".zshrc"),t=ae.existsSync(e)?PR(ae.readFileSync(e,"utf-8")):"",r=Er({content:t,body:_f(),startMarker:Zt,endMarker:Tt,placement:"append-end"});return ae.writeFileSync(e,r),{step:"zshrc",outcome:"written",message:`Added infra-kit shell functions to ${e}`,level:"info"}},oR=()=>{let e=le.join(Mc.homedir(),".zshenv"),t=ae.existsSync(e)?ae.readFileSync(e,"utf-8"):"",r=Er({content:t,body:Lc(),startMarker:Zt,endMarker:Tt});return ae.writeFileSync(e,r),{step:"zshenv",outcome:"written",message:`Added infra-kit session-env block to ${e}`,level:"info"}},sR=()=>{ae.rmSync(le.join(gu(),"projects"),{recursive:!0,force:!0})},iR=async()=>{await Af(),await Of(),await Df(),await If()},aR=()=>{let e=jc.env.SHELL??"",t=[];return e.includes("zsh")||t.push({step:"shell",outcome:"warned",message:`Your login shell ($SHELL=${e||"unset"}) is not zsh. The infra-kit shell integration (env-load/env-clear) is zsh-only and won't activate in bash/fish.`,level:"warn"}),t.push({step:"shell",outcome:"unchanged",message:Zr,level:"info"}),t},cR=()=>{let e=le.join(Mc.homedir(),".infra-kit"),t=le.join(e,"infra-kit.json");return ae.mkdirSync(e,{recursive:!0}),ae.writeFileSync(le.join(e,"infra-kit.example.jsonc"),Cc(),"utf-8"),ae.writeFileSync(le.join(e,"vendor.example.jsonc"),Ac(),"utf-8"),ae.existsSync(t)?{step:"user-config",outcome:"unchanged",message:`User-global config already present at ${t} (refreshed reference examples)`,level:"info"}:(ae.writeFileSync(t,`{}
357
+ `,"utf-8"),{step:"user-config",outcome:"written",message:`Wrote user-global config to ${t} (see the sibling .example.jsonc files for reference)`,level:"info"})},lR=async()=>{if(jc.env.INFRA_KIT_NO_SEED)return[Ws("skipped","INFRA_KIT_NO_SEED is set")];try{let e=await Q();if(!ae.existsSync(e.main))return[Ws("skipped",`no project config at ${e.main}`)];let t=await Gr(e);return t.createdConfig?[{step:"project-config",outcome:"written",message:Kr(t),level:"info"}]:[Ws("unchanged","the user-project config was already present")]}catch(e){return u.debug({err:e,msg:"Skipped seeding the user-project config (init)."}),[Ws("warned",e instanceof Error?e.message:String(e))]}},Ws=(e,t)=>({step:"project-config",outcome:e,message:`Skipped seeding the user-project config \u2014 ${t}`,level:"silent"}),dR=(e,t,r)=>{let n=[];for(let s of r){if(s.action==="unchanged")continue;let i=s.type===void 0?"":` (${s.type})`;n.push({step:"guidance",outcome:s.action==="failed"?"warned":"written",message:` ${s.action.padEnd(9)} ${le.relative(e,s.path)}${i}`,level:"info"})}n.push({step:"guidance",outcome:"written",message:`Agent-instruction files synced (infra-kit ${t})`,level:"info"});let o=r.filter(s=>s.action==="failed");return o.length===0||n.push({step:"guidance",outcome:"warned",message:`${o.length} package guidance files could not be written \u2014 run: infra-kit audit --fix --all`,level:"warn"}),n},uR=async()=>{let{skipped:e,root:t,version:r,written:n}=await bf();return e||t===null?{root:null,entries:[{step:"guidance",outcome:"skipped",message:"Agent-instruction files skipped \u2014 not an infra-kit repo",level:"silent"}]}:{root:t,entries:dR(t,r,n)}},pR=(e,t)=>{let r=le.relative(e,t.path);return t.status==="created"?{step:"plugin-pointer",outcome:"written",message:` created ${r} (Claude Code plugin pointer)`,level:"info"}:t.status==="added"?{step:"plugin-pointer",outcome:"written",message:` updated ${r} \u2014 added ${t.added.join(", ")}`,level:"info"}:{step:"plugin-pointer",outcome:t.status==="unchanged"?"unchanged":"warned",message:`${r} \u2014 ${t.status}`,level:"silent"}},mR=(e,t)=>{let r=Ae;if(t.kind==="stale"||t.kind==="wrong-key"){let o=t.kind==="stale"?se:t.key;return{step:"mcp-server",outcome:"unchanged",message:` ${r} still registers the infra-kit MCP server under "${o}" \u2014 the plugin no longer serves one, so this entry only spawns a failed server row. Delete the "${o}" entry from ${r} by hand in a PR, keeping its siblings`,level:"info"}}return t.kind==="unparseable"?{step:"mcp-server",outcome:"warned",message:`Could not read ${He} from ${le.join(e,Ae)} \u2014 fix the JSON and re-run: infra-kit setup --skip-tools`,level:"warn"}:{step:"mcp-server",outcome:"unchanged",message:` infra-kit MCP server: none wanted \u2014 the plugin is skills-only (${t.kind==="absent"?`${r} carries no "${se}" key`:`no ${r}`})`,level:"info"}},fR=(e,t)=>e===null||t!==null?[]:[{step:"plugin-pointer",outcome:"warned",message:`No infra-kit.json at ${e} \u2014 setting up Claude Code there anyway: writing .claude/settings.json and installing the ${K} plugin for that project. If that is not the repo you meant to set up, revert that file and uninstall the plugin.`,level:"warn"}],gR=()=>[Ha,st].map(e=>({step:"plugin-pointer",outcome:"manual",message:e,level:"info"})),hR=e=>{let r={step:"plugin-pointer",outcome:"warned",message:`Claude Code plugin not updated \u2014 ${e.stale?`CLI ${G.version} is behind ${e.latestVersion}, update it first with the command below`:`CLI ${G.version} is behind the published version, update it first`}. The plugin follows on the next update check after that.`,level:"warn"};return e.stale?[r,{step:"plugin-pointer",outcome:"manual",message:qo(e.updateCommand),level:"info"}]:[r]},yR=(e,t)=>e.status==="skipped-cli-stale"?hR(t):e.status==="updated"?[{step:"plugin-pointer",outcome:"unchanged",message:`Claude Code plugin ${K} up to date (project scope)`,level:"info"}]:e.status==="update-failed"?[{step:"plugin-pointer",outcome:"warned",message:`Could not update the Claude Code plugin \u2014 ${e.error}. Run by hand: ${Ir}`,level:"warn"}]:e.status==="installed"?[{step:"plugin-pointer",outcome:"written",message:`installed Claude Code plugin ${K} (project scope)`,level:"info"}]:e.status==="claude-missing"?[{step:"plugin-pointer",outcome:"skipped",message:"No `claude` on PATH, so the Claude Code plugin was not installed. Install Claude Code, then run:",level:"info"},...gR()]:[{step:"plugin-pointer",outcome:"warned",message:`Could not install the Claude Code plugin \u2014 ${e.status==="unverified"?"the install reported success but Claude Code recorded no installation":`the ${e.step} step failed: ${e.error}`}. Run by hand: ${st}`,level:"warn"}],Nf={stale:!1},vR=async()=>{let e=Rn(),t=e===null?await ca(jc.env):e.latestVersion;return t===null||!la(t,G.version)?Nf:{stale:!0,latestVersion:t,updateCommand:e?.updateCommand??vu(t)}},wR=async e=>{if(e===null)return[];let r=`${await je(e)}${pe}`,n=Object.values(vr).filter(o=>!ae.existsSync(le.join(r,o)));for(let o of Object.values(vr))ae.mkdirSync(le.join(r,o),{recursive:!0});return n.length===0?[{step:"worktrees",outcome:"unchanged",message:`Worktree directories already present at ${r}`,level:"info"}]:[{step:"worktrees",outcome:"written",message:`Created worktree directories at ${r} (${n.join(", ")})`,level:"info"}]},kR=async(e,t)=>{if(e===null){t({step:"plugin-pointer",outcome:"skipped",message:"Claude Code plugin steps skipped \u2014 no git root safe to write into",level:"silent"});return}try{t(pR(e,qa(le.join(e,".claude","settings.json"))));let n=Ft({projectPath:e}).kind==="installed"?await vR():Nf;t(...yR(Wa({projectRoot:e,cliIsStale:()=>n.stale}),n)),t(mR(e,Mn(e)))}catch(r){let n=r instanceof Error?r.message:String(r);t({step:"plugin-pointer",outcome:"warned",message:`Could not finish the Claude Code plugin step for ${e} (${n}). Run by hand: ${st}`,level:"warn"})}},bR=(e,t)=>{let r=le.relative(e,t.path);if(t.status!=="ok"&&t.status!=="failed")return[{step:"mcp-proxies",outcome:"warned",message:` ${r} could not be read as JSON \u2014 ik-mcp entries not synced`,level:"warn"}];if(t.status==="failed")return[{step:"mcp-proxies",outcome:"warned",message:` ${r} could not be written \u2014 ik-mcp entries not synced`,level:"warn"}];let n=[];for(let o of t.entries)o.status==="written"?n.push({step:"mcp-proxies",outcome:"written",message:` updated ${r} \u2014 ik-mcp "${o.name}"`,level:"info"}):(o.status==="conflict"||o.status==="stale")&&n.push({step:"mcp-proxies",outcome:"warned",message:` ${o.message}`,level:"warn"});return n},RR=async e=>{if(e===null)return[];if(!ae.existsSync(le.join(e,"infra-kit.json")))return[{step:"mcp-proxies",outcome:"skipped",message:"no infra-kit.json \u2014 no ik-mcp entries to derive",level:"silent"}];let t;try{t=(await M()).mcp}catch(r){let n=r instanceof Error?r.message:String(r);return[{step:"mcp-proxies",outcome:"warned",message:` ik-mcp entries not synced \u2014 infra-kit.json could not be loaded (${n.split(`
358
+ `)[0]??n})`,level:"warn"}]}return!t||Object.keys(t).length===0?[]:bR(e,bs({projectRoot:e,proxies:t,write:!0}))},SR=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("fi"),PR=e=>{let t=St(e,Zt,Tt);if(t!==null)return t;for(let[a,c]of eR){let l=St(e,a,c);if(l!==null)return l}let r=e.indexOf(tR);if(r===-1)return e;let n=e.slice(0,r).replace(/\n+$/,""),o=e.slice(r).split(`
359
+ `),s=0;for(;s<o.length&&SR(o[s]);)s++;let i=o.slice(s).join(`
349
360
  `);return n+(i?`
350
- ${i}`:"")},Jf=()=>{let e="pnpm exec infra-kit";return['if [[ -z "${INFRA_KIT_SESSION}" ]]; then'," export INFRA_KIT_SESSION=$(head -c 4 /dev/urandom | xxd -p)","fi",`env-load() { local f; f=$(${e} env-load "$@") || return; source "$f"; ${e} env-status; }`,`env-clear() { local f; f=$(${e} env-clear "$@") || return; source "$f"; ${e} env-status; }`,`env-status() { ${e} env-status; }`].join(`
351
- `)},Uf=()=>`${sr}
352
- ${Jf()}
353
- ${_t}`,el=()=>["# Inherit this terminal's infra-kit session env into every zsh it spawns, interactive or not.","# A fresh terminal has no session yet (it is minted in .zshrc, after this file) and skips.","# Only the canonical 8-hex id .zshrc mints is honoured. Load wins a tie with clear.","# Prints nothing of its own.",'if [[ -n "${INFRA_KIT_SESSION:-}" ]]; then'," () {"," emulate -L zsh -o extendedglob",' [[ "${INFRA_KIT_SESSION:-}" == [0-9a-f](#c8) ]] || return',' local _ik_dir="${XDG_CACHE_HOME:-$HOME/.cache}/infra-kit/$INFRA_KIT_SESSION"',' local _ik_load="$_ik_dir/env-load.sh" _ik_clear="$_ik_dir/env-clear.sh"',' if [[ -r "$_ik_load" && ! "$_ik_clear" -nt "$_ik_load" ]]; then',' source "$_ik_load"',' elif [[ -r "$_ik_clear" ]]; then',' source "$_ik_clear"'," fi"," }","fi"].join(`
354
- `),tl=()=>`${sr}
355
- ${el()}
356
- ${_t}`;var VR="Could not find requested project",BR="Could not find requested config",Gf="Invalid Auth token",Kf="does not have access to requested config",ir=e=>e.includes(Gf)||e.includes(Kf)?"auth":e.includes(VR)?"project":e.includes(BR)?"config":"unknown",ar=e=>e.includes(Kf)?"mis-scoped":e.includes(Gf)?"revoked":null;var Hf=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(`
357
- `),cn=class extends ks{authKind;constructor(t,r=null,n){super(n??Hf(t),t),this.name="DopplerAuthError",this.authKind=r}};var rl=({kind:e,project:t,config:r,available:n})=>{let o=e==="project"?[`Doppler project "${t}" not found (set in infra-kit.json \u2192 envManagement.config.name).`]:[`Doppler config "${r}" not found in project "${t}".`];if(n&&n.length>0){let s=e==="project"?"Available projects":`Available configs in "${t}"`;o.push(`${s}: ${n.join(", ")}.`)}return o.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."),o.join(`
358
- `)};import{$ as ti}from"zx";var WR=5e3,JR="DOPPLER_CONFIG",We=async()=>{let{envManagement:e}=await D();return e.config.name},nl=async({childEnv:e,project:t,config:r})=>{let n=ti.quiet;ti.quiet=!0;try{let s=(await ti({env:e})`doppler secrets get ${JR} --plain --project ${t} --config ${r}`.timeout(WR)).stdout.trim();return s!==r?{outcome:"mis-scoped",scopedTo:s}:{outcome:"valid",scopedTo:s}}catch(o){return{outcome:UR(o)}}finally{ti.quiet=n}},UR=e=>{let t=$r(e)??(e instanceof Error?e.message:String(e));return ir(t)!=="auth"?"unreachable":ar(t)??"unreachable"};import GR from"node:process";var de="INFRA_KIT_ENV_TOKEN",mo=async e=>{let t=GR.env[de];if(t)return{token:t,source:"env"};let n=(await ue())?.envs[e];if(n)return{token:n,source:"store"};throw new ks(KR(e,await lt()),e)},KR=(e,t)=>[`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 ${w(t)} (mode 0600, never in the repo).`,`CI / agents: set ${de} instead \u2014 it takes precedence and needs no home config.`].join(`
359
- `);import HR from"node:fs/promises";var fo=async(e,t)=>{if(!t)return{hasOverrides:!1,overrideKeys:[],unreadable:!1};try{let r=await HR.readFile(e,"utf-8"),n=r.trim()===""?{}:JSON.parse(r);if(typeof n!="object"||n===null||Array.isArray(n))return{hasOverrides:!1,overrideKeys:[],unreadable:!0};let o=Object.keys(n);return{hasOverrides:o.length>0,overrideKeys:o,unreadable:!1}}catch{return{hasOverrides:!1,overrideKeys:[],unreadable:!0}}},go=e=>e.unreadable?"(unreadable \u2014 invalid JSON)":e.overrideKeys.length===0?"(empty \u2014 no overrides)":`(${e.overrideKeys.length} override(s): ${e.overrideKeys.join(", ")})`;import zR from"node:fs";import YR from"node:os";import qf from"node:path";import XR from"node:process";import{$ as qR}from"zx";var cr=()=>qR({quiet:!0});var ZR=()=>[qf.join(YR.homedir(),".local","bin"),"/opt/homebrew/bin","/usr/local/bin"],QR=async e=>{try{return(await cr()`command -v ${e}`).stdout.trim()||null}catch{return null}},ho=()=>({runCommand:async e=>{let t=await cr()`${e}`;return{stdout:`${t.stdout}
360
- ${t.stderr}`}},resolveBinPath:async e=>{let t=await QR(e);return t!==null?t:ZR().map(r=>qf.join(r,e)).find(r=>zR.existsSync(r))??null},realpath:he,platform:XR.platform});var Mt=(...e)=>({steps:e,needsSudo:!1,fetchesNetworkScript:!1}),ln=e=>/\d{1,10}\.\d{1,10}\.\d{1,10}/.exec(e)?.[0]??null,dn=["darwin","linux"],si=e=>t=>ya(t,e)?"homebrew":"unknown",ii=(e,t)=>r=>r===null?null:t(e(r),r),sl=e=>ii(si(e.kegName),t=>t==="homebrew"?Mt(["brew","upgrade",e.brewFormula]):null),zf=e=>is(e,"Homebrew")||is(e,"homebrew")?"homebrew":"unknown",eS={id:"brew",binName:"brew",probeArgv:["brew","--version"],versionFrom:ln,platforms:dn,prerequisites:[],bootstrapInstall:{steps:[["/bin/bash","-c","$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"]],needsSudo:!0,fetchesNetworkScript:!0},identify:zf,updateFor:ii(zf,e=>e==="homebrew"?Mt(["brew","update"]):null)},ol={brewFormula:"awscli",brewInstallSpec:"awscli",kegName:"awscli"},Zf="https://awscli.amazonaws.com/v2/install.sh",Qf={steps:[["/bin/bash","-c",`curl -fsSL ${Zf} | bash`]],needsSudo:!1,fetchesNetworkScript:!0},tS="/usr/local/aws-cli",rS=e=>In(tS,e,he)?{steps:[["sudo","/bin/bash","-c",`curl -fsSL ${Zf} | bash -s -- --system`]],needsSudo:!0,fetchesNetworkScript:!0}:Qf,Yf=e=>ya(e,ol.kegName)?"homebrew":is(e,"aws-cli")?"script":"unknown",nS={id:"aws",binName:"aws",...ol,probeArgv:["aws","--version"],versionFrom:ln,platforms:dn,prerequisites:[],bootstrapInstall:Qf,identify:Yf,updateFor:ii(Yf,(e,t)=>e==="homebrew"?Mt(["brew","upgrade",ol.brewFormula]):e==="script"?rS(t):null)},ri={brewFormula:"git",brewInstallSpec:"git",kegName:"git"},oS={id:"git",binName:"git",...ri,probeArgv:["git","--version"],versionFrom:ln,platforms:dn,prerequisites:["brew"],bootstrapInstall:Mt(["brew","install",ri.brewInstallSpec]),identify:si(ri.kegName),updateFor:sl(ri)},ni={brewFormula:"gh",brewInstallSpec:"gh",kegName:"gh"},sS={id:"gh",binName:"gh",...ni,probeArgv:["gh","--version"],versionFrom:ln,platforms:dn,prerequisites:["brew"],bootstrapInstall:Mt(["brew","install",ni.brewInstallSpec]),identify:si(ni.kegName),updateFor:sl(ni)},oi={brewFormula:"doppler",brewInstallSpec:"dopplerhq/cli/doppler",kegName:"doppler"},iS={id:"doppler",binName:"doppler",...oi,probeArgv:["doppler","--version"],versionFrom:ln,platforms:dn,prerequisites:["brew"],bootstrapInstall:Mt(["brew","install","gnupg"],["brew","install",oi.brewInstallSpec]),identify:si(oi.kegName),updateFor:sl(oi)},yo="portless",Xf=e=>jp(e,yo)===null?"unknown":"npm",aS={id:"portless",binName:yo,npmPackage:yo,probeArgv:["portless","--version"],versionFrom:ln,platforms:[...dn,"win32"],prerequisites:[],bootstrapInstall:Mt(["npm","install","-g",yo]),identify:Xf,updateFor:ii(Xf,e=>e==="npm"?Mt(["npm","install","-g",`${yo}@latest`]):null)},il={brew:eS,git:oS,aws:nS,gh:sS,doppler:iS,portless:aS},lr=Object.keys(il),De=e=>il[e],al=(e,t)=>e.platforms.includes(t),cl=e=>{let t=[],r=new Set,n=(o,s)=>{if(s.includes(o))throw new Error(`dependency cycle: ${[...s,o].join(" -> ")}`);if(!r.has(o)){r.add(o);for(let i of De(o).prerequisites)n(i,[...s,o]);t.push(o)}};for(let o of e)n(o,[]);return t};var eg=e=>({id:e,present:!1,onPath:!1,binRealPath:null,version:null,manager:"unknown"}),tg=async(e,t)=>{try{return await e(t)}catch{return null}},cS=async(e,t)=>{try{let r=await e.resolveBinPath(t);return r==null?null:e.realpath(r)}catch{return null}},rg=async(e,t)=>{if(!al(e,t.platform))return eg(e.id);let r=await tg(t.runCommand,e.probeArgv),n=await cS(t,e.binName);if(r==null&&n==null)return eg(e.id);let o=r??(n==null?null:await tg(t.runCommand,[n,...e.probeArgv.slice(1)]));return{id:e.id,present:!0,onPath:r!=null,binRealPath:n,version:o==null?null:e.versionFrom(o.stdout),manager:n==null?"unknown":e.identify(n)}},vo=async(e,t)=>Promise.all(e.map(r=>rg(De(r),t)));var ng=["prod"],pn={allowed:!1,reason:"disallow"},jt=e=>ng.includes(e),lS=["dev","stage"],un=e=>lS.includes(e)||jt(e),gt=(e,t=pn)=>t.allowed?e:e.filter(r=>!jt(r)),dr=(e,t,r=pn)=>{if(!r.allowed&&jt(e))throw r.reason==="agent-blocked"?new E({status:"refused",env:e,agentMode:A.source},2,{operation:t,remediation:'a human runs it from their own terminal \u2014 this project sets `protectedEnvs: "cli-only"`',stderrExcerpt:`"${e}" is withheld from agents in this project (protectedEnvs: "cli-only")`}):new f(void 0,{operation:t,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. To allow ad-hoc deploys to "${e}" in this project, set \`protectedEnvs\` to "allow" or "cli-only" in infra-kit.json`,stderrExcerpt:`"${e}" is delivered, not deployed ad-hoc`})};var Je=async()=>{let e;try{e=(await D()).protectedEnvs??"disallow"}catch{return pn}return e==="disallow"?pn:e==="cli-only"&&ee()?{allowed:!1,reason:"agent-blocked"}:{allowed:!0,reason:"allowed"}};var wo=e=>{let{env:t,branch:r}=e;jt(t)&&p.warn([`\u26A0\uFE0F "${t}" is a delivery target \u2014 this project allows dispatching to it directly, but this is NOT the delivery flow.`,`Dispatching from "${r}" ships ${t} from a ref that is not merged to main, and skips:`," \u2022 the squash-merge of the release branch into main"," \u2022 the RC pull request"," \u2022 the Jira fix-version release","Run `infra-kit release deliver` instead if you want those."].join(`
361
- `))};import og from"node:fs/promises";import ll from"node:path";import dS from"yaml";var sg=".github/workflows",ht=async e=>{let t=await x();return ig(ll.resolve(t,sg,e))},dl=async()=>{let e=await x(),t=ll.resolve(e,sg),r;try{r=await og.readdir(t)}catch{return[]}let n=r.filter(s=>s.endsWith(".yml")||s.endsWith(".yaml")).sort(),o=await Promise.all(n.map(s=>ig(ll.resolve(t,s))));return[...new Set(o.flat())]},ig=async e=>{let t;try{t=dS.parse(await og.readFile(e,"utf-8"))}catch{return[]}let r=mn(t,"on")??mn(t,"true"),n=mn(mn(mn(mn(r,"workflow_dispatch"),"inputs"),"environment"),"options");return Array.isArray(n)?n.filter(o=>typeof o=="string"&&o.length>0):[]},mn=(e,t)=>{if(!(typeof e!="object"||e===null||Array.isArray(e)))return e[t]};var fn=async()=>{let e=await dl(),t=await ue(),r=e.map(s=>({env:s,source:"gh-workflow"})),n=new Set(e),o=Object.keys(t?.envs??{}).filter(s=>!n.has(s)).sort().map(s=>({env:s,source:"token-only"}));return[...r,...o]},pr=async()=>(await fn()).map(t=>t.env);import{$ as hS}from"zx";import{z as ag}from"zod";var cg=/^\d{4}-\d{2}-\d{2}$/,ko=e=>{if(!cg.test(e))return!1;let[t,r,n]=e.split("-").map(Number),o=new Date(Date.UTC(t,r-1,n));return o.getUTCFullYear()===t&&o.getUTCMonth()===r-1&&o.getUTCDate()===n},lg=e=>`Release date "${e}" is not a calendar date in yyyy-mm-dd form.`,gn=class extends Error{constructor(t){super(lg(t)),this.name="InvalidReleaseDateError"}},ur=e=>{let t=e.trim();if(!ko(t))throw new gn(t);return t},bo=e=>{let t=e.trim();return t===""||ko(t)?!0:lg(t)},pl=ag.string().refine(ko,{message:"Expected a calendar date in yyyy-mm-dd form."}),ul=ag.string().refine(e=>e===""||ko(e),{message:'Expected a calendar date in yyyy-mm-dd form, or "" to clear.'});var Ft=e=>e.slice(1).split(".").map(Number),hn=e=>[...e].sort((t,r)=>{let[n,o,s]=Ft(t),[i,a,c]=Ft(r);return n!==i?(n??0)-(i??0):o!==a?(o??0)-(a??0):(s??0)-(c??0)});var pg="next",pS=/^v?(\d+)\.(\d+)\.(\d+)$/,uS=e=>e.replace(/^.*release\//,""),ml=e=>{let t=uS(e.trim()),r=pS.exec(t);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null},dg=e=>`${e[0]}.${e[1]}.${e[2]}`,fl=e=>{let t=[...e.remoteBranches??[],...e.jiraVersions??[]],r=[],n=new Set;for(let o of t){let s=ml(o);if(!s)continue;let i=dg(s);n.has(i)||(n.add(i),r.push(s))}return hn(r.map(o=>dg(o))).map(o=>Ft(`v${o}`))},mr=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},gl=(e,t)=>{if(e.length===0)throw new mr;let r=e[e.length-1];if(t==="hotfix"){let[s,i]=r,a=e.reduce((c,l)=>l[0]===s&&l[1]===i?Math.max(c,l[2]):c,0);return`${s}.${i}.${a+1}`}let[n,o]=r;return`${n}.${o+1}.0`},yn=(e,t)=>{try{return gl(e,t)}catch(r){if(r instanceof mr)return null;throw r}},hl=e=>e.trim().toLowerCase()===pg,ci=e=>hl(e)||ml(e)!==null?{version:e}:{name:e},mS=e=>e==="regular"||e==="hotfix",ug=e=>"name"in e,fS=e=>{let t=e.indexOf("@");if(t===-1)return{token:e.trim()};let r=e.slice(0,t).trim(),n=e.slice(t+1);if(n.includes("@"))throw new Error(`Release spec "${e}" has more than one "@". Expected "<token>@yyyy-mm-dd".`);if(n.trim()==="")throw new Error(`Release spec "${e}" has an empty release date after "@". Expected "<token>@yyyy-mm-dd".`);return{token:r,releaseDate:ur(n)}},yl=e=>{let t=e.trim();if(t==="")throw new Error("Release spec is empty");let r=t.indexOf(":"),{token:n,releaseDate:o}=fS(r===-1?t:t.slice(0,r)),s="regular",i="";if(r!==-1){let a=t.slice(r+1),c=a.indexOf(":"),l=c===-1?a.trim():a.slice(0,c).trim();i=c===-1?"":a.slice(c+1).trim();let d=l.toLowerCase();if(!mS(d))throw new Error(`Invalid release type "${l}". Expected "regular" or "hotfix".`);s=d}return ai({...ci(n),type:s},{description:i,releaseDate:o})},vl=e=>{let t=e.releaseDate===void 0?e.id.raw:`${e.id.raw}@${e.releaseDate}`;return e.description!==void 0&&e.description!==""?`${t}:${e.type}:${e.description}`:e.type==="hotfix"?`${t}:hotfix`:t},ai=(e,t)=>{let{description:r,releaseDate:n}=t;return{...e,...r!==void 0&&r!==""?{description:r}:{},...n===void 0?{}:{releaseDate:n}}},gS=e=>{let t=e.name.trim();return ps(t),ai({id:{kind:"name",name:t,raw:t},type:e.type},e)},wl=(e,t)=>{let r=[...t];return e.map(n=>{if(ug(n))return gS(n);let o=n.version.trim();if(o==="")throw new Error("Release entry has an empty version");if(hl(o)){let a=gl(r,n.type);return r.push(Ft(`v${a}`)),ai({id:ve(a),type:n.type},n)}let s=ml(o);if(!s)throw new Error(`Invalid version "${o}". Expected semver like "1.2.5" or the token "next".`);let i=`${s[0]}.${s[1]}.${s[2]}`;return r.push(s),ai({id:ve(i),type:n.type},n)})},kl=e=>e.some(t=>!ug(t)&&hl(t.version));var yS=e=>e.split(`
362
- `).map(t=>{let r=t.indexOf(" ");return r===-1?null:K(t.slice(r+1))}).filter(t=>t!==null&&t.kind==="version").map(t=>t.raw),vS=async()=>{let e=await hS({quiet:!0})`git ls-remote --heads origin 'release/v*'`;return yS(e.stdout)},wS=async()=>{let e=await mt();return e?(await qr(e)).map(r=>r.name):[]},Ro=async()=>{let[e,t]=await Promise.allSettled([vS(),wS()]);return e.status==="rejected"&&p.warn({err:e.reason},"Failed to list remote release branches; continuing without them"),t.status==="rejected"&&p.warn({err:t.reason},"Failed to fetch Jira versions; continuing without them"),fl({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:t.status==="fulfilled"?t.value:[]})};import kS from"node:fs";import bS from"node:path";var bl=[".claude/settings.json",".claude/settings.local.json"],RS=["infra-kit","ik","pnpm exec infra-kit","pnpm exec ik","pnpm infra-kit"],SS=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),PS=e=>{let t=e.trim();if(t==="Bash")return"*";let r=/^Bash\((.*)\)$/s.exec(t);if(r===null)return null;let n=r[1]??"";return n.endsWith(":*")?`${n.slice(0,-2)}*`:n},ES=(e,t)=>{let r=e.indexOf("*");if(r===-1)return e===t||e.startsWith(`${t} `);let n=e.slice(0,r);return new RegExp(`^${e.split("*").map(SS).join(".*")}$`,"s").test(t)||n===t||n.startsWith(`${t} `)},xS=e=>{let t=e.groupPath.join(" ");return t===e.cliName?[t]:[t,e.cliName]},TS=()=>fr.filter(e=>e.mutating),CS=e=>{let t=PS(e);return t===null?[]:TS().filter(r=>RS.some(n=>xS(r).some(o=>ES(t,`${n} ${o}`)))).map(r=>r.groupPath.join(" "))},$S=(e,t)=>{let r;try{r=kS.readFileSync(bS.join(e,t),"utf-8")}catch(i){return i.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable",file:t}}let n;try{n=JSON.parse(r)}catch{return{kind:"unreadable",file:t}}let o=n?.permissions;if(o==null)return{kind:"read",patterns:[]};let s=o.allow;return s===void 0?{kind:"read",patterns:[]}:Array.isArray(s)?{kind:"read",patterns:s.filter(i=>typeof i=="string")}:{kind:"unreadable",file:t}},mg=e=>{let t={present:[],unreadable:[],hits:[]};for(let r of bl){let n=$S(e,r);if(n.kind!=="absent"){if(t.present.push(r),n.kind==="unreadable"){t.unreadable.push(r);continue}for(let o of n.patterns){let s=CS(o);s.length>0&&t.hits.push({file:r,pattern:o,commands:s})}}}return t};var AS=e=>e.every(t=>t.status!=="fail"),OS=["brew","git","gh","doppler","aws"],IS=async e=>{let t=await vo(OS,e);return new Map(t.map(r=>[r.id,{manager:r.manager,version:r.version,present:r.present,onPath:r.onPath}]))},yt=async(e,t,r,n)=>{try{return await cr()`${t}`,{name:e,status:"pass",message:r}}catch{return{name:e,status:"fail",message:n}}},DS=async()=>{let e="orca installed",t=await Ir();return t==="absent"?{name:e,status:"fail",message:"orca is not on PATH. Install with: brew install --cask stablyai/orca/orca, then register the CLI in Orca \u2192 Settings \u2192 Experimental \u2192 CLI"}:t==="unreachable"?{name:e,status:"warn",message:"orca is installed but the app is not running \u2014 start it with: orca open"}:{name:e,status:"pass",message:"Installed: orca (app running, runtime reachable)"}},Eg=(e,t,r,n)=>{let o=pe.join(Pg.homedir(),t),s="Run: infra-kit setup --skip-tools";if(!re.existsSync(o))return{name:e,status:"fail",message:`~/${t} not found. ${s}`};let i=re.readFileSync(o,"utf-8"),a=i.indexOf(sr),c=i.indexOf(_t);return a===-1||c===-1||c<a?{name:e,status:"fail",message:`infra-kit ${r} block missing from ~/${t}. ${s}`}:i.slice(a,c+_t.length).trim()!==n.trim()?{name:e,status:"fail",message:`infra-kit ${r} block in ~/${t} is out of date. ${s}`}:{name:e,status:"pass",message:`infra-kit ${r} block in ~/${t} is up to date`}},NS=()=>Eg("zshrc init block",".zshrc","shell",Uf()),_S=()=>Eg("zshenv session block",".zshenv","session-env",tl()),MS=async()=>{let e="pnpm enableGlobalVirtualStore";try{let t=await x(),r=pe.join(t,"pnpm-workspace.yaml");if(!re.existsSync(r))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${r}`};let n=re.readFileSync(r,"utf-8");return/^\s*enableGlobalVirtualStore\s*:\s*true\s*$/m.test(n)?{name:e,status:"pass",message:"enableGlobalVirtualStore: true is set"}:{name:e,status:"fail",message:"enableGlobalVirtualStore: true is missing in pnpm-workspace.yaml"}}catch(t){return{name:e,status:"fail",message:`Failed to read pnpm-workspace.yaml: ${t.message}`}}},jS=async()=>{try{return Ct(),{config:await D(),error:null}}catch(e){return{config:null,error:e}}},FS=e=>{let t="infra-kit config valid";return e.error?{name:t,status:"fail",message:e.error.message}:{name:t,status:"pass",message:"infra-kit.json is valid (user overrides applied if present)"}},LS=384,Rl=448,VS=e=>e.length===0?"no envs declared":e.map(t=>{let r=t.source===null?"no token":`token (${t.source})`;return`${t.env}: ${r}`}).join(", "),BS=async(e,t)=>Promise.all(e.map(async r=>{try{let{source:n}=await t(r);return{env:r,source:n}}catch{return{env:r,source:null}}})),WS=async(e,t={})=>{let r="env tokens configured",n=t.readStore??ue,o=t.resolveToken??mo;if(!e.config)return{name:r,status:"skip",message:"infra-kit config could not be read (see config check)"};try{await n()}catch(i){return{name:r,status:"fail",message:`Token store unreadable \u2014 ${i.message}`}}let s=await BS(await pr(),o);return{name:r,status:"pass",message:VS(s)}},JS=()=>ot.env[de]||void 0,US=async(e={})=>{let t="tokens.json present",r=e.readStore??ue,n=e.storePath??lt;if((e.readEnvToken??JS)())return{name:t,status:"skip",message:`${de} is set; that channel takes precedence over the store`};let s;try{s=w(await n())}catch{return{name:t,status:"skip",message:"the token store path could not be resolved"}}let i;try{i=await r()}catch{return{name:t,status:"skip",message:`The store at ${s} is unreadable (see env tokens configured)`}}let a=i===null?[]:Object.keys(i.envs);if(a.length===0){let c=i===null?`No token store at ${s}`:`${s} holds no tokens`;return{name:t,status:"fail",message:`${c} \u2014 every project needs one to authenticate. Fix: run \`infra-kit env-token-set <env>\`. CI / agents: set ${de} instead.`}}return{name:t,status:"pass",message:`${s} holds ${a.length} token(s): ${a.join(", ")}`}},So=(e,t)=>{let r=t(e);return r===null?null:r.mode&511},GS=async(e,t={})=>{let r="tokens.json perms",n=t.storePath??lt,o=t.statPath??KS,s=t.chmodPath??re.chmodSync,i;try{i=await n()}catch{return{name:r,status:"skip",message:"the token store path could not be resolved"}}if(So(i,o)===null)return{name:r,status:"skip",message:`No store to protect at ${w(i)} (see tokens.json present)`};let a=pe.dirname(i),c=pe.dirname(a),l=pe.dirname(c),u=[{target:l,expected:Rl,actual:So(l,o)},{target:c,expected:Rl,actual:So(c,o)},{target:a,expected:Rl,actual:So(a,o)},{target:i,expected:LS,actual:So(i,o)}].filter(g=>g.actual!==null&&g.actual!==g.expected);if(u.length===0)return{name:r,status:"pass",message:`${w(i)} is 0600 (0700 dirs)`};let m=u.map(g=>`${w(g.target)} is ${fg(g.actual)}, expected ${fg(g.expected)}`).join("; ");if(!e)return{name:r,status:"fail",message:`${m}. Fix: run \`infra-kit doctor --fix\`, or chmod them by hand.`};for(let g of u)s(g.target,g.expected);return{name:r,status:"pass",message:`Tightened ${u.length} path(s): ${m}`}},fg=e=>`0${e.toString(8).padStart(3,"0")}`,KS=e=>{try{return re.statSync(e)}catch{return null}},HS=async()=>{let e="user override path";try{let t=await te(),r=re.existsSync(t.userProject),n=await fo(t.userProject,r),o=r?go(n):"(not created \u2014 seed failed?)";return{name:e,status:"pass",message:`${w(t.userProject)} ${o} \u2014 project: ${t.projectName}`}}catch(t){return{name:e,status:"fail",message:t.message}}},qS=async()=>{let e="legacy user-global config",t;try{t=await te()}catch{return{name:e,status:"skip",message:"infra-kit config paths could not be resolved"}}let r=pe.join(pe.dirname(t.userGlobal),"config.json");return re.existsSync(r)?re.existsSync(t.userGlobal)?{name:e,status:"fail",message:`Stale legacy config.json found at ${w(r)} \u2014 ${w(t.userGlobal)} is active; remove the old file.`}:{name:e,status:"fail",message:`Legacy user-global config.json found at ${w(r)} \u2014 run \`infra-kit setup --skip-tools\` to migrate it (your overrides are not being applied).`}:{name:e,status:"pass",message:"No legacy user-global config.json"}},zS={cursor:{command:["cursor","--version"],label:"Cursor",failMsg:"Cursor is not installed. Install from: https://cursor.com/"}},YS=async e=>{let t=zS[e];try{return await cr()`${t.command}`,{ok:!0,label:t.label,failMsg:t.failMsg}}catch{return{ok:!1,label:t.label,failMsg:t.failMsg}}},XS=async e=>{let t="ide installed";if(!e.config)return{name:t,status:"skip",message:"infra-kit config could not be read (see config check)"};let r=Tt(e.config).map(s=>s.provider);if(r.length===0)return{name:t,status:"pass",message:"No IDE configured (ide unset)"};let n=await Promise.all(r.map(s=>YS(s))),o=n.filter(s=>!s.ok);return o.length===0?{name:t,status:"pass",message:`Installed: ${n.map(s=>s.label).join(", ")}`}:{name:t,status:"fail",message:o.map(s=>s.failMsg).join("; ")}},gg=/^\d+\.\d+\.\d+$/,ZS=(e,t)=>e===t||!gg.test(e)||!gg.test(t)?!1:hn([`v${e}`,`v${t}`])[0]===`v${e}`,QS=async(e,t)=>{let r;try{r=await ke(e)}catch{return[]}let n=[];for(let o of r){let s=Zt(Qt(pe.join(o,"CLAUDE.md")));s.state==="ok"&&s.version!==void 0&&ZS(s.version,t)&&n.push(s.version)}return n},eP=async(e,t)=>{let r=await QS(e,t);if(r.length===0)return"";let n=hn(r.map(o=>`v${o}`))[0].slice(1);return` \u2014 ${r.length} package guidance blocks were generated by an older infra-kit (oldest ${n}, current ${t}) \u2014 run: infra-kit audit --fix --all`},tP=async()=>{let e=[{name:"CLAUDE.md block",status:"skip",message:"no infra-kit config in this repo"}],t;try{t=(await te()).main}catch{return e}if(!re.existsSync(t))return e;let r=pe.dirname(t),n=pe.join(r,"CLAUDE.md"),o=re.existsSync(n)?re.readFileSync(n,"utf-8"):"",s=ze(o,Ae,Ye),i=s?"CLAUDE.md block present":"infra-kit block missing from CLAUDE.md. Run: infra-kit setup --skip-tools",a=await eP(r,q.version);return[{name:"CLAUDE.md block",status:s?"pass":"fail",message:`${i}${a}`}]},rP=async()=>{try{let e=(await te()).main;return re.existsSync(e)?pe.dirname(e):null}catch{return null}},nP=e=>{let t=hu();return t===null||!jn(t,e)?"":` \u2014 plugin ${t} is fetched but not applied. Run: ${Vr}`},oP=e=>{let t=e.kind==="installed"?vs(e.installation):null;return{name:"plugin version",status:t===null?"fail":"pass",message:t===null?"No infra-kit plugin installed for this project to read a version from":`Plugin ${H} version ${t}${nP(t)}`}},hg=3,yg=(e,t)=>he(e)===he(t),sP=e=>{if(e===void 0||e.gitRoot===null)return"";let t=w(e.gitRoot);if(e.projectDir!==null){if(yg(e.projectDir,e.gitRoot))return"";let r=In(e.gitRoot,he(e.projectDir),he)?"below the repo root":"not this checkout";return` \u2014 this session was launched from ${w(e.projectDir)}, ${r}: the plugin and this repo's .claude/settings.json hooks load only from ${t} (measured); restart Claude Code there`}return yg(e.cwd,e.gitRoot)?"":` \u2014 if Claude Code was launched from ${w(e.cwd)} rather than ${t}, it loaded neither the plugin nor this repo's hooks; launch it at ${t}`},iP=(e,t)=>{let r="plugin installed",n=sP(t);if(e.kind==="installed"){let{scope:c,projectPath:l}=e.installation,d=l===null?"":`, ${w(l)}`;return{name:r,status:"pass",message:`Plugin ${H} installed (${c??"unknown"} scope${d})${n}`}}if(e.kind==="absent")return{name:r,status:"fail",message:`Plugin ${H} is not installed. Run: ${pt}${n}`};let o=e.installations.map(c=>c.projectPath===null?"(unnamed project)":w(c.projectPath)),s=o.length-hg,i=s>0?` and ${s} more`:"",a=`${o.slice(0,hg).join(", ")}${i}`;return{name:r,status:"fail",message:`Plugin ${H} is installed for ${a} only, not this project. Run: ${pt}${n}`}},aP=()=>yt("claude CLI",["claude","--version"],"Installed: claude","claude CLI not found on PATH \u2014 `infra-kit setup` cannot install the plugin; install Claude Code first"),cP=(e,...t)=>{try{return JSON.parse(re.readFileSync(pe.join(e,...t),"utf-8"))}catch{return null}},lP=e=>{if(e.kind!=="installed")return{kind:"not-installed"};let t=vs(e.installation),{installPath:r}=e.installation;if(r===null)return{kind:"skills-only",version:t};let n=cP(r,Oe),o=n!==null&&typeof n=="object"?n[Ze]:void 0;return o==null||typeof o!="object"?{kind:"skills-only",version:t}:{kind:"stale-server",version:t,keys:Object.keys(o)}},vg=e=>`Plugin ${H} ${e===null?"(version unreadable)":e}`,dP=e=>{let t="plugin MCP server";if(e.kind==="not-installed")return{name:t,status:"fail",message:`No infra-kit plugin installed for this project \u2014 no skills to drive the CLI. Run: ${pt}`};if(e.kind==="stale-server"){let r=e.keys.length===0?"":` (under "${e.keys.join('", "')}")`;return{name:t,status:"pass",message:`${vg(e.version)} still carries an MCP server in its ${Oe}${r} \u2014 a copy from before the plugin went skills-only. Update it: infra-kit setup (or ${Vr}), then restart Claude Code`}}return{name:t,status:"pass",message:`${vg(e.version)} is skills-only \u2014 no ${Oe}, as shipped; the /infra-kit:* skills drive the infra-kit CLI`}},pP=(e,t)=>{let r=qt(e===null?{}:{projectPath:e}),n=Mn();return[{name:"marketplace registered",status:n?"pass":"fail",message:n?`Marketplace ${ae} is known to Claude Code`:`Marketplace ${ae} is not registered. Run: claude plugin marketplace add ${Et}`},iP(r,t),oP(r),dP(lP(r)),{name:"CLI version",status:"pass",message:`infra-kit CLI ${q.version}`}]},uP=({env:e,stdinIsTTY:t,flag:r})=>{let n=e.INFRA_KIT_AGENT===void 0?"unset":`= "${e.INFRA_KIT_AGENT}"`;return[`CLAUDECODE ${e.CLAUDECODE===void 0?"unset":"set"}`,`INFRA_KIT_AGENT ${n}`,`stdin ${t?"is a TTY":"is not a TTY"}`,`--agent ${r?"passed":"not passed"}`].join(", ")},mP=e=>{let t="Agent mode",r=ds(e),n=uP(e);return{name:t,status:"pass",message:`${r===null?"human":"agent"} \u2014 ${r==="flag"?"the --agent flag, which beats every environment value":e.env.INFRA_KIT_AGENT==="1"?"INFRA_KIT_AGENT=1":r==="env"?"CLAUDECODE is set and stdin is not a TTY":e.env.CLAUDECODE!==void 0&&e.stdinIsTTY?"CLAUDECODE is set but stdin is a TTY, so this is a terminal Claude Code spawned for a person":e.env.INFRA_KIT_AGENT==="0"?"INFRA_KIT_AGENT=0 suppresses the CLAUDECODE heuristic":"no source fires; pass --agent or set INFRA_KIT_AGENT=1 to drive this CLI as an agent"} (${n})`}},wg=4,fP=e=>{let t=e.slice(0,wg).join(", "),r=e.length-wg;return r>0?`${t} +${r} more`:t},gP=e=>{let t="Agent allowlist",{present:r,unreadable:n,hits:o}=mg(e);if(o.length>0){let s=o.map(i=>`${i.file} allows "${i.pattern}", which reaches ${i.commands.length} mutating infra-kit command${i.commands.length===1?"":"s"} (${fP(i.commands)})`);return{name:t,status:"warn",message:`${s.join("; ")} \u2014 a prefix allow lets an agent run the --yes re-run of a mutating command unprompted; narrow it to read-only argv (e.g. Bash(infra-kit release list:*)) so the host prompts for the rest`}}return n.length>0?{name:t,status:"warn",message:`Could not read permissions.allow from ${n.join(" and ")} \u2014 fix the JSON and re-run; until then the allowlist is unchecked`}:r.length===0?{name:t,status:"pass",message:`no ${bl.join(" or ")} at the repo root \u2014 no Bash allow pattern to reach a mutating infra-kit command`}:{name:t,status:"pass",message:`no permissions.allow pattern in ${r.join(" or ")} reaches a mutating infra-kit command`}},hP=(e,t)=>{let r=Math.floor((t-Date.parse(e))/36e5);return Number.isNaN(r)?"age unknown":r>=24?`${Math.floor(r/24)}d old`:`${Math.max(r,0)}h old`},yP=async(e,t=Date.now())=>{let r="merge-dev resolutions";if(e===null)return{name:r,status:"skip",message:"no git root"};let n;try{n=await yf(e)}catch(i){return{name:r,status:"skip",message:`could not read the merge-dev state: ${i.message}`}}if(n.length===0)return{name:r,status:"pass",message:"no merge-dev hand-off in progress"};let o=n.map(i=>{let a=i.worktreeExists?w(i.worktreePath):"worktree missing";return`${i.branch} (${hP(i.createdAt,t)}, ${a})`}),s=n.map(i=>i.branch).join(",");return{name:r,status:"warn",message:`${n.length} unfinished merge-dev hand-off${n.length===1?"":"s"}: ${o.join("; ")} \u2014 finish with: infra-kit release merge-dev --continue --versions ${s}, or drop with --abort`}},xg=e=>va(["trust"],{bin:e}),vP=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),kg="ERR_TLS_CERT_ALTNAME_INVALID",Tg=()=>`portless serving TLS on :${xt}`,wP=async(e,t,r)=>{let n=Tg();return await e(xt,!0)?{name:n,status:"pass",message:`portless is serving HTTPS on :${xt}`}:{name:n,status:"fail",message:`No portless daemon is serving HTTPS on :${xt}. Install it once (needs root): \`${St(t,r)}\`.`}},kP=async(e,t,r,n,o)=>{let s="portless CA chain valid",i=["localhost",...t.slice(0,1).map(d=>d.name)],c=(await Promise.all(i.map(async d=>({servername:d,result:await e(xt,d)})))).filter(d=>!d.result.ok);if(c.length===0)return{name:s,status:"pass",message:`Served certificate chains to ${w(r)} (${i.join(", ")})`};let l=c.map(d=>d.result.ok?"":d.result.code);return l.includes(kg)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${kg} for servername(s) ${c.map(d=>d.servername).join(", ")} \u2014 doctor's probe is wrong, your trust store is not implicated. Please report this.`}:l.some(d=>vP.has(d))?{name:s,status:"fail",message:`The daemon is serving a certificate that does not chain to ${w(r)}. Its CA was regenerated \u2014 run \`${xg(n)}\`, or reinstall: \`${St(n,o)}\`.`}:{name:s,status:"fail",message:`TLS handshake failed (${l.join(", ")})`}},bP=(e,t,r)=>{let n="portless CA trusted";return e?{name:n,status:"pass",message:`${w(t)} matches the recorded ca.trusted fingerprint`}:{name:n,status:"fail",message:`The portless CA is not trusted (or was regenerated). Run: \`${xg(r)}\` (no sudo needed).`}},RP=async(e,t,r)=>{let n="portless routes";if(e.length===0)return{name:n,status:"pass",message:"No portless routes registered"};let s=(await Promise.all(e.map(async i=>({route:i,live:await t(i.port)})))).filter(i=>!i.live).map(i=>i.route.name);return s.length===0?{name:n,status:"pass",message:`${e.length} portless route(s), all live`}:{name:n,status:"fail",message:`${s.length} stale portless route(s): ${s.join(", ")}. Remove with \`${va(["alias","--remove","<name>"],{bin:r})}\`.`}},Lt="portless service target",Eo=e=>({name:Lt,status:"warn",message:e}),Cg=e=>e==="darwin"?Up:e==="linux"?Gp:null,SP=e=>e==="darwin"?`sudo launchctl kickstart -k system/${Jp}`:`sudo systemctl restart ${Kp}`,PP="/bin/ps",EP=e=>{try{let t=Sg(PP,["-o","lstart=","-p",String(e)],{encoding:"utf-8"});if(t.status!==0)return null;let r=new Date(t.stdout.trim());return Number.isNaN(r.getTime())?null:r}catch{return null}},bg=e=>{try{return re.readFileSync(e,"utf-8")}catch{return null}},xP=e=>{try{return re.statSync(e).mtime}catch{return null}},TP=2e3,CP=e=>{try{let t=Sg(e,["-p","process.version"],{encoding:"utf-8",timeout:TP}),r=t.stdout?.trim()??"";return{version:r===""?null:r,status:t.status,signal:t.signal}}catch{return{version:null,status:null,signal:null}}},$P=(e,t)=>({platform:e.platform??ot.platform,readServiceFile:e.readServiceFile??bg,readFile:e.readFile??bg,exists:e.exists??re.existsSync,realpath:e.realpath??he,mtime:e.mtime??xP,execPath:e.execPath??ot.execPath,home:e.home??Pg.homedir(),cwd:e.cwd??ot.cwd(),repoRoot:e.repoRoot??po,stateDir:(e.stateDir??qp)(),processStartTime:e.processStartTime??EP,version:e.version??ot.version,arch:e.arch??ot.arch,nodeVersionOf:e.nodeVersionOf??CP,isGlobal:e.isGlobal??ls().node.isGlobal,nodeFs:e.nodeFs??re,stableNode:null,stableNodeSidecar:null,bin:t}),xo="portless node",gr="~/.infra-kit/node",Po=e=>({row:{name:xo,status:"fail",message:e},stableNode:null,sidecar:null}),Rg=(e,t)=>{try{return e(t,{throwIfNoEntry:!1})}catch{return}},AP=e=>e.signal!==null?`killed by ${e.signal}`:e.status===null?"did not start":e.status!==0?`exit ${e.status}`:`printed ${e.version??"nothing"}`,OP=(e,t)=>e.status===0&&e.signal===null&&e.version===t.version,IP=e=>{let t=Qp(e.home),r=Rg(e.nodeFs.lstatSync,t);if(r===void 0)return Po(`${gr} is missing and could not be written \u2014 run \`infra-kit setup\` and see the debug log`);if(!r.isFile())return Po(`${gr} is not a regular file; infra-kit will not replace it \u2014 move it away and run \`infra-kit setup\``);let n=eu(e.home,e.nodeFs);if(n===null)return Po(`${gr} has no readable node.source.json and it could not be rewritten \u2014 run \`infra-kit setup\``);let o=Rg(e.nodeFs.statSync,e.execPath),s=n.version===e.version&&n.arch===e.arch&&n.platform===e.platform,i=o!==void 0&&r.ino===o.ino&&r.dev===o.dev,a=n.method==="copy"&&o!==void 0&&n.sourceSize===o.size;if(!s||!(i||a))return Po(`${gr} is Node ${n.version} (${n.method} of ${w(n.source)}); infra-kit runs ${e.version} at ${w(e.execPath)}, a different file, and could not relink it \u2014 run \`infra-kit setup\``);if(!i){let c=e.nodeVersionOf(t);if(!OP(c,e))return Po(`${gr} does not run as Node ${e.version} (${AP(c)}). Re-run through the current Node: \`${St(e.bin,{...e,stableNode:null})}\`, then \`infra-kit setup\``)}return{row:{name:xo,status:"pass",message:`${gr} is Node ${n.version} (${n.arch}, ${n.method} of ${w(n.source)})`},stableNode:t,sidecar:n}},DP=e=>{if(Cg(e.platform)===null)return{row:{name:xo,status:"skip",message:"no portless OS service on this platform"},stableNode:null,sidecar:null};let t=IP(e);return e.isGlobal()?t:{...t,row:{name:xo,status:"skip",message:`not a global install; the global infra-kit keeps ${gr} current`}}},$g=(e,t)=>{let r=$P(e,t),n=DP(r);return{seams:{...r,stableNode:n.stableNode,stableNodeSidecar:n.sidecar},node:n.row}},NP=(e,t)=>{let r=t.readFile(pe.join(e,"package.json"));try{let n=r===null?null:fe.object({version:fe.string()}).safeParse(JSON.parse(r));return n?.success===!0?n.data.version:"?"}catch{return"?"}},_P=e=>{let t=Number.parseInt(e.readFile(pe.join(e.stateDir,"proxy.pid"))?.trim()??"",10);return!Number.isInteger(t)||t<=0?null:e.processStartTime(t)},MP=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?null:t},jP=(e,t,r)=>{let n=_P(r),o=a=>n!==null&&a!==null&&n.getTime()<a.getTime(),s=r.stableNodeSidecar,i=[...s!==null&&o(MP(s.versionChangedAt))?[`Node ${s.version}`]:[],...o(r.mtime(pe.join(e,"package.json")))?[`portless ${t}`]:[]];return i.length===0?null:i.join(" and ")},FP=async(e,t)=>{let r=t.realpath(t.cwd);return r===t.realpath(t.home)?!1:In(await t.repoRoot()??r,e,t.realpath)},hr=e=>({state:"drifted",row:e}),LP=async(e,t,r)=>{let n=St(r.bin,r);if(!r.exists(e))return hr({name:Lt,status:"fail",message:`The service runs \`${e}\`, which no longer exists (Node was upgraded, or its package dir was re-created). Re-run: \`${n}\``});let o=pe.join(wa(r.home),"dist","cli.js");if(t!==o)return hr(Eo(`The service points at \`${t}\`, a version-specific location. Re-run once to switch it to the stable link: \`${n}\``));if(cs(r.home,r.exists)===null)return hr({name:Lt,status:"fail",message:"~/.infra-kit/portless is broken. Run any infra-kit command from the global install (e.g. `infra-kit setup`) to repair it."});let s=r.realpath(wa(r.home));if(await FP(s,r))return hr({name:Lt,status:"fail",message:`The service runs portless from a project checkout (${s}). Re-run \`service install\` from the global install: \`${n}\``});let i=VP(e,n,r);if(i!==null)return i;let a=NP(s,r),c=jP(s,a,r);return c!==null?{state:"converged",row:Eo(`The running daemon predates ${c} that \`dev\` will talk to. Restart it: \`${SP(r.platform)}\` (or reboot).`)}:{state:"converged",row:{name:Lt,status:"pass",message:`service runs \`${e}\` (Node ${r.version}) + stable link \u2192 portless ${a}`}}},VP=(e,t,r)=>r.stableNode!==null?r.realpath(e)===r.realpath(r.stableNode)?null:hr(Eo(`The service runs \`${e}\`, a path its package manager will remove. Re-run once to switch it to the stable node: \`${t}\``)):r.realpath(e)===r.realpath(r.execPath)?null:hr(Eo(`The service runs \`${e}\`; infra-kit runs \`${r.execPath}\`. Works until the old Node is removed. Re-run when convenient: \`${t}\``)),Ag=async e=>{let t=Cg(e.platform);if(t===null)return{state:"absent",row:{name:Lt,status:"skip",message:"no portless OS service file on this platform"}};let r=e.readServiceFile(t);if(r===null)return{state:"absent",row:{name:Lt,status:"skip",message:`the OS service is not installed (no ${t})`}};let[n,o]=Fm(e.platform,r)??[];return n===void 0||o===void 0?hr(Eo(`could not parse ${t} \u2014 re-run \`${St(e.bin,e)}\` to rewrite it.`)):LP(n,o,e)},Og=async(e,t)=>{let{seams:r}=$g(e,t);return{state:(await Ag(r)).state,stableNode:r.stableNode}},BP=()=>[xo,Lt,Tg(),"portless CA chain valid","portless CA trusted","portless routes"],WP=async(e={})=>{let t=e.resolveBin??Wp,r=e.isProxyServing??Hp,n=e.handshake??Xp,o=e.caTrusted??Yp,s=e.routes??Nn,i=e.isListening??Dn,a=(e.caPath??zp)(),c=t();if(c===null)return[{name:"portless installed",status:"fail",message:"portless is not resolvable from node_modules \u2014 run `pnpm install`."},...BP().map(S=>({name:S,status:"skip",message:"portless not resolvable"}))];let l={name:"portless installed",status:"pass",message:"portless is resolvable from node_modules"},{seams:d,node:u}=$g(e,c),m=s(),g=await wP(r,c,d),y=g.status==="fail"?{name:"portless CA chain valid",status:"skip",message:"no daemon to handshake with"}:await kP(n,m,a,c,d);return[l,u,(await Ag(d)).row,g,y,bP(o(),a,c),await RP(m,i,c)]},JP=async(e={})=>{let t="portless routes",r=e.routes??Nn,n=e.isListening??Dn,o=e.devSessionRunning??Dm,s=r();if(s.length===0)return{name:t,status:"pass",message:"No portless routes registered"};let i=await Promise.all(s.map(async d=>({name:d.name,port:d.port,live:await n(d.port)}))),{prunable:a,withheld:c}=Im(i,o());if(c.length>0)return{name:t,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:t,status:"pass",message:`${s.length} portless route(s), all live`};let l=e.removeAlias??Zp().removeAlias;for(let d of a)await l(d);return{name:t,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},li=async(e={})=>{let t=await jS(),r=IS(e.probeDeps??ho()),n=async(m,g)=>{let[y,S]=await Promise.all([g,r]),v=S.get(m);return v===void 0?y:{...y,detail:v}},o=await Promise.all([n("brew",yt("brew installed",De("brew").probeArgv,"Homebrew is installed","Homebrew is not installed. Install from: https://brew.sh/")),n("git",yt("git installed",De("git").probeArgv,"git is installed","git is not installed. Install with: brew install git")),n("gh",yt("gh installed",De("gh").probeArgv,"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/")),yt("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),n("doppler",yt("doppler installed",De("doppler").probeArgv,"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli")),n("aws",yt("aws installed",De("aws").probeArgv,"AWS CLI is installed","AWS CLI is not installed. Install from: https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html")),yt("package manager installed",["pnpm","--version"],"Installed: pnpm","pnpm is not installed. Install from: https://pnpm.io/installation"),yt("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"),DS(),Promise.resolve(NS()),Promise.resolve(_S()),MS(),Promise.resolve(FS(t)),US(),WS(t),GS(e.fix??!1),HS(),qS(),XS(t)]),s=await WP(e.portlessDeps);if(e.fix){let m=await JP(),g=s.findIndex(y=>y.name===m.name);g>=0?s[g]=m:s.push(m)}let i=await rP(),a=await po(),c={projectDir:ot.env.CLAUDE_PROJECT_DIR||null,cwd:ot.cwd(),gitRoot:a},l=[await aP(),...pP(i,c),mP({env:ot.env,stdinIsTTY:ot.stdin.isTTY===!0,flag:A.source==="flag"}),a===null?{name:"Agent allowlist",status:"skip",message:"no git root"}:gP(a)],d=[...o,await yP(a),...s,...await tP(),...l],u={checks:d.map(m=>({name:m.name,status:m.status,message:m.message,fixable:Sc.has(m.name),detail:m.detail})),allPassed:AS(d),cliVersion:q.version};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}},Sl=R({name:"doctor",description:"Check installation and authentication status of gh, doppler, and aws CLIs. Read-only: a row marked fixable is one `infra-kit doctor --fix` repairs, and that flag is not reachable from this boundary \u2014 report such a row to the human instead.",inputSchema:{},outputSchema:{checks:fe.array(fe.object({name:fe.string().describe("Name of the check"),status:fe.enum(["pass","fail","warn","skip"]).describe("Check result; warn is advisory and never fails the run; skip is not evaluated; the message says why; never a failure"),message:fe.string().describe("Details about the check result"),fixable:fe.boolean().describe("Whether `infra-kit doctor --fix` repairs this row"),detail:fe.object({manager:fe.string().describe("Which package manager owns this install, read from its resolved path"),version:fe.string().nullable().describe("The version the tool reported, or null"),present:fe.boolean().describe("The tool is installed somewhere findable \u2014 on PATH or not"),onPath:fe.boolean().describe("The binary resolves on PATH")}).optional().describe("Probe facts about an external dependency. Never a fix: no action, no commands")})).describe("List of all check results"),allPassed:fe.boolean().describe("Whether no check failed (warnings and skips do not count)"),cliVersion:fe.string().describe("Version of the infra-kit CLI that produced this report")},handler:()=>li()});import{spawn as XP}from"node:child_process";import Tl from"node:process";import{z as V}from"zod";import{describeProxyRoutes as UP,loadDev as GP,readLocalContext as KP,slugifyHostLabel as Ig}from"@slip-stream-kit/config/internal";import Dg from"node:fs";import vn from"node:path";import Pl from"node:process";import{z as El}from"zod";var HP=async e=>{let t=vn.join(e,"apps"),r=Dg.existsSync(t)?Dg.readdirSync(t).toSorted():[],n=[];for(let o of r){let s=vn.join(t,o,"tests"),i=await Da(s).catch(()=>{});i?.e2e&&n.push({app:o,testsDir:s,e2e:i.e2e})}return n},qP=(e,t)=>{let[r,n]=vn.relative(e,t).split(vn.sep);return r==="apps"&&n?n:void 0},zP=(e,t,r,n)=>{let o=c=>e.find(l=>l.app===c),s=o(t)??(t===void 0?o(qP(n,r)):void 0);if(s)return s;if(t===void 0&&e.length===1)return e[0];let i=e.map(c=>c.app);if(i.length===0)throw new f(void 0,{operation:"find an e2e package",remediation:"declare `e2e: { target, baseUrlEnv }` in `apps/<app>/tests/infra-kit.config.ts` (see the `InfraKitE2e` type)",stderrExcerpt:`no apps/*/tests package under ${n} declares an e2e block`});let a="app";throw new E({status:"argument_required",argument:a,choices:El.toJSONSchema(El.object({app:El.enum(i)})),agentMode:A.source},2,{operation:"pick the e2e package to run",remediation:`pass --app ${i.join("|")}`,stderrExcerpt:t===void 0?"more than one app has e2e tests":`"${t}" has no e2e block; e2e apps: ${i.join(", ")}`})},YP=async(e,t,r)=>Promise.all(e.map(async n=>{if(n.source==="cloud")return{...n,live:null};let o=t.get(n.packageName)??0,s=o>0&&await r({tag:`${n.packageName}`,port:o,kind:"api"})==="ok";return{...n,live:s}})),xl=async(e,t={})=>{let r=t.cwd??Pl.cwd(),n=t.projectRoot??await x(),o=(t.env??Pl.env)[it]||null,s=t.healthProbe??Ku,i=zP(await HP(n),e,r,n),{target:a,baseUrlEnv:c,cloud:l}=i.e2e,[d,u]=a.split("/"),m=vn.join(n,"apps",d,u),g=(await zt(m)).name;if(!g)throw new f(void 0,{operation:`resolve e2e target ${a}`,remediation:`check \`e2e.target\` in ${vn.join(i.testsDir,"infra-kit.config.ts")}`,stderrExcerpt:`${m} has no package.json name`});let y=Hu(m),S=`${y}.${Ig(g)}.localhost`,v=KP(m),C=`https://${S}`,_=0;if(u==="ui")_=(t.listRoutes??Nn)().find(j=>j.name===S||j.name===`${y}.${Ig(g)}`)?.port??0;else{let j=v.info.get(g);_=j?.port??0,C=j?.origin??C}let O=_>0&&await s({tag:a,port:_,kind:u})==="ok",P={app:i.app,testsDir:i.testsDir,target:a,packageName:g,baseUrlEnv:c,release:y,env:o,localUrl:C};if(O){let j=u==="ui"?await GP(m):void 0,Ke=j?.proxy?UP({proxy:j.proxy,localContext:v,env:o??void 0,getRelease:()=>y}):[],xe=new Map([...v.info].map(([ha,ts])=>[ha,ts.port]));return{...P,mode:"local",baseUrl:C,routes:await YP(Ke,xe,s)}}let G=t.env??Pl.env,B=l?o&&l.replaceAll("<env>",o):G[c];if(!o||!B){let j=o?`${c} is not set (and \`e2e.cloud\` is not configured)`:`${it} is not set`;throw new f(void 0,{operation:`resolve where ${i.app}'s e2e tests run`,remediation:"start the dev server (`infra-kit dev`), or load an environment (`infra-kit env-load -c <env>`) to run against cloud",stderrExcerpt:`nothing serves ${a} at ${C}, and ${j}`})}return{...P,mode:"cloud",baseUrl:B,routes:[]}};var ZP=e=>{let t=[`${e.app} e2e \u2192 ${e.mode.toUpperCase()} ${e.baseUrl} (${e.baseUrlEnv})`,e.mode==="local"?` dev server for ${e.target} on release "${e.release}"`:` nothing serves ${e.target} at ${e.localUrl}; cloud env "${e.env}" (${it})`];for(let r of e.routes){let n="";r.live!==null&&(n=r.live?" \u2014 live":" \u2014 NOT responding"),t.push(` ${r.path.padEnd(24)} ${r.source.padEnd(5)} ${r.target??"(unresolved)"}${n}`)}return t.join(`
363
- `)},QP=e=>{let t=e.routes.filter(n=>n.source==="local"&&n.live!==!0);if(t.length===0)return;let r=t.map(n=>`${n.path} (${n.packageName})`);throw new f(void 0,{operation:`run ${e.app} e2e against the local dev server`,remediation:"check the backend rows in `infra-kit dev-status`, fix or restart it, then re-run",stderrExcerpt:`routes held local but their backend is not responding: ${r.join(", ")}`})},eE=async(e,t)=>{if(e.env===null||!jt(e.env))return;let r=await(t.protectedEnvAccess??Je)();if(r.allowed)return;let n=`run ${e.app} e2e against "${e.env}"`;throw r.reason==="agent-blocked"?new E({status:"refused",env:e.env},2,{operation:n,remediation:'a human runs it from their own terminal \u2014 this project sets `protectedEnvs: "cli-only"`',stderrExcerpt:`"${e.env}" is withheld from agents in this project`}):new f(void 0,{operation:n,remediation:"load a non-protected env (`infra-kit env-load -c dev`), or set `protectedEnvs` in infra-kit.json",stderrExcerpt:`"${e.env}" is a protected environment`})},tE=(e,t)=>new Promise((r,n)=>{let o=XP("pnpm",["exec","playwright","test",...t],{cwd:e.testsDir,env:{...Tl.env,[e.baseUrlEnv]:e.baseUrl},stdio:["inherit",at.enabled||ie()?2:"inherit","inherit"]});o.once("error",n),o.once("close",s=>{r(s??1)})}),di=async(e,t={})=>{let r=await xl(e.app,t);p.info(ZP(r));let n=(t.env??Tl.env)[r.baseUrlEnv];n&&n!==r.baseUrl&&p.info(` ${r.baseUrlEnv} was ${n} in this shell; the run uses ${r.baseUrl}`),r.mode==="local"?QP(r):await eE(r,t);let o={...r,playwrightArgs:e.playwrightArgs??[]};if(e.dryRun)return Ng({...o,ran:!1,exitCode:null});r.mode==="cloud"&&await W(e.yes,`Run ${r.app} e2e against ${r.baseUrl} ("${r.env}", shared)?`,{plan:o});let s=await(t.runPlaywright??tE)(r,e.playwrightArgs??[]);return s!==0&&(Tl.exitCode=s),Ng({...o,ran:!0,exitCode:s})},Ng=e=>({content:k(JSON.stringify(e,null,2)),structuredContent:e}),rE={app:V.string(),testsDir:V.string(),target:V.string().describe("The package under test, `<app>/ui` or `<app>/api`."),packageName:V.string(),mode:V.enum(["local","cloud"]).describe("local: this worktree\u2019s dev server serves the target. cloud: it does not; the run uses the env-loaded baseUrlEnv, or e2e.cloud at env."),baseUrl:V.string().describe("The URL the run was pointed at, via the baseUrlEnv variable."),baseUrlEnv:V.string(),release:V.string().describe("This worktree\u2019s release slug \u2014 the first label of every local alias."),env:V.string().nullable().describe("INFRA_KIT_ENV of this process; the env a cloud run targets."),localUrl:V.string().describe("The local address probed, whether or not anything answered."),routes:V.array(V.object({path:V.string(),packageName:V.string(),source:V.enum(["local","cloud"]),target:V.string().nullable(),live:V.boolean().nullable()})).describe("Local UI runs only: the dev proxy\u2019s route-by-route local/cloud split, local backends probed."),playwrightArgs:V.array(V.string()),ran:V.boolean().describe("False for --dry-run."),exitCode:V.number().nullable().describe("Playwright\u2019s exit code; null when it did not run.")},Cl=R({name:"e2e",description:"Run an app\u2019s Playwright e2e suite against this worktree\u2019s local dev server when it serves the target, else against the deployed app at INFRA_KIT_ENV. dryRun resolves and reports the target and the proxy topology without running. A cloud run is confirm-gated; a protected env (prod) follows protectedEnvs.",requiresHumanConfirm:!0,inputSchema:{app:V.string().optional().describe("App folder with an apps/<app>/tests e2e package; inferred from cwd when omitted."),dryRun:V.boolean().optional(),yes:V.boolean().optional()},outputSchema:rE,handler:e=>di(e)});import $l from"node:fs";import _g from"node:path";import{z as To}from"zod";var nE=e=>[...e.map(t=>`unset ${t}`),`unset ${it}`,`unset ${Er}`,`unset ${xr}`,`unset ${ns}`,`unset ${Tr}`],pi=async()=>{let e=bt(),t=_g.join(e,kt);if(!$l.existsSync(t))throw new Error("No loaded environment found. Run `env-load` first.");let r=os(t),n=nE(r),o=_g.resolve(e,rs);$l.mkdirSync(e,{recursive:!0,mode:448}),ss(o,`${n.join(`
364
- `)}
365
- `,384),$l.rmSync(t,{force:!0});let s={filePath:o,variableCount:r.length,unsetStatements:n};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}},Al=R({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 \u2014 returns the path to a script that must be sourced ("source <filePath>") for the vars to go away. The infra-kit shell wrapper auto-sources; direct callers must handle sourcing themselves or surface filePath to the user. Errors if no env is currently loaded.',requiresHumanConfirm:!0,inputSchema:{confirm:To.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{filePath:To.string().describe("Path to the file that must be sourced to apply"),variableCount:To.number().describe("Number of variables cleared"),unsetStatements:To.array(To.string()).describe("Unset statements generated")},handler:()=>pi()});import oE from"node:process";import{z as Vt}from"zod";var ui=(e,t,r)=>e.map(({env:n,source:o})=>({env:n,source:o,hasToken:!!(r||t[n])})),Mg=["Environment","Source","Token"],sE=e=>{let t=e.map(s=>[s.env,s.source,s.hasToken?"set":"not set"]),r=Mg.map((s,i)=>Math.max(s.length,...t.map(a=>(a[i]??"").length))),n=s=>s.map((i,a)=>i.padEnd(r[a]??0)).join(" | ").trimEnd(),o=r.map(s=>"\u2500".repeat(s)).join("\u2500\u253C\u2500");return["Environments:","",n(Mg),o,...t.map(n)]},mi=async()=>{let e=await We(),t=await fn(),r=await ue(),n=oE.env[de],o=ui(t,r?.envs??{},n);if(p.info(`Doppler project: ${e}
366
- `),o.length===0)return p.info("No environments found."),p.info(" Declare them in a workflow's `workflow_dispatch` `environment.options`,"),p.info(" or add a token for one manually."),jg({project:e,envs:o});for(let s of sE(o))p.info(s);return jg({project:e,envs:o})},jg=({project:e,envs:t})=>{let r={project:e,configs:t.map(n=>n.env),tokens:t};return{content:k(JSON.stringify(r,null,2)),structuredContent:r}},Ol=R({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:Vt.string().describe("Detected Doppler project name"),configs:Vt.array(Vt.string()).describe("Every environment name known to this project"),tokens:Vt.array(Vt.object({env:Vt.string().describe("Environment / Doppler config name"),source:Vt.enum(["gh-workflow","token-only"]).describe("Where we learned this environment exists \u2014 a workflow declaration, or a token we hold"),hasToken:Vt.boolean().describe("Whether a service token resolves locally for this environment")})).describe("Per-environment token presence \u2014 never the token value")},handler:mi});import dE from"@inquirer/select";import{Buffer as pE}from"node:buffer";import uE from"node:fs";import mE from"node:path";import Dl from"node:process";import{z as wn}from"zod";import{$ as fi}from"zx";import Vg from"node:process";import{z as Fg}from"zod";var Lg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),iE=async e=>{try{return await e}catch{return[]}},aE=async e=>{let t=await ue().catch(()=>null);return ui(e,t?.envs??{},Vg.env[de]).filter(r=>!r.hasToken).map(r=>r.env)},Il=()=>({get message(){return`Choose the environment to load into terminal session ${Vg.env[He]??`UNKNOWN \u2014 ${He} is not set, the load will fail`}. Picking one LOADS it; there is no further prompt.`},isFormable:e=>Lg(e)&&(e.config===void 0||e.config===""),buildRequestedSchema:async()=>{let e=await iE(fn());if(e.length===0)return p.info({msg:"Tool execution form options empty: env-load"}),null;let t=e.map(n=>n.env),r=await aE(e);return Fg.object({config:Fg.enum(t).describe(`The environment to load. ${r.length===0?"A service token is stored for every one of them.":`NO stored token for: ${r.join(", ")} \u2014 choosing one of those fails until you run \`infra-kit env-token-set <env>\`.`} The list is what env-list knows: workflow-declared environments first, then token-only ones.`)})},toArgs:(e,t)=>{let{config:r}=e;return typeof r!="string"||r.length===0?null:{...Lg(t)?t:{},config:r}}});import{z as cE}from"zod";var lE=async e=>{try{return await e.provider.buildRequestedSchema(e.params)}catch(t){return p.debug({err:t,operation:e.operation},"argument form builder threw; refusing without choices"),null}},Ne=async e=>{if(!ie()||!e.provider.isFormable(e.params))return;let t=await lE(e),r=typeof e.params=="object"&&e.params!==null?e.params:{},n=(t===null?[]:Object.keys(t.shape)).filter(i=>r[i]===void 0||r[i]===""),o=typeof e.argument=="string"?e.argument:e.argument(n),s=t===null?void 0:cE.toJSONSchema(t);throw new E({status:"argument_required",argument:o,...s===void 0?{}:{choices:s},agentMode:A.source},2,{operation:e.operation,remediation:s===void 0?`pass --${o} on the re-run \u2014 nothing could be listed to choose from`:`ask the human to pick from "choices", then pass --${o} on the re-run`,stderrExcerpt:`--${o} was not given and there is no human to ask`})};var fE="DOPPLER_CONFIG",Bg=new Set(["DOPPLER_TOKEN",de]),Wg=!1,gE=e=>{e.length===0||Wg||(Wg=!0,p.warn(`infra-kit: not exporting ${e.join(", ")} from Doppler into your shell \u2014 a service token must not be sourced into every process.`))},Ug=({pairs:e,config:t,project:r,projectRoot:n,loadedAt:o})=>{let s=e.filter(([i])=>!Bg.has(i));return gE(e.filter(([i])=>Bg.has(i)).map(([i])=>i)),["set -a",...s.map(([i,a])=>`${i}=${kn(a)}`),`${it}=${kn(t)}`,`${Er}=${kn(t)}`,`${xr}=${kn(r)}`,`${ns}=${kn(n)}`,`${Tr}=${kn(o)}`,"set +a"]},hE=async()=>{try{return await x()}catch{return""}},Gg=async({config:e})=>{let t=await We(),r=await hE(),n=await wE(t,e),o=new Date().toISOString(),i=`${Ug({pairs:n,config:e,project:t,projectRoot:r,loadedAt:o}).join(`
361
+ ${i}`:"")},_f=()=>{let e="pnpm exec infra-kit";return['if [[ -z "${INFRA_KIT_SESSION}" ]]; then'," export INFRA_KIT_SESSION=$(head -c 4 /dev/urandom | xxd -p)","fi",`env-load() { local f; f=$(${e} env-load "$@") || return; source "$f"; ${e} env-status; }`,`env-clear() { local f; f=$(${e} env-clear "$@") || return; source "$f"; ${e} env-status; }`,`env-status() { ${e} env-status; }`].join(`
362
+ `)},Mf=()=>`${Zt}
363
+ ${_f()}
364
+ ${Tt}`,Lc=()=>["# Inherit this terminal's infra-kit session env into every zsh it spawns, interactive or not.","# A fresh terminal has no session yet (it is minted in .zshrc, after this file) and skips.","# Only the canonical 8-hex id .zshrc mints is honoured. Load wins a tie with clear.","# Prints nothing of its own.",'if [[ -n "${INFRA_KIT_SESSION:-}" ]]; then'," () {"," emulate -L zsh -o extendedglob",' [[ "${INFRA_KIT_SESSION:-}" == [0-9a-f](#c8) ]] || return',' local _ik_dir="${XDG_CACHE_HOME:-$HOME/.cache}/infra-kit/$INFRA_KIT_SESSION"',' local _ik_load="$_ik_dir/env-load.sh" _ik_clear="$_ik_dir/env-clear.sh"',' if [[ -r "$_ik_load" && ! "$_ik_clear" -nt "$_ik_load" ]]; then',' source "$_ik_load"',' elif [[ -r "$_ik_clear" ]]; then',' source "$_ik_clear"'," fi"," }","fi"].join(`
365
+ `),Bc=()=>`${Zt}
366
+ ${Lc()}
367
+ ${Tt}`;import ER from"node:fs/promises";var to=async(e,t)=>{if(!t)return{hasOverrides:!1,overrideKeys:[],unreadable:!1};try{let r=await ER.readFile(e,"utf-8"),n=r.trim()===""?{}:JSON.parse(r);if(typeof n!="object"||n===null||Array.isArray(n))return{hasOverrides:!1,overrideKeys:[],unreadable:!0};let o=Object.keys(n);return{hasOverrides:o.length>0,overrideKeys:o,unreadable:!1}}catch{return{hasOverrides:!1,overrideKeys:[],unreadable:!0}}},ro=e=>e.unreadable?"(unreadable \u2014 invalid JSON)":e.overrideKeys.length===0?"(empty \u2014 no overrides)":`(${e.overrideKeys.length} override(s): ${e.overrideKeys.join(", ")})`;import TR from"node:fs";import CR from"node:os";import jf from"node:path";import $R from"node:process";import{$ as xR}from"zx";var Qt=()=>xR({quiet:!0});var AR=()=>[jf.join(CR.homedir(),".local","bin"),"/opt/homebrew/bin","/usr/local/bin"],OR=async e=>{try{return(await Qt()`command -v ${e}`).stdout.trim()||null}catch{return null}},no=()=>({runCommand:async e=>{let t=await Qt()`${e}`;return{stdout:`${t.stdout}
368
+ ${t.stderr}`}},resolveBinPath:async e=>{let t=await OR(e);return t!==null?t:AR().map(r=>jf.join(r,e)).find(r=>TR.existsSync(r))??null},realpath:me,platform:$R.platform});var Ct=(...e)=>({steps:e,needsSudo:!1,fetchesNetworkScript:!1}),Qr=e=>/\d{1,10}\.\d{1,10}\.\d{1,10}/.exec(e)?.[0]??null,en=["darwin","linux"],Ks=e=>t=>Zi(t,e)?"homebrew":"unknown",Hs=(e,t)=>r=>r===null?null:t(e(r),r),Wc=e=>Hs(Ks(e.kegName),t=>t==="homebrew"?Ct(["brew","upgrade",e.brewFormula]):null),Ff=e=>Ho(e,"Homebrew")||Ho(e,"homebrew")?"homebrew":"unknown",IR={id:"brew",binName:"brew",probeArgv:["brew","--version"],versionFrom:Qr,platforms:en,prerequisites:[],bootstrapInstall:{steps:[["/bin/bash","-c","$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"]],needsSudo:!0,fetchesNetworkScript:!0},identify:Ff,updateFor:Hs(Ff,e=>e==="homebrew"?Ct(["brew","update"]):null)},Vc={brewFormula:"awscli",brewInstallSpec:"awscli",kegName:"awscli"},Vf="https://awscli.amazonaws.com/v2/install.sh",Wf={steps:[["/bin/bash","-c",`curl -fsSL ${Vf} | bash`]],needsSudo:!1,fetchesNetworkScript:!0},DR="/usr/local/aws-cli",NR=e=>hn(DR,e,me)?{steps:[["sudo","/bin/bash","-c",`curl -fsSL ${Vf} | bash -s -- --system`]],needsSudo:!0,fetchesNetworkScript:!0}:Wf,Lf=e=>Zi(e,Vc.kegName)?"homebrew":Ho(e,"aws-cli")?"script":"unknown",_R={id:"aws",binName:"aws",...Vc,probeArgv:["aws","--version"],versionFrom:Qr,platforms:en,prerequisites:[],bootstrapInstall:Wf,identify:Lf,updateFor:Hs(Lf,(e,t)=>e==="homebrew"?Ct(["brew","upgrade",Vc.brewFormula]):e==="script"?NR(t):null)},Us={brewFormula:"git",brewInstallSpec:"git",kegName:"git"},MR={id:"git",binName:"git",...Us,probeArgv:["git","--version"],versionFrom:Qr,platforms:en,prerequisites:["brew"],bootstrapInstall:Ct(["brew","install",Us.brewInstallSpec]),identify:Ks(Us.kegName),updateFor:Wc(Us)},Js={brewFormula:"gh",brewInstallSpec:"gh",kegName:"gh"},jR={id:"gh",binName:"gh",...Js,probeArgv:["gh","--version"],versionFrom:Qr,platforms:en,prerequisites:["brew"],bootstrapInstall:Ct(["brew","install",Js.brewInstallSpec]),identify:Ks(Js.kegName),updateFor:Wc(Js)},Gs={brewFormula:"doppler",brewInstallSpec:"dopplerhq/cli/doppler",kegName:"doppler"},FR={id:"doppler",binName:"doppler",...Gs,probeArgv:["doppler","--version"],versionFrom:Qr,platforms:en,prerequisites:["brew"],bootstrapInstall:Ct(["brew","install","gnupg"],["brew","install",Gs.brewInstallSpec]),identify:Ks(Gs.kegName),updateFor:Wc(Gs)},oo="portless",Bf=e=>yu(e,oo)===null?"unknown":"npm",LR={id:"portless",binName:oo,npmPackage:oo,probeArgv:["portless","--version"],versionFrom:Qr,platforms:[...en,"win32"],prerequisites:[],bootstrapInstall:Ct(["npm","install","-g",oo]),identify:Bf,updateFor:Hs(Bf,e=>e==="npm"?Ct(["npm","install","-g",`${oo}@latest`]):null)},Uc={brew:IR,git:MR,aws:_R,gh:jR,doppler:FR,portless:LR},er=Object.keys(Uc),Ie=e=>Uc[e],Jc=(e,t)=>e.platforms.includes(t),Gc=e=>{let t=[],r=new Set,n=(o,s)=>{if(s.includes(o))throw new Error(`dependency cycle: ${[...s,o].join(" -> ")}`);if(!r.has(o)){r.add(o);for(let i of Ie(o).prerequisites)n(i,[...s,o]);t.push(o)}};for(let o of e)n(o,[]);return t};var Uf=e=>({id:e,present:!1,onPath:!1,binRealPath:null,version:null,manager:"unknown"}),Jf=async(e,t)=>{try{return await e(t)}catch{return null}},BR=async(e,t)=>{try{let r=await e.resolveBinPath(t);return r==null?null:e.realpath(r)}catch{return null}},Gf=async(e,t)=>{if(!Jc(e,t.platform))return Uf(e.id);let r=await Jf(t.runCommand,e.probeArgv),n=await BR(t,e.binName);if(r==null&&n==null)return Uf(e.id);let o=r??(n==null?null:await Jf(t.runCommand,[n,...e.probeArgv.slice(1)]));return{id:e.id,present:!0,onPath:r!=null,binRealPath:n,version:o==null?null:e.versionFrom(o.stdout),manager:n==null?"unknown":e.identify(n)}},so=async(e,t)=>Promise.all(e.map(r=>Gf(Ie(r),t)));import{$ as KR}from"zx";import{z as Kf}from"zod";var Hf=/^\d{4}-\d{2}-\d{2}$/,io=e=>{if(!Hf.test(e))return!1;let[t,r,n]=e.split("-").map(Number),o=new Date(Date.UTC(t,r-1,n));return o.getUTCFullYear()===t&&o.getUTCMonth()===r-1&&o.getUTCDate()===n},qf=e=>`Release date "${e}" is not a calendar date in yyyy-mm-dd form.`,tn=class extends Error{constructor(t){super(qf(t)),this.name="InvalidReleaseDateError"}},tr=e=>{let t=e.trim();if(!io(t))throw new tn(t);return t},ao=e=>{let t=e.trim();return t===""||io(t)?!0:qf(t)},Kc=Kf.string().refine(io,{message:"Expected a calendar date in yyyy-mm-dd form."}),Hc=Kf.string().refine(e=>e===""||io(e),{message:'Expected a calendar date in yyyy-mm-dd form, or "" to clear.'});var $t=e=>e.slice(1).split(".").map(Number),rn=e=>[...e].sort((t,r)=>{let[n,o,s]=$t(t),[i,a,c]=$t(r);return n!==i?(n??0)-(i??0):o!==a?(o??0)-(a??0):(s??0)-(c??0)});var zf="next",VR=/^v?(\d+)\.(\d+)\.(\d+)$/,WR=e=>e.replace(/^.*release\//,""),qc=e=>{let t=WR(e.trim()),r=VR.exec(t);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null},Yf=e=>`${e[0]}.${e[1]}.${e[2]}`,Yc=e=>{let t=[...e.remoteBranches??[],...e.jiraVersions??[]],r=[],n=new Set;for(let o of t){let s=qc(o);if(!s)continue;let i=Yf(s);n.has(i)||(n.add(i),r.push(s))}return rn(r.map(o=>Yf(o))).map(o=>$t(`v${o}`))},rr=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},zc=(e,t)=>{if(e.length===0)throw new rr;let r=e[e.length-1];if(t==="hotfix"){let[s,i]=r,a=e.reduce((c,l)=>l[0]===s&&l[1]===i?Math.max(c,l[2]):c,0);return`${s}.${i}.${a+1}`}let[n,o]=r;return`${n}.${o+1}.0`},nn=(e,t)=>{try{return zc(e,t)}catch(r){if(r instanceof rr)return null;throw r}},Xc=e=>e.trim().toLowerCase()===zf,Ys=e=>Xc(e)||qc(e)!==null?{version:e}:{name:e},UR=e=>e==="regular"||e==="hotfix",Xf=e=>"name"in e,JR=e=>{let t=e.indexOf("@");if(t===-1)return{token:e.trim()};let r=e.slice(0,t).trim(),n=e.slice(t+1);if(n.includes("@"))throw new Error(`Release spec "${e}" has more than one "@". Expected "<token>@yyyy-mm-dd".`);if(n.trim()==="")throw new Error(`Release spec "${e}" has an empty release date after "@". Expected "<token>@yyyy-mm-dd".`);return{token:r,releaseDate:tr(n)}},Zc=e=>{let t=e.trim();if(t==="")throw new Error("Release spec is empty");let r=t.indexOf(":"),{token:n,releaseDate:o}=JR(r===-1?t:t.slice(0,r)),s="regular",i="";if(r!==-1){let a=t.slice(r+1),c=a.indexOf(":"),l=c===-1?a.trim():a.slice(0,c).trim();i=c===-1?"":a.slice(c+1).trim();let d=l.toLowerCase();if(!UR(d))throw new Error(`Invalid release type "${l}". Expected "regular" or "hotfix".`);s=d}return qs({...Ys(n),type:s},{description:i,releaseDate:o})},Qc=e=>{let t=e.releaseDate===void 0?e.id.raw:`${e.id.raw}@${e.releaseDate}`;return e.description!==void 0&&e.description!==""?`${t}:${e.type}:${e.description}`:e.type==="hotfix"?`${t}:hotfix`:t},qs=(e,t)=>{let{description:r,releaseDate:n}=t;return{...e,...r!==void 0&&r!==""?{description:r}:{},...n===void 0?{}:{releaseDate:n}}},GR=e=>{let t=e.name.trim();return Zo(t),qs({id:{kind:"name",name:t,raw:t},type:e.type},e)},el=(e,t)=>{let r=[...t];return e.map(n=>{if(Xf(n))return GR(n);let o=n.version.trim();if(o==="")throw new Error("Release entry has an empty version");if(Xc(o)){let a=zc(r,n.type);return r.push($t(`v${a}`)),qs({id:ye(a),type:n.type},n)}let s=qc(o);if(!s)throw new Error(`Invalid version "${o}". Expected semver like "1.2.5" or the token "next".`);let i=`${s[0]}.${s[1]}.${s[2]}`;return r.push(s),qs({id:ye(i),type:n.type},n)})},tl=e=>e.some(t=>!Xf(t)&&Xc(t.version));var HR=e=>e.split(`
369
+ `).map(t=>{let r=t.indexOf(" ");return r===-1?null:J(t.slice(r+1))}).filter(t=>t!==null&&t.kind==="version").map(t=>t.raw),qR=async()=>{let e=await KR({quiet:!0})`git ls-remote --heads origin 'release/v*'`;return HR(e.stdout)},YR=async()=>{let e=await at();return e?(await Br(e)).map(r=>r.name):[]},co=async()=>{let[e,t]=await Promise.allSettled([qR(),YR()]);return e.status==="rejected"&&u.warn({err:e.reason},"Failed to list remote release branches; continuing without them"),t.status==="rejected"&&u.warn({err:t.reason},"Failed to fetch Jira versions; continuing without them"),Yc({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:t.status==="fulfilled"?t.value:[]})};import zR from"node:fs";import XR from"node:path";var rl=[".claude/settings.json",".claude/settings.local.json"],ZR=["infra-kit","ik","pnpm exec infra-kit","pnpm exec ik","pnpm infra-kit"],QR=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),eS=e=>{let t=e.trim();if(t==="Bash")return"*";let r=/^Bash\((.*)\)$/s.exec(t);if(r===null)return null;let n=r[1]??"";return n.endsWith(":*")?`${n.slice(0,-2)}*`:n},tS=(e,t)=>{let r=e.indexOf("*");if(r===-1)return e===t||e.startsWith(`${t} `);let n=e.slice(0,r);return new RegExp(`^${e.split("*").map(QR).join(".*")}$`,"s").test(t)||n===t||n.startsWith(`${t} `)},rS=e=>{let t=e.groupPath.join(" ");return t===e.cliName?[t]:[t,e.cliName]},nS=()=>nr.filter(e=>e.mutating),oS=e=>{let t=eS(e);return t===null?[]:nS().filter(r=>ZR.some(n=>rS(r).some(o=>tS(t,`${n} ${o}`)))).map(r=>r.groupPath.join(" "))},sS=(e,t)=>{let r;try{r=zR.readFileSync(XR.join(e,t),"utf-8")}catch(i){return i.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable",file:t}}let n;try{n=JSON.parse(r)}catch{return{kind:"unreadable",file:t}}let o=n?.permissions;if(o==null)return{kind:"read",patterns:[]};let s=o.allow;return s===void 0?{kind:"read",patterns:[]}:Array.isArray(s)?{kind:"read",patterns:s.filter(i=>typeof i=="string")}:{kind:"unreadable",file:t}},Zf=e=>{let t={present:[],unreadable:[],hits:[]};for(let r of rl){let n=sS(e,r);if(n.kind!=="absent"){if(t.present.push(r),n.kind==="unreadable"){t.unreadable.push(r);continue}for(let o of n.patterns){let s=oS(o);s.length>0&&t.hits.push({file:r,pattern:o,commands:s})}}}return t};var iS=e=>e.every(t=>t.status!=="fail"),aS=["brew","git","gh","doppler","aws"],cS=async e=>{let t=await so(aS,e);return new Map(t.map(r=>[r.id,{manager:r.manager,version:r.version,present:r.present,onPath:r.onPath}]))},lt=async(e,t,r,n)=>{try{return await Qt()`${t}`,{name:e,status:"pass",message:r}}catch{return{name:e,status:"fail",message:n}}},lS=async()=>{let e="orca installed",t=await Rr();return t==="absent"?{name:e,status:"fail",message:"orca is not on PATH. Install with: brew install --cask stablyai/orca/orca, then register the CLI in Orca \u2192 Settings \u2192 Experimental \u2192 CLI"}:t==="unreachable"?{name:e,status:"warn",message:"orca is installed but the app is not running \u2014 start it with: orca open"}:{name:e,status:"pass",message:"Installed: orca (app running, runtime reachable)"}},dg=(e,t,r,n)=>{let o=ce.join(lg.homedir(),t),s="Run: infra-kit setup --skip-tools";if(!ee.existsSync(o))return{name:e,status:"fail",message:`~/${t} not found. ${s}`};let i=ee.readFileSync(o,"utf-8"),a=i.indexOf(Zt),c=i.indexOf(Tt);return a===-1||c===-1||c<a?{name:e,status:"fail",message:`infra-kit ${r} block missing from ~/${t}. ${s}`}:i.slice(a,c+Tt.length).trim()!==n.trim()?{name:e,status:"fail",message:`infra-kit ${r} block in ~/${t} is out of date. ${s}`}:{name:e,status:"pass",message:`infra-kit ${r} block in ~/${t} is up to date`}},dS=()=>dg("zshrc init block",".zshrc","shell",Mf()),uS=()=>dg("zshenv session block",".zshenv","session-env",Bc()),pS=async()=>{let e="pnpm enableGlobalVirtualStore";try{let t=await E(),r=ce.join(t,"pnpm-workspace.yaml");if(!ee.existsSync(r))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${r}`};let n=ee.readFileSync(r,"utf-8");return/^\s*enableGlobalVirtualStore\s*:\s*true\s*$/m.test(n)?{name:e,status:"pass",message:"enableGlobalVirtualStore: true is set"}:{name:e,status:"fail",message:"enableGlobalVirtualStore: true is missing in pnpm-workspace.yaml"}}catch(t){return{name:e,status:"fail",message:`Failed to read pnpm-workspace.yaml: ${t.message}`}}},mS=async()=>{try{return vt(),{config:await M(),error:null}}catch(e){return{config:null,error:e}}},fS=e=>{let t="infra-kit config valid";return e.error?{name:t,status:"fail",message:e.error.message}:{name:t,status:"pass",message:"infra-kit.json is valid (user overrides applied if present)"}},gS=384,nl=448,hS=e=>e.length===0?"no envs declared":e.map(t=>{let r=t.source===null?"no token":`token (${t.source})`;return`${t.env}: ${r}`}).join(", "),yS=async(e,t)=>Promise.all(e.map(async r=>{try{let{source:n}=await t(r);return{env:r,source:n}}catch{return{env:r,source:null}}})),vS=async(e,t={})=>{let r="env tokens configured",n=t.readStore??Bt,o=t.resolveToken??Sp;if(!e.config)return{name:r,status:"skip",message:"infra-kit config could not be read (see config check)"};try{await n()}catch(i){return{name:r,status:"fail",message:`Token store unreadable \u2014 ${i.message}`}}let s=await yS(await ds(),o);return{name:r,status:"pass",message:hS(s)}},wS=()=>et.env[Vt]||void 0,kS=async(e={})=>{let t="tokens.json present",r=e.readStore??Bt,n=e.storePath??Lt;if((e.readEnvToken??wS)())return{name:t,status:"skip",message:`${Vt} is set; that channel takes precedence over the store`};let s;try{s=w(await n())}catch{return{name:t,status:"skip",message:"the token store path could not be resolved"}}let i;try{i=await r()}catch{return{name:t,status:"skip",message:`The store at ${s} is unreadable (see env tokens configured)`}}let a=i===null?[]:Object.keys(i.envs);if(a.length===0){let c=i===null?`No token store at ${s}`:`${s} holds no tokens`;return{name:t,status:"fail",message:`${c} \u2014 every project needs one to authenticate. Fix: run \`infra-kit env-token-set <env>\`. CI / agents: set ${Vt} instead.`}}return{name:t,status:"pass",message:`${s} holds ${a.length} token(s): ${a.join(", ")}`}},lo=(e,t)=>{let r=t(e);return r===null?null:r.mode&511},bS=async(e,t={})=>{let r="tokens.json perms",n=t.storePath??Lt,o=t.statPath??RS,s=t.chmodPath??ee.chmodSync,i;try{i=await n()}catch{return{name:r,status:"skip",message:"the token store path could not be resolved"}}if(lo(i,o)===null)return{name:r,status:"skip",message:`No store to protect at ${w(i)} (see tokens.json present)`};let a=ce.dirname(i),c=ce.dirname(a),l=ce.dirname(c),p=[{target:l,expected:nl,actual:lo(l,o)},{target:c,expected:nl,actual:lo(c,o)},{target:a,expected:nl,actual:lo(a,o)},{target:i,expected:gS,actual:lo(i,o)}].filter(g=>g.actual!==null&&g.actual!==g.expected);if(p.length===0)return{name:r,status:"pass",message:`${w(i)} is 0600 (0700 dirs)`};let m=p.map(g=>`${w(g.target)} is ${Qf(g.actual)}, expected ${Qf(g.expected)}`).join("; ");if(!e)return{name:r,status:"fail",message:`${m}. Fix: run \`infra-kit doctor --fix\`, or chmod them by hand.`};for(let g of p)s(g.target,g.expected);return{name:r,status:"pass",message:`Tightened ${p.length} path(s): ${m}`}},Qf=e=>`0${e.toString(8).padStart(3,"0")}`,RS=e=>{try{return ee.statSync(e)}catch{return null}},SS=async()=>{let e="user override path";try{let t=await Q(),r=ee.existsSync(t.userProject),n=await to(t.userProject,r),o=r?ro(n):"(not created \u2014 seed failed?)";return{name:e,status:"pass",message:`${w(t.userProject)} ${o} \u2014 project: ${t.projectName}`}}catch(t){return{name:e,status:"fail",message:t.message}}},PS=async()=>{let e="legacy user-global config",t;try{t=await Q()}catch{return{name:e,status:"skip",message:"infra-kit config paths could not be resolved"}}let r=ce.join(ce.dirname(t.userGlobal),"config.json");return ee.existsSync(r)?ee.existsSync(t.userGlobal)?{name:e,status:"fail",message:`Stale legacy config.json found at ${w(r)} \u2014 ${w(t.userGlobal)} is active; remove the old file.`}:{name:e,status:"fail",message:`Legacy user-global config.json found at ${w(r)} \u2014 run \`infra-kit setup --skip-tools\` to migrate it (your overrides are not being applied).`}:{name:e,status:"pass",message:"No legacy user-global config.json"}},ES={cursor:{command:["cursor","--version"],label:"Cursor",failMsg:"Cursor is not installed. Install from: https://cursor.com/"}},xS=async e=>{let t=ES[e];try{return await Qt()`${t.command}`,{ok:!0,label:t.label,failMsg:t.failMsg}}catch{return{ok:!1,label:t.label,failMsg:t.failMsg}}},TS=async e=>{let t="ide installed";if(!e.config)return{name:t,status:"skip",message:"infra-kit config could not be read (see config check)"};let r=yt(e.config).map(s=>s.provider);if(r.length===0)return{name:t,status:"pass",message:"No IDE configured (ide unset)"};let n=await Promise.all(r.map(s=>xS(s))),o=n.filter(s=>!s.ok);return o.length===0?{name:t,status:"pass",message:`Installed: ${n.map(s=>s.label).join(", ")}`}:{name:t,status:"fail",message:o.map(s=>s.failMsg).join("; ")}},eg=/^\d+\.\d+\.\d+$/,CS=(e,t)=>e===t||!eg.test(e)||!eg.test(t)?!1:rn([`v${e}`,`v${t}`])[0]===`v${e}`,$S=async(e,t)=>{let r;try{r=await ke(e)}catch{return[]}let n=[];for(let o of r){let s=Gt(Kt(ce.join(o,"CLAUDE.md")));s.state==="ok"&&s.version!==void 0&&CS(s.version,t)&&n.push(s.version)}return n},AS=async(e,t)=>{let r=await $S(e,t);if(r.length===0)return"";let n=rn(r.map(o=>`v${o}`))[0].slice(1);return` \u2014 ${r.length} package guidance blocks were generated by an older infra-kit (oldest ${n}, current ${t}) \u2014 run: infra-kit audit --fix --all`},OS=async()=>{let e=[{name:"CLAUDE.md block",status:"skip",message:"no infra-kit config in this repo"}],t;try{t=(await Q()).main}catch{return e}if(!ee.existsSync(t))return e;let r=ce.dirname(t),n=ce.join(r,"CLAUDE.md"),o=ee.existsSync(n)?ee.readFileSync(n,"utf-8"):"",s=Je(o,$e,Ge),i=s?"CLAUDE.md block present":"infra-kit block missing from CLAUDE.md. Run: infra-kit setup --skip-tools",a=await AS(r,G.version);return[{name:"CLAUDE.md block",status:s?"pass":"fail",message:`${i}${a}`}]},IS=async()=>{try{let e=(await Q()).main;return ee.existsSync(e)?ce.dirname(e):null}catch{return null}},DS=e=>{let t=ip();return t===null||!bn(t,e)?"":` \u2014 plugin ${t} is fetched but not applied. Run: ${Ir}`},NS=e=>{let t=e.kind==="installed"?ss(e.installation):null;return{name:"plugin version",status:t===null?"fail":"pass",message:t===null?"No infra-kit plugin installed for this project to read a version from":`Plugin ${K} version ${t}${DS(t)}`}},tg=3,rg=(e,t)=>me(e)===me(t),_S=e=>{if(e===void 0||e.gitRoot===null)return"";let t=w(e.gitRoot);if(e.projectDir!==null){if(rg(e.projectDir,e.gitRoot))return"";let r=hn(e.gitRoot,me(e.projectDir),me)?"below the repo root":"not this checkout";return` \u2014 this session was launched from ${w(e.projectDir)}, ${r}: the plugin and this repo's .claude/settings.json hooks load only from ${t} (measured); restart Claude Code there`}return rg(e.cwd,e.gitRoot)?"":` \u2014 if Claude Code was launched from ${w(e.cwd)} rather than ${t}, it loaded neither the plugin nor this repo's hooks; launch it at ${t}`},MS=(e,t)=>{let r="plugin installed",n=_S(t);if(e.kind==="installed"){let{scope:c,projectPath:l}=e.installation,d=l===null?"":`, ${w(l)}`;return{name:r,status:"pass",message:`Plugin ${K} installed (${c??"unknown"} scope${d})${n}`}}if(e.kind==="absent")return{name:r,status:"fail",message:`Plugin ${K} is not installed. Run: ${st}${n}`};let o=e.installations.map(c=>c.projectPath===null?"(unnamed project)":w(c.projectPath)),s=o.length-tg,i=s>0?` and ${s} more`:"",a=`${o.slice(0,tg).join(", ")}${i}`;return{name:r,status:"fail",message:`Plugin ${K} is installed for ${a} only, not this project. Run: ${st}${n}`}},jS=()=>lt("claude CLI",["claude","--version"],"Installed: claude","claude CLI not found on PATH \u2014 `infra-kit setup` cannot install the plugin; install Claude Code first"),FS=(e,...t)=>{try{return JSON.parse(ee.readFileSync(ce.join(e,...t),"utf-8"))}catch{return null}},LS=e=>{if(e.kind!=="installed")return{kind:"not-installed"};let t=ss(e.installation),{installPath:r}=e.installation;if(r===null)return{kind:"skills-only",version:t};let n=FS(r,Ae),o=n!==null&&typeof n=="object"?n[He]:void 0;return o==null||typeof o!="object"?{kind:"skills-only",version:t}:{kind:"stale-server",version:t,keys:Object.keys(o)}},ng=e=>`Plugin ${K} ${e===null?"(version unreadable)":e}`,BS=e=>{let t="plugin MCP server";if(e.kind==="not-installed")return{name:t,status:"fail",message:`No infra-kit plugin installed for this project \u2014 no skills to drive the CLI. Run: ${st}`};if(e.kind==="stale-server"){let r=e.keys.length===0?"":` (under "${e.keys.join('", "')}")`;return{name:t,status:"pass",message:`${ng(e.version)} still carries an MCP server in its ${Ae}${r} \u2014 a copy from before the plugin went skills-only. Update it: infra-kit setup (or ${Ir}), then restart Claude Code`}}return{name:t,status:"pass",message:`${ng(e.version)} is skills-only \u2014 no ${Ae}, as shipped; the /infra-kit:* skills drive the infra-kit CLI`}},VS=(e,t)=>{let r=Ft(e===null?{}:{projectPath:e}),n=kn();return[{name:"marketplace registered",status:n?"pass":"fail",message:n?`Marketplace ${se} is known to Claude Code`:`Marketplace ${se} is not registered. Run: claude plugin marketplace add ${wt}`},MS(r,t),NS(r),BS(LS(r)),{name:"CLI version",status:"pass",message:`infra-kit CLI ${G.version}`}]},WS=({env:e,stdinIsTTY:t,flag:r})=>{let n=e.INFRA_KIT_AGENT===void 0?"unset":`= "${e.INFRA_KIT_AGENT}"`;return[`CLAUDECODE ${e.CLAUDECODE===void 0?"unset":"set"}`,`INFRA_KIT_AGENT ${n}`,`stdin ${t?"is a TTY":"is not a TTY"}`,`--agent ${r?"passed":"not passed"}`].join(", ")},US=e=>{let t="Agent mode",r=Xo(e),n=WS(e);return{name:t,status:"pass",message:`${r===null?"human":"agent"} \u2014 ${r==="flag"?"the --agent flag, which beats every environment value":e.env.INFRA_KIT_AGENT==="1"?"INFRA_KIT_AGENT=1":r==="env"?"CLAUDECODE is set and stdin is not a TTY":e.env.CLAUDECODE!==void 0&&e.stdinIsTTY?"CLAUDECODE is set but stdin is a TTY, so this is a terminal Claude Code spawned for a person":e.env.INFRA_KIT_AGENT==="0"?"INFRA_KIT_AGENT=0 suppresses the CLAUDECODE heuristic":"no source fires; pass --agent or set INFRA_KIT_AGENT=1 to drive this CLI as an agent"} (${n})`}},og=4,JS=e=>{let t=e.slice(0,og).join(", "),r=e.length-og;return r>0?`${t} +${r} more`:t},GS=e=>{let t="Agent allowlist",{present:r,unreadable:n,hits:o}=Zf(e);if(o.length>0){let s=o.map(i=>`${i.file} allows "${i.pattern}", which reaches ${i.commands.length} mutating infra-kit command${i.commands.length===1?"":"s"} (${JS(i.commands)})`);return{name:t,status:"warn",message:`${s.join("; ")} \u2014 a prefix allow lets an agent run the --yes re-run of a mutating command unprompted; narrow it to read-only argv (e.g. Bash(infra-kit release list:*)) so the host prompts for the rest`}}return n.length>0?{name:t,status:"warn",message:`Could not read permissions.allow from ${n.join(" and ")} \u2014 fix the JSON and re-run; until then the allowlist is unchecked`}:r.length===0?{name:t,status:"pass",message:`no ${rl.join(" or ")} at the repo root \u2014 no Bash allow pattern to reach a mutating infra-kit command`}:{name:t,status:"pass",message:`no permissions.allow pattern in ${r.join(" or ")} reaches a mutating infra-kit command`}},KS=(e,t)=>{let r=Math.floor((t-Date.parse(e))/36e5);return Number.isNaN(r)?"age unknown":r>=24?`${Math.floor(r/24)}d old`:`${Math.max(r,0)}h old`},HS=async(e,t=Date.now())=>{let r="merge-dev resolutions";if(e===null)return{name:r,status:"skip",message:"no git root"};let n;try{n=await lf(e)}catch(i){return{name:r,status:"skip",message:`could not read the merge-dev state: ${i.message}`}}if(n.length===0)return{name:r,status:"pass",message:"no merge-dev hand-off in progress"};let o=n.map(i=>{let a=i.worktreeExists?w(i.worktreePath):"worktree missing";return`${i.branch} (${KS(i.createdAt,t)}, ${a})`}),s=n.map(i=>i.branch).join(",");return{name:r,status:"warn",message:`${n.length} unfinished merge-dev hand-off${n.length===1?"":"s"}: ${o.join("; ")} \u2014 finish with: infra-kit release merge-dev --continue --versions ${s}, or drop with --abort`}},ug=e=>Qi(["trust"],{bin:e}),qS=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),sg="ERR_TLS_CERT_ALTNAME_INVALID",pg=()=>`portless serving TLS on :${ht}`,YS=async(e,t,r)=>{let n=pg();return await e(ht,!0)?{name:n,status:"pass",message:`portless is serving HTTPS on :${ht}`}:{name:n,status:"fail",message:`No portless daemon is serving HTTPS on :${ht}. Install it once (needs root): \`${ft(t,r)}\`.`}},zS=async(e,t,r,n,o)=>{let s="portless CA chain valid",i=["localhost",...t.slice(0,1).map(d=>d.name)],c=(await Promise.all(i.map(async d=>({servername:d,result:await e(ht,d)})))).filter(d=>!d.result.ok);if(c.length===0)return{name:s,status:"pass",message:`Served certificate chains to ${w(r)} (${i.join(", ")})`};let l=c.map(d=>d.result.ok?"":d.result.code);return l.includes(sg)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${sg} for servername(s) ${c.map(d=>d.servername).join(", ")} \u2014 doctor's probe is wrong, your trust store is not implicated. Please report this.`}:l.some(d=>qS.has(d))?{name:s,status:"fail",message:`The daemon is serving a certificate that does not chain to ${w(r)}. Its CA was regenerated \u2014 run \`${ug(n)}\`, or reinstall: \`${ft(n,o)}\`.`}:{name:s,status:"fail",message:`TLS handshake failed (${l.join(", ")})`}},XS=(e,t,r)=>{let n="portless CA trusted";return e?{name:n,status:"pass",message:`${w(t)} matches the recorded ca.trusted fingerprint`}:{name:n,status:"fail",message:`The portless CA is not trusted (or was regenerated). Run: \`${ug(r)}\` (no sudo needed).`}},ZS=async(e,t,r)=>{let n="portless routes";if(e.length===0)return{name:n,status:"pass",message:"No portless routes registered"};let s=(await Promise.all(e.map(async i=>({route:i,live:await t(i.port)})))).filter(i=>!i.live).map(i=>i.route.name);return s.length===0?{name:n,status:"pass",message:`${e.length} portless route(s), all live`}:{name:n,status:"fail",message:`${s.length} stale portless route(s): ${s.join(", ")}. Remove with \`${Qi(["alias","--remove","<name>"],{bin:r})}\`.`}},At="portless service target",po=e=>({name:At,status:"warn",message:e}),mg=e=>e==="darwin"?Pu:e==="linux"?Eu:null,QS=e=>e==="darwin"?`sudo launchctl kickstart -k system/${Su}`:`sudo systemctl restart ${xu}`,eP="/bin/ps",tP=e=>{try{let t=cg(eP,["-o","lstart=","-p",String(e)],{encoding:"utf-8"});if(t.status!==0)return null;let r=new Date(t.stdout.trim());return Number.isNaN(r.getTime())?null:r}catch{return null}},ig=e=>{try{return ee.readFileSync(e,"utf-8")}catch{return null}},rP=e=>{try{return ee.statSync(e).mtime}catch{return null}},nP=2e3,oP=e=>{try{let t=cg(e,["-p","process.version"],{encoding:"utf-8",timeout:nP}),r=t.stdout?.trim()??"";return{version:r===""?null:r,status:t.status,signal:t.signal}}catch{return{version:null,status:null,signal:null}}},sP=(e,t)=>({platform:e.platform??et.platform,readServiceFile:e.readServiceFile??ig,readFile:e.readFile??ig,exists:e.exists??ee.existsSync,realpath:e.realpath??me,mtime:e.mtime??rP,execPath:e.execPath??et.execPath,home:e.home??lg.homedir(),cwd:e.cwd??et.cwd(),repoRoot:e.repoRoot??Qn,stateDir:(e.stateDir??Cu)(),processStartTime:e.processStartTime??tP,version:e.version??et.version,arch:e.arch??et.arch,nodeVersionOf:e.nodeVersionOf??oP,isGlobal:e.isGlobal??zo().node.isGlobal,nodeFs:e.nodeFs??ee,stableNode:null,stableNodeSidecar:null,bin:t}),mo="portless node",or="~/.infra-kit/node",uo=e=>({row:{name:mo,status:"fail",message:e},stableNode:null,sidecar:null}),ag=(e,t)=>{try{return e(t,{throwIfNoEntry:!1})}catch{return}},iP=e=>e.signal!==null?`killed by ${e.signal}`:e.status===null?"did not start":e.status!==0?`exit ${e.status}`:`printed ${e.version??"nothing"}`,aP=(e,t)=>e.status===0&&e.signal===null&&e.version===t.version,cP=e=>{let t=Du(e.home),r=ag(e.nodeFs.lstatSync,t);if(r===void 0)return uo(`${or} is missing and could not be written \u2014 run \`infra-kit setup\` and see the debug log`);if(!r.isFile())return uo(`${or} is not a regular file; infra-kit will not replace it \u2014 move it away and run \`infra-kit setup\``);let n=Nu(e.home,e.nodeFs);if(n===null)return uo(`${or} has no readable node.source.json and it could not be rewritten \u2014 run \`infra-kit setup\``);let o=ag(e.nodeFs.statSync,e.execPath),s=n.version===e.version&&n.arch===e.arch&&n.platform===e.platform,i=o!==void 0&&r.ino===o.ino&&r.dev===o.dev,a=n.method==="copy"&&o!==void 0&&n.sourceSize===o.size;if(!s||!(i||a))return uo(`${or} is Node ${n.version} (${n.method} of ${w(n.source)}); infra-kit runs ${e.version} at ${w(e.execPath)}, a different file, and could not relink it \u2014 run \`infra-kit setup\``);if(!i){let c=e.nodeVersionOf(t);if(!aP(c,e))return uo(`${or} does not run as Node ${e.version} (${iP(c)}). Re-run through the current Node: \`${ft(e.bin,{...e,stableNode:null})}\`, then \`infra-kit setup\``)}return{row:{name:mo,status:"pass",message:`${or} is Node ${n.version} (${n.arch}, ${n.method} of ${w(n.source)})`},stableNode:t,sidecar:n}},lP=e=>{if(mg(e.platform)===null)return{row:{name:mo,status:"skip",message:"no portless OS service on this platform"},stableNode:null,sidecar:null};let t=cP(e);return e.isGlobal()?t:{...t,row:{name:mo,status:"skip",message:`not a global install; the global infra-kit keeps ${or} current`}}},fg=(e,t)=>{let r=sP(e,t),n=lP(r);return{seams:{...r,stableNode:n.stableNode,stableNodeSidecar:n.sidecar},node:n.row}},dP=(e,t)=>{let r=t.readFile(ce.join(e,"package.json"));try{let n=r===null?null:de.object({version:de.string()}).safeParse(JSON.parse(r));return n?.success===!0?n.data.version:"?"}catch{return"?"}},uP=e=>{let t=Number.parseInt(e.readFile(ce.join(e.stateDir,"proxy.pid"))?.trim()??"",10);return!Number.isInteger(t)||t<=0?null:e.processStartTime(t)},pP=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?null:t},mP=(e,t,r)=>{let n=uP(r),o=a=>n!==null&&a!==null&&n.getTime()<a.getTime(),s=r.stableNodeSidecar,i=[...s!==null&&o(pP(s.versionChangedAt))?[`Node ${s.version}`]:[],...o(r.mtime(ce.join(e,"package.json")))?[`portless ${t}`]:[]];return i.length===0?null:i.join(" and ")},fP=async(e,t)=>{let r=t.realpath(t.cwd);return r===t.realpath(t.home)?!1:hn(await t.repoRoot()??r,e,t.realpath)},sr=e=>({state:"drifted",row:e}),gP=async(e,t,r)=>{let n=ft(r.bin,r);if(!r.exists(e))return sr({name:At,status:"fail",message:`The service runs \`${e}\`, which no longer exists (Node was upgraded, or its package dir was re-created). Re-run: \`${n}\``});let o=ce.join(ea(r.home),"dist","cli.js");if(t!==o)return sr(po(`The service points at \`${t}\`, a version-specific location. Re-run once to switch it to the stable link: \`${n}\``));if(Yo(r.home,r.exists)===null)return sr({name:At,status:"fail",message:"~/.infra-kit/portless is broken. Run any infra-kit command from the global install (e.g. `infra-kit setup`) to repair it."});let s=r.realpath(ea(r.home));if(await fP(s,r))return sr({name:At,status:"fail",message:`The service runs portless from a project checkout (${s}). Re-run \`service install\` from the global install: \`${n}\``});let i=hP(e,n,r);if(i!==null)return i;let a=dP(s,r),c=mP(s,a,r);return c!==null?{state:"converged",row:po(`The running daemon predates ${c} that \`dev\` will talk to. Restart it: \`${QS(r.platform)}\` (or reboot).`)}:{state:"converged",row:{name:At,status:"pass",message:`service runs \`${e}\` (Node ${r.version}) + stable link \u2192 portless ${a}`}}},hP=(e,t,r)=>r.stableNode!==null?r.realpath(e)===r.realpath(r.stableNode)?null:sr(po(`The service runs \`${e}\`, a path its package manager will remove. Re-run once to switch it to the stable node: \`${t}\``)):r.realpath(e)===r.realpath(r.execPath)?null:sr(po(`The service runs \`${e}\`; infra-kit runs \`${r.execPath}\`. Works until the old Node is removed. Re-run when convenient: \`${t}\``)),gg=async e=>{let t=mg(e.platform);if(t===null)return{state:"absent",row:{name:At,status:"skip",message:"no portless OS service file on this platform"}};let r=e.readServiceFile(t);if(r===null)return{state:"absent",row:{name:At,status:"skip",message:`the OS service is not installed (no ${t})`}};let[n,o]=Am(e.platform,r)??[];return n===void 0||o===void 0?sr(po(`could not parse ${t} \u2014 re-run \`${ft(e.bin,e)}\` to rewrite it.`)):gP(n,o,e)},hg=async(e,t)=>{let{seams:r}=fg(e,t);return{state:(await gg(r)).state,stableNode:r.stableNode}},yP=()=>[mo,At,pg(),"portless CA chain valid","portless CA trusted","portless routes"],vP=async(e={})=>{let t=e.resolveBin??Ru,r=e.isProxyServing??Tu,n=e.handshake??Ou,o=e.caTrusted??Au,s=e.routes??vn,i=e.isListening??yn,a=(e.caPath??$u)(),c=t();if(c===null)return[{name:"portless installed",status:"fail",message:"portless is not resolvable from node_modules \u2014 run `pnpm install`."},...yP().map(R=>({name:R,status:"skip",message:"portless not resolvable"}))];let l={name:"portless installed",status:"pass",message:"portless is resolvable from node_modules"},{seams:d,node:p}=fg(e,c),m=s(),g=await YS(r,c,d),y=g.status==="fail"?{name:"portless CA chain valid",status:"skip",message:"no daemon to handshake with"}:await zS(n,m,a,c,d);return[l,p,(await gg(d)).row,g,y,XS(o(),a,c),await ZS(m,i,c)]},wP=async(e={})=>{let t="portless routes",r=e.routes??vn,n=e.isListening??yn,o=e.devSessionRunning??Em,s=r();if(s.length===0)return{name:t,status:"pass",message:"No portless routes registered"};let i=await Promise.all(s.map(async d=>({name:d.name,port:d.port,live:await n(d.port)}))),{prunable:a,withheld:c}=Pm(i,o());if(c.length>0)return{name:t,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:t,status:"pass",message:`${s.length} portless route(s), all live`};let l=e.removeAlias??Iu().removeAlias;for(let d of a)await l(d);return{name:t,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},zs=async(e={})=>{let t=await mS(),r=cS(e.probeDeps??no()),n=async(m,g)=>{let[y,R]=await Promise.all([g,r]),v=R.get(m);return v===void 0?y:{...y,detail:v}},o=await Promise.all([n("brew",lt("brew installed",Ie("brew").probeArgv,"Homebrew is installed","Homebrew is not installed. Install from: https://brew.sh/")),n("git",lt("git installed",Ie("git").probeArgv,"git is installed","git is not installed. Install with: brew install git")),n("gh",lt("gh installed",Ie("gh").probeArgv,"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/")),lt("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),n("doppler",lt("doppler installed",Ie("doppler").probeArgv,"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli")),n("aws",lt("aws installed",Ie("aws").probeArgv,"AWS CLI is installed","AWS CLI is not installed. Install from: https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html")),lt("package manager installed",["pnpm","--version"],"Installed: pnpm","pnpm is not installed. Install from: https://pnpm.io/installation"),lt("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"),lS(),Promise.resolve(dS()),Promise.resolve(uS()),pS(),Promise.resolve(fS(t)),kS(),vS(t),bS(e.fix??!1),SS(),PS(),TS(t)]),s=await vP(e.portlessDeps);if(e.fix){let m=await wP(),g=s.findIndex(y=>y.name===m.name);g>=0?s[g]=m:s.push(m)}let i=await IS(),a=await Qn(),c={projectDir:et.env.CLAUDE_PROJECT_DIR||null,cwd:et.cwd(),gitRoot:a},l=[await jS(),...VS(i,c),US({env:et.env,stdinIsTTY:et.stdin.isTTY===!0,flag:I.source==="flag"}),a===null?{name:"Agent allowlist",status:"skip",message:"no git root"}:GS(a)],d=[...o,await HS(a),...s,...await OS(),...l],p={checks:d.map(m=>({name:m.name,status:m.status,message:m.message,fixable:cc.has(m.name),detail:m.detail})),allPassed:iS(d),cliVersion:G.version};return{content:k(JSON.stringify(p,null,2)),structuredContent:p}},ol=S({name:"doctor",description:"Check installation and authentication status of gh, doppler, and aws CLIs. Read-only: a row marked fixable is one `infra-kit doctor --fix` repairs, and that flag is not reachable from this boundary \u2014 report such a row to the human instead.",inputSchema:{},outputSchema:{checks:de.array(de.object({name:de.string().describe("Name of the check"),status:de.enum(["pass","fail","warn","skip"]).describe("Check result; warn is advisory and never fails the run; skip is not evaluated; the message says why; never a failure"),message:de.string().describe("Details about the check result"),fixable:de.boolean().describe("Whether `infra-kit doctor --fix` repairs this row"),detail:de.object({manager:de.string().describe("Which package manager owns this install, read from its resolved path"),version:de.string().nullable().describe("The version the tool reported, or null"),present:de.boolean().describe("The tool is installed somewhere findable \u2014 on PATH or not"),onPath:de.boolean().describe("The binary resolves on PATH")}).optional().describe("Probe facts about an external dependency. Never a fix: no action, no commands")})).describe("List of all check results"),allPassed:de.boolean().describe("Whether no check failed (warnings and skips do not count)"),cliVersion:de.string().describe("Version of the infra-kit CLI that produced this report")},handler:()=>zs()});import{E2E_MODE_ENV as TP}from"@slip-stream-kit/config/internal";import{spawn as CP}from"node:child_process";import $P from"node:fs";import AP from"node:path";import Rg from"node:process";import{z as _}from"zod";import{describeProxyRoutes as kP,loadDev as bP,readCloudOrigin as RP,readLocalContext as wg,slugifyHostLabel as yg}from"@slip-stream-kit/config/internal";import vg from"node:fs";import ir from"node:path";import Xs from"node:process";import{z as sl}from"zod";var SP=async e=>{let t=ir.join(e,"apps"),r=vg.existsSync(t)?vg.readdirSync(t).toSorted():[],n=[];for(let o of r){let s=ir.join(t,o,"tests"),i=await Pr(s);i?.e2e&&n.push({app:o,testsDir:s,e2e:i.e2e})}return n},PP=(e,t)=>{let[r,n]=ir.relative(e,t).split(ir.sep);return r==="apps"&&n?n:void 0},EP=(e,t,r,n)=>{let o=c=>e.find(l=>l.app===c),s=o(t)??(t===void 0?o(PP(n,r)):void 0);if(s)return s;if(t===void 0&&e.length===1)return e[0];let i=e.map(c=>c.app);if(i.length===0)throw new f(void 0,{operation:"find an e2e package",remediation:"declare `e2e: { target }` in `apps/<app>/tests/infra-kit.config.ts` (see the `InfraKitE2e` type)",stderrExcerpt:`no apps/*/tests package under ${n} declares an e2e block`});let a="app";throw new x({status:"argument_required",argument:a,choices:sl.toJSONSchema(sl.object({app:sl.enum(i)})),agentMode:I.source},2,{operation:"pick the e2e package to run",remediation:`pass --app ${i.join("|")}`,stderrExcerpt:t===void 0?"more than one app has e2e tests":`"${t}" has no e2e block; e2e apps: ${i.join(", ")}`})},xP=async(e,t,r)=>Promise.all(e.map(async n=>{if(n.source==="cloud")return{...n,live:null};let o=t.get(n.packageName)??0,s=o>0&&await r({tag:`${n.packageName}`,port:o,kind:"api"})==="ok";return{...n,live:s}})),il=async(e,t={})=>{let r=t.cwd??Xs.cwd(),n=t.projectRoot??await E(),o=(t.env??Xs.env)[hr]||null,s=t.healthProbe??da,i=EP(await SP(n),e,r,n),{target:a}=i.e2e,[c,l]=a.split("/"),d=ir.join(n,"apps",c,l),p=(await Wt(d)).name,m=(await Pr(d))?.deployedUrlEnv??null;if(!p)throw new f(void 0,{operation:`resolve e2e target ${a}`,remediation:`check \`e2e.target\` in ${ir.join(i.testsDir,"infra-kit.config.ts")}`,stderrExcerpt:`${d} has no package.json name`});let g=Dp(d),y=`${g}.${yg(p)}.localhost`,R=`https://${y}`,v=0;if(l==="ui")v=(t.listRoutes??vn)().find(D=>D.name===y||D.name===`${g}.${yg(p)}`)?.port??0;else{let D=wg(d).info.get(p);v=D?.port??0,R=D?.origin??R}let $=v>0&&await s({tag:a,port:v,kind:l})==="ok";return{app:i.app,testsDir:i.testsDir,target:a,kind:l,targetDir:d,packageName:p,deployedUrlEnv:m,release:g,env:o,localUrl:R,served:$}},kg=e=>{let{app:t,testsDir:r,target:n,packageName:o,deployedUrlEnv:s,release:i,env:a,localUrl:c}=e;return{app:t,testsDir:r,target:n,packageName:o,deployedUrlEnv:s,release:i,env:a,localUrl:c}},al=async(e,t={})=>{let r=t.healthProbe??da,n=wg(e.targetDir),o=e.kind==="ui"?await bP(e.targetDir):void 0,s=o?.proxy?kP({proxy:o.proxy,localContext:n,env:e.env??void 0,cloud:RP(e.deployedUrlEnv??void 0,t.env??Xs.env),getRelease:()=>e.release}):[],i=new Map([...n.info].map(([a,c])=>[a,c.port]));return{...kg(e),mode:"local",baseUrl:e.localUrl,routes:await xP(s,i,r)}},cl=(e,t={})=>{let{env:r,deployedUrlEnv:n,target:o}=e;if(!n)throw new f(void 0,{operation:`resolve the deployed app ${e.app}'s cloud e2e run targets`,remediation:`declare \`deployedUrlEnv: '<APP>_URL'\` in ${ir.join(e.targetDir,"infra-kit.config.ts")} and keep the URL per environment in Doppler`,stderrExcerpt:`${o} names no variable holding its deployed URL`});let s=(t.env??Xs.env)[n];if(!r||!s)throw new f(void 0,{operation:`resolve the deployed app ${e.app}'s cloud e2e run targets`,remediation:"load an environment (`infra-kit env-load -c <env>`), or drop --cloud to run against this worktree",stderrExcerpt:`a cloud run of ${o} needs ${n} and ${hr}, and ${s?hr:n} is not set`});return{...kg(e),mode:"cloud",baseUrl:s,routes:[]}};var OP=["playwright.config.ts","playwright.config.mts","playwright.config.js","playwright.config.mjs"],IP=e=>OP.some(t=>{try{return $P.readFileSync(AP.join(e,t),"utf8").includes("infraKitE2e")}catch{return!1}}),Sg=e=>`infra-kit dev ${e.target.split("/")[0]} --no-watch --reuse`,DP=(e,t)=>{let r=[`${e.app} e2e \u2192 ${e.mode.toUpperCase()} ${e.baseUrl}`];e.mode==="cloud"?r.push(` deployed app at env "${e.env}"`):t?r.push(` dev server for ${e.target} on release "${e.release}", already running`):r.push(` nothing serves ${e.target} yet; the Playwright config starts it and stops it after the run`);for(let n of e.routes){let o="";n.live!==null&&(o=n.live?" \u2014 live":" \u2014 NOT responding"),r.push(` ${n.path.padEnd(24)} ${n.source.padEnd(5)} ${n.target??"(unresolved)"}${o}`)}return r.join(`
370
+ `)},NP=e=>{let t=e.routes.filter(n=>n.source==="local"&&n.live!==!0);if(t.length===0)return;let r=t.map(n=>`${n.path} (${n.packageName})`);throw new f(void 0,{operation:`run ${e.app} e2e against the local dev server`,remediation:"check the backend rows in `infra-kit dev-status`, fix or restart it, then re-run",stderrExcerpt:`routes held local but their backend is not responding: ${r.join(", ")}`})},_P=async(e,t)=>{if(e.env===null||!Ip(e.env))return;let r=await(t.protectedEnvAccess??We)();if(r.allowed)return;let n=`run ${e.app} e2e against "${e.env}"`;throw r.reason==="agent-blocked"?new x({status:"refused",env:e.env},2,{operation:n,remediation:'a human runs it from their own terminal \u2014 this project sets `protectedEnvs: "cli-only"`',stderrExcerpt:`"${e.env}" is withheld from agents in this project`}):new f(void 0,{operation:n,remediation:"load a non-protected env (`infra-kit env-load -c dev`), or set `protectedEnvs` in infra-kit.json",stderrExcerpt:`"${e.env}" is a protected environment`})},MP=async(e,t)=>{if(e.served){let d=await al(e,t);return NP(d),d}if(!IP(e.testsDir))throw new f(void 0,{operation:`run ${e.app} e2e locally`,remediation:`start it (\`${Sg(e)}\`), or wire \`infraKitE2e()\` from @slip-stream-kit/config/playwright into its playwright.config.ts`,stderrExcerpt:`nothing serves ${e.target} and ${e.testsDir}'s Playwright config does not start it`});let{app:r,testsDir:n,target:o,packageName:s,deployedUrlEnv:i,release:a,env:c,localUrl:l}=e;return{app:r,testsDir:n,target:o,packageName:s,deployedUrlEnv:i,release:a,env:c,localUrl:l,mode:"local",baseUrl:l,routes:[]}},jP=(e,t)=>new Promise((r,n)=>{let o=CP("pnpm",["exec","playwright","test",...t],{cwd:e.testsDir,env:{...Rg.env,[TP]:e.mode},stdio:["inherit",rt.enabled||ge()?2:"inherit","inherit"]});o.once("error",n),o.once("close",s=>{r(s??1)})}),Zs=async(e,t={})=>{let r=await il(e.app,t),n=e.cloud?cl(r,t):await MP(r,t);u.info(DP(n,r.served)),n.mode==="cloud"&&await _P(n,t);let o={...n,served:r.served,devCommand:n.mode==="local"&&!r.served?Sg(r):null,playwrightArgs:e.playwrightArgs??[]};if(e.dryRun)return bg({...o,ran:!1,exitCode:null});n.mode==="cloud"&&await B(e.yes,`Run ${n.app} e2e against ${n.baseUrl} ("${n.env}", shared)?`,{plan:o});let s=await(t.runPlaywright??jP)(n,e.playwrightArgs??[]);return s!==0&&(Rg.exitCode=s),bg({...o,ran:!0,exitCode:s})},bg=e=>({content:k(JSON.stringify(e,null,2)),structuredContent:e}),FP={app:_.string(),testsDir:_.string(),target:_.string().describe("The package under test, `<app>/ui` or `<app>/api`."),packageName:_.string(),mode:_.enum(["local","cloud"]).describe("local (default): this worktree\u2019s dev server. cloud (--cloud): the deployed app at env."),baseUrl:_.string().describe("The URL the run was pointed at: the local alias, or the deployed URL."),deployedUrlEnv:_.string().nullable().describe("The target\u2019s variable holding its deployed URL; a cloud run reads it. Null when it declares none."),release:_.string().describe("This worktree\u2019s release slug \u2014 the first label of every local alias."),env:_.string().nullable().describe("INFRA_KIT_ENV of this process; the env a cloud run targets."),localUrl:_.string().describe("This worktree\u2019s address for the target, whether or not anything serves it."),served:_.boolean().describe("Whether this worktree\u2019s dev server already served the target when the run began."),devCommand:_.string().nullable().describe("Local runs with nothing served: the dev command the Playwright config starts, and stops after."),routes:_.array(_.object({path:_.string(),packageName:_.string(),source:_.enum(["local","cloud"]),target:_.string().nullable(),live:_.boolean().nullable()})).describe("Served local UI runs only: the dev proxy\u2019s route-by-route local/cloud split, local backends probed."),playwrightArgs:_.array(_.string()),ran:_.boolean().describe("False for --dry-run."),exitCode:_.number().nullable().describe("Playwright\u2019s exit code; null when it did not run.")},ll=S({name:"e2e",description:"Run an app\u2019s Playwright e2e suite against this worktree: the running dev server, or one the package\u2019s infraKitE2e() Playwright config starts and stops. cloud runs against the deployed app at INFRA_KIT_ENV instead, confirm-gated; a protected env (prod) follows protectedEnvs. dryRun reports the target without running.",requiresHumanConfirm:!0,inputSchema:{app:_.string().optional().describe("App folder with an apps/<app>/tests e2e package; inferred from cwd when omitted."),dryRun:_.boolean().optional(),yes:_.boolean().optional(),cloud:_.boolean().optional().describe("Run against the deployed app at INFRA_KIT_ENV instead of this worktree.")},outputSchema:FP,handler:e=>Zs(e)});import dl from"node:fs";import Pg from"node:path";import{z as fo}from"zod";var LP=e=>[...e.map(t=>`unset ${t}`),`unset ${hr}`,`unset ${Uo}`,`unset ${Jo}`,`unset ${pu}`,`unset ${Go}`],Qs=async()=>{let e=yr(),t=Pg.join(e,gr);if(!dl.existsSync(t))throw new Error("No loaded environment found. Run `env-load` first.");let r=Ko(t),n=LP(r),o=Pg.resolve(e,Wo);dl.mkdirSync(e,{recursive:!0,mode:448}),hu(o,`${n.join(`
367
371
  `)}
368
- `,a=bt(),c=mE.resolve(a,kt);return uE.mkdirSync(a,{recursive:!0,mode:448}),ss(c,i,384),{filePath:c,variableCount:n.length,project:t,config:e}},Kg=Il(),gi=async e=>{let{config:t}=e;await Ne({provider:Kg,params:e,operation:"env-load",argument:"config"});let r="";if(t)r=t;else{if(ee())throw new E({status:"argument_required",argument:"config",agentMode:A.source},2,{operation:"env-load",remediation:'call env-list, ask the human which environment, and re-call env-load with "config"'});let s=await pr();h.setInteractive(),r=await I(i=>dE({message:"Select environment config",choices:s.map(a=>({name:a,value:a}))},i),{output:Dl.stderr,whenHeadless:"refuse"})}h.addOption("--config",r);let n=await Gg({config:r});h.print();let o={filePath:n.filePath,variableCount:n.variableCount,project:n.project,config:n.config,sessionId:Dl.env[He]??null};return{content:k(JSON.stringify(o,null,2)),structuredContent:o}},Jg=1024*1024,yE=3e4,vE=["DOPPLER_TOKEN","DOPPLER_PROJECT","DOPPLER_CONFIG"],bn=(e,t=Dl.env)=>{let r={...t};for(let n of vE)delete r[n];return r.DOPPLER_TOKEN=e,r},wE=async(e,t)=>{let{token:r}=await mo(t),n=bn(r),o=fi.quiet;fi.quiet=!0;try{let s;try{s=await fi({env:n})`doppler secrets download --no-file --format json --project ${e} --config ${t}`.timeout(yE)}catch(a){throw kE(a,e,t)}bE(s.stdout);let i=yi(s.stdout);return hi(i,t),i}finally{fi.quiet=o}},hi=(e,t)=>{let r=e.find(([n])=>n===fE)?.[1];if(!(r===void 0||r===t))throw new cn(t,null,`Doppler returned secrets for config "${r}" but "${t}" was requested \u2014 the service token for env "${t}" is scoped to the wrong config. Refusing to load another environment's secrets.
369
- Fix: run \`infra-kit env-token-set ${t}\` with a token scoped to "${t}".`)},kE=(e,t,r)=>{let n=$r(e)??(e instanceof Error?e.message:String(e)),o=ir(n);return o==="auth"?new cn(r,ar(n)):o==="unknown"?e instanceof Error?e:new Error(String(e)):new Error(rl({kind:o,project:t,config:r,available:null}))},bE=e=>{let t=pE.byteLength(e,"utf-8");if(t>Jg)throw new Error(`doppler returned unexpectedly large output (${t} bytes > ${Jg}) \u2014 refusing to write to disk`)},kn=e=>`'${e.replaceAll("'","'\\''")}'`,RE=/^[A-Z_]\w*$/i,yi=e=>{let t;try{t=JSON.parse(e)}catch{throw new Error(`doppler returned non-JSON output for env-load (got: ${JSON.stringify(e.slice(0,80))})`)}if(t===null||typeof t!="object"||Array.isArray(t))throw new Error("doppler returned unexpected JSON shape for env-load (expected an object of KEY: value pairs)");let r=[];for(let[n,o]of Object.entries(t)){if(!RE.test(n))throw new Error(`doppler returned an invalid env var name for env-load (got: ${JSON.stringify(n.slice(0,80))})`);if(typeof o!="string")throw new TypeError(`doppler returned a non-string value for "${n}" (got ${typeof o})`);r.push([n,o])}if(r.length===0)throw new Error("doppler returned empty output for env-load");return r},Nl=R({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. This server picks the file up on its next tool call, so a tool that needs the variables can be called right after. Omit "config" and this server offers the human a form listing every environment env-list knows, token-less ones marked; a client that cannot render one gets a refusal naming the missing field \u2014 call env-list and ask the human, never guess.',inputSchema:{config:wn.string().optional().describe('Doppler config / environment name to load (e.g. "dev", "arthur"). Omit it to have the human choose from a form.')},formProvider:Kg,outputSchema:{filePath:wn.string().describe("Path to the file that must be sourced to apply variables"),variableCount:wn.number().describe("Number of variables loaded"),project:wn.string().describe("Doppler project name"),config:wn.string().describe("Doppler config name"),sessionId:wn.string().nullable().describe("The INFRA_KIT_SESSION the file was written for; null when the process had no session")},handler:gi});import SE from"node:path";import Co from"node:process";import{z as Rn}from"zod";var vi=async()=>{p.info("Environment session status:");let e=bt(),t=Co.env[He],r=SE.join(e,kt),n=0,o=0,s=Co.env[Er]??null,i=Co.env[xr]??null,a=Co.env[Tr]??null;if(s){let l=os(r);l.length>0&&(o=l.length,n=l.filter(u=>u in Co.env).length);let d=a?.replace(/\.\d{3}Z$/,"")??null;if(p.info(` ${s}: ${n} of ${o} vars loaded (project: ${i}, loadedAt: ${d}, session: ${t})
370
- `),o>0&&n<o){let u=o-n;p.warn(` ${u} cached var(s) are not present in the current process \u2014 env-load needs to be re-sourced, or vars were unset manually.`)}}else p.info(` Session ${t}: no env loaded
371
- `);let c={sessionId:t,sessionLoadedCount:n,sessionTotalCount:o,sessionConfig:s,sessionProject:i,sessionLoadedAt:a};return{content:k(JSON.stringify(c,null,2)),structuredContent:c}},_l=R({name:"env-status",description:"Report which Doppler project/config is currently loaded in the terminal session, when it was loaded, and how many variables are cached. 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. Over MCP this reflects the session file as of this call \u2014 the server re-reads it before every tool.",inputSchema:{},outputSchema:{sessionId:Rn.string().describe("Current terminal session ID"),sessionLoadedCount:Rn.number().describe("Number of cached vars active in the current session"),sessionTotalCount:Rn.number().describe("Total number of cached var names"),sessionConfig:Rn.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:Rn.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:Rn.string().nullable().describe("ISO 8601 timestamp of when the env was loaded")},handler:vi});import PE from"node:process";import{z as Bt}from"zod";var Hg="****",Sn=e=>typeof e!="string"||e.length<8?Hg:`${Hg}${e.slice(-4)}`;var qg=(e,t,r)=>e.map(n=>{let o=r||t[n];return o?{env:n,source:r?`env:${de}`:"store",redactedToken:Sn(o),present:!0}:{env:n,source:"-",redactedToken:"-",present:!1}}),EE=["ENV","SOURCE","TOKEN","PRESENT"],zg=(e,t)=>{let r=[...EE,...t?["CHECK"]:[]],n=e.map(s=>[s.env,s.source,s.redactedToken,s.present?"yes":"no",...t?[s.status??"-"]:[]]),o=r.map((s,i)=>Math.max(s.length,...n.map(a=>(a[i]??"").length)));return[r,...n].map(s=>s.map((i,a)=>i.padEnd(o[a])).join(" ").trimEnd())},wi=async({check:e}={})=>{let t=await pr(),r=await ue(),n=PE.env[de],o=qg(t,r?.envs??{},n);if(e){let a=await We();for(let c of o){if(!c.present)continue;let l=n||r.envs[c.env],d=await nl({childEnv:bn(l),project:a,config:c.env});c.status=d.outcome}}for(let a of zg(o,!!e))p.info(a);let s=o.filter(a=>!a.present);s.length>0&&p.info(`
372
- No token for: ${s.map(a=>a.env).join(", ")}. Add one with \`infra-kit env-token-set <env>\`.`);let i={tokens:o};return{content:k(JSON.stringify(i,null,2)),structuredContent:i}},Ml=R({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:Bt.boolean().optional().describe("Probe Doppler for each token\u2019s validity and scope (one cheap call per environment).")},outputSchema:{tokens:Bt.array(Bt.object({env:Bt.string().describe("Environment / Doppler config name"),source:Bt.string().describe('"store", "env:INFRA_KIT_ENV_TOKEN", or "-" when absent'),redactedToken:Bt.string().describe("Redacted token \u2014 last 4 chars at most, never the raw value"),present:Bt.boolean().describe("Whether a token is configured for this environment"),status:Bt.string().optional().describe("Only with check=true: valid | revoked | mis-scoped | unreachable")})).describe("One row per declared environment")},handler:wi});import{z as b}from"zod";import{$ as xE}from"zx";var TE=(e,t)=>({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0,dryRun:e,atomicPush:{attempted:!1,aborted:!1},results:[],skipped:t}),CE=e=>e.dualBase?"open PRs to both dev and main":e.titleMismatch?"title/base mismatch":e.type==="hotfix"?"hotfix (targets main)":null,$E=e=>{let t=new Map;for(let r of e)t.set(r.reason,(t.get(r.reason)??0)+1);return[...t].map(([r,n])=>`${r} \xD7${n}`).join(", ")},Fl=e=>({content:k(JSON.stringify(e,null,2)),structuredContent:e}),jl=new Set(["up-to-date","fast-forward","merged"]),AE=(e,t,r)=>{let n=(Array.isArray(e)?e:e.split(",")).map(a=>a.trim()).filter(a=>a.length>0),o=new Set(t),s=new Map(r.map(a=>[a.branch,a.reason])),i=new Set;for(let a of n){let c;try{c=Te(ve(a))}catch(l){throw new f(l,{operation:`resolve release selector "${a}"`,remediation:`pass one of: ${t.join(", ")}`})}if(!o.has(c)){let l=s.get(c);throw new f(void 0,{operation:`select release branch for "${a}"`,stderrExcerpt:l?`${c} is skipped: ${l}`:`${c} is not an open regular release branch`,remediation:`pass one of: ${t.join(", ")}`})}i.add(c)}return t.filter(a=>i.has(a))},OE={"up-to-date":"already up to date","fast-forward":"fast-forward",merged:"clean merge",conflict:"CONFLICT","hook-failed":"HOOK FAILED",error:"ERROR","not-attempted":"not attempted"},Xg=e=>{let t=OE[e.status];if(e.status==="conflict"){let r=e.conflictPaths?.length??0;return`${t}: ${r} file(s)`}return e.reason?`${t}: ${e.reason}`:t},IE=(e,t)=>{p.info(`
373
- \u{1F4CB} Merge plan:`);for(let r of e)p.info(` ${r.branch} \u2014 ${Xg(r)}`);for(let r of t)p.info(` ${r.branch} \u2014 skipped: ${r.reason}`)},DE=(e,t)=>{let r=t.find(n=>n.branch===e);return r?`git -C ${r.path} merge origin/dev`:`git switch ${e} && git merge origin/dev`},NE=async e=>{let{entries:t,toPlan:r,all:n,explicit:o}=e;if(o||n)return r;h.setInteractive();let s=new Map(t.flatMap(i=>{let a=K(i.branch);return a?[[ne(a),Xg(i)]]:[]}));return Nt(se({branches:r,descriptions:s}),{required:!0})},_E=async e=>{let{cwd:t,worktreePath:r,entries:n,selected:o,verify:s}=e,i=n.filter(y=>o.includes(y.branch)),a=y=>{for(let S of y)p.info(`\u2139\uFE0F ${S} was merged by someone else while we planned \u2014 dropping it from the push`)},c=await ao(t,ef(i));a(c.nowUpToDate);let l=c.kept,d=new Map;if(s&&l.length>0){p.info(`
374
- \u{1F50E} Verifying ${l.length} merge(s) with: ${s}`);let y=await rf({worktreePath:r,refs:l,command:s});d=y.failed;for(let[v,C]of y.failed)p.info(`\u2717 ${v} failed verification \u2014 not pushing it. ${C.split(`
375
- `)[0]??""}`);let S=await ao(t,y.kept);a(S.nowUpToDate),l=S.kept}if(l.length===0)return{pushed:!1,pushAborted:!1,verifyFailed:d};p.info(`
376
- \u2B06\uFE0F Pushing atomically: ${l.map(y=>y.branch).join(", ")}`);let u=await gs(t,l);if(u.pushed)return{pushed:!0,pushAborted:!1,verifyFailed:d};let g=(await Promise.all(l.map(async y=>({branch:y.branch,landed:await Or(t,y.branch)===y.sha})))).filter(y=>y.landed);return g.length>0&&p.warn(`\u26A0\uFE0F The push reported failure, but origin already carries ${g.map(y=>y.branch).join(", ")} \u2014 re-run to reconcile.`),{pushed:!1,pushAborted:!0,abortedBy:u.stderr?.split(`
377
- `)[0],observedLanded:g.map(y=>y.branch)}},ME=e=>{let t=["keepConflicts","continue","abort"].filter(n=>e[n]),r={keepConflicts:"--keep-conflicts",continue:"--continue",abort:"--abort"};if(t.length>1||t.length===1&&e.dryRun){let n=[...t.map(o=>r[o]),...e.dryRun?["--dry-run"]:[]];throw new f(void 0,{operation:"choose the merge-dev mode",stderrExcerpt:`${n.join(" and ")} cannot be combined`,remediation:"pass at most one of --keep-conflicts, --continue, --abort; --dry-run only on a plain run"})}if(e.tree!==void 0&&!e.continue)throw new f(void 0,{operation:"choose the merge-dev mode",stderrExcerpt:"--tree belongs to --continue",remediation:"run the rerun a --continue preview printed, unchanged"})},Yg=e=>{let{results:t,atomicPush:r,declined:n}=e;for(let i of t){let a=i.reason?.split(`
378
- `)[0];p.info(a?` ${i.branch} \u2014 ${i.status}: ${a}`:` ${i.branch} \u2014 ${i.status}`)}let o=n?[]:t.filter(i=>i.status!=="aborted"),s=o.filter(i=>!jl.has(i.status));return Fl({successfulMerges:o.length-s.length,failedMerges:s.length,failedBranches:s.map(i=>i.branch),totalBranches:t.length,dryRun:!1,atomicPush:r,results:t,skipped:[]})},jE=async e=>{let{all:t,versions:r,verify:n,confirmedCommand:o}=e,s=await Le();if(e.abort)return Yg(await Tf({cwd:s,versions:r,all:t,confirmedCommand:o}));let i=typeof n=="string"&&n.length>0?n:void 0;return Yg(await Ef({cwd:s,versions:r,all:t,verify:i,trees:xf(e.tree),confirmedCommand:o}))},ki=async e=>{let{all:t,versions:r,dryRun:n=!1,verify:o,keepConflicts:s=!1,confirmedCommand:i}=e;ME(e);let a=o===!0?tf:o||void 0;if(await Ec({operation:"merge dev into release branches"}),e.continue||e.abort)return jE(e);let c=[],l=[];for(let B of await F()){let j=CE(B);j?l.push({branch:B.branch,reason:j}):c.push(B.branch)}if(c.length===0)return p.info(l.length===0?"\u2139\uFE0F No open release branches found":`\u2139\uFE0F No open regular release branches \u2014 ${l.length} skipped (${$E(l)})`),h.print(),Fl(TE(n,l));let d=await Le();try{await xE({cwd:d,quiet:!0})`git fetch origin --prune`}catch(B){throw new f(B,{operation:"fetch origin before planning the merges",remediation:"check network access and that `origin` is reachable"})}let u=r===void 0?c:AE(r,c,l),m=await gu({cwd:d},async B=>{let j=Gs(B.remove);try{return await FE({cwd:d,worktree:B,toPlan:u,candidates:c,skipped:l,all:t,versions:r,dryRun:n,verify:a,keepConflicts:s,confirmedCommand:i})}finally{j()}}),{entries:g,selected:y,pushed:S,pushAborted:v,abortedBy:C,declined:_,verifyFailed:O,handOffs:P}=m,G=await Pt(d).catch(()=>[]);return BE({entries:g,selected:y,pushed:S,pushAborted:v,abortedBy:C,declined:_,verifyFailed:O,handOffs:P,dryRun:n,worktrees:G,skipped:l})},FE=async e=>{let{cwd:t,worktree:r,toPlan:n,candidates:o,skipped:s,all:i,versions:a,dryRun:c,verify:l,keepConflicts:d,confirmedCommand:u}=e,m=d?await $e(t,"origin/dev"):null,g=await Qm({cwd:t,worktreePath:r.path,branches:n}),y={entries:g,pushed:!1,pushAborted:!1,declined:!1};if(IE(g,s),c)return{...y,selected:n};let S=await NE({entries:g,toPlan:n,all:i,explicit:a!==void 0});S.length===o.length?h.addOption("--all",!0):h.addOption("--versions",S);let v=g.filter(P=>S.includes(P.branch)&&P.mergeSha).length;v>0&&p.info(`
379
- \u2139\uFE0F This will push ${v} branch(es), re-running CI on ${v} open PR(s). If the repo dismisses stale approvals on new commits, those PRs lose them.`);try{await W(u,`Are you sure you want to merge dev into these branches: ${S.join(", ")}?`,{throwOnDecline:!0,plan:LE(g,S,s)})}catch(P){if(!ct(P))throw P;return{...y,selected:S,declined:!0}}u||h.addOption("--yes",!0);let C=await _E({cwd:t,worktreePath:r.path,entries:g,selected:S,verify:l}),_=g.filter(P=>S.includes(P.branch)&&P.status==="conflict").map(P=>P.branch),O=d&&m&&_.length>0?await Rf({cwd:t,branches:_,devSha:m}):void 0;return{entries:g,selected:S,declined:!1,...C,handOffs:O}},LE=(e,t,r)=>({entries:e.filter(n=>t.includes(n.branch)).map(n=>({branch:n.branch,status:n.status,...n.conflictPaths?{conflictPaths:n.conflictPaths}:{},...n.status==="conflict"?{lockfileOnly:Vc(n.conflictPaths)}:{},...n.reason?{reason:n.reason}:{}})),skipped:r}),VE=(e,t)=>e.resolution?`# ${e.branch} \u2014 ${e.status}, left to resolve in ${e.resolution.worktreePath} (then --continue)
372
+ `,384),dl.rmSync(t,{force:!0});let s={filePath:o,variableCount:r.length,unsetStatements:n};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}},ul=S({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 \u2014 returns the path to a script that must be sourced ("source <filePath>") for the vars to go away. The infra-kit shell wrapper auto-sources; direct callers must handle sourcing themselves or surface filePath to the user. Errors if no env is currently loaded.',requiresHumanConfirm:!0,inputSchema:{confirm:fo.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{filePath:fo.string().describe("Path to the file that must be sourced to apply"),variableCount:fo.number().describe("Number of variables cleared"),unsetStatements:fo.array(fo.string()).describe("Unset statements generated")},handler:()=>Qs()});import BP from"node:path";import go from"node:process";import{z as on}from"zod";var ei=async()=>{u.info("Environment session status:");let e=yr(),t=go.env[gn],r=BP.join(e,gr),n=0,o=0,s=go.env[Uo]??null,i=go.env[Jo]??null,a=go.env[Go]??null;if(s){let l=Ko(r);l.length>0&&(o=l.length,n=l.filter(p=>p in go.env).length);let d=a?.replace(/\.\d{3}Z$/,"")??null;if(u.info(` ${s}: ${n} of ${o} vars loaded (project: ${i}, loadedAt: ${d}, session: ${t})
373
+ `),o>0&&n<o){let p=o-n;u.warn(` ${p} cached var(s) are not present in the current process \u2014 env-load needs to be re-sourced, or vars were unset manually.`)}}else u.info(` Session ${t}: no env loaded
374
+ `);let c={sessionId:t,sessionLoadedCount:n,sessionTotalCount:o,sessionConfig:s,sessionProject:i,sessionLoadedAt:a};return{content:k(JSON.stringify(c,null,2)),structuredContent:c}},pl=S({name:"env-status",description:"Report which Doppler project/config is currently loaded in the terminal session, when it was loaded, and how many variables are cached. 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. Over MCP this reflects the session file as of this call \u2014 the server re-reads it before every tool.",inputSchema:{},outputSchema:{sessionId:on.string().describe("Current terminal session ID"),sessionLoadedCount:on.number().describe("Number of cached vars active in the current session"),sessionTotalCount:on.number().describe("Total number of cached var names"),sessionConfig:on.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:on.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:on.string().nullable().describe("ISO 8601 timestamp of when the env was loaded")},handler:ei});import VP from"node:process";import{z as Ot}from"zod";var Eg="****",sn=e=>typeof e!="string"||e.length<8?Eg:`${Eg}${e.slice(-4)}`;var xg=(e,t,r)=>e.map(n=>{let o=r||t[n];return o?{env:n,source:r?`env:${Vt}`:"store",redactedToken:sn(o),present:!0}:{env:n,source:"-",redactedToken:"-",present:!1}}),WP=["ENV","SOURCE","TOKEN","PRESENT"],Tg=(e,t)=>{let r=[...WP,...t?["CHECK"]:[]],n=e.map(s=>[s.env,s.source,s.redactedToken,s.present?"yes":"no",...t?[s.status??"-"]:[]]),o=r.map((s,i)=>Math.max(s.length,...n.map(a=>(a[i]??"").length)));return[r,...n].map(s=>s.map((i,a)=>i.padEnd(o[a])).join(" ").trimEnd())},ti=async({check:e}={})=>{let t=await ds(),r=await Bt(),n=VP.env[Vt],o=xg(t,r?.envs??{},n);if(e){let a=await br();for(let c of o){if(!c.present)continue;let l=n||r.envs[c.env],d=await kp({childEnv:Pn(l),project:a,config:c.env});c.status=d.outcome}}for(let a of Tg(o,!!e))u.info(a);let s=o.filter(a=>!a.present);s.length>0&&u.info(`
375
+ No token for: ${s.map(a=>a.env).join(", ")}. Add one with \`infra-kit env-token-set <env>\`.`);let i={tokens:o};return{content:k(JSON.stringify(i,null,2)),structuredContent:i}},ml=S({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:Ot.boolean().optional().describe("Probe Doppler for each token\u2019s validity and scope (one cheap call per environment).")},outputSchema:{tokens:Ot.array(Ot.object({env:Ot.string().describe("Environment / Doppler config name"),source:Ot.string().describe('"store", "env:INFRA_KIT_ENV_TOKEN", or "-" when absent'),redactedToken:Ot.string().describe("Redacted token \u2014 last 4 chars at most, never the raw value"),present:Ot.boolean().describe("Whether a token is configured for this environment"),status:Ot.string().optional().describe("Only with check=true: valid | revoked | mis-scoped | unreachable")})).describe("One row per declared environment")},handler:ti});import{z as b}from"zod";import{$ as UP}from"zx";var JP=(e,t)=>({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0,dryRun:e,atomicPush:{attempted:!1,aborted:!1},results:[],skipped:t}),GP=e=>e.dualBase?"open PRs to both dev and main":e.titleMismatch?"title/base mismatch":e.type==="hotfix"?"hotfix (targets main)":null,KP=e=>{let t=new Map;for(let r of e)t.set(r.reason,(t.get(r.reason)??0)+1);return[...t].map(([r,n])=>`${r} \xD7${n}`).join(", ")},gl=e=>({content:k(JSON.stringify(e,null,2)),structuredContent:e}),fl=new Set(["up-to-date","fast-forward","merged"]),HP=(e,t,r)=>{let n=(Array.isArray(e)?e:e.split(",")).map(a=>a.trim()).filter(a=>a.length>0),o=new Set(t),s=new Map(r.map(a=>[a.branch,a.reason])),i=new Set;for(let a of n){let c;try{c=xe(ye(a))}catch(l){throw new f(l,{operation:`resolve release selector "${a}"`,remediation:`pass one of: ${t.join(", ")}`})}if(!o.has(c)){let l=s.get(c);throw new f(void 0,{operation:`select release branch for "${a}"`,stderrExcerpt:l?`${c} is skipped: ${l}`:`${c} is not an open regular release branch`,remediation:`pass one of: ${t.join(", ")}`})}i.add(c)}return t.filter(a=>i.has(a))},qP={"up-to-date":"already up to date","fast-forward":"fast-forward",merged:"clean merge",conflict:"CONFLICT","hook-failed":"HOOK FAILED",error:"ERROR","not-attempted":"not attempted"},$g=e=>{let t=qP[e.status];if(e.status==="conflict"){let r=e.conflictPaths?.length??0;return`${t}: ${r} file(s)`}return e.reason?`${t}: ${e.reason}`:t},YP=(e,t)=>{u.info(`
376
+ \u{1F4CB} Merge plan:`);for(let r of e)u.info(` ${r.branch} \u2014 ${$g(r)}`);for(let r of t)u.info(` ${r.branch} \u2014 skipped: ${r.reason}`)},zP=(e,t)=>{let r=t.find(n=>n.branch===e);return r?`git -C ${r.path} merge origin/dev`:`git switch ${e} && git merge origin/dev`},XP=async e=>{let{entries:t,toPlan:r,all:n,explicit:o}=e;if(o||n)return r;h.setInteractive();let s=new Map(t.flatMap(i=>{let a=J(i.branch);return a?[[te(a),$g(i)]]:[]}));return xt(oe({branches:r,descriptions:s}),{required:!0})},ZP=async e=>{let{cwd:t,worktreePath:r,entries:n,selected:o,verify:s}=e,i=n.filter(y=>o.includes(y.branch)),a=y=>{for(let R of y)u.info(`\u2139\uFE0F ${R} was merged by someone else while we planned \u2014 dropping it from the push`)},c=await zn(t,Km(i));a(c.nowUpToDate);let l=c.kept,d=new Map;if(s&&l.length>0){u.info(`
377
+ \u{1F50E} Verifying ${l.length} merge(s) with: ${s}`);let y=await qm({worktreePath:r,refs:l,command:s});d=y.failed;for(let[v,$]of y.failed)u.info(`\u2717 ${v} failed verification \u2014 not pushing it. ${$.split(`
378
+ `)[0]??""}`);let R=await zn(t,y.kept);a(R.nowUpToDate),l=R.kept}if(l.length===0)return{pushed:!1,pushAborted:!1,verifyFailed:d};u.info(`
379
+ \u2B06\uFE0F Pushing atomically: ${l.map(y=>y.branch).join(", ")}`);let p=await rs(t,l);if(p.pushed)return{pushed:!0,pushAborted:!1,verifyFailed:d};let g=(await Promise.all(l.map(async y=>({branch:y.branch,landed:await kr(t,y.branch)===y.sha})))).filter(y=>y.landed);return g.length>0&&u.warn(`\u26A0\uFE0F The push reported failure, but origin already carries ${g.map(y=>y.branch).join(", ")} \u2014 re-run to reconcile.`),{pushed:!1,pushAborted:!0,abortedBy:p.stderr?.split(`
380
+ `)[0],observedLanded:g.map(y=>y.branch)}},QP=e=>{let t=["keepConflicts","continue","abort"].filter(n=>e[n]),r={keepConflicts:"--keep-conflicts",continue:"--continue",abort:"--abort"};if(t.length>1||t.length===1&&e.dryRun){let n=[...t.map(o=>r[o]),...e.dryRun?["--dry-run"]:[]];throw new f(void 0,{operation:"choose the merge-dev mode",stderrExcerpt:`${n.join(" and ")} cannot be combined`,remediation:"pass at most one of --keep-conflicts, --continue, --abort; --dry-run only on a plain run"})}if(e.tree!==void 0&&!e.continue)throw new f(void 0,{operation:"choose the merge-dev mode",stderrExcerpt:"--tree belongs to --continue",remediation:"run the rerun a --continue preview printed, unchanged"})},Cg=e=>{let{results:t,atomicPush:r,declined:n}=e;for(let i of t){let a=i.reason?.split(`
381
+ `)[0];u.info(a?` ${i.branch} \u2014 ${i.status}: ${a}`:` ${i.branch} \u2014 ${i.status}`)}let o=n?[]:t.filter(i=>i.status!=="aborted"),s=o.filter(i=>!fl.has(i.status));return gl({successfulMerges:o.length-s.length,failedMerges:s.length,failedBranches:s.map(i=>i.branch),totalBranches:t.length,dryRun:!1,atomicPush:r,results:t,skipped:[]})},eE=async e=>{let{all:t,versions:r,verify:n,confirmedCommand:o}=e,s=await je();if(e.abort)return Cg(await wf({cwd:s,versions:r,all:t,confirmedCommand:o}));let i=typeof n=="string"&&n.length>0?n:void 0;return Cg(await yf({cwd:s,versions:r,all:t,verify:i,trees:vf(e.tree),confirmedCommand:o}))},ri=async e=>{let{all:t,versions:r,dryRun:n=!1,verify:o,keepConflicts:s=!1,confirmedCommand:i}=e;QP(e);let a=o===!0?Hm:o||void 0;if(await dc({operation:"merge dev into release branches"}),e.continue||e.abort)return eE(e);let c=[],l=[];for(let U of await F()){let ue=GP(U);ue?l.push({branch:U.branch,reason:ue}):c.push(U.branch)}if(c.length===0)return u.info(l.length===0?"\u2139\uFE0F No open release branches found":`\u2139\uFE0F No open regular release branches \u2014 ${l.length} skipped (${KP(l)})`),h.print(),gl(JP(n,l));let d=await je();try{await UP({cwd:d,quiet:!0})`git fetch origin --prune`}catch(U){throw new f(U,{operation:"fetch origin before planning the merges",remediation:"check network access and that `origin` is reachable"})}let p=r===void 0?c:HP(r,c,l),m=await zu({cwd:d},async U=>{let ue=Ds(U.remove);try{return await tE({cwd:d,worktree:U,toPlan:p,candidates:c,skipped:l,all:t,versions:r,dryRun:n,verify:a,keepConflicts:s,confirmedCommand:i})}finally{ue()}}),{entries:g,selected:y,pushed:R,pushAborted:v,abortedBy:$,declined:D,verifyFailed:A,handOffs:P}=m,q=await gt(d).catch(()=>[]);return oE({entries:g,selected:y,pushed:R,pushAborted:v,abortedBy:$,declined:D,verifyFailed:A,handOffs:P,dryRun:n,worktrees:q,skipped:l})},tE=async e=>{let{cwd:t,worktree:r,toPlan:n,candidates:o,skipped:s,all:i,versions:a,dryRun:c,verify:l,keepConflicts:d,confirmedCommand:p}=e,m=d?await Ce(t,"origin/dev"):null,g=await Gm({cwd:t,worktreePath:r.path,branches:n}),y={entries:g,pushed:!1,pushAborted:!1,declined:!1};if(YP(g,s),c)return{...y,selected:n};let R=await XP({entries:g,toPlan:n,all:i,explicit:a!==void 0});R.length===o.length?h.addOption("--all",!0):h.addOption("--versions",R);let v=g.filter(P=>R.includes(P.branch)&&P.mergeSha).length;v>0&&u.info(`
382
+ \u2139\uFE0F This will push ${v} branch(es), re-running CI on ${v} open PR(s). If the repo dismisses stale approvals on new commits, those PRs lose them.`);try{await B(p,`Are you sure you want to merge dev into these branches: ${R.join(", ")}?`,{throwOnDecline:!0,plan:rE(g,R,s)})}catch(P){if(!nt(P))throw P;return{...y,selected:R,declined:!0}}p||h.addOption("--yes",!0);let $=await ZP({cwd:t,worktreePath:r.path,entries:g,selected:R,verify:l}),D=g.filter(P=>R.includes(P.branch)&&P.status==="conflict").map(P=>P.branch),A=d&&m&&D.length>0?await ff({cwd:t,branches:D,devSha:m}):void 0;return{entries:g,selected:R,declined:!1,...$,handOffs:A}},rE=(e,t,r)=>({entries:e.filter(n=>t.includes(n.branch)).map(n=>({branch:n.branch,status:n.status,...n.conflictPaths?{conflictPaths:n.conflictPaths}:{},...n.status==="conflict"?{lockfileOnly:Ec(n.conflictPaths)}:{},...n.reason?{reason:n.reason}:{}})),skipped:r}),nE=(e,t)=>e.resolution?`# ${e.branch} \u2014 ${e.status}, left to resolve in ${e.resolution.worktreePath} (then --continue)
380
383
  `:`# ${e.branch} \u2014 ${e.status}
381
- ${DE(e.branch,t)}
382
- `,BE=e=>{let{entries:t,selected:r,pushed:n,pushAborted:o,abortedBy:s,declined:i,dryRun:a,worktrees:c,verifyFailed:l,handOffs:d,skipped:u}=e,m=new Set(n?t.filter(v=>r.includes(v.branch)&&v.mergeSha&&!l?.has(v.branch)).map(v=>v.branch):[]),g=t.filter(v=>r.includes(v.branch)).map(v=>{let C=!!v.mergeSha,_=e.verifyFailed?.get(v.branch),O=o&&C?"push-aborted":v.status,P=_?"verify-failed":O,G=d?.get(v.branch);return{branch:v.branch,status:P,mergeSha:v.mergeSha,conflictPaths:v.conflictPaths,pushed:m.has(v.branch),reason:_??G?.reason??v.reason,...G?.resolution?{resolution:G.resolution}:{}}}),y=g.filter(v=>!jl.has(v.status));for(let v of g){let C=t.find(_=>_.branch===v.branch);p.info({branch:v.branch,status:v.status,mergeSha:v.mergeSha,conflictCount:v.conflictPaths?.length??0,durationMs:C?.durationMs,pushed:v.pushed,msg:"merge-dev branch result"})}if(i||a)p.info(i?`
384
+ ${zP(e.branch,t)}
385
+ `,oE=e=>{let{entries:t,selected:r,pushed:n,pushAborted:o,abortedBy:s,declined:i,dryRun:a,worktrees:c,verifyFailed:l,handOffs:d,skipped:p}=e,m=new Set(n?t.filter(v=>r.includes(v.branch)&&v.mergeSha&&!l?.has(v.branch)).map(v=>v.branch):[]),g=t.filter(v=>r.includes(v.branch)).map(v=>{let $=!!v.mergeSha,D=e.verifyFailed?.get(v.branch),A=o&&$?"push-aborted":v.status,P=D?"verify-failed":A,q=d?.get(v.branch);return{branch:v.branch,status:P,mergeSha:v.mergeSha,conflictPaths:v.conflictPaths,pushed:m.has(v.branch),reason:D??q?.reason??v.reason,...q?.resolution?{resolution:q.resolution}:{}}}),y=g.filter(v=>!fl.has(v.status));for(let v of g){let $=t.find(D=>D.branch===v.branch);u.info({branch:v.branch,status:v.status,mergeSha:v.mergeSha,conflictCount:v.conflictPaths?.length??0,durationMs:$?.durationMs,pushed:v.pushed,msg:"merge-dev branch result"})}if(i||a)u.info(i?`
383
386
  Operation cancelled \u2014 nothing was pushed.
384
387
  `:`
385
388
  \u{1F50D} Dry run \u2014 nothing was pushed.
386
- `);else if(y.length>0){p.info(`
389
+ `);else if(y.length>0){u.info(`
387
390
  \u26A0\uFE0F ${y.length} branch(es) did not merge.
388
- `);for(let v of y)p.info(VE(v,c))}else p.info(`\u2705 All merges completed successfully!
389
- `);h.print();let S=a||i;return Fl({successfulMerges:S?0:g.filter(v=>jl.has(v.status)).length,failedMerges:S?0:y.length,failedBranches:S?[]:y.map(v=>v.branch),totalBranches:g.length,dryRun:a,atomicPush:{attempted:!a&&!i,aborted:o,abortedBy:s},results:g.map(v=>S?{...v,pushed:!1}:v),skipped:u})},Ll=R({name:"gh-merge-dev",description:"Merge origin/dev into open regular release branches and push them in one atomic push. A release PR is classified by its base branch, not its title: a PR to main is a hotfix and is skipped, as is any row whose title disagrees with its base or whose head has open PRs to both dev and main \u2014 every skipped row is reported in `skipped` with its reason. Merges happen in a disposable scratch worktree, so no existing checkout is touched and the branches may be checked out elsewhere. When invoked via MCP, pass all=true or an explicit versions list \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.",requiresHumanConfirm:!0,inputSchema:{all:b.boolean().optional().describe("Target every open regular release branch. Must be true for MCP calls unless `versions` is supplied (the interactive picker is unavailable without a TTY)."),versions:b.union([b.string(),b.array(b.string())]).optional().describe('Target a subset of the open regular release branches. Each entry may be a version label ("1.2.5") or a raw branch name ("release/v1.2.5"). A selector that is not an open regular release is an error; one that names a skipped row (hotfix, title/base mismatch, dual-base) quotes that reason. Takes precedence over `all`.'),dryRun:b.boolean().optional().describe("Compute and print the merge plan without pushing anything."),verify:b.union([b.boolean(),b.string()]).optional().describe("Check each merge before pushing it. `true` runs `pnpm install --frozen-lockfile` \u2014 which catches the characteristic dev\u2192release failure, a pnpm-lock.yaml whose text merge is clean but whose result is broken. A string runs that command instead. A branch that fails verification is dropped from the push; nothing is ever rolled back, because verification runs pre-push. Under `continue`, a string runs after the mandatory `pnpm install --frozen-lockfile --ignore-scripts`."),keepConflicts:b.boolean().optional().describe("On the confirmed run, after the clean branches are pushed, leave each conflicted branch mid-merge in a detached worktree under `<root>-worktrees/merge-dev/` for resolution. Excludes `continue`, `abort` and `dryRun`."),continue:b.boolean().optional().describe("Check the selected resolutions (only conflicted paths edited, no markers, install passes), preview them, and on confirmation commit exactly the previewed tree and push atomically. Excludes `keepConflicts`, `abort` and `dryRun`."),abort:b.boolean().optional().describe("Discard the selected resolution worktrees and their state. Excludes `keepConflicts`, `continue` and `dryRun`."),tree:b.union([b.string(),b.array(b.string())]).optional().describe("With `continue` and confirmation: `<branch>=<treeSha>`, comma-separated or repeated \u2014 the trees the human approved in the `continue` preview. Pass the preview `rerun` unchanged; a branch whose resolved tree differs is reported `tree-changed` and not committed."),confirm:b.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{successfulMerges:b.number().describe("Number of branches that reached their desired state"),failedMerges:b.number().describe("Number of branches that did not"),failedBranches:b.array(b.string()).describe("List of branches that did not merge"),totalBranches:b.number().describe("Total number of branches processed"),dryRun:b.boolean().describe("True when nothing was pushed because this was a plan-only run"),atomicPush:b.object({attempted:b.boolean(),aborted:b.boolean(),abortedBy:b.string().optional()}).describe("Outcome of the single all-or-nothing push"),results:b.array(b.object({branch:b.string(),status:b.string(),mergeSha:b.string().optional(),conflictPaths:b.array(b.string()).optional(),pushed:b.boolean(),reason:b.string().optional(),resolution:b.object({worktreePath:b.string(),baseSha:b.string(),devSha:b.string(),conflictPaths:b.array(b.string()),lockfileOnly:b.boolean(),rererePreResolved:b.array(b.string()),state:b.enum(["needs-agent","lockfile-only","exists"])}).optional().describe("The `keepConflicts` hand-off for a conflicted branch"),blocked:b.object({code:b.enum(["unmerged-paths","markers-remaining","out-of-scope-edit","verify-failed","verify-mutated-tree","parents-mismatch","git-too-old","tree-changed"]),paths:b.array(b.string()).optional(),detail:b.string()}).optional().describe("Why a `continue` run did not commit this resolution")})).describe("Per-branch terminal state"),skipped:b.array(b.object({branch:b.string(),reason:b.enum(["hotfix (targets main)","title/base mismatch","open PRs to both dev and main"])})).describe("Every discovered release PR that was not a merge candidate, with why. Empty only when nothing was discovered.")},handler:ki});import{z as Io}from"zod";import{$ as _e}from"zx";var Zg=(e,t)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-t).trim()},Wt=e=>{if(e===null||typeof e!="object")return{message:String(e)};let t=e,r={};e instanceof Error?(r.name=e.name,r.message=e.message):typeof t.message=="string"&&(r.message=t.message);let n=t.exitCode;(typeof n=="number"||n===null)&&(r.exitCode=n);let o=Zg(t.stderr,500);o&&(r.stderr=o);let s=Zg(t.stdout,200);return s&&(r.stdout=s),r};var $o=e=>{let{removed:t,failed:r}=e;if(t.length>0){p.info("\u274C Removed worktrees:");for(let n of t)p.info(n);p.info("")}if(r.length>0){p.warn("\u26A0\uFE0F Not removed:");for(let{branch:n,reason:o}of r)p.warn(`${n} \u2014 ${o}`);p.warn("")}t.length===0&&r.length===0&&p.info("\u2139\uFE0F No worktrees to remove")};var Ao=e=>{let{result:t,operation:r}=e,n={removedWorktrees:t.removed,failedWorktrees:t.failed.map(i=>i.branch),count:t.removed.length},o=k(JSON.stringify(n,null,2));if(t.failed.length===0)return{content:o,structuredContent:n};let s={operation:r,remediation:`not removed: ${n.failedWorktrees.join(", ")} \u2014 fix the cause above and re-run`,stderrExcerpt:t.failed.map(i=>`${i.branch}: ${i.reason}`).join("; ")};throw ee()?new E({status:"partial_failure",...n},1,s):new f(void 0,s)};import Ri from"node:fs/promises";import{$ as rh}from"zx";var WE=new Set([".omc",".DS_Store"]),JE=new Set(["state","sessions"]),UE=2e3,GE="check 'git worktree list' for the path; uncommitted changes block removal",KE=e=>new Promise(t=>{setTimeout(t,e)}),Vl=e=>typeof e=="object"&&e!==null?e.code:void 0,Qg=e=>{let t=e.length;for(;t>1&&e[t-1]==="/";)t-=1;return e.slice(0,t)},eh=async e=>{try{return Qg(await Ri.realpath(e))}catch{return Qg(e)}},HE=async e=>{let{projectRoot:t,worktreePath:r}=e;try{let n=await Pt(t),o=await eh(r);for(let s of n)if(await eh(s.path)===o)return!0;return!1}catch{return!0}},qE=async e=>{let t;try{t=await Ri.readdir(e)}catch(n){return{kind:Vl(n)==="ENOENT"?"gone":"not-sweepable",entries:[]}}if(!t.every(n=>WE.has(n)))return{kind:"not-sweepable",entries:t};if(!t.includes(".omc"))return{kind:"sweepable",entries:t};try{return{kind:(await Ri.readdir(`${e}/.omc`)).every(s=>JE.has(s))?"sweepable":"not-sweepable",entries:t}}catch(n){return{kind:Vl(n)==="ENOENT"?"sweepable":"not-sweepable",entries:t}}},th=async e=>{try{return await Ri.rm(e,{recursive:!0,force:!0}),"removed"}catch(t){return Vl(t)==="ENOTEMPTY"?"busy":"failed"}},zE=async e=>{let{worktreePath:t,sleep:r}=e,n=await th(t);return n!=="busy"?n==="removed":(await r(UE),await th(t)==="removed")},bi=(e,t,r)=>{let n=new f(t,{operation:`remove worktree for ${e}`,remediation:r});return p.error({error:t,branch:e,msg:n.message}),{branch:e,status:"failed",reason:n.message}},YE=async e=>{let{branch:t,worktreePath:r,projectRoot:n,error:o,sleep:s}=e;if(await HE({projectRoot:n,worktreePath:r}))return bi(t,o,GE);let i=await qE(r);if(i.kind==="gone")return{branch:t,status:"removed"};let a=`git already unregistered this worktree; inspect and remove it manually: rm -r ${r}`;return i.kind==="not-sweepable"||!await zE({worktreePath:r,sleep:s})?bi(t,o,a):(p.warn(`\u26A0\uFE0F swept leftover ${i.entries.join(", ")} from ${r}: a post-exit hook (e.g. oh-my-claudecode SessionEnd) wrote into the worktree while git was deleting it; set OMC_STATE_DIR to keep tool state out of worktrees`),{branch:t,status:"removed"})},XE=async e=>{let{branch:t,worktreeDir:r,projectRoot:n,orcaProbe:o,sleep:s}=e,i=`${r}/${t}`,a=await Lu(i,o);if(!a.closed&&"error"in a)return bi(t,a.error,"close the Orca terminals of this worktree manually (orca terminal close --terminal <handle>) and re-run");try{return await rh`git worktree remove ${i}`,{branch:t,status:"removed"}}catch(c){return YE({branch:t,worktreePath:i,projectRoot:n,error:c,sleep:s})}},yr=async e=>{let{branches:t,worktreeDir:r,projectRoot:n,pruneFolder:o=!1,sleep:s=KE}=e,i=t.length>0?await Ir():"unreachable",a=await Promise.all(t.map(l=>XE({branch:l,worktreeDir:r,projectRoot:n,orcaProbe:i,sleep:s}))),c={removed:[],failed:[]};for(let l of a)l.status==="removed"?c.removed.push(l.branch):c.failed.push({branch:l.branch,reason:l.reason});return o&&c.removed.length===t.length&&await rh`git worktree prune`,c};var Oo=async(e,t)=>{if(!(await Ce("release")).includes(e))return[];let n=await x(),o=`${n}${ge}`,{removed:s,failed:i}=await yr({branches:[e],worktreeDir:o,projectRoot:n});if(!s.includes(e)){let a=i.find(c=>c.branch===e);throw new f(void 0,{...t,stderrExcerpt:a?.reason})}return s};var Pn=async(e,t,r)=>{try{return await r()}catch(n){throw p.debug({err:Wt(n)},`Failed to ${e}`),new f(n,{operation:e,remediation:t})}},ZE=async e=>{let t=ka(e),r=await _e`gh pr list --head dev --base main --state merged --json number,state,title,baseRefName,headRefName --limit 20`;return JSON.parse(r.stdout).find(s=>s.title===t)??null},nh=async()=>{let e=await _e`gh pr list --head dev --base main --state open --json number,state,title,baseRefName,headRefName --limit 5`;return JSON.parse(e.stdout)[0]??null},QE=async e=>{let t=ft(e),r=await Cc(t);if(r.length>1){let s=r.map(i=>`#${i.number} \u2192 ${i.baseRefName}`).join(", ");throw new f(void 0,{operation:`deliver release ${t}`,remediation:`the branch has open PRs to both dev and main (${s}); close the one that should not be delivered`})}let n=r[0]??await Gr(t);if(!n)throw p.error(`\u274C No PR found for branch ${t}.`),new f(void 0,{operation:`deliver release ${t}`,remediation:`confirm a PR exists ('gh pr list --head ${t} --state all')`});let o=to(n.baseRefName);if(!o)throw new f(void 0,{operation:`deliver release ${t}`,remediation:`PR #${n.number} targets '${n.baseRefName}', which is neither dev nor main; retarget it ('gh pr edit ${n.number} --base <dev|main>')`});return{selectedReleaseBranch:t,releaseType:o,prNumber:n.number}},ex=async()=>{let e=await F(),t=e.map(i=>i.branch),r=new Map(e.map(i=>[i.branch,i.type]));h.setInteractive();let n=await oe(),o=await Dt(se({branches:t,descriptions:n,types:r})),s=e.find(i=>i.branch===o);if(!s)throw p.error(`\u274C Release branch ${o} not found in open PRs.`),new f(void 0,{operation:`deliver release ${o}`,remediation:`confirm an open PR exists for ${o} ('gh pr list')`});if(s.dualBase)throw new f(void 0,{operation:`deliver release ${o}`,remediation:"the branch has open PRs to both dev and main; close the one that should not be delivered"});return{selectedReleaseBranch:o,releaseType:s.type,prNumber:s.number}},tx=async e=>{let{selectedReleaseBranch:t,releaseType:r,prNumber:n}=e,o=Qe(r),s=await $c(n);if(s.state==="MERGED"){p.info(`\u2713 Release PR ${t} already merged \u2014 skipping`);return}if(s.state==="CLOSED")throw new f(void 0,{operation:`merge release PR ${t} into ${o}`,remediation:"the PR is closed without merge; reopen it or create a new release"});if(s.baseRefName!==o||s.headRefName!==t)throw new f(void 0,{operation:`merge release PR #${n} ${t} into ${o}`,remediation:`PR #${n} now reads ${s.headRefName} \u2192 ${s.baseRefName}; it changed since it was resolved \u2014 re-run the command`});await Pn(`merge release PR #${n} ${t} into ${o}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await _e`gh pr merge ${n} --squash --admin --delete-branch`})},rx=async e=>{let t=Y(e),r=ka(e),n=await nh();if(n){let s=n.number;return n.title!==r&&(p.info(`Adopting open dev \u2192 main PR #${s} ("${n.title}") and retitling for ${t}`),await Pn(`retitle dev \u2192 main PR #${s} to "${r}"`,`update manually: gh pr edit ${s} --title "${r}"`,async()=>{await _e`gh pr edit ${s} --title ${r}`})),s}await Pn(`create RC PR (dev \u2192 main) for ${t}`,"run 'gh pr create --base main --head dev' manually to surface the underlying error (e.g. no commits between dev and main)",async()=>{await _e`gh pr create --base main --head dev --title ${r} --body ""`});let o=await nh();if(!o)throw new f(void 0,{operation:`look up RC PR for ${t}`,remediation:"verify the RC PR was created ('gh pr list --head dev --base main')"});return o.number},nx=async e=>{let t=Y(e);if(await ZE(e)){p.info(`\u2713 RC PR for ${t} already merged into main \u2014 skipping`);return}let n=await rx(e);await Pn(`merge RC PR #${n} (dev \u2192 main) for ${t}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await _e`gh pr merge ${n} --squash --admin`})},ox=async()=>{_e.quiet=!1,await Pn("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await _e`gh workflow run deploy-all.yml --ref main -f environment=prod`}),_e.quiet=!0},sx=async()=>{await Pn("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 _e`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},ix=async e=>{try{await ms(e)}catch(t){p.warn({err:Wt(t)},`Failed to delete local branch ${e} (non-blocking)`)}try{await fs(e)}catch(t){p.warn({err:Wt(t)},`Failed to delete remote branch ${e} (non-blocking)`)}},ax=async e=>{let t=await mt();if(!t){p.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let r=ne(e);await Oc({versionName:r},t)}catch(r){let n=no(r)&&r.kind==="auth"?" \u2014 reissue the Atlassian API token and update JIRA_TOKEN":"";p.error({err:Wt(r)},`Failed to deliver Jira release (non-blocking)${n}`)}},Si=async e=>{let{version:t,confirmedCommand:r}=e;await be({operation:"deliver release"});let{selectedReleaseBranch:n,releaseType:o,prNumber:s}=t?await QE(t):await ex(),i=K(n);if(!i)throw new f(void 0,{operation:`deliver release ${n}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let a=Y(i);if(h.addOption("--version",a),p.info(`Delivering ${i.kind==="name"?"named release":"version"} ${n}`),ee())throw new E({status:"refused",agentMode:A.source},2,{operation:`deliver release ${n}`,remediation:"ask a human to run `infra-kit release deliver` from their own shell \u2014 delivery is never confirmed by an agent",stderrExcerpt:"release deliver is CLI-only: refused in agent mode regardless of --yes"});await W(r,`Are you sure you want to deliver version ${n} to production?`),h.addOption("--yes",!0),_e.quiet=!0;let l=`${await x()}${ge}`;await Oo(n,{operation:`remove worktree for ${n} before merge`,remediation:`run manually: git worktree remove ${l}/${n} (use --force if uncommitted changes)`}),await tx({selectedReleaseBranch:n,releaseType:o,prNumber:s}),o!=="hotfix"&&await nx(i),await ox(),await sx(),await ix(n),_e.quiet=!1,await ax(i),p.info(`Successfully delivered ${n} to production!`),h.print();let d={releaseBranch:n,version:a,type:o,success:!0};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}},Bl=R({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).',requiresHumanConfirm:!0,inputSchema:{version:Io.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:Io.string().describe("The release branch that was delivered"),version:Io.string().describe("The version that was delivered"),type:Io.enum(["regular","hotfix"]).describe("Release type"),success:Io.boolean().describe("Whether the delivery was successful")},handler:Si});import{z as vt}from"zod";import{$ as Xl}from"zx";import{z as _o}from"zod";import oh from"node:fs/promises";import Wl from"node:path";var sh=".github/workflows",cx=/script_name:\s*(?<service>[a-z0-9-]+)/,lx=/uses:\s*\.\/\.github\/workflows\/_deploy-(?<service>[a-z0-9-]+)-jobs\.ya?ml/,dx=/inputs\.environment\s*==\s*'(?<env>[a-z0-9-]+)'/g,Jl=async e=>{let t=Wl.resolve(e,sh),r;try{r=await oh.readdir(t)}catch{return new Map}return ih(t,r.filter(n=>n.endsWith(".yml")||n.endsWith(".yaml")))},Do=async(e,t)=>ih(Wl.resolve(e,sh),[t]),ih=async(e,t)=>{let r=new Map;for(let n of t){let o;try{o=await oh.readFile(Wl.resolve(e,n),"utf-8")}catch{continue}px(o,r)}return r},px=(e,t)=>{for(let r of e.split(/\n(?= {2}[\w-]+:)/i)){let n=cx.exec(r)?.groups?.service??lx.exec(r)?.groups?.service;if(n===void 0||r.trimStart().startsWith("#"))continue;let o=[...r.matchAll(dx)].map(s=>s.groups?.env??"");o.length!==0&&t.set(n,[...new Set([...t.get(n)??[],...o])])}},Ul=(e,t)=>e===null?t??null:t===void 0?e:e.filter(r=>t.includes(r));import ux from"node:fs/promises";import mx from"node:path";import fx from"yaml";var gx=".github/workflows",hx="skip_terraform_deploy",No=async(e,t)=>{let r=mx.resolve(e,gx,t),n;try{n=fx.parse(await ux.readFile(r,"utf-8"))}catch{return[]}let s=n?.on?.workflow_dispatch?.inputs;return typeof s!="object"||s===null?[]:Object.entries(s).filter(([i,a])=>a?.type==="boolean"&&i!==hx).map(([i])=>i)};var ah="dev",Gl=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ch=(e,t)=>e[t]===void 0,lh=(e,t)=>{let r=e[t];return typeof r=="string"&&r.length>0?r:void 0},Kl=async e=>{try{return await e}catch{return[]}},yx=async()=>{let e=await F();return nr(e.map(t=>t.branch))},vx=(e,t)=>{let r=e.filter(o=>t.get(o)!==void 0);if(r.length===0)return"none declared.";let n=r.map(o=>`${o}: ${(t.get(o)??[]).join(", ")} only.`).join(" ");return r.length<e.length?`${n} Others: any environment.`:n},vr=e=>{let{workflowFile:t,fields:r,toolName:n}=e,o=c=>(p.info({msg:`Tool execution form options empty (${t}): ${n}`,emptyList:c}),null),s=async c=>{let l=await Kl(yx());if(l.length===0)return null;let d=lh(c,"version");return _o.enum([...new Set([...l,ah])]).optional().describe(`Which release to deploy from. "${ah}" deploys from the dev branch instead of a release branch. ${d===void 0?"Leaving it blank sends no version, and the tool will refuse rather than guess one.":`Leave it blank to keep the caller's "${d}".`}`)},i=async c=>{let l=gt(await Kl(ht(t)),await Je());if(l.length===0)return null;let d=l.filter(un),u=l.filter(g=>!un(g)),m=lh(c,"env");return _o.enum(l).optional().describe(`Target environment. Shared with the whole team: ${d.length>0?d.join(", "):"none"}. Personal accounts: ${u.length>0?u.join(", "):"none"}. This list is read from .github/workflows/${t} in the WORKING TREE, not from the branch being deployed or from GitHub. ${m===void 0?"Leaving it blank sends no environment at all.":`Leave it blank to keep the caller's "${m}" \u2014 including when this tree does not declare it.`}`)},a=async()=>{let c=await x(),l=await Kl(No(c,t));if(l.length===0)return null;let d=await Do(c,t);return _o.array(_o.enum(l)).optional().describe(`Services to deploy. Environment gates declared by ${t} \u2014 ${vx(l,d)} A service the chosen environment gates out is REFUSED before dispatch, not skipped in silence. Selecting none discards the form and falls back to the caller's arguments.`)};return{message:`Choose the arguments for ${n}. Anything left blank keeps what the caller sent.`,isFormable:c=>Gl(c)?r.some(l=>ch(c,l)):!1,buildRequestedSchema:async c=>{let l=Gl(c)?c:{},d={};if(r.includes("version")){let u=await s(l);if(u===null)return o("releases");d.version=u}if(r.includes("env")){let u=await i(l);if(u===null)return o("envs");d.env=u}if(r.includes("services")&&ch(l,"services")){let u=await a();if(u===null)return o("services");d.services=u}return Object.keys(d).length===0?o("fields"):_o.object(d)},toArgs:(c,l)=>{let d={...Gl(l)?l:{}};for(let u of r){let m=c[u];if(m!==void 0){if(u==="services"&&(!Array.isArray(m)||m.length===0))return null;d[u]=m}}return d}}};import wx from"@inquirer/select";var En=async(e,t)=>{if(e.length===0)throw new f(void 0,{operation:t,remediation:"pass --env <name> explicitly",stderrExcerpt:"the workflow declares no `environment` choices to pick from"});return I(r=>wx({message:"\u{1F9EA} Select environment",choices:e.map(n=>({name:n,value:n}))},r),{whenHeadless:"refuse"})};import kx from"@inquirer/confirm";var Mo=async e=>{let{confirmedCommand:t,branch:r,env:n}=e;if(t)return!0;let o=`Deploy ${r} \u2192 ${n} via GitHub Actions?`;ie()&&ws(o,{branch:r,env:n}),h.setInteractive();let s=await I(i=>kx({message:o,default:!1},i),{whenHeadless:"refuse"});return s&&h.addOption("--yes",!0),s};import bx from"@inquirer/select";import Rx from"node:process";var Hl=()=>!ie()&&Rx.stdin.isTTY===!0,Sx={ci:"Dispatch the GitHub workflow for a release ref",local:"Run devops/scripts/deploy-*.sh here, against your current checkout"},ql=async()=>I(e=>bx({message:"\u{1F680} Where should this deploy run?",choices:Jt.filter(t=>t!=="local").map(t=>({name:t,value:t,description:Sx[t]}))},e),{whenHeadless:"refuse"});var Jt=["ci","local"],Px={ci:["--version","--skip-terraform"],local:["--dry-run","--print-env"]},dh=e=>{if(!e){let r={operation:"resolve the deploy source",remediation:`pass --from with one of: ${Jt.join(", ")}`,stderrExcerpt:"--from is required \u2014 it decides whether this deploy runs in CI or on this machine"};throw ie()?new E({status:"argument_required",argument:"from",agentMode:A.source},2,r):new f(void 0,r)}let t=Jt.find(r=>r===e);if(!t)throw new f(void 0,{operation:"resolve the deploy source",remediation:`use one of: ${Jt.join(", ")}`,stderrExcerpt:`unknown --from value "${e}"`});return t},zl=(e,t)=>{let n=Px[e==="ci"?"local":"ci"].filter(o=>{let s=t[o];return s!==void 0&&s!==!1});if(n.length!==0)throw new f(void 0,{operation:`deploy --from ${e}`,remediation:e==="ci"?"drop the flag, or use --from local to deploy from this machine":"drop the flag, or use --from ci to dispatch the release workflow",stderrExcerpt:`${n.join(", ")} ${n.length===1?"is":"are"} not valid with --from ${e}`})},Yl=async e=>e||!Hl()?dh(e):ql();var jo=async e=>{if(e)return e==="dev"?"dev":ft(e);h.setInteractive();let t=await F(),r=t.map(s=>s.branch),n=new Map(t.map(s=>[s.branch,s.type])),o=await oe();return Dt([{value:"dev",label:"dev"},...se({branches:r,descriptions:o,types:n})])};var ph="deploy-all.yml",uh=vr({workflowFile:ph,fields:["version","env"],toolName:"gh-release-deploy-all"}),Pi=async e=>{let{version:t,env:r,skipTerraform:n,confirmedCommand:o}=e;await Ne({provider:uh,params:e,operation:"launch deploy-all workflow",argument:u=>u[0]??"version"});let s=await jo(t),i=io(s);h.addOption("--version",i);let a=await Je(),c=gt(await ht(ph),a),l="";r?l=r:(h.setInteractive(),l=await En(c,"launch deploy-all workflow")),h.addOption("--env",l),dr(l,"launch deploy-all workflow",a),wo({env:l,branch:s});let d=n??!1;if(d&&h.addOption("--skip-terraform",!0),!await Mo({confirmedCommand:o,branch:s,env:l})){p.info("Deployment cancelled");let u={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:d,success:!1};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}}try{Xl.quiet=!0,await Xl`gh workflow run deploy-all.yml --ref ${s} -f environment=${l} ${d?["-f","skip_terraform_deploy=true"]:[]}`,Xl.quiet=!1,p.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${s} and environment: ${l}`),h.print();let m={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:d,success:!0};return{content:k(JSON.stringify(m,null,2)),structuredContent:m}}catch(u){throw p.error({error:u},"\u274C Error launching workflow"),new f(u,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},Zl=R({name:"gh-release-deploy-all",formProvider:uh,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. Omit "version" or "env" and this server offers the human a form listing the real releases and the environments this workflow declares; a client that cannot render one gets a refusal naming the missing field, never a guess.',requiresHumanConfirm:!0,inputSchema:{version:vt.string().optional().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. Omit it to be offered the open releases.'),env:vt.string().optional().describe('Target environment name \u2014 must match an env this project may reach (e.g. "dev", "renana", "oriana"). Omit it to be offered the environments deploy-all.yml declares.'),skipTerraform:vt.boolean().optional().describe("Skip the terraform deployment stage."),confirm:vt.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:vt.string().describe("The release branch that was deployed"),version:vt.string().describe("The version that was deployed"),environment:vt.string().describe("The environment deployed to"),skipTerraformDeploy:vt.boolean().describe("Whether terraform deployment was skipped"),success:vt.boolean().describe("Whether the deployment was successful")},handler:Pi});import Ex from"@inquirer/checkbox";import{z as Se}from"zod";import{$ as Ql}from"zx";var wr="deploy-selected-services.yml",mh=vr({workflowFile:wr,fields:["version","env","services"],toolName:"gh-release-deploy-selected"}),Ei=async e=>{let{version:t,env:r,services:n,skipTerraform:o,confirmedCommand:s}=e;await Ne({provider:mh,params:e,operation:"launch deploy-selected workflow",argument:O=>O[0]??"version"});let i=await jo(t),a=io(i);h.addOption("--version",a);let c=await Je(),l=gt(await ht(wr),c),d="";r?d=r:(h.setInteractive(),d=await En(l,"launch deploy-selected workflow")),h.addOption("--env",d),dr(d,"launch deploy-selected workflow",c),wo({env:d,branch:i});let u=await x(),m=await No(u,wr);if(m.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${wr}`,stderrExcerpt:`no services found in .github/workflows/${wr}`});let g=[];if(n&&n.length>0?g=n:(h.setInteractive(),g=await I(O=>Ex({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:m.map(P=>({name:P,value:P}))},O),{whenHeadless:"refuse"})),h.addOption("--services",g),g.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${m.join(", ")}`,stderrExcerpt:"no services selected"});let y=g.filter(O=>!m.includes(O));if(y.length>0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${m.join(", ")}`,stderrExcerpt:`invalid services: ${y.join(", ")}`});let S=await Do(u,wr),v=g.filter(O=>{let P=S.get(O);return P!==void 0&&!P.includes(d)});if(v.length>0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:v.map(O=>`${O} deploys only to: ${(S.get(O)??[]).join(", ")}`).join("; "),stderrExcerpt:`${wr} gates these services out of ${d}: ${v.join(", ")}`});let C=o??!1;C&&h.addOption("--skip-terraform",!0);let _=O=>{let P={releaseBranch:i,version:a,environment:d,services:g,skipTerraformDeploy:C,success:O};return{content:k(JSON.stringify(P,null,2)),structuredContent:P}};if(!await Mo({confirmedCommand:s,branch:i,env:d}))return p.info("Deployment cancelled"),_(!1);try{Ql.quiet=!0;let O=g.flatMap(G=>["-f",`${G}=true`]);return await Ql`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${d} ${O} ${C?["-f","skip_terraform_deploy=true"]:[]}`,Ql.quiet=!1,p.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${d}, services: ${g.join(", ")}`),h.print(),_(!0)}catch(O){throw p.error({error:O},"\u274C Error launching workflow"),new f(O,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},ed=R({name:"gh-release-deploy-selected",requiresHumanConfirm:!0,formProvider:mh,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, and a service the target environment gates out is refused BEFORE dispatch rather than dispatched and silently skipped. Use gh-release-deploy-all for every service. Omit any of "version", "env" or "services" and this server offers the human a form built from the real releases, environments and services; a client that cannot render one gets a refusal naming the missing field, never a guess.',inputSchema:{version:Se.string().optional().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. Omit it to be offered the open releases.'),env:Se.string().optional().describe('Target environment name \u2014 must match an env this project may reach (e.g. "dev", "renana", "oriana"). Omit it to be offered the environments deploy-selected-services.yml declares.'),services:Se.array(Se.string()).optional().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"). Some services are gated to particular environments by that workflow and are refused here rather than skipped by CI. Omit it to be offered the declared services.'),skipTerraform:Se.boolean().optional().describe("Skip the terraform deployment stage."),confirm:Se.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},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"),services:Se.array(Se.string()).describe("The services that were deployed"),skipTerraformDeploy:Se.boolean().describe("Whether terraform deployment was skipped"),success:Se.boolean().describe("Whether the deployment was successful")},handler:Ei});import{z as Ut}from"zod";var xi=async()=>{let t=(await F()).flatMap(i=>{let a=K(i.branch);return a?[{version:Y(a),jiraKey:ne(a),type:i.type,titleMismatch:i.titleMismatch}]:[]}),r=await Ws(),n=Math.max(...t.map(i=>i.version.length)),o=t.map(i=>{let a=so(i.version,i.type,n),c=r.get(i.jiraKey),l=c?.description?` ${c.description}`:"",d=c?.releaseDate?` \xB7 ships ${c.releaseDate}`:"",u=i.titleMismatch?" \u26A0 title/base mismatch":"";return`${a}${l}${d}${u}`});p.info(`All release branches:
390
- `),p.info(`
391
+ `);for(let v of y)u.info(nE(v,c))}else u.info(`\u2705 All merges completed successfully!
392
+ `);h.print();let R=a||i;return gl({successfulMerges:R?0:g.filter(v=>fl.has(v.status)).length,failedMerges:R?0:y.length,failedBranches:R?[]:y.map(v=>v.branch),totalBranches:g.length,dryRun:a,atomicPush:{attempted:!a&&!i,aborted:o,abortedBy:s},results:g.map(v=>R?{...v,pushed:!1}:v),skipped:p})},hl=S({name:"gh-merge-dev",description:"Merge origin/dev into open regular release branches and push them in one atomic push. A release PR is classified by its base branch, not its title: a PR to main is a hotfix and is skipped, as is any row whose title disagrees with its base or whose head has open PRs to both dev and main \u2014 every skipped row is reported in `skipped` with its reason. Merges happen in a disposable scratch worktree, so no existing checkout is touched and the branches may be checked out elsewhere. When invoked via MCP, pass all=true or an explicit versions list \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.",requiresHumanConfirm:!0,inputSchema:{all:b.boolean().optional().describe("Target every open regular release branch. Must be true for MCP calls unless `versions` is supplied (the interactive picker is unavailable without a TTY)."),versions:b.union([b.string(),b.array(b.string())]).optional().describe('Target a subset of the open regular release branches. Each entry may be a version label ("1.2.5") or a raw branch name ("release/v1.2.5"). A selector that is not an open regular release is an error; one that names a skipped row (hotfix, title/base mismatch, dual-base) quotes that reason. Takes precedence over `all`.'),dryRun:b.boolean().optional().describe("Compute and print the merge plan without pushing anything."),verify:b.union([b.boolean(),b.string()]).optional().describe("Check each merge before pushing it. `true` runs `pnpm install --frozen-lockfile` \u2014 which catches the characteristic dev\u2192release failure, a pnpm-lock.yaml whose text merge is clean but whose result is broken. A string runs that command instead. A branch that fails verification is dropped from the push; nothing is ever rolled back, because verification runs pre-push. Under `continue`, a string runs after the mandatory `pnpm install --frozen-lockfile --ignore-scripts`."),keepConflicts:b.boolean().optional().describe("On the confirmed run, after the clean branches are pushed, leave each conflicted branch mid-merge in a detached worktree under `<root>-worktrees/merge-dev/` for resolution. Excludes `continue`, `abort` and `dryRun`."),continue:b.boolean().optional().describe("Check the selected resolutions (only conflicted paths edited, no markers, install passes), preview them, and on confirmation commit exactly the previewed tree and push atomically. Excludes `keepConflicts`, `abort` and `dryRun`."),abort:b.boolean().optional().describe("Discard the selected resolution worktrees and their state. Excludes `keepConflicts`, `continue` and `dryRun`."),tree:b.union([b.string(),b.array(b.string())]).optional().describe("With `continue` and confirmation: `<branch>=<treeSha>`, comma-separated or repeated \u2014 the trees the human approved in the `continue` preview. Pass the preview `rerun` unchanged; a branch whose resolved tree differs is reported `tree-changed` and not committed."),confirm:b.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{successfulMerges:b.number().describe("Number of branches that reached their desired state"),failedMerges:b.number().describe("Number of branches that did not"),failedBranches:b.array(b.string()).describe("List of branches that did not merge"),totalBranches:b.number().describe("Total number of branches processed"),dryRun:b.boolean().describe("True when nothing was pushed because this was a plan-only run"),atomicPush:b.object({attempted:b.boolean(),aborted:b.boolean(),abortedBy:b.string().optional()}).describe("Outcome of the single all-or-nothing push"),results:b.array(b.object({branch:b.string(),status:b.string(),mergeSha:b.string().optional(),conflictPaths:b.array(b.string()).optional(),pushed:b.boolean(),reason:b.string().optional(),resolution:b.object({worktreePath:b.string(),baseSha:b.string(),devSha:b.string(),conflictPaths:b.array(b.string()),lockfileOnly:b.boolean(),rererePreResolved:b.array(b.string()),state:b.enum(["needs-agent","lockfile-only","exists"])}).optional().describe("The `keepConflicts` hand-off for a conflicted branch"),blocked:b.object({code:b.enum(["unmerged-paths","markers-remaining","out-of-scope-edit","verify-failed","verify-mutated-tree","parents-mismatch","git-too-old","tree-changed"]),paths:b.array(b.string()).optional(),detail:b.string()}).optional().describe("Why a `continue` run did not commit this resolution")})).describe("Per-branch terminal state"),skipped:b.array(b.object({branch:b.string(),reason:b.enum(["hotfix (targets main)","title/base mismatch","open PRs to both dev and main"])})).describe("Every discovered release PR that was not a merge candidate, with why. Empty only when nothing was discovered.")},handler:ri});import{z as wo}from"zod";import{$ as De}from"zx";var Ag=(e,t)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-t).trim()},It=e=>{if(e===null||typeof e!="object")return{message:String(e)};let t=e,r={};e instanceof Error?(r.name=e.name,r.message=e.message):typeof t.message=="string"&&(r.message=t.message);let n=t.exitCode;(typeof n=="number"||n===null)&&(r.exitCode=n);let o=Ag(t.stderr,500);o&&(r.stderr=o);let s=Ag(t.stdout,200);return s&&(r.stdout=s),r};var ho=e=>{let{removed:t,failed:r}=e;if(t.length>0){u.info("\u274C Removed worktrees:");for(let n of t)u.info(n);u.info("")}if(r.length>0){u.warn("\u26A0\uFE0F Not removed:");for(let{branch:n,reason:o}of r)u.warn(`${n} \u2014 ${o}`);u.warn("")}t.length===0&&r.length===0&&u.info("\u2139\uFE0F No worktrees to remove")};var yo=e=>{let{result:t,operation:r}=e,n={removedWorktrees:t.removed,failedWorktrees:t.failed.map(i=>i.branch),count:t.removed.length},o=k(JSON.stringify(n,null,2));if(t.failed.length===0)return{content:o,structuredContent:n};let s={operation:r,remediation:`not removed: ${n.failedWorktrees.join(", ")} \u2014 fix the cause above and re-run`,stderrExcerpt:t.failed.map(i=>`${i.branch}: ${i.reason}`).join("; ")};throw fe()?new x({status:"partial_failure",...n},1,s):new f(void 0,s)};import oi from"node:fs/promises";import{$ as Ng}from"zx";var sE=new Set([".omc",".DS_Store"]),iE=new Set(["state","sessions"]),aE=2e3,cE="check 'git worktree list' for the path; uncommitted changes block removal",lE=e=>new Promise(t=>{setTimeout(t,e)}),yl=e=>typeof e=="object"&&e!==null?e.code:void 0,Og=e=>{let t=e.length;for(;t>1&&e[t-1]==="/";)t-=1;return e.slice(0,t)},Ig=async e=>{try{return Og(await oi.realpath(e))}catch{return Og(e)}},dE=async e=>{let{projectRoot:t,worktreePath:r}=e;try{let n=await gt(t),o=await Ig(r);for(let s of n)if(await Ig(s.path)===o)return!0;return!1}catch{return!0}},uE=async e=>{let t;try{t=await oi.readdir(e)}catch(n){return{kind:yl(n)==="ENOENT"?"gone":"not-sweepable",entries:[]}}if(!t.every(n=>sE.has(n)))return{kind:"not-sweepable",entries:t};if(!t.includes(".omc"))return{kind:"sweepable",entries:t};try{return{kind:(await oi.readdir(`${e}/.omc`)).every(s=>iE.has(s))?"sweepable":"not-sweepable",entries:t}}catch(n){return{kind:yl(n)==="ENOENT"?"sweepable":"not-sweepable",entries:t}}},Dg=async e=>{try{return await oi.rm(e,{recursive:!0,force:!0}),"removed"}catch(t){return yl(t)==="ENOTEMPTY"?"busy":"failed"}},pE=async e=>{let{worktreePath:t,sleep:r}=e,n=await Dg(t);return n!=="busy"?n==="removed":(await r(aE),await Dg(t)==="removed")},ni=(e,t,r)=>{let n=new f(t,{operation:`remove worktree for ${e}`,remediation:r});return u.error({error:t,branch:e,msg:n.message}),{branch:e,status:"failed",reason:n.message}},mE=async e=>{let{branch:t,worktreePath:r,projectRoot:n,error:o,sleep:s}=e;if(await dE({projectRoot:n,worktreePath:r}))return ni(t,o,cE);let i=await uE(r);if(i.kind==="gone")return{branch:t,status:"removed"};let a=`git already unregistered this worktree; inspect and remove it manually: rm -r ${r}`;return i.kind==="not-sweepable"||!await pE({worktreePath:r,sleep:s})?ni(t,o,a):(u.warn(`\u26A0\uFE0F swept leftover ${i.entries.join(", ")} from ${r}: a post-exit hook (e.g. oh-my-claudecode SessionEnd) wrote into the worktree while git was deleting it; set OMC_STATE_DIR to keep tool state out of worktrees`),{branch:t,status:"removed"})},fE=async e=>{let{branch:t,worktreeDir:r,projectRoot:n,orcaProbe:o,sleep:s}=e,i=`${r}/${t}`,a=await Ep(i,o);if(!a.closed&&"error"in a)return ni(t,a.error,"close the Orca terminals of this worktree manually (orca terminal close --terminal <handle>) and re-run");try{return await Ng`git worktree remove ${i}`,{branch:t,status:"removed"}}catch(c){return mE({branch:t,worktreePath:i,projectRoot:n,error:c,sleep:s})}},ar=async e=>{let{branches:t,worktreeDir:r,projectRoot:n,pruneFolder:o=!1,sleep:s=lE}=e,i=t.length>0?await Rr():"unreachable",a=await Promise.all(t.map(l=>fE({branch:l,worktreeDir:r,projectRoot:n,orcaProbe:i,sleep:s}))),c={removed:[],failed:[]};for(let l of a)l.status==="removed"?c.removed.push(l.branch):c.failed.push({branch:l.branch,reason:l.reason});return o&&c.removed.length===t.length&&await Ng`git worktree prune`,c};var vo=async(e,t)=>{if(!(await Te("release")).includes(e))return[];let n=await E(),o=`${n}${pe}`,{removed:s,failed:i}=await ar({branches:[e],worktreeDir:o,projectRoot:n});if(!s.includes(e)){let a=i.find(c=>c.branch===e);throw new f(void 0,{...t,stderrExcerpt:a?.reason})}return s};var an=async(e,t,r)=>{try{return await r()}catch(n){throw u.debug({err:It(n)},`Failed to ${e}`),new f(n,{operation:e,remediation:t})}},gE=async e=>{let t=ta(e),r=await De`gh pr list --head dev --base main --state merged --json number,state,title,baseRefName,headRefName --limit 20`;return JSON.parse(r.stdout).find(s=>s.title===t)??null},_g=async()=>{let e=await De`gh pr list --head dev --base main --state open --json number,state,title,baseRefName,headRefName --limit 5`;return JSON.parse(e.stdout)[0]??null},hE=async e=>{let t=ct(e),r=await mc(t);if(r.length>1){let s=r.map(i=>`#${i.number} \u2192 ${i.baseRefName}`).join(", ");throw new f(void 0,{operation:`deliver release ${t}`,remediation:`the branch has open PRs to both dev and main (${s}); close the one that should not be delivered`})}let n=r[0]??await jr(t);if(!n)throw u.error(`\u274C No PR found for branch ${t}.`),new f(void 0,{operation:`deliver release ${t}`,remediation:`confirm a PR exists ('gh pr list --head ${t} --state all')`});let o=Jn(n.baseRefName);if(!o)throw new f(void 0,{operation:`deliver release ${t}`,remediation:`PR #${n.number} targets '${n.baseRefName}', which is neither dev nor main; retarget it ('gh pr edit ${n.number} --base <dev|main>')`});return{selectedReleaseBranch:t,releaseType:o,prNumber:n.number}},yE=async()=>{let e=await F(),t=e.map(i=>i.branch),r=new Map(e.map(i=>[i.branch,i.type]));h.setInteractive();let n=await ne(),o=await Et(oe({branches:t,descriptions:n,types:r})),s=e.find(i=>i.branch===o);if(!s)throw u.error(`\u274C Release branch ${o} not found in open PRs.`),new f(void 0,{operation:`deliver release ${o}`,remediation:`confirm an open PR exists for ${o} ('gh pr list')`});if(s.dualBase)throw new f(void 0,{operation:`deliver release ${o}`,remediation:"the branch has open PRs to both dev and main; close the one that should not be delivered"});return{selectedReleaseBranch:o,releaseType:s.type,prNumber:s.number}},vE=async e=>{let{selectedReleaseBranch:t,releaseType:r,prNumber:n}=e,o=Ye(r),s=await fc(n);if(s.state==="MERGED"){u.info(`\u2713 Release PR ${t} already merged \u2014 skipping`);return}if(s.state==="CLOSED")throw new f(void 0,{operation:`merge release PR ${t} into ${o}`,remediation:"the PR is closed without merge; reopen it or create a new release"});if(s.baseRefName!==o||s.headRefName!==t)throw new f(void 0,{operation:`merge release PR #${n} ${t} into ${o}`,remediation:`PR #${n} now reads ${s.headRefName} \u2192 ${s.baseRefName}; it changed since it was resolved \u2014 re-run the command`});await an(`merge release PR #${n} ${t} into ${o}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await De`gh pr merge ${n} --squash --admin --delete-branch`})},wE=async e=>{let t=Y(e),r=ta(e),n=await _g();if(n){let s=n.number;return n.title!==r&&(u.info(`Adopting open dev \u2192 main PR #${s} ("${n.title}") and retitling for ${t}`),await an(`retitle dev \u2192 main PR #${s} to "${r}"`,`update manually: gh pr edit ${s} --title "${r}"`,async()=>{await De`gh pr edit ${s} --title ${r}`})),s}await an(`create RC PR (dev \u2192 main) for ${t}`,"run 'gh pr create --base main --head dev' manually to surface the underlying error (e.g. no commits between dev and main)",async()=>{await De`gh pr create --base main --head dev --title ${r} --body ""`});let o=await _g();if(!o)throw new f(void 0,{operation:`look up RC PR for ${t}`,remediation:"verify the RC PR was created ('gh pr list --head dev --base main')"});return o.number},kE=async e=>{let t=Y(e);if(await gE(e)){u.info(`\u2713 RC PR for ${t} already merged into main \u2014 skipping`);return}let n=await wE(e);await an(`merge RC PR #${n} (dev \u2192 main) for ${t}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await De`gh pr merge ${n} --squash --admin`})},bE=async()=>{De.quiet=!1,await an("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await De`gh workflow run deploy-all.yml --ref main -f environment=prod`}),De.quiet=!0},RE=async()=>{await an("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 De`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},SE=async e=>{try{await es(e)}catch(t){u.warn({err:It(t)},`Failed to delete local branch ${e} (non-blocking)`)}try{await ts(e)}catch(t){u.warn({err:It(t)},`Failed to delete remote branch ${e} (non-blocking)`)}},PE=async e=>{let t=await at();if(!t){u.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let r=te(e);await hc({versionName:r},t)}catch(r){let n=Kn(r)&&r.kind==="auth"?" \u2014 reissue the Atlassian API token and update JIRA_TOKEN":"";u.error({err:It(r)},`Failed to deliver Jira release (non-blocking)${n}`)}},si=async e=>{let{version:t,confirmedCommand:r}=e;await be({operation:"deliver release"});let{selectedReleaseBranch:n,releaseType:o,prNumber:s}=t?await hE(t):await yE(),i=J(n);if(!i)throw new f(void 0,{operation:`deliver release ${n}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let a=Y(i);if(h.addOption("--version",a),u.info(`Delivering ${i.kind==="name"?"named release":"version"} ${n}`),fe())throw new x({status:"refused",agentMode:I.source},2,{operation:`deliver release ${n}`,remediation:"ask a human to run `infra-kit release deliver` from their own shell \u2014 delivery is never confirmed by an agent",stderrExcerpt:"release deliver is CLI-only: refused in agent mode regardless of --yes"});await B(r,`Are you sure you want to deliver version ${n} to production?`),h.addOption("--yes",!0),De.quiet=!0;let l=`${await E()}${pe}`;await vo(n,{operation:`remove worktree for ${n} before merge`,remediation:`run manually: git worktree remove ${l}/${n} (use --force if uncommitted changes)`}),await vE({selectedReleaseBranch:n,releaseType:o,prNumber:s}),o!=="hotfix"&&await kE(i),await bE(),await RE(),await SE(n),De.quiet=!1,await PE(i),u.info(`Successfully delivered ${n} to production!`),h.print();let d={releaseBranch:n,version:a,type:o,success:!0};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}},vl=S({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).',requiresHumanConfirm:!0,inputSchema:{version:wo.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:wo.string().describe("The release branch that was delivered"),version:wo.string().describe("The version that was delivered"),type:wo.enum(["regular","hotfix"]).describe("Release type"),success:wo.boolean().describe("Whether the delivery was successful")},handler:si});import{z as dt}from"zod";import{$ as Cl}from"zx";import{z as Ro}from"zod";import Mg from"node:fs/promises";import wl from"node:path";var jg=".github/workflows",EE=/script_name:\s*(?<service>[a-z0-9-]+)/,xE=/uses:\s*\.\/\.github\/workflows\/_deploy-(?<service>[a-z0-9-]+)-jobs\.ya?ml/,TE=/inputs\.environment\s*==\s*'(?<env>[a-z0-9-]+)'/g,kl=async e=>{let t=wl.resolve(e,jg),r;try{r=await Mg.readdir(t)}catch{return new Map}return Fg(t,r.filter(n=>n.endsWith(".yml")||n.endsWith(".yaml")))},ko=async(e,t)=>Fg(wl.resolve(e,jg),[t]),Fg=async(e,t)=>{let r=new Map;for(let n of t){let o;try{o=await Mg.readFile(wl.resolve(e,n),"utf-8")}catch{continue}CE(o,r)}return r},CE=(e,t)=>{for(let r of e.split(/\n(?= {2}[\w-]+:)/i)){let n=EE.exec(r)?.groups?.service??xE.exec(r)?.groups?.service;if(n===void 0||r.trimStart().startsWith("#"))continue;let o=[...r.matchAll(TE)].map(s=>s.groups?.env??"");o.length!==0&&t.set(n,[...new Set([...t.get(n)??[],...o])])}},bl=(e,t)=>e===null?t??null:t===void 0?e:e.filter(r=>t.includes(r));import $E from"node:fs/promises";import AE from"node:path";import OE from"yaml";var IE=".github/workflows",DE="skip_terraform_deploy",bo=async(e,t)=>{let r=AE.resolve(e,IE,t),n;try{n=OE.parse(await $E.readFile(r,"utf-8"))}catch{return[]}let s=n?.on?.workflow_dispatch?.inputs;return typeof s!="object"||s===null?[]:Object.entries(s).filter(([i,a])=>a?.type==="boolean"&&i!==DE).map(([i])=>i)};var Lg="dev",Rl=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Bg=(e,t)=>e[t]===void 0,Vg=(e,t)=>{let r=e[t];return typeof r=="string"&&r.length>0?r:void 0},Sl=async e=>{try{return await e}catch{return[]}},NE=async()=>{let e=await F();return zt(e.map(t=>t.branch))},_E=(e,t)=>{let r=e.filter(o=>t.get(o)!==void 0);if(r.length===0)return"none declared.";let n=r.map(o=>`${o}: ${(t.get(o)??[]).join(", ")} only.`).join(" ");return r.length<e.length?`${n} Others: any environment.`:n},cr=e=>{let{workflowFile:t,fields:r,toolName:n}=e,o=c=>(u.info({msg:`Tool execution form options empty (${t}): ${n}`,emptyList:c}),null),s=async c=>{let l=await Sl(NE());if(l.length===0)return null;let d=Vg(c,"version");return Ro.enum([...new Set([...l,Lg])]).optional().describe(`Which release to deploy from. "${Lg}" deploys from the dev branch instead of a release branch. ${d===void 0?"Leaving it blank sends no version, and the tool will refuse rather than guess one.":`Leave it blank to keep the caller's "${d}".`}`)},i=async c=>{let l=kt(await Sl(bt(t)),await We());if(l.length===0)return null;let d=l.filter(Sn),p=l.filter(g=>!Sn(g)),m=Vg(c,"env");return Ro.enum(l).optional().describe(`Target environment. Shared with the whole team: ${d.length>0?d.join(", "):"none"}. Personal accounts: ${p.length>0?p.join(", "):"none"}. This list is read from .github/workflows/${t} in the WORKING TREE, not from the branch being deployed or from GitHub. ${m===void 0?"Leaving it blank sends no environment at all.":`Leave it blank to keep the caller's "${m}" \u2014 including when this tree does not declare it.`}`)},a=async()=>{let c=await E(),l=await Sl(bo(c,t));if(l.length===0)return null;let d=await ko(c,t);return Ro.array(Ro.enum(l)).optional().describe(`Services to deploy. Environment gates declared by ${t} \u2014 ${_E(l,d)} A service the chosen environment gates out is REFUSED before dispatch, not skipped in silence. Selecting none discards the form and falls back to the caller's arguments.`)};return{message:`Choose the arguments for ${n}. Anything left blank keeps what the caller sent.`,isFormable:c=>Rl(c)?r.some(l=>Bg(c,l)):!1,buildRequestedSchema:async c=>{let l=Rl(c)?c:{},d={};if(r.includes("version")){let p=await s(l);if(p===null)return o("releases");d.version=p}if(r.includes("env")){let p=await i(l);if(p===null)return o("envs");d.env=p}if(r.includes("services")&&Bg(l,"services")){let p=await a();if(p===null)return o("services");d.services=p}return Object.keys(d).length===0?o("fields"):Ro.object(d)},toArgs:(c,l)=>{let d={...Rl(l)?l:{}};for(let p of r){let m=c[p];if(m!==void 0){if(p==="services"&&(!Array.isArray(m)||m.length===0))return null;d[p]=m}}return d}}};import ME from"@inquirer/select";var cn=async(e,t)=>{if(e.length===0)throw new f(void 0,{operation:t,remediation:"pass --env <name> explicitly",stderrExcerpt:"the workflow declares no `environment` choices to pick from"});return O(r=>ME({message:"\u{1F9EA} Select environment",choices:e.map(n=>({name:n,value:n}))},r),{whenHeadless:"refuse"})};import jE from"@inquirer/confirm";var So=async e=>{let{confirmedCommand:t,branch:r,env:n}=e;if(t)return!0;let o=`Deploy ${r} \u2192 ${n} via GitHub Actions?`;ge()&&is(o,{branch:r,env:n}),h.setInteractive();let s=await O(i=>jE({message:o,default:!1},i),{whenHeadless:"refuse"});return s&&h.addOption("--yes",!0),s};import FE from"@inquirer/select";import LE from"node:process";var Pl=()=>!ge()&&LE.stdin.isTTY===!0,BE={ci:"Dispatch the GitHub workflow for a release ref",local:"Run devops/scripts/deploy-*.sh here, against your current checkout"},El=async()=>O(e=>FE({message:"\u{1F680} Where should this deploy run?",choices:Dt.filter(t=>t!=="local").map(t=>({name:t,value:t,description:BE[t]}))},e),{whenHeadless:"refuse"});var Dt=["ci","local"],VE={ci:["--version","--skip-terraform"],local:["--dry-run","--print-env"]},Wg=e=>{if(!e){let r={operation:"resolve the deploy source",remediation:`pass --from with one of: ${Dt.join(", ")}`,stderrExcerpt:"--from is required \u2014 it decides whether this deploy runs in CI or on this machine"};throw ge()?new x({status:"argument_required",argument:"from",agentMode:I.source},2,r):new f(void 0,r)}let t=Dt.find(r=>r===e);if(!t)throw new f(void 0,{operation:"resolve the deploy source",remediation:`use one of: ${Dt.join(", ")}`,stderrExcerpt:`unknown --from value "${e}"`});return t},xl=(e,t)=>{let n=VE[e==="ci"?"local":"ci"].filter(o=>{let s=t[o];return s!==void 0&&s!==!1});if(n.length!==0)throw new f(void 0,{operation:`deploy --from ${e}`,remediation:e==="ci"?"drop the flag, or use --from local to deploy from this machine":"drop the flag, or use --from ci to dispatch the release workflow",stderrExcerpt:`${n.join(", ")} ${n.length===1?"is":"are"} not valid with --from ${e}`})},Tl=async e=>e||!Pl()?Wg(e):El();var Po=async e=>{if(e)return e==="dev"?"dev":ct(e);h.setInteractive();let t=await F(),r=t.map(s=>s.branch),n=new Map(t.map(s=>[s.branch,s.type])),o=await ne();return Et([{value:"dev",label:"dev"},...oe({branches:r,descriptions:o,types:n})])};var Ug="deploy-all.yml",Jg=cr({workflowFile:Ug,fields:["version","env"],toolName:"gh-release-deploy-all"}),ii=async e=>{let{version:t,env:r,skipTerraform:n,confirmedCommand:o}=e;await Ue({provider:Jg,params:e,operation:"launch deploy-all workflow",argument:p=>p[0]??"version"});let s=await Po(t),i=Yn(s);h.addOption("--version",i);let a=await We(),c=kt(await bt(Ug),a),l="";r?l=r:(h.setInteractive(),l=await cn(c,"launch deploy-all workflow")),h.addOption("--env",l),Sr(l,"launch deploy-all workflow",a),ls({env:l,branch:s});let d=n??!1;if(d&&h.addOption("--skip-terraform",!0),!await So({confirmedCommand:o,branch:s,env:l})){u.info("Deployment cancelled");let p={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:d,success:!1};return{content:k(JSON.stringify(p,null,2)),structuredContent:p}}try{Cl.quiet=!0,await Cl`gh workflow run deploy-all.yml --ref ${s} -f environment=${l} ${d?["-f","skip_terraform_deploy=true"]:[]}`,Cl.quiet=!1,u.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${s} and environment: ${l}`),h.print();let m={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:d,success:!0};return{content:k(JSON.stringify(m,null,2)),structuredContent:m}}catch(p){throw u.error({error:p},"\u274C Error launching workflow"),new f(p,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},$l=S({name:"gh-release-deploy-all",formProvider:Jg,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. Omit "version" or "env" and this server offers the human a form listing the real releases and the environments this workflow declares; a client that cannot render one gets a refusal naming the missing field, never a guess.',requiresHumanConfirm:!0,inputSchema:{version:dt.string().optional().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. Omit it to be offered the open releases.'),env:dt.string().optional().describe('Target environment name \u2014 must match an env this project may reach (e.g. "dev", "renana", "oriana"). Omit it to be offered the environments deploy-all.yml declares.'),skipTerraform:dt.boolean().optional().describe("Skip the terraform deployment stage."),confirm:dt.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:dt.string().describe("The release branch that was deployed"),version:dt.string().describe("The version that was deployed"),environment:dt.string().describe("The environment deployed to"),skipTerraformDeploy:dt.boolean().describe("Whether terraform deployment was skipped"),success:dt.boolean().describe("Whether the deployment was successful")},handler:ii});import WE from"@inquirer/checkbox";import{z as Se}from"zod";import{$ as Al}from"zx";var lr="deploy-selected-services.yml",Gg=cr({workflowFile:lr,fields:["version","env","services"],toolName:"gh-release-deploy-selected"}),ai=async e=>{let{version:t,env:r,services:n,skipTerraform:o,confirmedCommand:s}=e;await Ue({provider:Gg,params:e,operation:"launch deploy-selected workflow",argument:A=>A[0]??"version"});let i=await Po(t),a=Yn(i);h.addOption("--version",a);let c=await We(),l=kt(await bt(lr),c),d="";r?d=r:(h.setInteractive(),d=await cn(l,"launch deploy-selected workflow")),h.addOption("--env",d),Sr(d,"launch deploy-selected workflow",c),ls({env:d,branch:i});let p=await E(),m=await bo(p,lr);if(m.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${lr}`,stderrExcerpt:`no services found in .github/workflows/${lr}`});let g=[];if(n&&n.length>0?g=n:(h.setInteractive(),g=await O(A=>WE({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:m.map(P=>({name:P,value:P}))},A),{whenHeadless:"refuse"})),h.addOption("--services",g),g.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${m.join(", ")}`,stderrExcerpt:"no services selected"});let y=g.filter(A=>!m.includes(A));if(y.length>0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${m.join(", ")}`,stderrExcerpt:`invalid services: ${y.join(", ")}`});let R=await ko(p,lr),v=g.filter(A=>{let P=R.get(A);return P!==void 0&&!P.includes(d)});if(v.length>0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:v.map(A=>`${A} deploys only to: ${(R.get(A)??[]).join(", ")}`).join("; "),stderrExcerpt:`${lr} gates these services out of ${d}: ${v.join(", ")}`});let $=o??!1;$&&h.addOption("--skip-terraform",!0);let D=A=>{let P={releaseBranch:i,version:a,environment:d,services:g,skipTerraformDeploy:$,success:A};return{content:k(JSON.stringify(P,null,2)),structuredContent:P}};if(!await So({confirmedCommand:s,branch:i,env:d}))return u.info("Deployment cancelled"),D(!1);try{Al.quiet=!0;let A=g.flatMap(q=>["-f",`${q}=true`]);return await Al`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${d} ${A} ${$?["-f","skip_terraform_deploy=true"]:[]}`,Al.quiet=!1,u.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${d}, services: ${g.join(", ")}`),h.print(),D(!0)}catch(A){throw u.error({error:A},"\u274C Error launching workflow"),new f(A,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},Ol=S({name:"gh-release-deploy-selected",requiresHumanConfirm:!0,formProvider:Gg,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, and a service the target environment gates out is refused BEFORE dispatch rather than dispatched and silently skipped. Use gh-release-deploy-all for every service. Omit any of "version", "env" or "services" and this server offers the human a form built from the real releases, environments and services; a client that cannot render one gets a refusal naming the missing field, never a guess.',inputSchema:{version:Se.string().optional().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. Omit it to be offered the open releases.'),env:Se.string().optional().describe('Target environment name \u2014 must match an env this project may reach (e.g. "dev", "renana", "oriana"). Omit it to be offered the environments deploy-selected-services.yml declares.'),services:Se.array(Se.string()).optional().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"). Some services are gated to particular environments by that workflow and are refused here rather than skipped by CI. Omit it to be offered the declared services.'),skipTerraform:Se.boolean().optional().describe("Skip the terraform deployment stage."),confirm:Se.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},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"),services:Se.array(Se.string()).describe("The services that were deployed"),skipTerraformDeploy:Se.boolean().describe("Whether terraform deployment was skipped"),success:Se.boolean().describe("Whether the deployment was successful")},handler:ai});import{z as Nt}from"zod";var ci=async()=>{let t=(await F()).flatMap(i=>{let a=J(i.branch);return a?[{version:Y(a),jiraKey:te(a),type:i.type,titleMismatch:i.titleMismatch}]:[]}),r=await As(),n=Math.max(...t.map(i=>i.version.length)),o=t.map(i=>{let a=qn(i.version,i.type,n),c=r.get(i.jiraKey),l=c?.description?` ${c.description}`:"",d=c?.releaseDate?` \xB7 ships ${c.releaseDate}`:"",p=i.titleMismatch?" \u26A0 title/base mismatch":"";return`${a}${l}${d}${p}`});u.info(`All release branches:
393
+ `),u.info(`
391
394
  ${o.join(`
392
395
  `)}
393
- `);let s={releases:t.map(i=>({version:i.version,type:i.type,description:r.get(i.jiraKey)?.description??null,releaseDate:r.get(i.jiraKey)?.releaseDate??null,titleMismatch:i.titleMismatch})),count:t.length};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}},td=R({name:"gh-release-list",description:"List every open release PR with its version, type (regular / hotfix), and the associated Jira fix version\u2019s description and planned release date. Read-only; sourced from GitHub and Jira.",inputSchema:{},outputSchema:{releases:Ut.array(Ut.object({version:Ut.string().describe("Release version"),type:Ut.enum(["regular","hotfix"]).describe("Release type"),description:Ut.string().nullable().describe("Jira version description"),releaseDate:Ut.string().nullable().describe("Planned release date of the Jira version (yyyy-mm-dd)"),titleMismatch:Ut.boolean().describe("The PR title names a different release type than its base branch")})).describe("List of all release branches"),count:Ut.number().describe("Number of release branches")},handler:xi});import xx from"node:process";var rd=e=>({...e}),nd=e=>{let{env:t,branch:r,sha:n,isClean:o,ambient:s=xx.env}=e,i={VITE_DOMAIN_ENV:t,VITE_BRANCH_NAME:r,VITE_COMMIT_HASH:o?n:`${n}-dirty`},a={},c=[];for(let[l,d]of Object.entries(s)){if(l.startsWith("VITE_")){c.push(l);continue}a[l]=d}return c.sort(),{childEnv:{...a,...i,DEPLOY_ENV:t,DEPLOY_BRANCH:r,DEPLOY_SHA:n,DEPLOY_SHA_LABEL:i.VITE_COMMIT_HASH,TURBO_TELEMETRY_DISABLED:"1"},contract:i,stripped:c}},Ti=e=>{let t=Object.entries(e.contract).map(([r,n])=>` ${r.padEnd(17)}= ${n}`);return e.stripped.length>0&&t.push(` stripped from shell: ${e.stripped.join(", ")}`),t.join(`
394
- `)};import Vx from"@inquirer/checkbox";import Bx from"@inquirer/confirm";import Wx from"@inquirer/select";import{spawn as Jx}from"node:child_process";import Ux from"node:process";import{z}from"zod";import{$ as Lo}from"zx";import{$ as Fo}from"zx";var Tx=async e=>{let t=Fo.quiet;Fo.quiet=!0;try{let r=`/${e}/environment`,n=await Fo`aws sts get-caller-identity --query Account --output text`,o=await Fo`aws ssm get-parameter --name ${r} --query Parameter.Value --output text`;return{accountId:n.stdout.trim(),stage:o.stdout.trim()}}catch(r){throw new f(r,{operation:"resolve the AWS account for this deploy",remediation:`check that credentials are loaded and that \`/${e}/environment\` exists in the account they point at \u2014 run \`aws sts get-caller-identity\` to see which account that is`})}finally{Fo.quiet=t}},fh=(e,t)=>{if(t.stage!==e)throw new f(void 0,{operation:"verify the target environment",remediation:"switch AWS_PROFILE to the account for this environment, or pass the env this account is",stderrExcerpt:`you asked for "${e}", but AWS account ${t.accountId} reports "${t.stage}" \u2014 refusing to deploy to an environment you did not name`})},gh=e=>{let{env:t,isShared:r,isClean:n}=e;if(!(!r||n))throw new f(void 0,{operation:`deploy to shared environment "${t}"`,remediation:"commit, or `git stash -u` (plain stash leaves untracked files), or deploy to a personal environment",stderrExcerpt:"the working tree has uncommitted or untracked changes and this environment is shared"})},hh=(e,t)=>{if(t.includes(e))throw new f(void 0,{operation:`deploy to "${e}"`,remediation:"wait for the CI run to finish, or watch it with `gh run watch`",stderrExcerpt:`a CI deploy to "${e}" is already in flight \u2014 running both would interleave`})},od=async e=>{let{env:t,project:r,isShared:n,isClean:o,runningEnvs:s,protectedEnvAccess:i}=e;dr(t,`deploy to "${t}"`,i),hh(t,s),gh({env:t,isShared:n,isClean:o});let a=await Tx(r);return fh(t,a),{identity:a}};import yh from"node:fs/promises";import Ci from"node:path";var Cx="devops/scripts",$x=/^deploy-(?<service>[a-z0-9-]+)\.sh$/,Ax=/skip_unless_env_enabled\s+"[^"]*"\s+"[^"]*"\s+"(?<envs>[^"]*)"/,Ox=/aws\s+ssm\s+get-parameter\s+--name[=\s]+(?<arg>[^\s)]+)/,Ix=/aws\s+ssm\s+get-parameter\s+--name[=\s]+["']?\/(?<prefix>[\w.-]+)\/environment["']?(?![\w./-])/,sd=async e=>{let t=Ci.resolve(e,Cx),r;try{r=await yh.readdir(t)}catch{return[]}let n=await Jl(e);return(await Promise.all(r.map(s=>({entry:s,match:$x.exec(s)})).filter(s=>s.match!==null).map(async({entry:s,match:i})=>{let a=Ci.resolve(t,s),c=i?.groups?.service??"",l=Nx(await Dx(a));return{name:c,scriptPath:a,allowedEnvs:Ul(_x(l),n.get(c)),ssmPrefix:jx(l)}}))).sort((s,i)=>s.name.localeCompare(i.name))},Dx=async e=>{try{return await yh.readFile(e,"utf-8")}catch{return""}},Nx=e=>e.split(`
395
- `).map((t,r)=>({line:r+1,text:t})).filter(({text:t})=>!t.trimStart().startsWith("#")),_x=e=>{let t=e.reduce((n,{text:o})=>n??Ax.exec(o)?.groups?.envs,void 0);if(t===void 0)return null;let r=t.split(/\s+/).filter(Boolean);return r.length>0?r:null},Mx=e=>{let t=e.replaceAll(/["']/g,"");return t.includes("$")&&(t.includes("/environment")||t.startsWith("$"))},jx=e=>{for(let{line:t,text:r}of e){let n=Ix.exec(r)?.groups?.prefix;if(n!==void 0)return n;let o=Ox.exec(r)?.groups?.arg;if(o!==void 0&&Mx(o))return{unparseable:{line:t,text:r.trim()}}}return null},Fx=e=>{let t=new Map;for(let r of e)typeof r.ssmPrefix=="string"&&t.set(r.ssmPrefix,[...t.get(r.ssmPrefix)??[],Ci.basename(r.scriptPath)]);return t},Lx=e=>{let t=e.flatMap(r=>{if(r.ssmPrefix===null||typeof r.ssmPrefix=="string")return[];let{line:n,text:o}=r.ssmPrefix.unparseable;return[`${Ci.basename(r.scriptPath)}:${n}: ${o}`]});if(t.length!==0)throw new f(void 0,{operation:"resolve the SSM project prefix",remediation:"write the parameter name as a literal `/<project>/environment` so infra-kit can preflight it",stderrExcerpt:t.join("; ")})},vh=e=>{Lx(e);let t=Fx(e),[r,...n]=t.keys();if(r===void 0)throw new f(void 0,{operation:"resolve the SSM project prefix",remediation:'add `aws ssm get-parameter --name "/<project>/environment"` to at least one devops/scripts/deploy-*.sh',stderrExcerpt:`none of ${e.length} deploy scripts reads /<project>/environment`});if(n.length>0){let o=[...t.entries()].sort(([,s],[,i])=>s.length-i.length).map(([s,i])=>`${s}: ${i.join(", ")}`).join("; ");throw new f(void 0,{operation:"resolve the SSM project prefix",remediation:"make every deploy script read the same /<project>/environment parameter",stderrExcerpt:`${t.size} different prefixes across ${e.length} deploy scripts \u2014 ${o}`})}return r},$i=(e,t)=>e.allowedEnvs===null||e.allowedEnvs.includes(t),id=(e,t)=>e.filter(r=>$i(r,t));var cd="deploy-all.yml",kh="/bin/sh",Gx=async()=>{let e=Lo.quiet;Lo.quiet=!0;try{let t=await Lo`gh run list --workflow=${cd} --status=in_progress --json displayTitle`;return JSON.parse(t.stdout).flatMap(n=>/\[(?<env>[a-z0-9-]+)\]/.exec(n.displayTitle??"")?.groups?.env??[])}catch{return[]}finally{Lo.quiet=e}},Kx=async(e,t)=>{let r=e.map(o=>({name:o.name,value:o.name})),n=await I(o=>Vx({message:`Deploy which services to ${t}?`,choices:r,pageSize:20},o),{whenHeadless:{refuse:"service"}});if(n.length===0)throw new f(void 0,{operation:"select services",remediation:"pick at least one service, or use `local deploy-all`",stderrExcerpt:"no services selected"});return n},Hx=async e=>{let{env:t,isShared:r,names:n,accountId:o}=e,s=n.length,i=r?`"${t}" is a SHARED environment \u2014 deploying ${s} service(s) from this machine. Continue?`:`Deploy ${s} service(s) to ${t} from this machine?`;return ie()&&ws(i,{env:t,services:n,accountId:o,shared:r}),r?I(a=>Wx({message:i,choices:[{name:"No, cancel",value:!1},{name:`Yes, deploy to ${t}`,value:!0}]},a),{whenHeadless:"refuse"}):I(a=>Bx({message:i,default:!1},a),{whenHeadless:"refuse"})},qx=(e,t,r)=>new Promise((n,o)=>{let s=Jx(kh,[e.scriptPath],{cwd:r,env:t,stdio:"inherit"});s.on("error",o),s.on("close",i=>{n(i??1)})}),zx=async e=>{let{chosen:t,childEnv:r,cwd:n,env:o}=e,s=[],i=[];for(let a of t){p.info(`\u2192 ${a.name} \u2192 ${o}`);let c=await qx(a,r,n);if(c!==0){i.push(a.name),p.error(`\u2717 ${a.name} failed (exit ${c})`);break}s.push(a.name),p.info(`\u2713 ${a.name}`)}return{deployed:s,failed:i}},Yx=e=>{let{names:t,services:r,env:n}=e,o=new Map(r.map(a=>[a.name,a])),s=t.filter(a=>!o.has(a));if(s.length>0)throw new f(void 0,{operation:"resolve the requested services",remediation:`known services: ${r.map(a=>a.name).join(", ")}`,stderrExcerpt:`no deploy script for: ${s.join(", ")}`});let i=t.filter(a=>{let c=o.get(a);return c!==void 0&&!$i(c,n)});if(i.length>0)throw new f(void 0,{operation:`deploy to "${n}"`,remediation:"drop those services, or deploy them to an environment they allow",stderrExcerpt:`not enabled for "${n}": ${i.join(", ")} (the scripts would skip them)`});return t.map(a=>o.get(a))},ad=e=>{let{env:t,accountId:r,names:n,built:o,deployed:s,failed:i,dryRun:a,success:c}=e,l={environment:t,accountId:r,services:n,deployed:s,failed:i,contract:rd(o.contract),strippedVars:o.stripped,dryRun:a,success:c};return{content:k(JSON.stringify(l,null,2)),structuredContent:l}},Xx=async e=>{let{selection:t,eligible:r,service:n,env:o}=e;return t==="all"?r.map(s=>s.name):n&&n.length>0?n:(h.setInteractive(),Kx(r,o))},bh=async(e,t)=>{let{env:r,service:n,confirmedCommand:o,dryRun:s,printEnv:i}=e,a=await x(),c=await sd(a);if(c.length===0)throw new f(void 0,{operation:"discover deployable services",remediation:"run this from a repo that has devops/scripts/deploy-*.sh",stderrExcerpt:`no deploy scripts found under ${a}/devops/scripts`});let l=vh(c);await Ne({provider:ld[t],params:e,operation:"deploy locally",argument:"env"});let d=await Je(),u=gt(await ht(cd),d),m=r??"";m||(h.setInteractive(),m=await En(u,"deploy locally")),h.addOption("--env",m);let g=id(c,m);if(g.length===0)throw new f(void 0,{operation:`deploy to "${m}"`,remediation:"pick an environment these services allow",stderrExcerpt:`no service on disk is enabled for "${m}"`});let y=await Xx({selection:t,eligible:g,service:n,env:m}),S=Yx({names:y,services:c,env:m});if(t==="selected")for(let xe of y)h.addOption("--service",xe);let v=un(m),C=await Ar(),_=(await Lo`git rev-parse HEAD`.quiet()).stdout.trim(),O=await lu(),P=nd({env:m,branch:C,sha:_,isClean:O});i&&p.info(`Deploy contract for ${m}:
396
- ${Ti(P)}`);let B=(await od({env:m,project:l,isShared:v,isClean:O,runningEnvs:await Gx(),protectedEnvAccess:d})).identity.accountId;if(s)return p.info([`Would deploy to "${m}" (AWS account ${B}) from this machine`,`Preflight parameter: /${l}/environment`,Ti(P),"Commands:",...S.map(xe=>` ${kh} ${xe.scriptPath}`),"","Dry run: preflight and contract only \u2014 says nothing about whether the deploy would succeed."].join(`
397
- `)),ad({env:m,accountId:B,names:y,built:P,deployed:[],failed:[],dryRun:!0,success:!0});if(!o&&!await Hx({env:m,isShared:v,names:y,accountId:B}))return p.info("Deployment cancelled"),ad({env:m,accountId:B,names:y,built:P,deployed:[],failed:[],dryRun:!1,success:!1});P.stripped.length>0&&p.info(`Stripped ambient VITE_* from the build env: ${P.stripped.join(", ")}`);let{deployed:j,failed:Ke}=await zx({chosen:S,childEnv:P.childEnv,cwd:a,env:m});return Ke.length>0&&(p.error(`Partial deploy to "${m}": succeeded [${j.join(", ")||"none"}], failed [${Ke.join(", ")}]. There is no rollback \u2014 redeploy the previous commit to restore it.`),Ux.exitCode=1),h.print(),ad({env:m,accountId:B,names:y,built:P,deployed:j,failed:Ke,dryRun:!1,success:Ke.length===0})},Rh=async e=>bh(e,"all"),Sh=async e=>bh(e,"selected"),Ph='Runs the repo\'s own devops/scripts/deploy-*.sh on THIS machine instead of dispatching CI. Supplies the build contract (VITE_DOMAIN_ENV/BRANCH/COMMIT) that the workflow YAML normally provides and that the scripts do not set themselves, and refuses unless the requested environment matches the AWS account the shell is authenticated to. "prod" is refused by default \u2014 it is delivered, not deployed \u2014 and is reachable only if this project sets `protectedEnvs` in infra-kit.json; "cli-only" allows it in a terminal but still refuses it here. Services the environment forbids are refused, matching the workflow\'s own per-service gates. Use dryRun first.',Eh={env:z.string().optional().describe('Target environment, e.g. "dev" or a personal env like "arthur". Omit it to be offered the environments this project may reach.'),dryRun:z.boolean().optional().describe("Resolve target, contract and commands without deploying."),confirm:z.boolean().optional().describe("Set true to execute; omit for a dry-run gate.")},xh={environment:z.string().describe("Environment deployed to"),accountId:z.string().describe("AWS account the deploy targeted"),services:z.array(z.string()).describe("Services requested"),deployed:z.array(z.string()).describe("Services that completed successfully"),failed:z.array(z.string()).describe("Services that failed"),contract:z.record(z.string(),z.string()).describe("Build contract passed to the scripts"),strippedVars:z.array(z.string()).describe("Ambient VITE_* names removed from the build env"),dryRun:z.boolean().describe("Whether this was a dry run"),success:z.boolean().describe("Whether every requested service deployed")},wh=e=>vr({workflowFile:cd,fields:["env"],toolName:e}),ld={all:wh("local-deploy-all"),selected:wh("local-deploy-selected")},dd=R({name:"local-deploy-all",description:`Deploy EVERY service enabled for an environment, from this machine. ${Ph}`,requiresHumanConfirm:!0,formProvider:ld.all,inputSchema:Eh,outputSchema:xh,handler:Rh}),pd=R({name:"local-deploy-selected",description:`Deploy a NAMED SUBSET of services from this machine. ${Ph}`,requiresHumanConfirm:!0,formProvider:ld.selected,inputSchema:{...Eh,service:z.array(z.string()).min(1).describe('Service names as in devops/scripts/deploy-<name>.sh, e.g. ["client-be"]. Required for MCP.')},outputSchema:xh,handler:Sh});import eT from"@inquirer/confirm";import Ai from"@inquirer/input";import Ah from"@inquirer/select";import md from"node:process";import{z as J}from"zod";import{z as Vo}from"zod";var xn=async(e,t)=>new Promise(r=>{let n=setTimeout(()=>{r(null)},t);e.then(o=>{clearTimeout(n),r(o)},()=>{clearTimeout(n),r(null)})});var $h=2500,Th=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ch=e=>typeof e=="string"&&e.trim()!==""?e.trim():void 0,Zx=async()=>{let e=await Ro();return{regular:yn(e,"regular"),hotfix:yn(e,"hotfix")}},Qx=(e,t)=>e===null?(p.info({msg:"Tool execution form hint unavailable (timeout): release-create"}),`The "next" hint could not be computed within ${t/1e3} s \u2014 "next" still works and is resolved at execution.`):e.regular===null&&e.hotfix===null?(p.info({msg:"Tool execution form hint unavailable (no prior versions): release-create"}),'No prior version is known from origin release/v* branches or Jira, so "next" will be REFUSED \u2014 pass an explicit semver.'):`"next" resolves to ${e.regular} for a regular release or ${e.hotfix} for a hotfix (computed now from origin release/v* branches and Jira fix versions; recomputed at execution).`,ud=(e={})=>{let t=e.hintBudgetMs??$h;return{message:"Choose the release to cut. Nothing runs yet: the confirm gate follows, and the agent will show you the resolved arguments to approve.",isFormable:r=>Th(r)&&(r.releases===void 0||Array.isArray(r.releases)&&r.releases.length===0),buildRequestedSchema:async()=>{let r=await xn(Zx(),t);return Vo.object({type:Vo.enum(["regular","hotfix"]).describe('Release type. "regular" branches off dev and bumps the minor; "hotfix" branches off main and bumps the patch.'),release:Vo.string().describe(`A semver such as "1.64.0", the literal "next", or a kebab-case name such as "checkout-redesign" \u2014 no "@" here, the date has its own field. ${Qx(r,t)}`),description:Vo.string().optional().describe("Optional. Becomes the Jira fix version description and feeds the PR body. Blank means none."),releaseDate:Vo.string().optional().describe("Optional. Planned production date, yyyy-mm-dd. Becomes the Jira fix version's release date; delivery overwrites it with the actual date. On the re-run it is passed as <token>@yyyy-mm-dd inside -r.")})},toArgs:(r,n)=>{let o=typeof r.release=="string"?r.release.trim():"";if(o==="")return null;let s=r.type==="hotfix"?"hotfix":"regular",i=Ch(r.description),a=Ch(r.releaseDate),c=ci(o);return{...Th(n)?n:{},releases:[{...c,type:s,...i===void 0?{}:{description:i},...a===void 0?{}:{releaseDate:a}}]}}}};var tT='"1.2.5" or "next"',fd=(e,t)=>{try{return wl(e,t)}catch(r){throw r instanceof mr?new f(r,{operation:"resolve release version",remediation:'pass an explicit version (e.g. "1.2.5") instead of "next" when there are no prior versions'}):r instanceof su?new f(r,{operation:"validate release name",remediation:'use a kebab-case name like "checkout-redesign" (lowercase, digits, single hyphens, not a reserved word)'}):r}},rT=async(e,t)=>{let r=yn(e,t),n=r?` [${r}]`:"",o=(await I(i=>Ai({message:` Version (e.g. ${tT})${n}: `},i),{whenHeadless:"refuse"})).trim(),s=o===""?r??"":o;return s===""&&(p.error("No version provided. Exiting..."),md.exit(1)),s},nT=async()=>{let e=(await I(t=>Ai({message:' Name (kebab-case, e.g. "checkout-redesign"): '},t),{whenHeadless:"refuse"})).trim();e===""&&(p.error("No name provided. Exiting..."),md.exit(1));try{ps(e)}catch(t){let r=t instanceof Error?t.message:String(t);p.error(`${r} Exiting...`),md.exit(1)}return e},oT=async()=>(await I(e=>Ai({message:" Release date (yyyy-mm-dd, optional, press Enter to skip): ",validate:bo},e),{whenHeadless:"refuse"})).trim(),sT=async e=>{h.setInteractive();let t=null,r=[],n=async()=>(t===null&&(t=await e(),r.push(...t)),r),o=[],s=!0;for(;s;){let i=o.length+1,a=await I(m=>Ah({message:`Release #${i} \u2014 version or name?`,choices:[{name:"version (semver / next)",value:"version"},{name:"name (free-form)",value:"name"}],default:"version"},m),{whenHeadless:"refuse"}),c=await I(m=>Ah({message:`Release #${i} \u2014 select type:`,choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"},m),{whenHeadless:"refuse"}),l;if(a==="name"){let m=await nT();l=fd([{name:m,type:c}],[])[0]}else{let m=await rT(await n(),c);l=fd([{version:m,type:c}],r)[0],l.id.kind==="version"&&r.push(Ft(`v${l.id.raw}`))}let d=(await I(m=>Ai({message:" Description (optional, press Enter to skip): "},m),{whenHeadless:"refuse"})).trim(),u=await oT();o.push({...l,...d!==""?{description:d}:{},...u!==""?{releaseDate:u}:{}}),s=await I(m=>eT({message:"Add another release?",default:!1},m),{whenHeadless:"refuse"})}return o},iT=e=>{let r=[e.id.kind==="version"?`v${e.id.raw}`:e.id.name,e.type];return e.description&&r.push(e.description),e.releaseDate&&r.push(`ships ${e.releaseDate}`),r.join(" \xB7 ")},Oh=e=>{for(let t of e)h.addOption("--release",vl(t))},aT=async(e,t)=>{if(e&&e.length>0){let n=kl(e)?await t():[],o=fd(e,n);return Oh(o),o}if(ee())throw new E({status:"argument_required",argument:"release",agentMode:A.source},2,{operation:"create release",remediation:'pass "releases" explicitly, or call from a client that can render the argument form (omit "releases" and the human is asked)',stderrExcerpt:"no releases provided and no human to ask"});let r=await sT(t);return Oh(r),r},cT=e=>{if(new Set(e.map(r=>r.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"})},lT=async(e,t)=>{let r=e.map(iT).join(`
398
- - `);await W(t,`Create the following ${e.length} release(s)?
396
+ `);let s={releases:t.map(i=>({version:i.version,type:i.type,description:r.get(i.jiraKey)?.description??null,releaseDate:r.get(i.jiraKey)?.releaseDate??null,titleMismatch:i.titleMismatch})),count:t.length};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}},Il=S({name:"gh-release-list",description:"List every open release PR with its version, type (regular / hotfix), and the associated Jira fix version\u2019s description and planned release date. Read-only; sourced from GitHub and Jira.",inputSchema:{},outputSchema:{releases:Nt.array(Nt.object({version:Nt.string().describe("Release version"),type:Nt.enum(["regular","hotfix"]).describe("Release type"),description:Nt.string().nullable().describe("Jira version description"),releaseDate:Nt.string().nullable().describe("Planned release date of the Jira version (yyyy-mm-dd)"),titleMismatch:Nt.boolean().describe("The PR title names a different release type than its base branch")})).describe("List of all release branches"),count:Nt.number().describe("Number of release branches")},handler:ci});import UE from"node:process";var Dl=e=>({...e}),Nl=e=>{let{env:t,branch:r,sha:n,isClean:o,ambient:s=UE.env}=e,i={VITE_DOMAIN_ENV:t,VITE_BRANCH_NAME:r,VITE_COMMIT_HASH:o?n:`${n}-dirty`},a={},c=[];for(let[l,d]of Object.entries(s)){if(l.startsWith("VITE_")){c.push(l);continue}a[l]=d}return c.sort(),{childEnv:{...a,...i,DEPLOY_ENV:t,DEPLOY_BRANCH:r,DEPLOY_SHA:n,DEPLOY_SHA_LABEL:i.VITE_COMMIT_HASH,TURBO_TELEMETRY_DISABLED:"1"},contract:i,stripped:c}},li=e=>{let t=Object.entries(e.contract).map(([r,n])=>` ${r.padEnd(17)}= ${n}`);return e.stripped.length>0&&t.push(` stripped from shell: ${e.stripped.join(", ")}`),t.join(`
397
+ `)};import nx from"@inquirer/checkbox";import ox from"@inquirer/confirm";import sx from"@inquirer/select";import{spawn as ix}from"node:child_process";import ax from"node:process";import{z as H}from"zod";import{$ as xo}from"zx";import{$ as Eo}from"zx";var JE=async e=>{let t=Eo.quiet;Eo.quiet=!0;try{let r=`/${e}/environment`,n=await Eo`aws sts get-caller-identity --query Account --output text`,o=await Eo`aws ssm get-parameter --name ${r} --query Parameter.Value --output text`;return{accountId:n.stdout.trim(),stage:o.stdout.trim()}}catch(r){throw new f(r,{operation:"resolve the AWS account for this deploy",remediation:`check that credentials are loaded and that \`/${e}/environment\` exists in the account they point at \u2014 run \`aws sts get-caller-identity\` to see which account that is`})}finally{Eo.quiet=t}},Kg=(e,t)=>{if(t.stage!==e)throw new f(void 0,{operation:"verify the target environment",remediation:"switch AWS_PROFILE to the account for this environment, or pass the env this account is",stderrExcerpt:`you asked for "${e}", but AWS account ${t.accountId} reports "${t.stage}" \u2014 refusing to deploy to an environment you did not name`})},Hg=e=>{let{env:t,isShared:r,isClean:n}=e;if(!(!r||n))throw new f(void 0,{operation:`deploy to shared environment "${t}"`,remediation:"commit, or `git stash -u` (plain stash leaves untracked files), or deploy to a personal environment",stderrExcerpt:"the working tree has uncommitted or untracked changes and this environment is shared"})},qg=(e,t)=>{if(t.includes(e))throw new f(void 0,{operation:`deploy to "${e}"`,remediation:"wait for the CI run to finish, or watch it with `gh run watch`",stderrExcerpt:`a CI deploy to "${e}" is already in flight \u2014 running both would interleave`})},_l=async e=>{let{env:t,project:r,isShared:n,isClean:o,runningEnvs:s,protectedEnvAccess:i}=e;Sr(t,`deploy to "${t}"`,i),qg(t,s),Hg({env:t,isShared:n,isClean:o});let a=await JE(r);return Kg(t,a),{identity:a}};import Yg from"node:fs/promises";import di from"node:path";var GE="devops/scripts",KE=/^deploy-(?<service>[a-z0-9-]+)\.sh$/,HE=/skip_unless_env_enabled\s+"[^"]*"\s+"[^"]*"\s+"(?<envs>[^"]*)"/,qE=/aws\s+ssm\s+get-parameter\s+--name[=\s]+(?<arg>[^\s)]+)/,YE=/aws\s+ssm\s+get-parameter\s+--name[=\s]+["']?\/(?<prefix>[\w.-]+)\/environment["']?(?![\w./-])/,Ml=async e=>{let t=di.resolve(e,GE),r;try{r=await Yg.readdir(t)}catch{return[]}let n=await kl(e);return(await Promise.all(r.map(s=>({entry:s,match:KE.exec(s)})).filter(s=>s.match!==null).map(async({entry:s,match:i})=>{let a=di.resolve(t,s),c=i?.groups?.service??"",l=XE(await zE(a));return{name:c,scriptPath:a,allowedEnvs:bl(ZE(l),n.get(c)),ssmPrefix:ex(l)}}))).sort((s,i)=>s.name.localeCompare(i.name))},zE=async e=>{try{return await Yg.readFile(e,"utf-8")}catch{return""}},XE=e=>e.split(`
398
+ `).map((t,r)=>({line:r+1,text:t})).filter(({text:t})=>!t.trimStart().startsWith("#")),ZE=e=>{let t=e.reduce((n,{text:o})=>n??HE.exec(o)?.groups?.envs,void 0);if(t===void 0)return null;let r=t.split(/\s+/).filter(Boolean);return r.length>0?r:null},QE=e=>{let t=e.replaceAll(/["']/g,"");return t.includes("$")&&(t.includes("/environment")||t.startsWith("$"))},ex=e=>{for(let{line:t,text:r}of e){let n=YE.exec(r)?.groups?.prefix;if(n!==void 0)return n;let o=qE.exec(r)?.groups?.arg;if(o!==void 0&&QE(o))return{unparseable:{line:t,text:r.trim()}}}return null},tx=e=>{let t=new Map;for(let r of e)typeof r.ssmPrefix=="string"&&t.set(r.ssmPrefix,[...t.get(r.ssmPrefix)??[],di.basename(r.scriptPath)]);return t},rx=e=>{let t=e.flatMap(r=>{if(r.ssmPrefix===null||typeof r.ssmPrefix=="string")return[];let{line:n,text:o}=r.ssmPrefix.unparseable;return[`${di.basename(r.scriptPath)}:${n}: ${o}`]});if(t.length!==0)throw new f(void 0,{operation:"resolve the SSM project prefix",remediation:"write the parameter name as a literal `/<project>/environment` so infra-kit can preflight it",stderrExcerpt:t.join("; ")})},zg=e=>{rx(e);let t=tx(e),[r,...n]=t.keys();if(r===void 0)throw new f(void 0,{operation:"resolve the SSM project prefix",remediation:'add `aws ssm get-parameter --name "/<project>/environment"` to at least one devops/scripts/deploy-*.sh',stderrExcerpt:`none of ${e.length} deploy scripts reads /<project>/environment`});if(n.length>0){let o=[...t.entries()].sort(([,s],[,i])=>s.length-i.length).map(([s,i])=>`${s}: ${i.join(", ")}`).join("; ");throw new f(void 0,{operation:"resolve the SSM project prefix",remediation:"make every deploy script read the same /<project>/environment parameter",stderrExcerpt:`${t.size} different prefixes across ${e.length} deploy scripts \u2014 ${o}`})}return r},ui=(e,t)=>e.allowedEnvs===null||e.allowedEnvs.includes(t),jl=(e,t)=>e.filter(r=>ui(r,t));var Ll="deploy-all.yml",Zg="/bin/sh",cx=async()=>{let e=xo.quiet;xo.quiet=!0;try{let t=await xo`gh run list --workflow=${Ll} --status=in_progress --json displayTitle`;return JSON.parse(t.stdout).flatMap(n=>/\[(?<env>[a-z0-9-]+)\]/.exec(n.displayTitle??"")?.groups?.env??[])}catch{return[]}finally{xo.quiet=e}},lx=async(e,t)=>{let r=e.map(o=>({name:o.name,value:o.name})),n=await O(o=>nx({message:`Deploy which services to ${t}?`,choices:r,pageSize:20},o),{whenHeadless:{refuse:"service"}});if(n.length===0)throw new f(void 0,{operation:"select services",remediation:"pick at least one service, or use `local deploy-all`",stderrExcerpt:"no services selected"});return n},dx=async e=>{let{env:t,isShared:r,names:n,accountId:o}=e,s=n.length,i=r?`"${t}" is a SHARED environment \u2014 deploying ${s} service(s) from this machine. Continue?`:`Deploy ${s} service(s) to ${t} from this machine?`;return ge()&&is(i,{env:t,services:n,accountId:o,shared:r}),r?O(a=>sx({message:i,choices:[{name:"No, cancel",value:!1},{name:`Yes, deploy to ${t}`,value:!0}]},a),{whenHeadless:"refuse"}):O(a=>ox({message:i,default:!1},a),{whenHeadless:"refuse"})},ux=(e,t,r)=>new Promise((n,o)=>{let s=ix(Zg,[e.scriptPath],{cwd:r,env:t,stdio:"inherit"});s.on("error",o),s.on("close",i=>{n(i??1)})}),px=async e=>{let{chosen:t,childEnv:r,cwd:n,env:o}=e,s=[],i=[];for(let a of t){u.info(`\u2192 ${a.name} \u2192 ${o}`);let c=await ux(a,r,n);if(c!==0){i.push(a.name),u.error(`\u2717 ${a.name} failed (exit ${c})`);break}s.push(a.name),u.info(`\u2713 ${a.name}`)}return{deployed:s,failed:i}},mx=e=>{let{names:t,services:r,env:n}=e,o=new Map(r.map(a=>[a.name,a])),s=t.filter(a=>!o.has(a));if(s.length>0)throw new f(void 0,{operation:"resolve the requested services",remediation:`known services: ${r.map(a=>a.name).join(", ")}`,stderrExcerpt:`no deploy script for: ${s.join(", ")}`});let i=t.filter(a=>{let c=o.get(a);return c!==void 0&&!ui(c,n)});if(i.length>0)throw new f(void 0,{operation:`deploy to "${n}"`,remediation:"drop those services, or deploy them to an environment they allow",stderrExcerpt:`not enabled for "${n}": ${i.join(", ")} (the scripts would skip them)`});return t.map(a=>o.get(a))},Fl=e=>{let{env:t,accountId:r,names:n,built:o,deployed:s,failed:i,dryRun:a,success:c}=e,l={environment:t,accountId:r,services:n,deployed:s,failed:i,contract:Dl(o.contract),strippedVars:o.stripped,dryRun:a,success:c};return{content:k(JSON.stringify(l,null,2)),structuredContent:l}},fx=async e=>{let{selection:t,eligible:r,service:n,env:o}=e;return t==="all"?r.map(s=>s.name):n&&n.length>0?n:(h.setInteractive(),lx(r,o))},Qg=async(e,t)=>{let{env:r,service:n,confirmedCommand:o,dryRun:s,printEnv:i}=e,a=await E(),c=await Ml(a);if(c.length===0)throw new f(void 0,{operation:"discover deployable services",remediation:"run this from a repo that has devops/scripts/deploy-*.sh",stderrExcerpt:`no deploy scripts found under ${a}/devops/scripts`});let l=zg(c);await Ue({provider:Bl[t],params:e,operation:"deploy locally",argument:"env"});let d=await We(),p=kt(await bt(Ll),d),m=r??"";m||(h.setInteractive(),m=await cn(p,"deploy locally")),h.addOption("--env",m);let g=jl(c,m);if(g.length===0)throw new f(void 0,{operation:`deploy to "${m}"`,remediation:"pick an environment these services allow",stderrExcerpt:`no service on disk is enabled for "${m}"`});let y=await fx({selection:t,eligible:g,service:n,env:m}),R=mx({names:y,services:c,env:m});if(t==="selected")for(let Be of y)h.addOption("--service",Be);let v=Sn(m),$=await wr(),D=(await xo`git rev-parse HEAD`.quiet()).stdout.trim(),A=await Ju(),P=Nl({env:m,branch:$,sha:D,isClean:A});i&&u.info(`Deploy contract for ${m}:
399
+ ${li(P)}`);let U=(await _l({env:m,project:l,isShared:v,isClean:A,runningEnvs:await cx(),protectedEnvAccess:d})).identity.accountId;if(s)return u.info([`Would deploy to "${m}" (AWS account ${U}) from this machine`,`Preflight parameter: /${l}/environment`,li(P),"Commands:",...R.map(Be=>` ${Zg} ${Be.scriptPath}`),"","Dry run: preflight and contract only \u2014 says nothing about whether the deploy would succeed."].join(`
400
+ `)),Fl({env:m,accountId:U,names:y,built:P,deployed:[],failed:[],dryRun:!0,success:!0});if(!o&&!await dx({env:m,isShared:v,names:y,accountId:U}))return u.info("Deployment cancelled"),Fl({env:m,accountId:U,names:y,built:P,deployed:[],failed:[],dryRun:!1,success:!1});P.stripped.length>0&&u.info(`Stripped ambient VITE_* from the build env: ${P.stripped.join(", ")}`);let{deployed:ue,failed:pt}=await px({chosen:R,childEnv:P.childEnv,cwd:a,env:m});return pt.length>0&&(u.error(`Partial deploy to "${m}": succeeded [${ue.join(", ")||"none"}], failed [${pt.join(", ")}]. There is no rollback \u2014 redeploy the previous commit to restore it.`),ax.exitCode=1),h.print(),Fl({env:m,accountId:U,names:y,built:P,deployed:ue,failed:pt,dryRun:!1,success:pt.length===0})},eh=async e=>Qg(e,"all"),th=async e=>Qg(e,"selected"),rh='Runs the repo\'s own devops/scripts/deploy-*.sh on THIS machine instead of dispatching CI. Supplies the build contract (VITE_DOMAIN_ENV/BRANCH/COMMIT) that the workflow YAML normally provides and that the scripts do not set themselves, and refuses unless the requested environment matches the AWS account the shell is authenticated to. "prod" is refused by default \u2014 it is delivered, not deployed \u2014 and is reachable only if this project sets `protectedEnvs` in infra-kit.json; "cli-only" allows it in a terminal but still refuses it here. Services the environment forbids are refused, matching the workflow\'s own per-service gates. Use dryRun first.',nh={env:H.string().optional().describe('Target environment, e.g. "dev" or a personal env like "arthur". Omit it to be offered the environments this project may reach.'),dryRun:H.boolean().optional().describe("Resolve target, contract and commands without deploying."),confirm:H.boolean().optional().describe("Set true to execute; omit for a dry-run gate.")},oh={environment:H.string().describe("Environment deployed to"),accountId:H.string().describe("AWS account the deploy targeted"),services:H.array(H.string()).describe("Services requested"),deployed:H.array(H.string()).describe("Services that completed successfully"),failed:H.array(H.string()).describe("Services that failed"),contract:H.record(H.string(),H.string()).describe("Build contract passed to the scripts"),strippedVars:H.array(H.string()).describe("Ambient VITE_* names removed from the build env"),dryRun:H.boolean().describe("Whether this was a dry run"),success:H.boolean().describe("Whether every requested service deployed")},Xg=e=>cr({workflowFile:Ll,fields:["env"],toolName:e}),Bl={all:Xg("local-deploy-all"),selected:Xg("local-deploy-selected")},Vl=S({name:"local-deploy-all",description:`Deploy EVERY service enabled for an environment, from this machine. ${rh}`,requiresHumanConfirm:!0,formProvider:Bl.all,inputSchema:nh,outputSchema:oh,handler:eh}),Wl=S({name:"local-deploy-selected",description:`Deploy a NAMED SUBSET of services from this machine. ${rh}`,requiresHumanConfirm:!0,formProvider:Bl.selected,inputSchema:{...nh,service:H.array(H.string()).min(1).describe('Service names as in devops/scripts/deploy-<name>.sh, e.g. ["client-be"]. Required for MCP.')},outputSchema:oh,handler:th});import yx from"@inquirer/confirm";import pi from"@inquirer/input";import ch from"@inquirer/select";import Jl from"node:process";import{z as V}from"zod";import{z as To}from"zod";var ln=async(e,t)=>new Promise(r=>{let n=setTimeout(()=>{r(null)},t);e.then(o=>{clearTimeout(n),r(o)},()=>{clearTimeout(n),r(null)})});var ah=2500,sh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ih=e=>typeof e=="string"&&e.trim()!==""?e.trim():void 0,gx=async()=>{let e=await co();return{regular:nn(e,"regular"),hotfix:nn(e,"hotfix")}},hx=(e,t)=>e===null?(u.info({msg:"Tool execution form hint unavailable (timeout): release-create"}),`The "next" hint could not be computed within ${t/1e3} s \u2014 "next" still works and is resolved at execution.`):e.regular===null&&e.hotfix===null?(u.info({msg:"Tool execution form hint unavailable (no prior versions): release-create"}),'No prior version is known from origin release/v* branches or Jira, so "next" will be REFUSED \u2014 pass an explicit semver.'):`"next" resolves to ${e.regular} for a regular release or ${e.hotfix} for a hotfix (computed now from origin release/v* branches and Jira fix versions; recomputed at execution).`,Ul=(e={})=>{let t=e.hintBudgetMs??ah;return{message:"Choose the release to cut. Nothing runs yet: the confirm gate follows, and the agent will show you the resolved arguments to approve.",isFormable:r=>sh(r)&&(r.releases===void 0||Array.isArray(r.releases)&&r.releases.length===0),buildRequestedSchema:async()=>{let r=await ln(gx(),t);return To.object({type:To.enum(["regular","hotfix"]).describe('Release type. "regular" branches off dev and bumps the minor; "hotfix" branches off main and bumps the patch.'),release:To.string().describe(`A semver such as "1.64.0", the literal "next", or a kebab-case name such as "checkout-redesign" \u2014 no "@" here, the date has its own field. ${hx(r,t)}`),description:To.string().optional().describe("Optional. Becomes the Jira fix version description and feeds the PR body. Blank means none."),releaseDate:To.string().optional().describe("Optional. Planned production date, yyyy-mm-dd. Becomes the Jira fix version's release date; delivery overwrites it with the actual date. On the re-run it is passed as <token>@yyyy-mm-dd inside -r.")})},toArgs:(r,n)=>{let o=typeof r.release=="string"?r.release.trim():"";if(o==="")return null;let s=r.type==="hotfix"?"hotfix":"regular",i=ih(r.description),a=ih(r.releaseDate),c=Ys(o);return{...sh(n)?n:{},releases:[{...c,type:s,...i===void 0?{}:{description:i},...a===void 0?{}:{releaseDate:a}}]}}}};var vx='"1.2.5" or "next"',Gl=(e,t)=>{try{return el(e,t)}catch(r){throw r instanceof rr?new f(r,{operation:"resolve release version",remediation:'pass an explicit version (e.g. "1.2.5") instead of "next" when there are no prior versions'}):r instanceof Bu?new f(r,{operation:"validate release name",remediation:'use a kebab-case name like "checkout-redesign" (lowercase, digits, single hyphens, not a reserved word)'}):r}},wx=async(e,t)=>{let r=nn(e,t),n=r?` [${r}]`:"",o=(await O(i=>pi({message:` Version (e.g. ${vx})${n}: `},i),{whenHeadless:"refuse"})).trim(),s=o===""?r??"":o;return s===""&&(u.error("No version provided. Exiting..."),Jl.exit(1)),s},kx=async()=>{let e=(await O(t=>pi({message:' Name (kebab-case, e.g. "checkout-redesign"): '},t),{whenHeadless:"refuse"})).trim();e===""&&(u.error("No name provided. Exiting..."),Jl.exit(1));try{Zo(e)}catch(t){let r=t instanceof Error?t.message:String(t);u.error(`${r} Exiting...`),Jl.exit(1)}return e},bx=async()=>(await O(e=>pi({message:" Release date (yyyy-mm-dd, optional, press Enter to skip): ",validate:ao},e),{whenHeadless:"refuse"})).trim(),Rx=async e=>{h.setInteractive();let t=null,r=[],n=async()=>(t===null&&(t=await e(),r.push(...t)),r),o=[],s=!0;for(;s;){let i=o.length+1,a=await O(m=>ch({message:`Release #${i} \u2014 version or name?`,choices:[{name:"version (semver / next)",value:"version"},{name:"name (free-form)",value:"name"}],default:"version"},m),{whenHeadless:"refuse"}),c=await O(m=>ch({message:`Release #${i} \u2014 select type:`,choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"},m),{whenHeadless:"refuse"}),l;if(a==="name"){let m=await kx();l=Gl([{name:m,type:c}],[])[0]}else{let m=await wx(await n(),c);l=Gl([{version:m,type:c}],r)[0],l.id.kind==="version"&&r.push($t(`v${l.id.raw}`))}let d=(await O(m=>pi({message:" Description (optional, press Enter to skip): "},m),{whenHeadless:"refuse"})).trim(),p=await bx();o.push({...l,...d!==""?{description:d}:{},...p!==""?{releaseDate:p}:{}}),s=await O(m=>yx({message:"Add another release?",default:!1},m),{whenHeadless:"refuse"})}return o},Sx=e=>{let r=[e.id.kind==="version"?`v${e.id.raw}`:e.id.name,e.type];return e.description&&r.push(e.description),e.releaseDate&&r.push(`ships ${e.releaseDate}`),r.join(" \xB7 ")},lh=e=>{for(let t of e)h.addOption("--release",Qc(t))},Px=async(e,t)=>{if(e&&e.length>0){let n=tl(e)?await t():[],o=Gl(e,n);return lh(o),o}if(fe())throw new x({status:"argument_required",argument:"release",agentMode:I.source},2,{operation:"create release",remediation:'pass "releases" explicitly, or call from a client that can render the argument form (omit "releases" and the human is asked)',stderrExcerpt:"no releases provided and no human to ask"});let r=await Rx(t);return lh(r),r},Ex=e=>{if(new Set(e.map(r=>r.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"})},xx=async(e,t)=>{let r=e.map(Sx).join(`
401
+ - `);await B(t,`Create the following ${e.length} release(s)?
399
402
  - ${r}
400
- `),h.addOption("--yes",!0)},dT=async e=>{let{entry:t,jiraConfig:r}=e,n=Y(t.id),o=t.id.kind==="version"?`v${t.id.raw}`:t.id.name;try{await Jr({operation:`create release ${o}`});let s=await Dc(t.type),i=await Nc({id:t.id,jiraConfig:r,description:t.description,...t.releaseDate===void 0?{}:{releaseDate:t.releaseDate},type:t.type,baseSha:s});return p.info(`\u2705 Successfully created release: ${o} (${t.type})`),p.info(`\u{1F517} GitHub PR: ${i.prUrl}`),p.info(`\u{1F517} Jira Version: ${i.jiraVersionUrl}
401
- `),{result:i}}catch(s){let i=no(s)?s:void 0,a=new f(s,{operation:`create release ${o} (${t.type})`,remediation:i?.kind==="auth"?"reissue the Atlassian API token and update JIRA_TOKEN":"verify the version or name is unique and the base branch is clean",stderrExcerpt:i?.message});return p.error(`\u274C ${a.message}
402
- `),{failure:{version:n,error:a.message}}}},pT=(e,t,r)=>{t===e?p.info(`\u2705 All ${e} release branch(es) were created successfully.`):t>0?(p.warn(`\u26A0\uFE0F ${t} of ${e} release branches were created successfully.`),p.warn(`\u274C ${r} release(s) failed.`)):p.error(`\u274C All ${e} release branch(es) failed to create.`)},Ih=ud(),Oi=async e=>{let{releases:t,confirmedCommand:r}=e;await be({operation:"create release"}),await Ne({provider:Ih,params:e,operation:"create release",argument:"release"});let n=await Yr(),o=null,i=await aT(t,async()=>(o===null&&(o=await Ro()),o));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"});cT(i),await Zn({operation:"create release",base:Qe(i[0].type)}),await lT(i,!!r);let a=[],c=[];for(let d of i){let{result:u,failure:m}=await dT({entry:d,jiraConfig:n});u&&a.push(u),m&&c.push(m)}pT(i.length,a.length,c.length),h.print();let l={createdBranches:a.map(d=>d.branchName),successCount:a.length,failureCount:c.length,releases:a,failedReleases:c};return{content:k(JSON.stringify(l,null,2)),structuredContent:l}},gd=R({name:"release-create",requiresHumanConfirm:!0,formProvider:Ih,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. Omit "releases" and this server offers the human a form for ONE release (type, version/next/name, description); the accepted form feeds the confirm gate. A client that cannot render a form gets a gate with no releases \u2014 confirming it is refused, never guessed. Pass "releases" explicitly for a batch or when the human already named the release. Continues on per-release failure and reports successes/failures.',inputSchema:{releases:J.array(J.object({version:J.string().optional().describe('Version to create (e.g., "1.2.5") or the literal token "next" for auto-increment. Mutually exclusive with "name".'),name:J.string().optional().describe('Free-form kebab-case release name (e.g., "checkout-redesign"). Mutually exclusive with "version". Named releases never auto-bump.'),type:J.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" (branches off dev) or "hotfix" (branches off main).'),description:J.string().optional().describe("Optional description for the Jira version."),releaseDate:pl.optional().describe('Optional planned production date, yyyy-mm-dd. Written to the Jira fix version as its release date; "release deliver" overwrites it with the actual date. Rides in the CLI spec as "<token>@yyyy-mm-dd".')}).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=>{let t={...e.description?{description:e.description}:{},...e.releaseDate===void 0?{}:{releaseDate:e.releaseDate}};return e.name!==void 0?{name:e.name,type:e.type,...t}:{version:e.version,type:e.type,...t}})).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. Optional over MCP: omit it to have the human fill one release from a form.').optional(),confirm:J.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{createdBranches:J.array(J.string()).describe("List of created release branch names"),successCount:J.number().describe("Number of releases created successfully"),failureCount:J.number().describe("Number of releases that failed"),releases:J.array(J.object({version:J.string().describe("Version number"),type:J.enum(["regular","hotfix"]).describe("Release type"),branchName:J.string().describe("Release branch name"),prUrl:J.string().describe("GitHub PR URL"),jiraVersionUrl:J.string().describe("Jira version URL"),releaseDate:J.string().nullable().describe("The release date the Jira fix version now carries (yyyy-mm-dd), or null when it has none")})).describe("Detailed information for each created release with URLs"),failedReleases:J.array(J.object({version:J.string().describe("Version number that failed"),error:J.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:Oi});import Dh from"@inquirer/input";import{z as Me}from"zod";var Nh=["description","releaseDate"],uT=async()=>{let e=await F(),t=e.map(s=>s.branch),r=new Map(e.map(s=>[s.branch,s.type])),n=await oe(),o=await Dt(se({branches:t,descriptions:n,types:r}));return{branch:o,type:r.get(o)||"regular"}},mT=async e=>{let r=(await F()).find(n=>n.branch===e);if(!r)throw new f(void 0,{operation:`edit release ${e}`,remediation:`confirm an open PR exists for ${e} ('gh pr list')`});return r.type},fT=async e=>{let t=e===""?"(no current description)":`current: "${e}"`,n=(await I(o=>Dh({message:` New description ${t} (press Enter to keep current): `},o),{whenHeadless:{refuse:"description"}})).trim();return n===""?e:n},gT=async e=>{let t=e===null?"(no current date)":`current: ${e}`,n=(await I(o=>Dh({message:` Release date yyyy-mm-dd ${t} (press Enter to keep current): `,validate:bo},o),{whenHeadless:{refuse:"releaseDate"}})).trim();return n===""?e:ur(n)},hT=e=>{if(e!==void 0)return e===""?null:e},yT=async e=>(h.setInteractive(),{description:await fT(e.description),releaseDate:await gT(e.releaseDate)}),hd=e=>e??"(none)",vT=(e,t,r)=>e==="description"?` description: "${t.description}" \u2192 "${r.description}"`:` release date: ${hd(t.releaseDate)} \u2192 ${hd(r.releaseDate)}`,Ii=async e=>{let{version:t,description:r,releaseDate:n,confirmedCommand:o}=e,s=hT(n),i=await Yr(),a;t?(a=ft(t),await mT(a)):(h.setInteractive(),a=(await uT()).branch);let c=K(a);if(!c)throw new f(void 0,{operation:`edit release ${a}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let l=Y(c);h.addOption("--version",l);let d=ne(c),u=await ut(d,i);if(!u)throw new f(void 0,{operation:`edit release ${d}`,remediation:`create the Jira fix version "${d}" first or pick a different release`});let m={description:u.description??"",releaseDate:u.releaseDate||null},g=r!==void 0||s!==void 0;if(!g&&ie())throw new E({status:"argument_required",argument:"description",agentMode:A.source},2,{operation:"edit release",remediation:"pass --description and/or --release-date on the re-run",stderrExcerpt:"no field to edit and no human to ask"});let y=g?{description:r??m.description,releaseDate:s===void 0?m.releaseDate:s}:await yT(m),S=Nh.filter(G=>y[G]!==m[G]),v=S.includes("description"),C=S.includes("releaseDate"),_=rr(i,u),O=G=>{let B={version:l,branch:a,jiraVersionUrl:_,previousDescription:m.description,newDescription:y.description,previousReleaseDate:m.releaseDate,newReleaseDate:y.releaseDate,changedFields:S,changed:G};return{content:k(JSON.stringify(B,null,2)),structuredContent:B}};if(S.length===0)return p.info(`No change \u2014 ${d} already has description "${m.description}" and release date ${hd(m.releaseDate)}`),h.print(),O(!1);v&&h.addOption("--description",y.description),C&&h.addOption("--release-date",y.releaseDate??"");let P=S.map(G=>vT(G,m,y));return await W(o,`Update ${d}?
403
+ `),h.addOption("--yes",!0)},Tx=async e=>{let{entry:t,jiraConfig:r}=e,n=Y(t.id),o=t.id.kind==="version"?`v${t.id.raw}`:t.id.name;try{await _r({operation:`create release ${o}`});let s=await vc(t.type),i=await wc({id:t.id,jiraConfig:r,description:t.description,...t.releaseDate===void 0?{}:{releaseDate:t.releaseDate},type:t.type,baseSha:s});return u.info(`\u2705 Successfully created release: ${o} (${t.type})`),u.info(`\u{1F517} GitHub PR: ${i.prUrl}`),u.info(`\u{1F517} Jira Version: ${i.jiraVersionUrl}
404
+ `),{result:i}}catch(s){let i=Kn(s)?s:void 0,a=new f(s,{operation:`create release ${o} (${t.type})`,remediation:i?.kind==="auth"?"reissue the Atlassian API token and update JIRA_TOKEN":"verify the version or name is unique and the base branch is clean",stderrExcerpt:i?.message});return u.error(`\u274C ${a.message}
405
+ `),{failure:{version:n,error:a.message}}}},Cx=(e,t,r)=>{t===e?u.info(`\u2705 All ${e} release branch(es) were created successfully.`):t>0?(u.warn(`\u26A0\uFE0F ${t} of ${e} release branches were created successfully.`),u.warn(`\u274C ${r} release(s) failed.`)):u.error(`\u274C All ${e} release branch(es) failed to create.`)},dh=Ul(),mi=async e=>{let{releases:t,confirmedCommand:r}=e;await be({operation:"create release"}),await Ue({provider:dh,params:e,operation:"create release",argument:"release"});let n=await Wr(),o=null,i=await Px(t,async()=>(o===null&&(o=await co()),o));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"});Ex(i),await Vn({operation:"create release",base:Ye(i[0].type)}),await xx(i,!!r);let a=[],c=[];for(let d of i){let{result:p,failure:m}=await Tx({entry:d,jiraConfig:n});p&&a.push(p),m&&c.push(m)}Cx(i.length,a.length,c.length),h.print();let l={createdBranches:a.map(d=>d.branchName),successCount:a.length,failureCount:c.length,releases:a,failedReleases:c};return{content:k(JSON.stringify(l,null,2)),structuredContent:l}},Kl=S({name:"release-create",requiresHumanConfirm:!0,formProvider:dh,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. Omit "releases" and this server offers the human a form for ONE release (type, version/next/name, description); the accepted form feeds the confirm gate. A client that cannot render a form gets a gate with no releases \u2014 confirming it is refused, never guessed. Pass "releases" explicitly for a batch or when the human already named the release. Continues on per-release failure and reports successes/failures.',inputSchema:{releases:V.array(V.object({version:V.string().optional().describe('Version to create (e.g., "1.2.5") or the literal token "next" for auto-increment. Mutually exclusive with "name".'),name:V.string().optional().describe('Free-form kebab-case release name (e.g., "checkout-redesign"). Mutually exclusive with "version". Named releases never auto-bump.'),type:V.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" (branches off dev) or "hotfix" (branches off main).'),description:V.string().optional().describe("Optional description for the Jira version."),releaseDate:Kc.optional().describe('Optional planned production date, yyyy-mm-dd. Written to the Jira fix version as its release date; "release deliver" overwrites it with the actual date. Rides in the CLI spec as "<token>@yyyy-mm-dd".')}).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=>{let t={...e.description?{description:e.description}:{},...e.releaseDate===void 0?{}:{releaseDate:e.releaseDate}};return e.name!==void 0?{name:e.name,type:e.type,...t}:{version:e.version,type:e.type,...t}})).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. Optional over MCP: omit it to have the human fill one release from a form.').optional(),confirm:V.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{createdBranches:V.array(V.string()).describe("List of created release branch names"),successCount:V.number().describe("Number of releases created successfully"),failureCount:V.number().describe("Number of releases that failed"),releases:V.array(V.object({version:V.string().describe("Version number"),type:V.enum(["regular","hotfix"]).describe("Release type"),branchName:V.string().describe("Release branch name"),prUrl:V.string().describe("GitHub PR URL"),jiraVersionUrl:V.string().describe("Jira version URL"),releaseDate:V.string().nullable().describe("The release date the Jira fix version now carries (yyyy-mm-dd), or null when it has none")})).describe("Detailed information for each created release with URLs"),failedReleases:V.array(V.object({version:V.string().describe("Version number that failed"),error:V.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:mi});import uh from"@inquirer/input";import{z as Ne}from"zod";var ph=["description","releaseDate"],$x=async()=>{let e=await F(),t=e.map(s=>s.branch),r=new Map(e.map(s=>[s.branch,s.type])),n=await ne(),o=await Et(oe({branches:t,descriptions:n,types:r}));return{branch:o,type:r.get(o)||"regular"}},Ax=async e=>{let r=(await F()).find(n=>n.branch===e);if(!r)throw new f(void 0,{operation:`edit release ${e}`,remediation:`confirm an open PR exists for ${e} ('gh pr list')`});return r.type},Ox=async e=>{let t=e===""?"(no current description)":`current: "${e}"`,n=(await O(o=>uh({message:` New description ${t} (press Enter to keep current): `},o),{whenHeadless:{refuse:"description"}})).trim();return n===""?e:n},Ix=async e=>{let t=e===null?"(no current date)":`current: ${e}`,n=(await O(o=>uh({message:` Release date yyyy-mm-dd ${t} (press Enter to keep current): `,validate:ao},o),{whenHeadless:{refuse:"releaseDate"}})).trim();return n===""?e:tr(n)},Dx=e=>{if(e!==void 0)return e===""?null:e},Nx=async e=>(h.setInteractive(),{description:await Ox(e.description),releaseDate:await Ix(e.releaseDate)}),Hl=e=>e??"(none)",_x=(e,t,r)=>e==="description"?` description: "${t.description}" \u2192 "${r.description}"`:` release date: ${Hl(t.releaseDate)} \u2192 ${Hl(r.releaseDate)}`,fi=async e=>{let{version:t,description:r,releaseDate:n,confirmedCommand:o}=e,s=Dx(n),i=await Wr(),a;t?(a=ct(t),await Ax(a)):(h.setInteractive(),a=(await $x()).branch);let c=J(a);if(!c)throw new f(void 0,{operation:`edit release ${a}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let l=Y(c);h.addOption("--version",l);let d=te(c),p=await it(d,i);if(!p)throw new f(void 0,{operation:`edit release ${d}`,remediation:`create the Jira fix version "${d}" first or pick a different release`});let m={description:p.description??"",releaseDate:p.releaseDate||null},g=r!==void 0||s!==void 0;if(!g&&ge())throw new x({status:"argument_required",argument:"description",agentMode:I.source},2,{operation:"edit release",remediation:"pass --description and/or --release-date on the re-run",stderrExcerpt:"no field to edit and no human to ask"});let y=g?{description:r??m.description,releaseDate:s===void 0?m.releaseDate:s}:await Nx(m),R=ph.filter(q=>y[q]!==m[q]),v=R.includes("description"),$=R.includes("releaseDate"),D=Yt(i,p),A=q=>{let U={version:l,branch:a,jiraVersionUrl:D,previousDescription:m.description,newDescription:y.description,previousReleaseDate:m.releaseDate,newReleaseDate:y.releaseDate,changedFields:R,changed:q};return{content:k(JSON.stringify(U,null,2)),structuredContent:U}};if(R.length===0)return u.info(`No change \u2014 ${d} already has description "${m.description}" and release date ${Hl(m.releaseDate)}`),h.print(),A(!1);v&&h.addOption("--description",y.description),$&&h.addOption("--release-date",y.releaseDate??"");let P=R.map(q=>_x(q,m,y));return await B(o,`Update ${d}?
403
406
  ${P.join(`
404
407
  `)}
405
- `),h.addOption("--yes",!0),await zr({versionId:u.id,...v?{description:y.description}:{},...C?{releaseDate:y.releaseDate}:{}},i),v&&await Ls({branch:a,body:ro(_,y.description)}),p.info(`\u2705 Updated ${S.join(" and ")} for ${d}`),p.info(`\u{1F517} Jira Version: ${_}`),p.info(`\u{1F517} PR branch: ${a}
406
- `),h.print(),O(!0)},yd=R({name:"release-edit",description:"Edit a release's description and/or planned release date in Jira; a changed description is mirrored into the 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. `version` and at least one of `description`/`releaseDate` are required for MCP calls (the picker and prompts are unreachable without a TTY). Empty string clears a field. Confirmation is auto-skipped for MCP, so the caller is responsible for gating.",inputSchema:{version:Me.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:Me.string().optional().describe("New description. Empty string clears the description."),releaseDate:ul.optional().describe("New planned release date (yyyy-mm-dd). Empty string clears the date.")},outputSchema:{version:Me.string().describe("Release version"),branch:Me.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:Me.string().describe("Jira fix version URL"),previousDescription:Me.string().describe("The description before the update"),newDescription:Me.string().describe("The description after the update"),previousReleaseDate:Me.string().nullable().describe("The planned release date before the update, or null"),newReleaseDate:Me.string().nullable().describe("The planned release date after the update, or null"),changedFields:Me.array(Me.enum(Nh)).describe("The fields whose value actually changed"),changed:Me.boolean().describe("Whether anything actually changed")},handler:Ii});import{z as M}from"zod";import{$ as Sd}from"zx";import _h from"node:fs/promises";import Di from"node:path";var vd=async e=>{let{workspacePath:t,folderPaths:r}=e,n=Di.dirname(t),o;try{o=await _h.readFile(t,"utf-8")}catch(d){throw new Error(`Cursor workspace file not found at ${t}: ${d.message}`)}let s;try{s=JSON.parse(o)}catch(d){throw new Error(`Failed to parse ${t} as JSON. Comments (JSONC) are not supported. ${d.message}`)}let i=s.folders??[],a=new Set(i.map(d=>Di.resolve(n,d.path))),c=[],l=[];for(let d of r){let u=Di.resolve(d);if(a.has(u)){l.push(d);continue}let m=Di.relative(n,u);i.push({path:m}),a.add(u),c.push(d)}return s.folders=i,await _h.writeFile(t,`${JSON.stringify(s,null,2)}
407
- `,"utf-8"),{added:c,skipped:l}};import{$ as wT}from"zx";var wd=async e=>{await wT`cursor ${e}`};import Mh from"node:fs/promises";import Ni from"node:path";var kd=async e=>{let{workspacePath:t,folderPaths:r}=e,n=Ni.dirname(t),o;try{o=await Mh.readFile(t,"utf-8")}catch(m){throw new Error(`Cursor workspace file not found at ${t}: ${m.message}`)}let s;try{s=JSON.parse(o)}catch(m){throw new Error(`Failed to parse ${t} as JSON. Comments (JSONC) are not supported. ${m.message}`)}let i=s.folders??[],a=new Set(r.map(m=>Ni.resolve(m))),c=new Set,l=i.filter(m=>{let g=Ni.resolve(n,m.path);return a.has(g)?(c.add(g),!1):!0});s.folders=l,await Mh.writeFile(t,`${JSON.stringify(s,null,2)}
408
- `,"utf-8");let d=[],u=[];for(let m of r){let g=Ni.resolve(m);c.has(g)?d.push(m):u.push(m)}return{removed:d,notFound:u}};import jh from"node:path";var Bo=(e,t)=>jh.isAbsolute(e)?e:jh.resolve(t,e);var bd=async e=>{let{projectRoot:t,worktreeDir:r,branches:n}=e,o=await D(),s=Tt(o),i=n.map(c=>`${r}/${c}`),a=[];for(let c of s)a.push(await kT({ide:c,projectRoot:t,folderPaths:i}));return a},kT=async e=>{let{ide:t,projectRoot:r,folderPaths:n}=e;if(!t.config.workspaceConfigPath)return p.warn("\u26A0\uFE0F Skipping Cursor: ide.config.workspaceConfigPath is not set in infra-kit config"),{ran:!1,provider:"cursor",added:0,skipped:0};let o=Bo(t.config.workspaceConfigPath,r),{added:s,skipped:i}=await vd({workspacePath:o,folderPaths:n}),a=i.length>0?` (${i.length} already present)`:"";return p.info(`\u2705 Added ${s.length} folder(s) to ${o}${a}`),await wd(o),{ran:!0,provider:"cursor",added:s.length,skipped:i.length}};var kr=async e=>{let{projectRoot:t,worktreeDir:r,removedWorktrees:n}=e;if(n.length===0)return[];let o=await D(),s=Tt(o),i=n.map(c=>`${r}/${c}`),a=[];for(let c of s)a.push(await bT({ide:c,projectRoot:t,folderPaths:i}));return a},bT=async e=>{let{ide:t,projectRoot:r,folderPaths:n}=e;if(!t.config.workspaceConfigPath)return{provider:"cursor",supported:!0,removed:[]};let o=Bo(t.config.workspaceConfigPath,r);try{let{removed:s}=await kd({workspacePath:o,folderPaths:n});return s.length>0&&p.info(`\u2705 Removed ${s.length} folder(s) from ${o}`),{provider:"cursor",supported:!0,removed:s}}catch(s){return p.warn({error:s},`\u26A0\uFE0F Failed to update Cursor workspace at ${o}`),{provider:"cursor",supported:!0,removed:[]}}};var br=["workspace","none"];import{z as Fh}from"zod";var Bh=2500,_i="release-remove",Lh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),RT=e=>e.version===void 0||e.version==="",ST=async()=>{try{return{outcome:"listed",prs:await F()}}catch(e){return e instanceof f&&e.operation===eo?{outcome:"empty"}:{outcome:"failed"}}},Vh=(e,t)=>(e===null?p.info({msg:`Tool execution form enumeration timed out (gh pr list, ${t/1e3} s): ${_i}`}):e.outcome==="failed"?p.info({msg:`Tool execution form enumeration failed (gh pr list): ${_i}`}):p.info({msg:`Tool execution form options empty (open release PRs): ${_i}`}),null),PT=(e,t)=>{let r=new Map(e.map(n=>[n.branch,n.type]));return Js(e.map(n=>n.branch)).map(({branch:n,id:o,label:s})=>{let i=t?.get(ne(o)),a=i===void 0?"":` \u2014 ${i}`;return{label:s,prose:`${s} [${r.get(n)??"regular"}]${a}`}})},ET=(e,t,r)=>{let n=e.map(o=>o.prose).join("; ");return t!==null?`Open release PRs right now: ${n}. `:(p.info({msg:`Tool execution form descriptions unavailable (timeout): ${_i}`}),`Open release PRs right now: ${n}. Jira descriptions could not be fetched within ${r/1e3} s. `)},Rd=(e={})=>{let t=e.fetchBudgetMs??Bh;return{message:"Choose the release to remove. Nothing runs yet: the confirm gate follows, and the agent will show you the resolved arguments to approve.",isFormable:r=>Lh(r)&&RT(r),buildRequestedSchema:async()=>{let[r,n]=await Promise.all([xn(ST(),t),xn(oe(),t)]);if(r===null||r.outcome!=="listed")return Vh(r,t);let o=PT(r.prs,n);return o.length===0?Vh({outcome:"empty"},t):Fh.object({version:Fh.enum(o.map(s=>s.label)).describe(`The ONE release to tear down. ${ET(o,n,t)}Nothing runs yet: the confirm gate follows, and the agent will show you the resolved arguments to approve. Removal deletes the worktree, closes the PR, deletes both branches AND removes the Jira fix version \u2014 the last is irreversible.`)})},toArgs:(r,n)=>typeof r.version!="string"?null:{...Lh(n)?n:{},version:r.version}}};var Wh=["worktree","ide-folders","pr","local-branch","remote-branch","jira"],ji={worktree:"remove the worktree","ide-folders":"strip the worktree from configured editors",pr:"close the PR","local-branch":"delete the local branch","remote-branch":"delete the remote branch",jira:"remove the Jira fix version"},Rr="remove a release",Ue=e=>{throw p.warn({operation:e.operation},`\u26D4 ${e.stderrExcerpt??e.operation}`),new f(void 0,e)},Jh=(e,t)=>{throw p.warn({operation:t.operation},`\u26D4 ${t.stderrExcerpt??t.operation}`),new E({...e,agentMode:A.source},2,t)},xT=e=>{ee()&&(e.version||Jh({status:"argument_required",argument:"version"},{operation:Rr,remediation:"pass --version <ref> (a release version or name) on the re-run \u2014 `infra-kit release list --json` lists the candidates",stderrExcerpt:"release remove reached the handler without --version under agent mode"}),e.skipJira&&Jh({status:"refused"},{operation:Rr,remediation:"drop --skip-jira \u2014 under agent mode the fix version is checked and removed with the release; to keep it, ask a human to run `infra-kit release remove --skip-jira` from their own terminal",stderrExcerpt:"--skip-jira is not permitted under agent mode: it would tear down the branch and PR and leave a live Jira fix version behind with nothing in the result pointing at it"}))},Gh=e=>{e.pr?.state==="MERGED"&&Ue({operation:`remove release ${e.label}`,remediation:`this release has shipped \u2014 removing it would delete the branch recording the merge and strip its Jira fix version from delivered work. To undo a delivery, revert the merge commit on ${e.baseBranch} and cut a new release.`,stderrExcerpt:`PR #${e.pr.number} for ${e.branch} is MERGED`})},TT=(e,t)=>{if(t.skipJira||(e.jiraConfig||Ue({operation:`remove release ${e.label}`,remediation:"set JIRA_BASE_URL / JIRA_TOKEN / JIRA_PROJECT_ID / JIRA_EMAIL, or pass --skip-jira to tear down the branch and PR and leave any fix version alone",stderrExcerpt:"Jira is not configured, so a fix version for this release cannot be checked or removed"}),!e.jira))return;let{version:r,fixCount:n,affectsCount:o}=e.jira;(r.released||r.archived)&&Ue({operation:`remove Jira fix version "${r.name}"`,remediation:"un-release it in Jira first, or remove the release without it via --skip-jira",stderrExcerpt:`fix version "${r.name}" is already ${r.released?"released":"archived"}`}),!(n===0&&o===0)&&(e.moveIssuesTo||Ue({operation:`remove Jira fix version "${r.name}"`,remediation:"deleting it would clear both fields on those issues with no way to restore them \u2014 pass --move-issues-to <version> to reassign both, or clear the version from the issues in Jira first",stderrExcerpt:`${r.name} is set as fixVersion on ${n} issue(s) and as affectsVersion on ${o} issue(s)`}))},CT=e=>{if(e.worktreePresent||e.pr!==null||e.localTipSha!==null||e.remoteTipSha!==null||e.jira)return;Ue({operation:`remove release ${e.label}`,remediation:`nothing named "${e.label}" exists to remove \u2014 check the spelling against \`infra-kit release list\`. (A release this command already removed keeps a CLOSED PR, so a genuine re-run is not affected.)`,stderrExcerpt:"found no worktree, no PR (any state), no local or remote branch, and no Jira fix version"})},$T=e=>{!e.worktreeDirty||e.worktreeDirty.length===0||Ue({operation:`remove release ${e.label}`,remediation:`commit or discard those changes (\`git -C ${e.worktreePath} stash -u\`), then re-run`,stderrExcerpt:`the worktree at ${e.worktreePath} has uncommitted changes: ${e.worktreeDirty.slice(0,4).join(", ")}`})},AT=async e=>(await Sd`git -C ${e} status --porcelain`).stdout.split(`
409
- `).map(r=>r.trimEnd()).filter(r=>r.length>0),OT=async e=>{try{let{terminals:t}=await Fu(e);return t.filter(r=>r.connected).length}catch(t){return p.debug({error:t,worktreePath:e},"release remove: orca terminal probe failed"),0}},IT=async e=>{let t=await Rs([e]);if(t!==null)throw p.warn({operation:Rr},`\u26D4 this command runs inside an Orca terminal of ${t}`),new E({status:"refused",reason:"orca_caller_inside_target",agentMode:A.source},2,{operation:Rr,remediation:`re-run from a terminal that is not an Orca pane of ${t} (a non-Orca terminal, or another worktree's row)`,stderrExcerpt:`this command runs inside an Orca terminal of ${t}, which the removal would close`})},DT=async(e,t)=>{let r={jiraConfig:null,jira:null,moveIssuesTo:null};if(t.skipJira)return r;let n=await mt();if(!n)return r;let o=await ut(ne(e),n),s=t.moveIssuesTo?await NT(t.moveIssuesTo,n):null;if(!o)return{jiraConfig:n,jira:null,moveIssuesTo:s};let i=await Bs(o.id,n);return{jiraConfig:n,moveIssuesTo:s,jira:{version:o,fixCount:i.issuesFixedCount,affectsCount:i.issuesAffectedCount,url:rr(n,o)}}},NT=async(e,t)=>{let r=await ut(e,t);return r||Ue({operation:`reassign issues to Jira fix version "${e}"`,remediation:'name an existing fix version exactly as it appears in Jira (e.g. "v1.2.6")',stderrExcerpt:`no Jira fix version named "${e}"`})},_T=async(e,t)=>{let r=K(e);r||Ue({operation:`remove release ${e}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")',stderrExcerpt:`"${e}" is not a release branch`});let n=await x(),o=`${n}${ge}`,s=`${o}/${e}`,[i,a,c,l]=await Promise.all([Ce("release"),Gr(e),$e(n,`refs/heads/${e}`),Or(n,e)]),d=i.includes(e);return d&&await IT(s),{...await DT(r,t),branch:e,id:r,label:Y(r),baseBranch:a?.baseRefName??Qe("regular"),projectRoot:n,worktreeDir:o,worktreePath:s,worktreePresent:d,orcaTerminalCount:d?await OT(s):0,worktreeDirty:d?await AT(s):null,localTipSha:c,remoteTipSha:l,pr:a}},Uh=e=>({branch:e.branch,label:e.label,baseBranch:e.baseBranch,worktreePath:e.worktreePath,worktreePresent:e.worktreePresent,worktreeDirty:e.worktreeDirty,orcaTerminalCount:e.orcaTerminalCount,localTipSha:e.localTipSha,remoteTipSha:e.remoteTipSha,pr:e.pr,jiraConfigured:e.jiraConfig!==null,jiraVersion:e.jira?{id:e.jira.version.id,name:e.jira.version.name}:null,jiraFixCount:e.jira?.fixCount??null,jiraAffectsCount:e.jira?.affectsCount??null,moveIssuesTo:e.moveIssuesTo?{id:e.moveIssuesTo.id,name:e.moveIssuesTo.name}:null}),MT=(e,t)=>{if(t)return"skipped (--skip-jira)";if(!e.jiraConfig)return"skipped (Jira not configured)";if(!e.jira)return"none found";let{version:r,fixCount:n,affectsCount:o}=e.jira,s=`fixVersion on ${n} issue(s), affectsVersion on ${o} issue(s)`,i=e.moveIssuesTo?`, reassigned to ${e.moveIssuesTo.name}`:"";return`${r.name} \u2014 ${s}${i}`},jT=(e,t)=>{let r=e.pr?`#${e.pr.number} (${e.pr.state})`:"none",n=[`Remove release ${e.label} (${e.branch})? This will:`,` \u2022 worktree: ${e.worktreePresent?e.worktreePath:"none"}`,` \u2022 PR: ${r}`,` \u2022 local branch: ${e.localTipSha??"absent"} (switching to ${e.baseBranch} first)`,` \u2022 remote branch: ${e.remoteTipSha??"absent"}`,` \u2022 Jira version: ${MT(e,t)}`];return e.orcaTerminalCount>0&&n.push(` \u2022 ${e.orcaTerminalCount} Orca terminal(s) in ${e.worktreePath} will be closed`),n.join(`
410
- `)},Mi=class extends Error{constructor(r,n){super(`step ${r} failed`,{cause:n});this.step=r;this.reason=n;this.name="StepFailure"}step;reason},FT=e=>typeof e=="string"?e:e.outcome;async function Wo(e,t,r){try{let n=await r(),o=FT(n);return t.push({step:e}),p.info({step:e,outcome:o},`\u2705 ${ji[e]} \u2014 ${o}`),n}catch(n){throw new Mi(e,n)}}var LT=async(e,t,r)=>{try{await r(),t.push({step:e})}catch(n){t.push({step:e,detail:"attempted"}),p.warn({err:Wt(n),step:e},`\u26A0\uFE0F ${ji[e]} failed (non-blocking)`)}},VT=(e,t)=>t.step==="local-branch"&&e.localTipSha?`local-branch (was ${e.localTipSha.slice(0,7)})`:t.detail?`${t.step} (${t.detail})`:t.step,BT=e=>{let{plan:t,step:r,done:n,cause:o}=e,s=n.map(u=>VT(t,u)).join(", ")||"nothing",i=t.jira?`The Jira fix version ${t.jira.version.name} was NOT removed. `:"",a=t.localTipSha?`Restore the branch with \`git branch ${t.branch} ${t.localTipSha}\`. `:"",c=`Re-run \`infra-kit release remove --version ${t.label}\` to finish; completed steps are skipped.`,l=`completed: ${s}. ${i}${a}${c}`,d=o instanceof f?o.remediation:void 0;return new f(o,{operation:`remove release ${t.label} \u2014 step ${Wh.indexOf(r)+1} of ${Wh.length} (${ji[r]})`,remediation:d?`${d} \u2014 ${l}`:l})},WT=async e=>{let t=await Oo(e.branch,{operation:`remove the worktree for ${e.branch}`,remediation:`commit or discard the changes inside ${e.worktreePath} (\`git -C ${e.worktreePath} stash -u\`), then re-run`});return{outcome:t.includes(e.branch)?"removed":"absent",removedBranches:t}},JT=e=>{let t=e.map(s=>({provider:s.provider,outcome:UT(s),removed:s.removed})),r=t.some(s=>s.outcome==="verified"),o=t.some(s=>s.outcome==="attempted")?"attempted":"skipped";return{outcome:r?"verified":o,providers:t}},UT=e=>e.removed.length>0?"verified":"attempted",GT=async(e,t,r)=>{let n={outcome:"attempted",providers:[]};return await LT("ide-folders",r,async()=>{let o=await kr({projectRoot:e.projectRoot,worktreeDir:e.worktreeDir,removedWorktrees:t});n=JT(o)}),p.info({outcome:n.outcome,step:"ide-folders"},`\u2705 ${ji["ide-folders"]} \u2014 ${n.outcome}`),n},KT=async e=>{let t=await Gr(e.branch);if(Gh({...e,pr:t}),!t)return{outcome:"absent",number:null};if(t.state==="CLOSED")return{outcome:"already-closed",number:t.number};let r=`Closed by \`infra-kit release remove\`: release ${e.label} was torn down.`;return await Sd`gh pr close ${String(t.number)} --comment ${r}`,{outcome:"closed",number:t.number}},HT=async e=>(await Ar()===e.branch&&await Sd`git switch ${e.baseBranch}`,await ms(e.branch),await pu(e.branch)?Ue({operation:`delete local branch ${e.branch}`,remediation:`delete it by hand with \`git branch -D ${e.branch}\`, then re-run to finish the removal`,stderrExcerpt:`${e.branch} still exists after the delete`}):e.localTipSha?"deleted":"absent"),qT=async e=>(await fs(e.branch),e.remoteTipSha?"deleted":"absent"),zT=async(e,t,r)=>{let n=await Bs(t.version.id,r);if(n.issuesFixedCount===t.fixCount&&n.issuesAffectedCount===t.affectsCount)return;let o=`re-run \`infra-kit release remove --version ${e.label}\``;Ue({operation:`remove Jira fix version "${t.version.name}"`,remediation:`the fix version was NOT removed and every other step is complete \u2014 ${o} so the guard re-evaluates the new counts`,stderrExcerpt:`issue counts changed since preflight: fixVersion ${t.fixCount} \u2192 ${n.issuesFixedCount}, affectsVersion ${t.affectsCount} \u2192 ${n.issuesAffectedCount}`})},YT=async(e,t)=>t.skipJira?"skipped":!e.jira||!e.jiraConfig?"absent":(await zT(e,e.jira,e.jiraConfig),p.info({jiraVersionId:e.jira.version.id,jiraVersionName:e.jira.version.name},"\u{1F5D1}\uFE0F removing Jira fix version"),await Ic({versionId:e.jira.version.id,moveFixIssuesTo:e.moveIssuesTo?.id,moveAffectedIssuesTo:e.moveIssuesTo?.id},e.jiraConfig),"removed"),XT=(e,t)=>({branch:e.branch,version:e.label,baseBranch:e.baseBranch,worktree:t.worktree.outcome,ideFolders:t.ideFolders,pr:t.pr.outcome,prNumber:t.pr.number,localBranch:t.localBranch,localTipSha:e.localTipSha,remoteBranch:t.remoteBranch,remoteTipSha:e.remoteTipSha,jira:t.jira,jiraVersion:e.jira?{id:e.jira.version.id,name:e.jira.version.name,url:e.jira.url}:null}),ZT=async(e,t,r)=>{let n=await Wo("worktree",r,()=>WT(e)),o=await GT(e,n.removedBranches,r),s=await Wo("pr",r,()=>KT(e));p.info({branch:e.branch,localTipSha:e.localTipSha,remoteTipSha:e.remoteTipSha},"\u{1F516} branch tips before deletion");let i=await Wo("local-branch",r,()=>HT(e)),a=await Wo("remote-branch",r,()=>qT(e)),c=await Wo("jira",r,()=>YT(e,t));return{worktree:n,ideFolders:o,pr:s,localBranch:i,remoteBranch:a,jira:c}},QT=async(e,t)=>{let r=[];try{return XT(e,await ZT(e,t,r))}catch(n){throw n instanceof Mi?BT({plan:e,step:n.step,done:r,cause:n.reason}):n}},eC=async e=>{if(e)return ft(e);h.setInteractive();let[t,r]=await Promise.all([oe(),F()]),n=r.map(s=>s.branch);n.length===0&&Ue({operation:"select a release to remove",remediation:"pass `--version <ref>` to remove a release that is already partially torn down",stderrExcerpt:"no open release PRs to pick from"});let o=new Map(r.map(s=>[s.branch,s.type]));try{return await Dt(se({branches:n,descriptions:t,types:o}))}catch(s){throw we(s)?s:new f(s,{operation:"select a release to remove",remediation:"pass `--version <ref>` (e.g. `--version 1.2.5`); the picker needs an interactive terminal"})}},Kh=Rd(),Fi=async e=>{let{confirmedCommand:t,version:r,moveIssuesTo:n,skipJira:o}=e;await be({operation:Rr}),await D(),await Ne({provider:Kh,params:e,operation:Rr,argument:"version"}),xT(e);try{let s=await _T(await eC(r),e);p.debug({plan:Uh(s)},"release remove: resolved plan"),Gh(s),TT(s,e),CT(s),await Zn({operation:`remove release ${s.label}`,base:s.baseBranch}),$T(s),h.addOption("--version",s.label),n&&h.addOption("--move-issues-to",n),o&&h.addOption("--skip-jira",!0),await W(t,jT(s,!!o),{throwOnDecline:!0,plan:{...Uh(s),skipJira:!!o}}),t||h.addOption("--yes",!0);let i=await QT(s,e);return h.print(),{content:k(JSON.stringify(i,null,2)),structuredContent:i}}catch(s){throw we(s)||ct(s)||s instanceof f?s:(p.error({err:Wt(s)},"\u274C Error removing release"),new f(s,{operation:Rr,remediation:"check `gh auth status`, `git worktree list` and the Jira credentials, then re-run"}))}},Pd=R({name:"release-remove",description:'Tear down ONE release created by release-create: removes its git worktree (closing every Orca terminal open in it first \u2014 a call made from an Orca terminal inside that worktree is refused as orca_caller_inside_target before anything is touched), strips the worktree from the Cursor workspace, closes its pull request with a comment, deletes the release branch locally and on origin, and REMOVES ITS JIRA FIX VERSION \u2014 the one irreversible step (new id, new URL, lost issue links), which is why every call is gated behind human confirmation. Omit "version" and this server offers the human a form listing the open release PRs; the accepted choice feeds the confirm gate. A client that cannot render a form gets a gate with no version \u2014 confirming it is refused, never guessed. Pass "version" when the human already named the release. One release per call \u2014 repeat the call for another; there is no "versions" field. Refuses before any mutation when the PR is MERGED (the release has shipped), when the fix version is released/archived, when the fix version still carries issues (pass "moveIssuesTo" to reassign them), or when nothing named that version exists. skipJira is CLI-only and has no field here: it would leave a live fix version behind with nothing in the result pointing at it. Resumable: every step is a verified no-op when its artefact is already gone, so a re-run finishes a partial teardown. What is lost with the worktree directory: gitignored contents including a hydrated .env of Doppler secrets (re-fetch with env-load) and node_modules/dist.',requiresHumanConfirm:!0,formProvider:Kh,inputSchema:{version:M.string().optional().describe('The release version or name to remove (e.g. "1.2.5" or "checkout-redesign"). Omit it to be offered the open release PRs.'),moveIssuesTo:M.string().optional().describe(`Optional. An EXISTING Jira fix version name (exactly as in Jira, e.g. "v1.2.6") to move this release's issues to before its fix version is removed \u2014 both fixVersion and affectsVersion. Pass it only after a refusal reported the issue counts, or when the human named the target; a name Jira does not know is refused in preflight before anything is touched.`),confirm:M.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{branch:M.string().describe("The release branch that was targeted"),version:M.string().describe('The release label (e.g. "1.2.5")'),baseBranch:M.string().describe("The branch HEAD was moved to before the local delete"),worktree:M.enum(["removed","absent"]).describe("Whether a git worktree was removed or none existed"),ideFolders:M.object({outcome:M.enum(["verified","attempted","skipped"]).describe('"verified" only when an editor reported a real diff; "skipped" when no editor is configured'),providers:M.array(M.object({provider:M.string(),outcome:M.enum(["verified","attempted","skipped"]),removed:M.array(M.string()).describe("Folder paths confirmed removed")}))}).describe("Per-editor outcome of stripping the worktree folder"),pr:M.enum(["closed","already-closed","absent"]).describe("What happened to the release pull request"),prNumber:M.number().nullable().describe("The pull request number, or null when none exists"),localBranch:M.enum(["deleted","absent"]).describe("Whether a local branch was deleted or none existed"),localTipSha:M.string().nullable().describe("The local tip before deletion \u2014 the handle that restores the branch"),remoteBranch:M.enum(["deleted","absent"]).describe("Whether the origin branch was deleted or none existed"),remoteTipSha:M.string().nullable().describe("The origin tip before deletion"),jira:M.enum(["removed","absent","skipped"]).describe('"removed" when the fix version was deleted; "absent" when Jira knows none for this release (the resume path); "skipped" only on the CLI with --skip-jira'),jiraVersion:M.object({id:M.string(),name:M.string(),url:M.string()}).nullable().describe("The fix version this release owned, captured before removal \u2014 the id is the only handle that survives it")},handler:Fi});import{spawnSync as oC}from"node:child_process";import{homedir as sC}from"node:os";import iC from"node:process";var tC=e=>{let t=new Set(e.steps.map(r=>r[0]));return t.has("brew")?"homebrew":t.has("npm")?"npm":null},rC=e=>{let t=[];return e.needsSudo&&t.push("needs-sudo"),e.fetchesNetworkScript&&t.push("fetches-network-script"),t},nC=(e,t)=>{let r=tC(e);if(r===null)return[];let n=[];return t.present.includes(r)||n.push("manager-absent"),t.owner!==null&&t.owner!==r&&n.push("manager-mismatch"),n},Jo=(e,t)=>{let r=[...rC(e),...nC(e,t)];return r.length===0?{executable:!0}:{executable:!1,reasons:r}},Uo=e=>e.steps.map(Rt);var aC=["NONINTERACTIVE","CI","INTERACTIVE","HAVE_SUDO_ACCESS","SUDO_ASKPASS"],cC=e=>{let t={...Bp(e)};for(let r of aC)delete t[r];return t},Ed=(e,t,r={})=>{let n=r.spawnSync??oC,o=r.env??iC.env,s=(r.agentMode??ee)(),i=Uo(e),a=Jo(e,t);return a.executable?s?{ran:!1,commands:i,refusedBecause:["agent-mode"]}:pC({recipe:e,spawn:n,env:o,commands:i,notify:r.notify??lC}):{ran:!1,commands:i,refusedBecause:a.reasons}},lC=e=>{p.info(e)},qh=64,dC=qh*1024*1024,pC=({recipe:e,spawn:t,env:r,commands:n,notify:o})=>{let s=cC(r);for(let[i,a]of e.steps.entries()){o(` ${"running".padEnd(9)} ${n[i]}`);let c=t(a[0],a.slice(1),{stdio:["ignore","pipe","pipe"],encoding:"utf8",maxBuffer:dC,cwd:sC(),env:s}),l=yC(c);if(l!==null)return{ran:!0,ok:!1,commands:n,failedStep:n[i],detail:l}}return{ran:!0,ok:!0,commands:n}},uC=5,mC=/^(?:error|fatal|warning: failed|[a-z-]{0,20} ERR!)[:\s]/i,Hh=e=>e==null?[]:String(e).split(`
411
- `).map(t=>t.trim()).filter(t=>t.length>0),fC=e=>{let t=Hh(e.stderr),r=Hh(e.stdout),n=[...t,...r].filter(s=>mC.test(s)),o=t.length>0?t:r;return(n.length>0?n:o).slice(-uC).join(" / ")},gC="ENOBUFS",hC=e=>e.error?.code===gC,yC=e=>{if(hC(e))return`terminated after exceeding the ${qh} MiB output limit \u2014 it may be part-installed`;if(e.error)return`could not start: ${e.error.message}`;if(e.signal)return`terminated by signal ${e.signal}`;if(e.status===0)return null;let t=fC(e),r=t===""?"":`: ${t}`;return`exited ${e.status??"unknown"}${r}`};var vC=e=>{let t=[];return e.some(n=>n.id==="brew"&&n.present)&&t.push("homebrew"),t.push("npm"),t},wC=e=>{let t=De(e.id);return e.present?t.updateFor(e.binRealPath):t.bootstrapInstall},kC=(e,t)=>{let r=wC(e),n={...t,owner:e.present?e.manager:null};if(r===null)return{state:e,action:"none",recipe:null,executable:!1,refusedBecause:[],commands:[],context:n};let o=Jo(r,n);return{state:e,action:e.present?"update":"install",recipe:r,executable:o.executable,refusedBecause:o.executable?[]:o.reasons,commands:Uo(r),context:n}},Li=async(e=lr,t=ho())=>{let r=await vo(lr,t),n={owner:null,present:vC(r)},o=cl(e),s=new Map(r.map(a=>[a.id,a]));return{plans:o.filter(a=>e.includes(a)).map(a=>kC(s.get(a),n)),context:n}};var xd=(e,t)=>({...Go(e),action:"skipped",commands:e.commands,detail:t}),Go=e=>({id:e.state.id,before:{present:e.state.present,onPath:e.state.onPath,version:e.state.version,manager:e.state.manager}}),zh=(e,t)=>e.action==="none"?xd(e,`nothing to do: ${e.state.manager} installs are not managed from here`):t==="update"&&e.action==="install"?xd(e,"not installed, and --update only updates \u2014 drop the flag to install it"):e.executable?null:{...Go(e),action:"refused",commands:e.commands,detail:`refused (${e.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},bC=(e,t)=>t.ran?t.ok?{...Go(e),action:e.action==="install"?"installed":"updated",commands:t.commands,detail:e.action==="install"?"installed":"updated"}:{...Go(e),action:"failed",commands:t.commands,detail:`${t.failedStep??"a step"} ${t.detail??"failed"}`}:{...Go(e),action:"refused",commands:t.commands,detail:`refused (${t.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},Td=async e=>{let t=e.run??Ed,{plans:r}=await Li(e.ids,e.probeDeps),n=[];for(let o of r){let s=zh(o,e.mode);if(s!==null){n.push(s);continue}n.push(bC(o,t(o.recipe,o.context)))}return n},Cd=async(e,t)=>{let{plans:r}=await Li(e,t);return r.map(n=>zh(n,"converge")??xd(n,`would ${n.action} \u2014 nothing was run (--skip-tools)`))};import jC from"node:process";import{z as T}from"zod";var $d={zshrc:0,zshenv:1,migrations:2,"user-config":3,guidance:4,worktrees:5,"plugin-pointer":6,"mcp-server":7,"mcp-proxies":8,"project-config":9,shell:10},RC=Object.keys($d).sort((e,t)=>$d[e]-$d[t]),Yh={skipped:0,ok:1,changed:2,manual:3,warn:4,fail:5},Xh=new Set(["manual","warn","fail"]),Ad=e=>{switch(e){case"written":return"changed";case"unchanged":return"ok";case"skipped":return"skipped";case"manual":return"manual";case"warned":return"warn";case"failed":return"fail";default:return qe(e)}},SC=e=>e.reduce((t,r)=>Yh[r]>Yh[t]?r:t,"skipped"),Qh=e=>e.message.trim(),PC=e=>["written","unchanged","skipped"].map(r=>{let n=e.filter(o=>o.outcome===r).length;return n>0?`${n} ${r}`:""}).filter(r=>r.length>0).join(" \xB7 "),Zh=e=>e.message===an,EC=(e,t)=>{let[r]=e;return e.length===1&&r!==void 0?Qh(r):e.length>1?PC(e):t?"activate with the last line below":"see below"},xC=(e,t)=>{if(t.length===0)return{name:e,status:"skipped",message:"did not run"};let r=t.map(i=>Ad(i.outcome)),n=t.filter(i=>Xh.has(Ad(i.outcome))).map(Qh),o=t.filter(i=>!Xh.has(Ad(i.outcome))&&!Zh(i)),s={name:e,status:SC(r),message:EC(o,t.some(Zh))};return n.length>0?{...s,notes:n}:s},TC=e=>({label:"Local setup",rows:RC.map(t=>xC(t,e.filter(r=>r.step===t)))}),CC=(e,t)=>{switch(e.action){case"installed":case"updated":return"changed";case"skipped":return t.skipTools&&e.commands.length>0?"manual":"skipped";case"refused":return"manual";case"failed":return"fail";default:return qe(e.action)}},$C=(e,t)=>{let r=CC(e,t),n={name:e.id,status:r,message:e.detail};return r==="manual"&&e.commands.length>0?{...n,notes:[...e.commands]}:n},AC=(e,t)=>({label:t.skipTools?"Tools (probe: nothing installed)":"Tools",rows:e.map(r=>$C(r,t))}),OC=e=>{switch(e){case"created":case"repointed":return"changed";case"unchanged":return"ok";case"skipped-local":case"skipped-unresolved":return"skipped";case"failed":return"fail";default:return qe(e)}},IC=e=>{switch(e){case"created":case"refreshed":return"changed";case"unchanged":return"ok";case"skipped-local":case"skipped-platform":return"skipped";case"failed":return"fail";default:return qe(e)}},DC=e=>{switch(e){case"created":return"linked ~/.infra-kit/portless to the running portless";case"repointed":return"re-pointed ~/.infra-kit/portless to the running portless";case"unchanged":return"already linked to the running portless";case"skipped-local":return"skipped \u2014 this install is not global";case"skipped-unresolved":return"skipped \u2014 portless is not installed";case"failed":return"could not update the link \u2014 see the debug log";default:return qe(e)}},NC=e=>{let t=e.method==="copy"?"copied":"linked";switch(e.outcome){case"created":return`${t} Node ${e.version} to ~/.infra-kit/node`;case"refreshed":return`re-${t} Node ${e.version} to ~/.infra-kit/node`;case"unchanged":return`~/.infra-kit/node is already Node ${e.version}`;case"skipped-local":return"skipped \u2014 this install is not global";case"skipped-platform":return"skipped \u2014 no portless OS service on this platform";case"failed":return"could not write ~/.infra-kit/node \u2014 see the debug log";default:return qe(e.outcome)}},_C=(e,t)=>{let r="service";switch(e){case"converged":return{name:r,status:"ok",message:"installed service runs through the link and the node"};case"absent":return{name:r,status:"manual",message:"no service installed",notes:t===null?[]:[t]};case"drifted":return{name:r,status:"manual",message:"installed service is out of date",notes:t===null?[]:[t]};case"skipped":return{name:r,status:"skipped",message:"not judged \u2014 portless is not installed"};default:return qe(e)}},MC=e=>({label:"Portless service",rows:[{name:"link",status:OC(e.link),message:DC(e.link)},{name:"node",status:IC(e.node.outcome),message:NC(e.node)},_C(e.service,e.command)]}),ey=(e,t)=>[TC(e.init),AC(e.tools,t),MC(e.portless)],ty=e=>e.some(t=>t.rows.some(r=>r.status==="fail"));var FC=()=>{let{link:e,node:t}=ls();return{link:e,node:t,target:{home:e.home,isGlobal:e.isGlobal,processStartTime:()=>null}}},LC=async e=>{let t=ru(e.link).outcome,r=tu(e.node),n=cs(e.link.home,e.target.exists)??e.link.resolveBin();if(n===null)return{link:t,node:r,service:"skipped",command:null};let{state:o,stableNode:s}=await Og(e.target,n);if(o==="converged")return{link:t,node:r,service:o,command:null};let i=St(n,{home:e.link.home,exists:e.target.exists,execPath:e.target.execPath,stableNode:s});return{link:t,node:r,service:o,command:i}},ny="--skip-tools cannot be combined with --tools or --update: --skip-tools installs and updates nothing at all, so narrowing what it would act on is a contradiction. Use one or the other.",VC=e=>{let t=Array.isArray(e.update)?e.update:void 0,r=e.update===!0||t!==void 0,n=e.skipTools===!0;if(n&&(e.tools!==void 0||r))throw new Error(ny);return{ids:e.tools??t??lr,mode:r?"update":"converge",skipTools:n}},ry=(e,t)=>e instanceof sn?e.step:t.at(-1)?.step??"zshrc",BC=async()=>{let e=[];try{await Qc(t=>{e.push(t)})}catch(t){e.push({step:ry(t,e),outcome:"failed",message:`The ${ry(t,e)} step failed: ${t instanceof Error?t.message:String(t)}`,level:"warn"})}return e},WC=(e,t)=>{let r=t instanceof Error?t.message:String(t);return e.map(n=>({id:n,action:"failed",before:{present:!1,onPath:!1,version:null,manager:"unknown"},commands:[],detail:`the dependency step failed before reaching this tool: ${r}`}))},JC=async(e,t)=>{try{return e.skipTools?await Cd(e.ids,t.probeDeps):await Td({ids:e.ids,mode:e.mode,probeDeps:t.probeDeps,run:t.run})}catch(r){return WC(e.ids,r)}},UC=e=>({step:e.step,outcome:e.outcome,message:e.message}),Vi=async(e={})=>{let t=VC(e),r=await BC(),n=await JC(t,e),o=await LC(e.portlessDeps??FC()),s=ey({init:r,tools:n,portless:o},{skipTools:t.skipTools});It({title:"infra-kit setup",sections:s},{ascii:e.ascii}),p.info(an),ty(s)&&(jC.exitCode=1);let i={init:r.map(UC),tools:n,portlessService:{link:o.link,node:o.node.outcome,service:o.service,command:o.command},report:s,converged:!t.skipTools,changed:n.some(a=>a.action==="installed"||a.action==="updated"),allSucceeded:n.every(a=>a.action!=="failed")};return{content:k(JSON.stringify(i,null,2)),structuredContent:i}},GC=T.object({step:T.enum(["zshrc","zshenv","migrations","user-config","guidance","worktrees","plugin-pointer","mcp-server","mcp-proxies","project-config","shell"]).describe("Which init step this reports on"),outcome:T.enum(["written","unchanged","skipped","manual","warned","failed"]).describe("What that step did: changed something, found nothing to change, did not run, left a command for a human to run (the message carries it), failed non-fatally, or threw and ended the init half (setup exits 1)"),message:T.string().describe("The same line a human running this would have read")}),KC=T.object({id:T.string().describe("Dependency id"),action:T.enum(["installed","updated","skipped","refused","failed"]).describe("What happened"),before:T.object({present:T.boolean(),onPath:T.boolean(),version:T.string().nullable(),manager:T.string()}).describe("The tool\u2019s state before this run"),commands:T.array(T.string()).describe("The exact commands, one per step \u2014 printed even when refused"),detail:T.string().describe("Why, in one line")}),HC=T.object({link:T.enum(["created","repointed","unchanged","skipped-local","skipped-unresolved","failed"]).describe("What the ~/.infra-kit/portless link step did"),node:T.enum(["created","refreshed","unchanged","skipped-local","skipped-platform","failed"]).describe("What the ~/.infra-kit/node step did"),service:T.enum(["absent","converged","drifted","skipped"]).describe("The installed portless system service against the link and node: not installed, already running through both, installed but pointing elsewhere, or not judged because portless is not installed"),command:T.string().nullable().describe("The sudo `service install` command a human has to run; present if and only if service is absent or drifted, null otherwise")}),qC={init:T.array(GC).describe("One entry per init step, in the order they ran"),tools:T.array(KC).describe("One result per requested dependency"),portlessService:HC.describe("The portless link, node, and system-service step \u2014 run on every setup, never gated on the tool options"),converged:T.boolean().describe("Whether the dependency step could act at all (false under skipTools)"),changed:T.boolean().describe("Whether anything was installed or updated"),report:T.array(T.object({label:T.string().describe("Section heading"),rows:T.array(T.object({name:T.string().describe("Init step, tool id, or portless part"),status:T.enum(["ok","changed","skipped","manual","warn","fail"]).describe("ok: nothing to change; changed: changed something; skipped: did not run; manual: not run by the CLI, the notes hold the command a human runs; warn: advisory problem; fail: failed (setup exits 1)"),message:T.string().describe("The row message, as printed"),notes:T.array(T.string()).optional().describe("Lines printed under the row, verbatim: the manual commands, warnings and failures")}))})).describe("The exact rows of the table printed on stderr; setup exits 1 iff a row is fail"),allSucceeded:T.boolean().describe("Whether no tool failed (a refusal is not a failure)")},zC={tools:T.array(T.enum(lr)).optional().describe("Which tools to act on. Omit for all six."),mode:T.enum(["converge","update"]).optional().describe("converge (default): install what is missing and update the rest. update: never install."),skipTools:T.boolean().optional().describe("Read-only: run the init half, then REPORT what each tool needs without installing anything.")},Od=R({name:"setup",description:'Set this machine up in one call: inject the shell integration into .zshrc and the session-env block into .zshenv, run the config migrations, seed the user-global config, refresh the agent-instruction files, register the Claude Code plugin pointer and install or update the skills plugin (the `/infra-kit:*` skills drive the infra-kit CLI on PATH; a leftover .mcp.json entry is reported, never written), then bring brew, git, aws, gh, doppler and portless to a working state \u2014 installing what is missing and updating what is present. Pass mode:"update" to update only and never install, or skipTools:true to do the local setup and then REPORT what each tool needs without installing anything. Recipes that need sudo or pipe a script fetched over the network \u2014 the Homebrew bootstrap and the first AWS CLI install \u2014 are never run; they are reported with the exact commands for you to run yourself. Use `doctor` first to see the state of this machine without changing it.',inputSchema:zC,outputSchema:qC,requiresHumanConfirm:!0,handler:e=>Vi({tools:e.tools,update:e.mode==="update",skipTools:e.skipTools})});import{existsSync as sy}from"node:fs";import iy from"node:path";import i$ from"node:process";import{z as wt}from"zod";import{createHash as YC}from"node:crypto";import{readFileSync as XC}from"node:fs";var Sr=e=>YC("sha256").update(XC(e)).digest("hex");import{readFileSync as n$,writeFileSync as o$}from"node:fs";import Ui from"node:path";import{z as st}from"zod";var Z="vendor",ZC=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack"]),QC=new Set([".sync-manifest.json",".eslintcache","log.txt","routeTree.gen.ts"]),e$=[".tsbuildinfo"],Id=e=>ZC.has(e),Dd=e=>QC.has(e)?!0:e$.some(t=>e.endsWith(t)),Bi=e=>{let t=e.split("/"),r=t.pop()??"";return t.some(o=>Id(o))||Dd(r)};import{readdirSync as t$}from"node:fs";import Nd from"node:path";var r$=e=>e.split(Nd.sep).join("/"),Wi=e=>{let t=[],r=n=>{for(let o of t$(n,{withFileTypes:!0})){let s=Nd.join(n,o.name);if(o.isDirectory()){if(Id(o.name))continue;r(s);continue}Dd(o.name)||t.push(r$(Nd.relative(e,s)))}};return r(e),t.sort()};var je=".sync-manifest.json",Ji=1,s$=st.object({schemaVersion:st.number().optional(),source:st.string(),commit:st.string(),syncedAt:st.string(),fileCount:st.number(),files:st.record(st.string(),st.string())}),_d=e=>(e.schemaVersion??Ji)>Ji,oy=(e,t)=>{let r={},n=t?[...new Set(t)].sort():Wi(e);for(let o of n)try{r[o]=Sr(Ui.join(e,o))}catch(s){let i=s instanceof Error?s.message:String(s);throw new Error(`Cannot hash vendor file "${o}" (broken symlink or unreadable file): ${i}`)}return r},Ko=e=>{let t=Ui.join(e,je),r;try{r=n$(t,"utf8")}catch{throw new Error(`Missing ${je} at ${t}`)}let n=s$.safeParse(JSON.parse(r));if(!n.success)throw new Error(`Invalid ${je} at ${t}: ${st.prettifyError(n.error)}`);return n.data},Md=(e,t,r)=>{let n=oy(e,r),o={schemaVersion:Ji,source:t.source,commit:t.commit,syncedAt:new Date().toISOString(),fileCount:Object.keys(n).length,files:n};return o$(Ui.join(e,je),`${JSON.stringify(o,null,2)}
412
- `),o},jd=(e,t)=>{let r=Object.fromEntries(Object.entries(t.files).filter(([c])=>!Bi(c))),n=Wi(e),o=[],s=[];for(let c of n){if(!(c in r)){s.push(c);continue}Sr(Ui.join(e,c))!==r[c]&&o.push(c)}let i=new Set(n),a=Object.keys(r).filter(c=>!i.has(c));return{modified:o,added:s,removed:a}};var Fd=30,Ld=(e,t)=>{if(t.length!==0){p.info(`
413
- ${e} (${t.length}):`);for(let r of t.slice(0,Fd))p.info(` ${r}`);t.length>Fd&&p.info(` \u2026and ${t.length-Fd} more`)}},Gi=async(e={})=>{let t=e.cwd??await x(),r=iy.join(t,Z),n={modified:[],added:[],removed:[],fileCount:0};if(!sy(r)){p.info(`\u2139\uFE0F No ${Z}/ folder found \u2014 nothing to check.`);let d={status:"skipped",ok:!0,...n};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}}if(!sy(iy.join(r,je))){p.error(`\u274C Missing ${Z}/${je}. Re-run the vendor sync to generate it.`);let d={status:"missing-manifest",ok:!1,...n};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}}let o=Ko(r);if(_d(o)){p.error(`\u274C ${Z}/${je} has a newer schemaVersion (${String(o.schemaVersion)}) than this CLI supports. Upgrade infra-kit.`);let d={status:"unknown-schema",ok:!1,...n};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}}let{modified:s,added:i,removed:a}=jd(r,o),c=s.length>0||i.length>0||a.length>0;c?(p.error(`\u274C ${Z}/ has drifted from ${Z}/${je}.`),p.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),Ld("Modified",s),Ld("Added (not in manifest)",i),Ld("Removed (in manifest, now missing)",a)):p.info(`\u2705 ${Z}/ matches manifest (${o.fileCount} files).`);let l={status:c?"drift":"clean",ok:!c,fileCount:o.fileCount,modified:s,added:i,removed:a};return{content:k(JSON.stringify(l,null,2)),structuredContent:l}},a$={status:wt.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:wt.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:wt.number(),modified:wt.array(wt.string()),added:wt.array(wt.string()),removed:wt.array(wt.string())},Vd=R({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:a$,handler:()=>Gi({cwd:i$.cwd()})});import ay from"node:process";import{z as Ho}from"zod";var cy=async e=>{try{return await e()}catch{return null}},Ki=async()=>{let e=q.version;p.info(e);let t=await cy(x),r=t===null?null:await cy(()=>Le(t)),n={version:e,cwd:ay.cwd(),repoRoot:t,mainRepoRoot:r,projectDir:ay.env.CLAUDE_PROJECT_DIR||null};return{content:k(JSON.stringify(n,null,2)),structuredContent:n}},Bd=R({name:"version",description:"Print the installed infra-kit CLI version and where this process runs (cwd, repo root, main repo root, CLAUDE_PROJECT_DIR)",inputSchema:{},outputSchema:{version:Ho.string().describe("Installed infra-kit CLI version (from package.json)"),cwd:Ho.string().describe("The working directory of this process"),repoRoot:Ho.string().nullable().describe("git toplevel of cwd \u2014 the worktree itself in a linked worktree; null when git cannot answer"),mainRepoRoot:Ho.string().nullable().describe("The main checkout a linked worktree belongs to (equals repoRoot outside worktrees); null with repoRoot"),projectDir:Ho.string().nullable().describe("CLAUDE_PROJECT_DIR as Claude Code set it for this process, or null")},handler:Ki});import dy from"@inquirer/confirm";import c$ from"node:path";import{z as U}from"zod";import{$ as qo}from"zx";var Hi="create worktrees",l$=["already_open","orca_unreachable","orca_absent","orca_worktree_not_selectable","orca_error"],Wd=()=>({orcaOpened:[],orcaSkipped:[],orcaHidden:[]}),qi=async e=>{let{confirmedCommand:t,all:r,versions:n,githubDesktop:o,orca:s}=e,i=e.ide??e.cursor;await be({operation:Hi});try{let a=await Ce("release"),c=await x(),l=`${c}${ge}`;await ly(`${l}/${Cr.release}`),await ly(`${l}/${Cr.feature}`);let d=[];if(n)d=n.split(",").map(j=>Te(ve(j.trim())));else{let j=await F(),Ke=j.map(xe=>xe.branch);if(Ke.length===0){p.info("\u2139\uFE0F No open release branches found"),h.print();let xe={createdWorktrees:[],count:0,...Wd()};return{content:k(JSON.stringify(xe,null,2)),structuredContent:xe}}if(r)d=Ke;else{h.setInteractive();let xe=new Map(j.map(ts=>[ts.branch,ts.type])),ha=await oe();d=await Nt(se({branches:Ke,descriptions:ha,types:xe}),{required:!0})}}r?h.addOption("--all",!0):h.addOption("--versions",nr(d));let u=await D(),m=i??(Tt(u).length>0?"workspace":"none");h.addOption("--ide",m);let g=await d$(o,u),y=await p$(s,u),S=await Le(c),v=c$.basename(S),C=y?await u$({explicit:s!==void 0,mainRepoRoot:S}):null;await W(t,m$(C,v)),t||h.addOption("--yes",!0);let _=C?await f$(C,S):null,{branchesToCreate:O}=v$({selectedReleaseBranches:d,currentWorktrees:a}),P=await w$(O,l);if(k$(P),m==="workspace"&&await bd({projectRoot:c,worktreeDir:l,branches:P}),g)for(let j of P)await qo`github ${l}/${j}`,await qo`sleep 5`;let G=_?await h$({registration:_,createdWorktrees:P,worktreeDir:l,mainRepoRoot:S,repoName:v,config:u}):Wd();y$(G),h.print();let B={createdWorktrees:P,count:P.length,...G};return{content:k(JSON.stringify(B,null,2)),structuredContent:B}}catch(a){throw we(a)||a instanceof E?a:(p.debug({err:a},"Error managing worktrees"),new f(a,{operation:Hi,remediation:"verify branches don't already exist as worktrees: 'git worktree list'"}))}},d$=async(e,t)=>{let r=t.worktrees?.openInGithubDesktop,n=e??r??await I(o=>dy({message:"Open created worktrees in GitHub Desktop?"},o),{whenHeadless:{value:!1}});return e===void 0&&r===void 0&&h.setInteractive(),h.addOption(n?"--github-desktop":"--no-github-desktop",!0),n},p$=async(e,t)=>{let r=t.worktrees?.openInOrca,n=e??r??await I(o=>dy({message:"Open created worktrees in Orca?",default:!0},o),{whenHeadless:{value:!1}});return e===void 0&&r===void 0&&h.setInteractive(),h.addOption(n?"--orca":"--no-orca",!0),n},py=e=>e==="absent"?{reason:"orca_absent",text:"the orca CLI is not installed (Orca \u2192 Settings \u2192 Experimental \u2192 CLI)"}:{reason:"orca_unreachable",text:"Orca is not running"},u$=async e=>{let{explicit:t,mainRepoRoot:r}=e,n=await Ir();if(n!=="ready"){let{reason:s,text:i}=py(n);if(t)throw p.warn({operation:Hi},`\u26D4 --orca was passed but ${i}`),new E({status:"refused",reason:s,agentMode:A.source},2,{operation:Hi,remediation:n==="absent"?"install Orca (brew install --cask stablyai/orca/orca) and register its CLI from Settings \u2192 Experimental \u2192 CLI, or re-run with --no-orca":"open Orca (`orca open`) and re-run, or re-run with --no-orca",stderrExcerpt:`--orca was passed but ${i}; no worktree was created`});return p.warn(`\u26A0\uFE0F ${i} \u2014 worktrees will be created but not opened in Orca`),{probe:n,registered:!1,visibility:void 0}}let o=await Vu(r);return{probe:n,registered:o.registered,visibility:o.visibility}},m$=(e,t)=>{let r=["Are you sure you want to proceed with these worktree changes?"];return e?.probe==="ready"&&!e.registered&&r.push(` \u2022 will register ${t} in Orca (orca repo add); its worktrees start hidden in Orca's sidebar until you choose Show`),r.join(`
414
- `)},f$=async(e,t)=>{if(e.probe!=="ready")return{kind:"skip",reason:py(e.probe).reason};if(e.registered)return{kind:"ready",visibility:e.visibility};try{let{visibility:r}=await Bu(t);return{kind:"ready",visibility:r}}catch(r){return p.warn({error:r},"\u26A0\uFE0F orca repo add failed \u2014 worktrees will be created but not opened in Orca"),{kind:"skip",reason:"orca_error",code:r instanceof bs?r.code:void 0}}},g$=e=>`Orca \u2192 ${e} \u2192 "hidden worktrees" card \u2192 Show, or Settings \u2192 General \u2192 Workspace \u2192 external-worktree sources`,h$=async e=>{let{registration:t,createdWorktrees:r,worktreeDir:n,mainRepoRoot:o,repoName:s,config:i}=e,a=Wd();if(t.kind==="skip"){for(let u of r)a.orcaSkipped.push({branch:u,reason:t.reason,code:t.code});return a}let c=Ru(i),l=r.length===1&&t.visibility!=="hide",d=Ju();for(let u of r){let m=`${n}/${u}`;try{let{layout:g}=await Uu({cwd:m,title:Gu({branch:u}),focus:l,layout:"full",panes:c,poll:d});await Wu(o,m)?a.orcaOpened.push({branch:u,layout:g}):a.orcaHidden.push({branch:u,path:m,fix:g$(s)})}catch(g){p.warn({error:g,branch:u},`\u26A0\uFE0F Failed to open Orca terminals for ${u}`),g instanceof bs&&g.code==="orca_worktree_not_selectable"?a.orcaSkipped.push({branch:u,reason:"orca_worktree_not_selectable"}):a.orcaSkipped.push({branch:u,reason:"orca_error",code:g instanceof bs?g.code:void 0})}}return a},y$=e=>{for(let t of e.orcaOpened)p.info(`\u{1FA9F} Opened ${t.branch} in Orca (${t.layout})`);for(let t of e.orcaHidden)p.info(`\u{1F648} ${t.branch} opened in Orca but its row is hidden (${t.path}) \u2014 ${t.fix}`);for(let t of e.orcaSkipped){let r=t.code?` (${t.code})`:"";p.info(`\u21A9\uFE0F ${t.branch} not opened in Orca: ${t.reason}${r}`)}},ly=async e=>{await qo`mkdir -p ${e}`},v$=e=>{let{selectedReleaseBranches:t,currentWorktrees:r}=e,n=r.filter(s=>us(s));return{branchesToCreate:t.filter(s=>!n.includes(s))}},w$=async(e,t)=>{let r=await Promise.allSettled(e.map(async o=>{let s=`${t}/${o}`;return await qo`git worktree add ${s} ${o}`,await qo({cwd:s})`pnpm install`,o})),n=[];for(let[o,s]of r.entries())if(s.status==="fulfilled")n.push(s.value);else{let i=e[o],a=new f(s.reason,{operation:`git worktree add for ${i}`,remediation:"check the branch name and that the parent dir is writable"});p.error({error:s.reason,msg:a.message})}return n},k$=e=>{if(e.length>0){p.info("\u2705 Created git worktrees:");for(let t of e)p.info(t);p.info("")}else p.info("\u2139\uFE0F No new git worktrees to create")},Jd=R({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 / Orca" follow-up prompts are unreachable without a TTY, and the CLI confirmation is auto-skipped for MCP calls. With "orca" true each created worktree gets an Orca terminal tab laid out per "worktrees.orca.layout"; the result reports orcaOpened, orcaSkipped (with a reason) and orcaHidden (a worktree Orca's sidebar hides, with the UI steps to reveal it). An unregistered repo is registered in Orca first (orca repo add).`,inputSchema:{all:U.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:U.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:U.enum(br).optional().describe('Editor open mode for created worktrees, applied to the configured editor (Cursor, per the "ide" config). "workspace" (the only attach style) adds each worktree to the Cursor workspace and opens it. "none" skips the editor. Resolution order: this flag \u2192 "workspace" when an "ide" is configured \u2192 "none" otherwise.'),cursor:U.enum(br).optional().describe('Deprecated alias for "ide". Prefer "ide". Ignored when "ide" is provided.'),githubDesktop:U.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).'),orca:U.boolean().optional().describe('Open each created worktree in Orca: one terminal tab per worktree, laid out per "worktrees.orca.layout" (default "two-columns": left | right; or "three-pane": left split top/bottom + full-height right). Resolution order: this flag \u2192 "worktrees.openInOrca" from infra-kit config \u2192 interactive prompt (CLI, default yes) / false (MCP, no TTY). Passed explicitly, an Orca that is absent or not running is refused before any worktree is created (orca_absent / orca_unreachable); resolved from config it degrades to orcaSkipped with that reason.')},outputSchema:{createdWorktrees:U.array(U.string()).describe("List of created git worktree branches"),count:U.number().describe("Number of git worktrees created"),orcaOpened:U.array(U.object({branch:U.string(),layout:U.enum(["full","single-pane"])})).describe("Created worktrees that got an Orca terminal tab on a row the sidebar shows, with the layout applied"),orcaSkipped:U.array(U.object({branch:U.string(),reason:U.enum(l$),code:U.string().optional()})).describe("Created worktrees NOT opened in Orca and why: orca_absent / orca_unreachable (config-derived ask, Orca down), orca_worktree_not_selectable (Orca had not scanned the fresh worktree yet), orca_error (code carries the Orca error code)"),orcaHidden:U.array(U.object({branch:U.string(),path:U.string(),fix:U.string()})).describe("Created worktrees whose Orca terminals opened on a row the sidebar HIDES (the repo hides external worktrees); fix names the in-app steps to reveal it")},handler:qi});import{z as Tn}from"zod";var zi=async()=>{await D();let e=await Ce("release");if(e.length===0)return p.info("\u2139\uFE0F No active worktrees found"),{content:k(JSON.stringify({worktrees:[],count:0},null,2)),structuredContent:{worktrees:[],count:0}};let[t,r]=await Promise.all([F(),oe()]),n=new Map(t.map(c=>[c.branch,c.type])),o=e.flatMap(c=>{let l=K(c);if(!l)return[];let d=Y(l),u=n.get(c)||"regular",m=r.get(ne(l))||null;return[{version:d,type:u,description:m}]}),s=Math.max(...o.map(c=>c.version.length)),i=o.map(c=>{let l=so(c.version,c.type,s);return c.description?`${l} ${c.description}`:l});p.info(`\u{1F33F} Active worktrees:
408
+ `),h.addOption("--yes",!0),await Vr({versionId:p.id,...v?{description:y.description}:{},...$?{releaseDate:y.releaseDate}:{}},i),v&&await Ts({branch:a,body:Gn(D,y.description)}),u.info(`\u2705 Updated ${R.join(" and ")} for ${d}`),u.info(`\u{1F517} Jira Version: ${D}`),u.info(`\u{1F517} PR branch: ${a}
409
+ `),h.print(),A(!0)},ql=S({name:"release-edit",description:"Edit a release's description and/or planned release date in Jira; a changed description is mirrored into the 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. `version` and at least one of `description`/`releaseDate` are required for MCP calls (the picker and prompts are unreachable without a TTY). Empty string clears a field. Confirmation is auto-skipped for MCP, so the caller is responsible for gating.",inputSchema:{version:Ne.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:Ne.string().optional().describe("New description. Empty string clears the description."),releaseDate:Hc.optional().describe("New planned release date (yyyy-mm-dd). Empty string clears the date.")},outputSchema:{version:Ne.string().describe("Release version"),branch:Ne.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:Ne.string().describe("Jira fix version URL"),previousDescription:Ne.string().describe("The description before the update"),newDescription:Ne.string().describe("The description after the update"),previousReleaseDate:Ne.string().nullable().describe("The planned release date before the update, or null"),newReleaseDate:Ne.string().nullable().describe("The planned release date after the update, or null"),changedFields:Ne.array(Ne.enum(ph)).describe("The fields whose value actually changed"),changed:Ne.boolean().describe("Whether anything actually changed")},handler:fi});import{z as j}from"zod";import{$ as ed}from"zx";import mh from"node:fs/promises";import gi from"node:path";var Yl=async e=>{let{workspacePath:t,folderPaths:r}=e,n=gi.dirname(t),o;try{o=await mh.readFile(t,"utf-8")}catch(d){throw new Error(`Cursor workspace file not found at ${t}: ${d.message}`)}let s;try{s=JSON.parse(o)}catch(d){throw new Error(`Failed to parse ${t} as JSON. Comments (JSONC) are not supported. ${d.message}`)}let i=s.folders??[],a=new Set(i.map(d=>gi.resolve(n,d.path))),c=[],l=[];for(let d of r){let p=gi.resolve(d);if(a.has(p)){l.push(d);continue}let m=gi.relative(n,p);i.push({path:m}),a.add(p),c.push(d)}return s.folders=i,await mh.writeFile(t,`${JSON.stringify(s,null,2)}
410
+ `,"utf-8"),{added:c,skipped:l}};import{$ as Mx}from"zx";var zl=async e=>{await Mx`cursor ${e}`};import fh from"node:fs/promises";import hi from"node:path";var Xl=async e=>{let{workspacePath:t,folderPaths:r}=e,n=hi.dirname(t),o;try{o=await fh.readFile(t,"utf-8")}catch(m){throw new Error(`Cursor workspace file not found at ${t}: ${m.message}`)}let s;try{s=JSON.parse(o)}catch(m){throw new Error(`Failed to parse ${t} as JSON. Comments (JSONC) are not supported. ${m.message}`)}let i=s.folders??[],a=new Set(r.map(m=>hi.resolve(m))),c=new Set,l=i.filter(m=>{let g=hi.resolve(n,m.path);return a.has(g)?(c.add(g),!1):!0});s.folders=l,await fh.writeFile(t,`${JSON.stringify(s,null,2)}
411
+ `,"utf-8");let d=[],p=[];for(let m of r){let g=hi.resolve(m);c.has(g)?d.push(m):p.push(m)}return{removed:d,notFound:p}};import gh from"node:path";var Co=(e,t)=>gh.isAbsolute(e)?e:gh.resolve(t,e);var Zl=async e=>{let{projectRoot:t,worktreeDir:r,branches:n}=e,o=await M(),s=yt(o),i=n.map(c=>`${r}/${c}`),a=[];for(let c of s)a.push(await jx({ide:c,projectRoot:t,folderPaths:i}));return a},jx=async e=>{let{ide:t,projectRoot:r,folderPaths:n}=e;if(!t.config.workspaceConfigPath)return u.warn("\u26A0\uFE0F Skipping Cursor: ide.config.workspaceConfigPath is not set in infra-kit config"),{ran:!1,provider:"cursor",added:0,skipped:0};let o=Co(t.config.workspaceConfigPath,r),{added:s,skipped:i}=await Yl({workspacePath:o,folderPaths:n}),a=i.length>0?` (${i.length} already present)`:"";return u.info(`\u2705 Added ${s.length} folder(s) to ${o}${a}`),await zl(o),{ran:!0,provider:"cursor",added:s.length,skipped:i.length}};var dr=async e=>{let{projectRoot:t,worktreeDir:r,removedWorktrees:n}=e;if(n.length===0)return[];let o=await M(),s=yt(o),i=n.map(c=>`${r}/${c}`),a=[];for(let c of s)a.push(await Fx({ide:c,projectRoot:t,folderPaths:i}));return a},Fx=async e=>{let{ide:t,projectRoot:r,folderPaths:n}=e;if(!t.config.workspaceConfigPath)return{provider:"cursor",supported:!0,removed:[]};let o=Co(t.config.workspaceConfigPath,r);try{let{removed:s}=await Xl({workspacePath:o,folderPaths:n});return s.length>0&&u.info(`\u2705 Removed ${s.length} folder(s) from ${o}`),{provider:"cursor",supported:!0,removed:s}}catch(s){return u.warn({error:s},`\u26A0\uFE0F Failed to update Cursor workspace at ${o}`),{provider:"cursor",supported:!0,removed:[]}}};var ur=["workspace","none"];import{z as hh}from"zod";var wh=2500,yi="release-remove",yh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Lx=e=>e.version===void 0||e.version==="",Bx=async()=>{try{return{outcome:"listed",prs:await F()}}catch(e){return e instanceof f&&e.operation===Un?{outcome:"empty"}:{outcome:"failed"}}},vh=(e,t)=>(e===null?u.info({msg:`Tool execution form enumeration timed out (gh pr list, ${t/1e3} s): ${yi}`}):e.outcome==="failed"?u.info({msg:`Tool execution form enumeration failed (gh pr list): ${yi}`}):u.info({msg:`Tool execution form options empty (open release PRs): ${yi}`}),null),Vx=(e,t)=>{let r=new Map(e.map(n=>[n.branch,n.type]));return Os(e.map(n=>n.branch)).map(({branch:n,id:o,label:s})=>{let i=t?.get(te(o)),a=i===void 0?"":` \u2014 ${i}`;return{label:s,prose:`${s} [${r.get(n)??"regular"}]${a}`}})},Wx=(e,t,r)=>{let n=e.map(o=>o.prose).join("; ");return t!==null?`Open release PRs right now: ${n}. `:(u.info({msg:`Tool execution form descriptions unavailable (timeout): ${yi}`}),`Open release PRs right now: ${n}. Jira descriptions could not be fetched within ${r/1e3} s. `)},Ql=(e={})=>{let t=e.fetchBudgetMs??wh;return{message:"Choose the release to remove. Nothing runs yet: the confirm gate follows, and the agent will show you the resolved arguments to approve.",isFormable:r=>yh(r)&&Lx(r),buildRequestedSchema:async()=>{let[r,n]=await Promise.all([ln(Bx(),t),ln(ne(),t)]);if(r===null||r.outcome!=="listed")return vh(r,t);let o=Vx(r.prs,n);return o.length===0?vh({outcome:"empty"},t):hh.object({version:hh.enum(o.map(s=>s.label)).describe(`The ONE release to tear down. ${Wx(o,n,t)}Nothing runs yet: the confirm gate follows, and the agent will show you the resolved arguments to approve. Removal deletes the worktree, closes the PR, deletes both branches AND removes the Jira fix version \u2014 the last is irreversible.`)})},toArgs:(r,n)=>typeof r.version!="string"?null:{...yh(n)?n:{},version:r.version}}};var kh=["worktree","ide-folders","pr","local-branch","remote-branch","jira"],wi={worktree:"remove the worktree","ide-folders":"strip the worktree from configured editors",pr:"close the PR","local-branch":"delete the local branch","remote-branch":"delete the remote branch",jira:"remove the Jira fix version"},pr="remove a release",Fe=e=>{throw u.warn({operation:e.operation},`\u26D4 ${e.stderrExcerpt??e.operation}`),new f(void 0,e)},bh=(e,t)=>{throw u.warn({operation:t.operation},`\u26D4 ${t.stderrExcerpt??t.operation}`),new x({...e,agentMode:I.source},2,t)},Ux=e=>{fe()&&(e.version||bh({status:"argument_required",argument:"version"},{operation:pr,remediation:"pass --version <ref> (a release version or name) on the re-run \u2014 `infra-kit release list --json` lists the candidates",stderrExcerpt:"release remove reached the handler without --version under agent mode"}),e.skipJira&&bh({status:"refused"},{operation:pr,remediation:"drop --skip-jira \u2014 under agent mode the fix version is checked and removed with the release; to keep it, ask a human to run `infra-kit release remove --skip-jira` from their own terminal",stderrExcerpt:"--skip-jira is not permitted under agent mode: it would tear down the branch and PR and leave a live Jira fix version behind with nothing in the result pointing at it"}))},Sh=e=>{e.pr?.state==="MERGED"&&Fe({operation:`remove release ${e.label}`,remediation:`this release has shipped \u2014 removing it would delete the branch recording the merge and strip its Jira fix version from delivered work. To undo a delivery, revert the merge commit on ${e.baseBranch} and cut a new release.`,stderrExcerpt:`PR #${e.pr.number} for ${e.branch} is MERGED`})},Jx=(e,t)=>{if(t.skipJira||(e.jiraConfig||Fe({operation:`remove release ${e.label}`,remediation:"set JIRA_BASE_URL / JIRA_TOKEN / JIRA_PROJECT_ID / JIRA_EMAIL, or pass --skip-jira to tear down the branch and PR and leave any fix version alone",stderrExcerpt:"Jira is not configured, so a fix version for this release cannot be checked or removed"}),!e.jira))return;let{version:r,fixCount:n,affectsCount:o}=e.jira;(r.released||r.archived)&&Fe({operation:`remove Jira fix version "${r.name}"`,remediation:"un-release it in Jira first, or remove the release without it via --skip-jira",stderrExcerpt:`fix version "${r.name}" is already ${r.released?"released":"archived"}`}),!(n===0&&o===0)&&(e.moveIssuesTo||Fe({operation:`remove Jira fix version "${r.name}"`,remediation:"deleting it would clear both fields on those issues with no way to restore them \u2014 pass --move-issues-to <version> to reassign both, or clear the version from the issues in Jira first",stderrExcerpt:`${r.name} is set as fixVersion on ${n} issue(s) and as affectsVersion on ${o} issue(s)`}))},Gx=e=>{if(e.worktreePresent||e.pr!==null||e.localTipSha!==null||e.remoteTipSha!==null||e.jira)return;Fe({operation:`remove release ${e.label}`,remediation:`nothing named "${e.label}" exists to remove \u2014 check the spelling against \`infra-kit release list\`. (A release this command already removed keeps a CLOSED PR, so a genuine re-run is not affected.)`,stderrExcerpt:"found no worktree, no PR (any state), no local or remote branch, and no Jira fix version"})},Kx=e=>{!e.worktreeDirty||e.worktreeDirty.length===0||Fe({operation:`remove release ${e.label}`,remediation:`commit or discard those changes (\`git -C ${e.worktreePath} stash -u\`), then re-run`,stderrExcerpt:`the worktree at ${e.worktreePath} has uncommitted changes: ${e.worktreeDirty.slice(0,4).join(", ")}`})},Hx=async e=>(await ed`git -C ${e} status --porcelain`).stdout.split(`
412
+ `).map(r=>r.trimEnd()).filter(r=>r.length>0),qx=async e=>{try{let{terminals:t}=await Pp(e);return t.filter(r=>r.connected).length}catch(t){return u.debug({error:t,worktreePath:e},"release remove: orca terminal probe failed"),0}},Yx=async e=>{let t=await cs([e]);if(t!==null)throw u.warn({operation:pr},`\u26D4 this command runs inside an Orca terminal of ${t}`),new x({status:"refused",reason:"orca_caller_inside_target",agentMode:I.source},2,{operation:pr,remediation:`re-run from a terminal that is not an Orca pane of ${t} (a non-Orca terminal, or another worktree's row)`,stderrExcerpt:`this command runs inside an Orca terminal of ${t}, which the removal would close`})},zx=async(e,t)=>{let r={jiraConfig:null,jira:null,moveIssuesTo:null};if(t.skipJira)return r;let n=await at();if(!n)return r;let o=await it(te(e),n),s=t.moveIssuesTo?await Xx(t.moveIssuesTo,n):null;if(!o)return{jiraConfig:n,jira:null,moveIssuesTo:s};let i=await $s(o.id,n);return{jiraConfig:n,moveIssuesTo:s,jira:{version:o,fixCount:i.issuesFixedCount,affectsCount:i.issuesAffectedCount,url:Yt(n,o)}}},Xx=async(e,t)=>{let r=await it(e,t);return r||Fe({operation:`reassign issues to Jira fix version "${e}"`,remediation:'name an existing fix version exactly as it appears in Jira (e.g. "v1.2.6")',stderrExcerpt:`no Jira fix version named "${e}"`})},Zx=async(e,t)=>{let r=J(e);r||Fe({operation:`remove release ${e}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")',stderrExcerpt:`"${e}" is not a release branch`});let n=await E(),o=`${n}${pe}`,s=`${o}/${e}`,[i,a,c,l]=await Promise.all([Te("release"),jr(e),Ce(n,`refs/heads/${e}`),kr(n,e)]),d=i.includes(e);return d&&await Yx(s),{...await zx(r,t),branch:e,id:r,label:Y(r),baseBranch:a?.baseRefName??Ye("regular"),projectRoot:n,worktreeDir:o,worktreePath:s,worktreePresent:d,orcaTerminalCount:d?await qx(s):0,worktreeDirty:d?await Hx(s):null,localTipSha:c,remoteTipSha:l,pr:a}},Rh=e=>({branch:e.branch,label:e.label,baseBranch:e.baseBranch,worktreePath:e.worktreePath,worktreePresent:e.worktreePresent,worktreeDirty:e.worktreeDirty,orcaTerminalCount:e.orcaTerminalCount,localTipSha:e.localTipSha,remoteTipSha:e.remoteTipSha,pr:e.pr,jiraConfigured:e.jiraConfig!==null,jiraVersion:e.jira?{id:e.jira.version.id,name:e.jira.version.name}:null,jiraFixCount:e.jira?.fixCount??null,jiraAffectsCount:e.jira?.affectsCount??null,moveIssuesTo:e.moveIssuesTo?{id:e.moveIssuesTo.id,name:e.moveIssuesTo.name}:null}),Qx=(e,t)=>{if(t)return"skipped (--skip-jira)";if(!e.jiraConfig)return"skipped (Jira not configured)";if(!e.jira)return"none found";let{version:r,fixCount:n,affectsCount:o}=e.jira,s=`fixVersion on ${n} issue(s), affectsVersion on ${o} issue(s)`,i=e.moveIssuesTo?`, reassigned to ${e.moveIssuesTo.name}`:"";return`${r.name} \u2014 ${s}${i}`},eT=(e,t)=>{let r=e.pr?`#${e.pr.number} (${e.pr.state})`:"none",n=[`Remove release ${e.label} (${e.branch})? This will:`,` \u2022 worktree: ${e.worktreePresent?e.worktreePath:"none"}`,` \u2022 PR: ${r}`,` \u2022 local branch: ${e.localTipSha??"absent"} (switching to ${e.baseBranch} first)`,` \u2022 remote branch: ${e.remoteTipSha??"absent"}`,` \u2022 Jira version: ${Qx(e,t)}`];return e.orcaTerminalCount>0&&n.push(` \u2022 ${e.orcaTerminalCount} Orca terminal(s) in ${e.worktreePath} will be closed`),n.join(`
413
+ `)},vi=class extends Error{constructor(r,n){super(`step ${r} failed`,{cause:n});this.step=r;this.reason=n;this.name="StepFailure"}step;reason},tT=e=>typeof e=="string"?e:e.outcome;async function $o(e,t,r){try{let n=await r(),o=tT(n);return t.push({step:e}),u.info({step:e,outcome:o},`\u2705 ${wi[e]} \u2014 ${o}`),n}catch(n){throw new vi(e,n)}}var rT=async(e,t,r)=>{try{await r(),t.push({step:e})}catch(n){t.push({step:e,detail:"attempted"}),u.warn({err:It(n),step:e},`\u26A0\uFE0F ${wi[e]} failed (non-blocking)`)}},nT=(e,t)=>t.step==="local-branch"&&e.localTipSha?`local-branch (was ${e.localTipSha.slice(0,7)})`:t.detail?`${t.step} (${t.detail})`:t.step,oT=e=>{let{plan:t,step:r,done:n,cause:o}=e,s=n.map(p=>nT(t,p)).join(", ")||"nothing",i=t.jira?`The Jira fix version ${t.jira.version.name} was NOT removed. `:"",a=t.localTipSha?`Restore the branch with \`git branch ${t.branch} ${t.localTipSha}\`. `:"",c=`Re-run \`infra-kit release remove --version ${t.label}\` to finish; completed steps are skipped.`,l=`completed: ${s}. ${i}${a}${c}`,d=o instanceof f?o.remediation:void 0;return new f(o,{operation:`remove release ${t.label} \u2014 step ${kh.indexOf(r)+1} of ${kh.length} (${wi[r]})`,remediation:d?`${d} \u2014 ${l}`:l})},sT=async e=>{let t=await vo(e.branch,{operation:`remove the worktree for ${e.branch}`,remediation:`commit or discard the changes inside ${e.worktreePath} (\`git -C ${e.worktreePath} stash -u\`), then re-run`});return{outcome:t.includes(e.branch)?"removed":"absent",removedBranches:t}},iT=e=>{let t=e.map(s=>({provider:s.provider,outcome:aT(s),removed:s.removed})),r=t.some(s=>s.outcome==="verified"),o=t.some(s=>s.outcome==="attempted")?"attempted":"skipped";return{outcome:r?"verified":o,providers:t}},aT=e=>e.removed.length>0?"verified":"attempted",cT=async(e,t,r)=>{let n={outcome:"attempted",providers:[]};return await rT("ide-folders",r,async()=>{let o=await dr({projectRoot:e.projectRoot,worktreeDir:e.worktreeDir,removedWorktrees:t});n=iT(o)}),u.info({outcome:n.outcome,step:"ide-folders"},`\u2705 ${wi["ide-folders"]} \u2014 ${n.outcome}`),n},lT=async e=>{let t=await jr(e.branch);if(Sh({...e,pr:t}),!t)return{outcome:"absent",number:null};if(t.state==="CLOSED")return{outcome:"already-closed",number:t.number};let r=`Closed by \`infra-kit release remove\`: release ${e.label} was torn down.`;return await ed`gh pr close ${String(t.number)} --comment ${r}`,{outcome:"closed",number:t.number}},dT=async e=>(await wr()===e.branch&&await ed`git switch ${e.baseBranch}`,await es(e.branch),await Ku(e.branch)?Fe({operation:`delete local branch ${e.branch}`,remediation:`delete it by hand with \`git branch -D ${e.branch}\`, then re-run to finish the removal`,stderrExcerpt:`${e.branch} still exists after the delete`}):e.localTipSha?"deleted":"absent"),uT=async e=>(await ts(e.branch),e.remoteTipSha?"deleted":"absent"),pT=async(e,t,r)=>{let n=await $s(t.version.id,r);if(n.issuesFixedCount===t.fixCount&&n.issuesAffectedCount===t.affectsCount)return;let o=`re-run \`infra-kit release remove --version ${e.label}\``;Fe({operation:`remove Jira fix version "${t.version.name}"`,remediation:`the fix version was NOT removed and every other step is complete \u2014 ${o} so the guard re-evaluates the new counts`,stderrExcerpt:`issue counts changed since preflight: fixVersion ${t.fixCount} \u2192 ${n.issuesFixedCount}, affectsVersion ${t.affectsCount} \u2192 ${n.issuesAffectedCount}`})},mT=async(e,t)=>t.skipJira?"skipped":!e.jira||!e.jiraConfig?"absent":(await pT(e,e.jira,e.jiraConfig),u.info({jiraVersionId:e.jira.version.id,jiraVersionName:e.jira.version.name},"\u{1F5D1}\uFE0F removing Jira fix version"),await yc({versionId:e.jira.version.id,moveFixIssuesTo:e.moveIssuesTo?.id,moveAffectedIssuesTo:e.moveIssuesTo?.id},e.jiraConfig),"removed"),fT=(e,t)=>({branch:e.branch,version:e.label,baseBranch:e.baseBranch,worktree:t.worktree.outcome,ideFolders:t.ideFolders,pr:t.pr.outcome,prNumber:t.pr.number,localBranch:t.localBranch,localTipSha:e.localTipSha,remoteBranch:t.remoteBranch,remoteTipSha:e.remoteTipSha,jira:t.jira,jiraVersion:e.jira?{id:e.jira.version.id,name:e.jira.version.name,url:e.jira.url}:null}),gT=async(e,t,r)=>{let n=await $o("worktree",r,()=>sT(e)),o=await cT(e,n.removedBranches,r),s=await $o("pr",r,()=>lT(e));u.info({branch:e.branch,localTipSha:e.localTipSha,remoteTipSha:e.remoteTipSha},"\u{1F516} branch tips before deletion");let i=await $o("local-branch",r,()=>dT(e)),a=await $o("remote-branch",r,()=>uT(e)),c=await $o("jira",r,()=>mT(e,t));return{worktree:n,ideFolders:o,pr:s,localBranch:i,remoteBranch:a,jira:c}},hT=async(e,t)=>{let r=[];try{return fT(e,await gT(e,t,r))}catch(n){throw n instanceof vi?oT({plan:e,step:n.step,done:r,cause:n.reason}):n}},yT=async e=>{if(e)return ct(e);h.setInteractive();let[t,r]=await Promise.all([ne(),F()]),n=r.map(s=>s.branch);n.length===0&&Fe({operation:"select a release to remove",remediation:"pass `--version <ref>` to remove a release that is already partially torn down",stderrExcerpt:"no open release PRs to pick from"});let o=new Map(r.map(s=>[s.branch,s.type]));try{return await Et(oe({branches:n,descriptions:t,types:o}))}catch(s){throw ve(s)?s:new f(s,{operation:"select a release to remove",remediation:"pass `--version <ref>` (e.g. `--version 1.2.5`); the picker needs an interactive terminal"})}},Ph=Ql(),ki=async e=>{let{confirmedCommand:t,version:r,moveIssuesTo:n,skipJira:o}=e;await be({operation:pr}),await M(),await Ue({provider:Ph,params:e,operation:pr,argument:"version"}),Ux(e);try{let s=await Zx(await yT(r),e);u.debug({plan:Rh(s)},"release remove: resolved plan"),Sh(s),Jx(s,e),Gx(s),await Vn({operation:`remove release ${s.label}`,base:s.baseBranch}),Kx(s),h.addOption("--version",s.label),n&&h.addOption("--move-issues-to",n),o&&h.addOption("--skip-jira",!0),await B(t,eT(s,!!o),{throwOnDecline:!0,plan:{...Rh(s),skipJira:!!o}}),t||h.addOption("--yes",!0);let i=await hT(s,e);return h.print(),{content:k(JSON.stringify(i,null,2)),structuredContent:i}}catch(s){throw ve(s)||nt(s)||s instanceof f?s:(u.error({err:It(s)},"\u274C Error removing release"),new f(s,{operation:pr,remediation:"check `gh auth status`, `git worktree list` and the Jira credentials, then re-run"}))}},td=S({name:"release-remove",description:'Tear down ONE release created by release-create: removes its git worktree (closing every Orca terminal open in it first \u2014 a call made from an Orca terminal inside that worktree is refused as orca_caller_inside_target before anything is touched), strips the worktree from the Cursor workspace, closes its pull request with a comment, deletes the release branch locally and on origin, and REMOVES ITS JIRA FIX VERSION \u2014 the one irreversible step (new id, new URL, lost issue links), which is why every call is gated behind human confirmation. Omit "version" and this server offers the human a form listing the open release PRs; the accepted choice feeds the confirm gate. A client that cannot render a form gets a gate with no version \u2014 confirming it is refused, never guessed. Pass "version" when the human already named the release. One release per call \u2014 repeat the call for another; there is no "versions" field. Refuses before any mutation when the PR is MERGED (the release has shipped), when the fix version is released/archived, when the fix version still carries issues (pass "moveIssuesTo" to reassign them), or when nothing named that version exists. skipJira is CLI-only and has no field here: it would leave a live fix version behind with nothing in the result pointing at it. Resumable: every step is a verified no-op when its artefact is already gone, so a re-run finishes a partial teardown. What is lost with the worktree directory: gitignored contents including a hydrated .env of Doppler secrets (re-fetch with env-load) and node_modules/dist.',requiresHumanConfirm:!0,formProvider:Ph,inputSchema:{version:j.string().optional().describe('The release version or name to remove (e.g. "1.2.5" or "checkout-redesign"). Omit it to be offered the open release PRs.'),moveIssuesTo:j.string().optional().describe(`Optional. An EXISTING Jira fix version name (exactly as in Jira, e.g. "v1.2.6") to move this release's issues to before its fix version is removed \u2014 both fixVersion and affectsVersion. Pass it only after a refusal reported the issue counts, or when the human named the target; a name Jira does not know is refused in preflight before anything is touched.`),confirm:j.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{branch:j.string().describe("The release branch that was targeted"),version:j.string().describe('The release label (e.g. "1.2.5")'),baseBranch:j.string().describe("The branch HEAD was moved to before the local delete"),worktree:j.enum(["removed","absent"]).describe("Whether a git worktree was removed or none existed"),ideFolders:j.object({outcome:j.enum(["verified","attempted","skipped"]).describe('"verified" only when an editor reported a real diff; "skipped" when no editor is configured'),providers:j.array(j.object({provider:j.string(),outcome:j.enum(["verified","attempted","skipped"]),removed:j.array(j.string()).describe("Folder paths confirmed removed")}))}).describe("Per-editor outcome of stripping the worktree folder"),pr:j.enum(["closed","already-closed","absent"]).describe("What happened to the release pull request"),prNumber:j.number().nullable().describe("The pull request number, or null when none exists"),localBranch:j.enum(["deleted","absent"]).describe("Whether a local branch was deleted or none existed"),localTipSha:j.string().nullable().describe("The local tip before deletion \u2014 the handle that restores the branch"),remoteBranch:j.enum(["deleted","absent"]).describe("Whether the origin branch was deleted or none existed"),remoteTipSha:j.string().nullable().describe("The origin tip before deletion"),jira:j.enum(["removed","absent","skipped"]).describe('"removed" when the fix version was deleted; "absent" when Jira knows none for this release (the resume path); "skipped" only on the CLI with --skip-jira'),jiraVersion:j.object({id:j.string(),name:j.string(),url:j.string()}).nullable().describe("The fix version this release owned, captured before removal \u2014 the id is the only handle that survives it")},handler:ki});import{spawnSync as bT}from"node:child_process";import{homedir as RT}from"node:os";import ST from"node:process";var vT=e=>{let t=new Set(e.steps.map(r=>r[0]));return t.has("brew")?"homebrew":t.has("npm")?"npm":null},wT=e=>{let t=[];return e.needsSudo&&t.push("needs-sudo"),e.fetchesNetworkScript&&t.push("fetches-network-script"),t},kT=(e,t)=>{let r=vT(e);if(r===null)return[];let n=[];return t.present.includes(r)||n.push("manager-absent"),t.owner!==null&&t.owner!==r&&n.push("manager-mismatch"),n},Ao=(e,t)=>{let r=[...wT(e),...kT(e,t)];return r.length===0?{executable:!0}:{executable:!1,reasons:r}},Oo=e=>e.steps.map(mt);var PT=["NONINTERACTIVE","CI","INTERACTIVE","HAVE_SUDO_ACCESS","SUDO_ASKPASS"],ET=e=>{let t={...bu(e)};for(let r of PT)delete t[r];return t},rd=(e,t,r={})=>{let n=r.spawnSync??bT,o=r.env??ST.env,s=(r.agentMode??fe)(),i=Oo(e),a=Ao(e,t);return a.executable?s?{ran:!1,commands:i,refusedBecause:["agent-mode"]}:CT({recipe:e,spawn:n,env:o,commands:i,notify:r.notify??xT}):{ran:!1,commands:i,refusedBecause:a.reasons}},xT=e=>{u.info(e)},xh=64,TT=xh*1024*1024,CT=({recipe:e,spawn:t,env:r,commands:n,notify:o})=>{let s=ET(r);for(let[i,a]of e.steps.entries()){o(` ${"running".padEnd(9)} ${n[i]}`);let c=t(a[0],a.slice(1),{stdio:["ignore","pipe","pipe"],encoding:"utf8",maxBuffer:TT,cwd:RT(),env:s}),l=NT(c);if(l!==null)return{ran:!0,ok:!1,commands:n,failedStep:n[i],detail:l}}return{ran:!0,ok:!0,commands:n}},$T=5,AT=/^(?:error|fatal|warning: failed|[a-z-]{0,20} ERR!)[:\s]/i,Eh=e=>e==null?[]:String(e).split(`
414
+ `).map(t=>t.trim()).filter(t=>t.length>0),OT=e=>{let t=Eh(e.stderr),r=Eh(e.stdout),n=[...t,...r].filter(s=>AT.test(s)),o=t.length>0?t:r;return(n.length>0?n:o).slice(-$T).join(" / ")},IT="ENOBUFS",DT=e=>e.error?.code===IT,NT=e=>{if(DT(e))return`terminated after exceeding the ${xh} MiB output limit \u2014 it may be part-installed`;if(e.error)return`could not start: ${e.error.message}`;if(e.signal)return`terminated by signal ${e.signal}`;if(e.status===0)return null;let t=OT(e),r=t===""?"":`: ${t}`;return`exited ${e.status??"unknown"}${r}`};var _T=e=>{let t=[];return e.some(n=>n.id==="brew"&&n.present)&&t.push("homebrew"),t.push("npm"),t},MT=e=>{let t=Ie(e.id);return e.present?t.updateFor(e.binRealPath):t.bootstrapInstall},jT=(e,t)=>{let r=MT(e),n={...t,owner:e.present?e.manager:null};if(r===null)return{state:e,action:"none",recipe:null,executable:!1,refusedBecause:[],commands:[],context:n};let o=Ao(r,n);return{state:e,action:e.present?"update":"install",recipe:r,executable:o.executable,refusedBecause:o.executable?[]:o.reasons,commands:Oo(r),context:n}},bi=async(e=er,t=no())=>{let r=await so(er,t),n={owner:null,present:_T(r)},o=Gc(e),s=new Map(r.map(a=>[a.id,a]));return{plans:o.filter(a=>e.includes(a)).map(a=>jT(s.get(a),n)),context:n}};var nd=(e,t)=>({...Io(e),action:"skipped",commands:e.commands,detail:t}),Io=e=>({id:e.state.id,before:{present:e.state.present,onPath:e.state.onPath,version:e.state.version,manager:e.state.manager}}),Th=(e,t)=>e.action==="none"?nd(e,`nothing to do: ${e.state.manager} installs are not managed from here`):t==="update"&&e.action==="install"?nd(e,"not installed, and --update only updates \u2014 drop the flag to install it"):e.executable?null:{...Io(e),action:"refused",commands:e.commands,detail:`refused (${e.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},FT=(e,t)=>t.ran?t.ok?{...Io(e),action:e.action==="install"?"installed":"updated",commands:t.commands,detail:e.action==="install"?"installed":"updated"}:{...Io(e),action:"failed",commands:t.commands,detail:`${t.failedStep??"a step"} ${t.detail??"failed"}`}:{...Io(e),action:"refused",commands:t.commands,detail:`refused (${t.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},od=async e=>{let t=e.run??rd,{plans:r}=await bi(e.ids,e.probeDeps),n=[];for(let o of r){let s=Th(o,e.mode);if(s!==null){n.push(s);continue}n.push(FT(o,t(o.recipe,o.context)))}return n},sd=async(e,t)=>{let{plans:r}=await bi(e,t);return r.map(n=>Th(n,"converge")??nd(n,`would ${n.action} \u2014 nothing was run (--skip-tools)`))};import eC from"node:process";import{z as T}from"zod";var id={zshrc:0,zshenv:1,migrations:2,"user-config":3,guidance:4,worktrees:5,"plugin-pointer":6,"mcp-server":7,"mcp-proxies":8,"project-config":9,shell:10},LT=Object.keys(id).sort((e,t)=>id[e]-id[t]),Ch={skipped:0,ok:1,changed:2,manual:3,warn:4,fail:5},$h=new Set(["manual","warn","fail"]),ad=e=>{switch(e){case"written":return"changed";case"unchanged":return"ok";case"skipped":return"skipped";case"manual":return"manual";case"warned":return"warn";case"failed":return"fail";default:return Ve(e)}},BT=e=>e.reduce((t,r)=>Ch[r]>Ch[t]?r:t,"skipped"),Oh=e=>e.message.trim(),VT=e=>["written","unchanged","skipped"].map(r=>{let n=e.filter(o=>o.outcome===r).length;return n>0?`${n} ${r}`:""}).filter(r=>r.length>0).join(" \xB7 "),Ah=e=>e.message===Zr,WT=(e,t)=>{let[r]=e;return e.length===1&&r!==void 0?Oh(r):e.length>1?VT(e):t?"activate with the last line below":"see below"},UT=(e,t)=>{if(t.length===0)return{name:e,status:"skipped",message:"did not run"};let r=t.map(i=>ad(i.outcome)),n=t.filter(i=>$h.has(ad(i.outcome))).map(Oh),o=t.filter(i=>!$h.has(ad(i.outcome))&&!Ah(i)),s={name:e,status:BT(r),message:WT(o,t.some(Ah))};return n.length>0?{...s,notes:n}:s},JT=e=>({label:"Local setup",rows:LT.map(t=>UT(t,e.filter(r=>r.step===t)))}),GT=(e,t)=>{switch(e.action){case"installed":case"updated":return"changed";case"skipped":return t.skipTools&&e.commands.length>0?"manual":"skipped";case"refused":return"manual";case"failed":return"fail";default:return Ve(e.action)}},KT=(e,t)=>{let r=GT(e,t),n={name:e.id,status:r,message:e.detail};return r==="manual"&&e.commands.length>0?{...n,notes:[...e.commands]}:n},HT=(e,t)=>({label:t.skipTools?"Tools (probe: nothing installed)":"Tools",rows:e.map(r=>KT(r,t))}),qT=e=>{switch(e){case"created":case"repointed":return"changed";case"unchanged":return"ok";case"skipped-local":case"skipped-unresolved":return"skipped";case"failed":return"fail";default:return Ve(e)}},YT=e=>{switch(e){case"created":case"refreshed":return"changed";case"unchanged":return"ok";case"skipped-local":case"skipped-platform":return"skipped";case"failed":return"fail";default:return Ve(e)}},zT=e=>{switch(e){case"created":return"linked ~/.infra-kit/portless to the running portless";case"repointed":return"re-pointed ~/.infra-kit/portless to the running portless";case"unchanged":return"already linked to the running portless";case"skipped-local":return"skipped \u2014 this install is not global";case"skipped-unresolved":return"skipped \u2014 portless is not installed";case"failed":return"could not update the link \u2014 see the debug log";default:return Ve(e)}},XT=e=>{let t=e.method==="copy"?"copied":"linked";switch(e.outcome){case"created":return`${t} Node ${e.version} to ~/.infra-kit/node`;case"refreshed":return`re-${t} Node ${e.version} to ~/.infra-kit/node`;case"unchanged":return`~/.infra-kit/node is already Node ${e.version}`;case"skipped-local":return"skipped \u2014 this install is not global";case"skipped-platform":return"skipped \u2014 no portless OS service on this platform";case"failed":return"could not write ~/.infra-kit/node \u2014 see the debug log";default:return Ve(e.outcome)}},ZT=(e,t)=>{let r="service";switch(e){case"converged":return{name:r,status:"ok",message:"installed service runs through the link and the node"};case"absent":return{name:r,status:"manual",message:"no service installed",notes:t===null?[]:[t]};case"drifted":return{name:r,status:"manual",message:"installed service is out of date",notes:t===null?[]:[t]};case"skipped":return{name:r,status:"skipped",message:"not judged \u2014 portless is not installed"};default:return Ve(e)}},QT=e=>({label:"Portless service",rows:[{name:"link",status:qT(e.link),message:zT(e.link)},{name:"node",status:YT(e.node.outcome),message:XT(e.node)},ZT(e.service,e.command)]}),Ih=(e,t)=>[JT(e.init),HT(e.tools,t),QT(e.portless)],Dh=e=>e.some(t=>t.rows.some(r=>r.status==="fail"));var tC=()=>{let{link:e,node:t}=zo();return{link:e,node:t,target:{home:e.home,isGlobal:e.isGlobal,processStartTime:()=>null}}},rC=async e=>{let t=Mu(e.link).outcome,r=_u(e.node),n=Yo(e.link.home,e.target.exists)??e.link.resolveBin();if(n===null)return{link:t,node:r,service:"skipped",command:null};let{state:o,stableNode:s}=await hg(e.target,n);if(o==="converged")return{link:t,node:r,service:o,command:null};let i=ft(n,{home:e.link.home,exists:e.target.exists,execPath:e.target.execPath,stableNode:s});return{link:t,node:r,service:o,command:i}},_h="--skip-tools cannot be combined with --tools or --update: --skip-tools installs and updates nothing at all, so narrowing what it would act on is a contradiction. Use one or the other.",nC=e=>{let t=Array.isArray(e.update)?e.update:void 0,r=e.update===!0||t!==void 0,n=e.skipTools===!0;if(n&&(e.tools!==void 0||r))throw new Error(_h);return{ids:e.tools??t??er,mode:r?"update":"converge",skipTools:n}},Nh=(e,t)=>e instanceof Xr?e.step:t.at(-1)?.step??"zshrc",oC=async()=>{let e=[];try{await Fc(t=>{e.push(t)})}catch(t){e.push({step:Nh(t,e),outcome:"failed",message:`The ${Nh(t,e)} step failed: ${t instanceof Error?t.message:String(t)}`,level:"warn"})}return e},sC=(e,t)=>{let r=t instanceof Error?t.message:String(t);return e.map(n=>({id:n,action:"failed",before:{present:!1,onPath:!1,version:null,manager:"unknown"},commands:[],detail:`the dependency step failed before reaching this tool: ${r}`}))},iC=async(e,t)=>{try{return e.skipTools?await sd(e.ids,t.probeDeps):await od({ids:e.ids,mode:e.mode,probeDeps:t.probeDeps,run:t.run})}catch(r){return sC(e.ids,r)}},aC=e=>({step:e.step,outcome:e.outcome,message:e.message}),Ri=async(e={})=>{let t=nC(e),r=await oC(),n=await iC(t,e),o=await rC(e.portlessDeps??tC()),s=Ih({init:r,tools:n,portless:o},{skipTools:t.skipTools});qe({title:"infra-kit setup",sections:s},{ascii:e.ascii}),u.info(Zr),Dh(s)&&(eC.exitCode=1);let i={init:r.map(aC),tools:n,portlessService:{link:o.link,node:o.node.outcome,service:o.service,command:o.command},report:s,converged:!t.skipTools,changed:n.some(a=>a.action==="installed"||a.action==="updated"),allSucceeded:n.every(a=>a.action!=="failed")};return{content:k(JSON.stringify(i,null,2)),structuredContent:i}},cC=T.object({step:T.enum(["zshrc","zshenv","migrations","user-config","guidance","worktrees","plugin-pointer","mcp-server","mcp-proxies","project-config","shell"]).describe("Which init step this reports on"),outcome:T.enum(["written","unchanged","skipped","manual","warned","failed"]).describe("What that step did: changed something, found nothing to change, did not run, left a command for a human to run (the message carries it), failed non-fatally, or threw and ended the init half (setup exits 1)"),message:T.string().describe("The same line a human running this would have read")}),lC=T.object({id:T.string().describe("Dependency id"),action:T.enum(["installed","updated","skipped","refused","failed"]).describe("What happened"),before:T.object({present:T.boolean(),onPath:T.boolean(),version:T.string().nullable(),manager:T.string()}).describe("The tool\u2019s state before this run"),commands:T.array(T.string()).describe("The exact commands, one per step \u2014 printed even when refused"),detail:T.string().describe("Why, in one line")}),dC=T.object({link:T.enum(["created","repointed","unchanged","skipped-local","skipped-unresolved","failed"]).describe("What the ~/.infra-kit/portless link step did"),node:T.enum(["created","refreshed","unchanged","skipped-local","skipped-platform","failed"]).describe("What the ~/.infra-kit/node step did"),service:T.enum(["absent","converged","drifted","skipped"]).describe("The installed portless system service against the link and node: not installed, already running through both, installed but pointing elsewhere, or not judged because portless is not installed"),command:T.string().nullable().describe("The sudo `service install` command a human has to run; present if and only if service is absent or drifted, null otherwise")}),uC={init:T.array(cC).describe("One entry per init step, in the order they ran"),tools:T.array(lC).describe("One result per requested dependency"),portlessService:dC.describe("The portless link, node, and system-service step \u2014 run on every setup, never gated on the tool options"),converged:T.boolean().describe("Whether the dependency step could act at all (false under skipTools)"),changed:T.boolean().describe("Whether anything was installed or updated"),report:T.array(T.object({label:T.string().describe("Section heading"),rows:T.array(T.object({name:T.string().describe("Init step, tool id, or portless part"),status:T.enum(["ok","changed","skipped","manual","warn","fail"]).describe("ok: nothing to change; changed: changed something; skipped: did not run; manual: not run by the CLI, the notes hold the command a human runs; warn: advisory problem; fail: failed (setup exits 1)"),message:T.string().describe("The row message, as printed"),notes:T.array(T.string()).optional().describe("Lines printed under the row, verbatim: the manual commands, warnings and failures")}))})).describe("The exact rows of the table printed on stderr; setup exits 1 iff a row is fail"),allSucceeded:T.boolean().describe("Whether no tool failed (a refusal is not a failure)")},pC={tools:T.array(T.enum(er)).optional().describe("Which tools to act on. Omit for all six."),mode:T.enum(["converge","update"]).optional().describe("converge (default): install what is missing and update the rest. update: never install."),skipTools:T.boolean().optional().describe("Read-only: run the init half, then REPORT what each tool needs without installing anything.")},cd=S({name:"setup",description:'Set this machine up in one call: inject the shell integration into .zshrc and the session-env block into .zshenv, run the config migrations, seed the user-global config, refresh the agent-instruction files, register the Claude Code plugin pointer and install or update the skills plugin (the `/infra-kit:*` skills drive the infra-kit CLI on PATH; a leftover .mcp.json entry is reported, never written), then bring brew, git, aws, gh, doppler and portless to a working state \u2014 installing what is missing and updating what is present. Pass mode:"update" to update only and never install, or skipTools:true to do the local setup and then REPORT what each tool needs without installing anything. Recipes that need sudo or pipe a script fetched over the network \u2014 the Homebrew bootstrap and the first AWS CLI install \u2014 are never run; they are reported with the exact commands for you to run yourself. Use `doctor` first to see the state of this machine without changing it.',inputSchema:pC,outputSchema:uC,requiresHumanConfirm:!0,handler:e=>Ri({tools:e.tools,update:e.mode==="update",skipTools:e.skipTools})});import{existsSync as jh}from"node:fs";import Fh from"node:path";import SC from"node:process";import{z as ut}from"zod";import{createHash as mC}from"node:crypto";import{readFileSync as fC}from"node:fs";var mr=e=>mC("sha256").update(fC(e)).digest("hex");import{readFileSync as kC,writeFileSync as bC}from"node:fs";import xi from"node:path";import{z as tt}from"zod";var X="vendor",gC=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack"]),hC=new Set([".sync-manifest.json",".eslintcache","log.txt","routeTree.gen.ts"]),yC=[".tsbuildinfo"],ld=e=>gC.has(e),dd=e=>hC.has(e)?!0:yC.some(t=>e.endsWith(t)),Si=e=>{let t=e.split("/"),r=t.pop()??"";return t.some(o=>ld(o))||dd(r)};import{readdirSync as vC}from"node:fs";import ud from"node:path";var wC=e=>e.split(ud.sep).join("/"),Pi=e=>{let t=[],r=n=>{for(let o of vC(n,{withFileTypes:!0})){let s=ud.join(n,o.name);if(o.isDirectory()){if(ld(o.name))continue;r(s);continue}dd(o.name)||t.push(wC(ud.relative(e,s)))}};return r(e),t.sort()};var _e=".sync-manifest.json",Ei=1,RC=tt.object({schemaVersion:tt.number().optional(),source:tt.string(),commit:tt.string(),syncedAt:tt.string(),fileCount:tt.number(),files:tt.record(tt.string(),tt.string())}),pd=e=>(e.schemaVersion??Ei)>Ei,Mh=(e,t)=>{let r={},n=t?[...new Set(t)].sort():Pi(e);for(let o of n)try{r[o]=mr(xi.join(e,o))}catch(s){let i=s instanceof Error?s.message:String(s);throw new Error(`Cannot hash vendor file "${o}" (broken symlink or unreadable file): ${i}`)}return r},Do=e=>{let t=xi.join(e,_e),r;try{r=kC(t,"utf8")}catch{throw new Error(`Missing ${_e} at ${t}`)}let n=RC.safeParse(JSON.parse(r));if(!n.success)throw new Error(`Invalid ${_e} at ${t}: ${tt.prettifyError(n.error)}`);return n.data},md=(e,t,r)=>{let n=Mh(e,r),o={schemaVersion:Ei,source:t.source,commit:t.commit,syncedAt:new Date().toISOString(),fileCount:Object.keys(n).length,files:n};return bC(xi.join(e,_e),`${JSON.stringify(o,null,2)}
415
+ `),o},fd=(e,t)=>{let r=Object.fromEntries(Object.entries(t.files).filter(([c])=>!Si(c))),n=Pi(e),o=[],s=[];for(let c of n){if(!(c in r)){s.push(c);continue}mr(xi.join(e,c))!==r[c]&&o.push(c)}let i=new Set(n),a=Object.keys(r).filter(c=>!i.has(c));return{modified:o,added:s,removed:a}};var gd=30,hd=(e,t)=>{if(t.length!==0){u.info(`
416
+ ${e} (${t.length}):`);for(let r of t.slice(0,gd))u.info(` ${r}`);t.length>gd&&u.info(` \u2026and ${t.length-gd} more`)}},Ti=async(e={})=>{let t=e.cwd??await E(),r=Fh.join(t,X),n={modified:[],added:[],removed:[],fileCount:0};if(!jh(r)){u.info(`\u2139\uFE0F No ${X}/ folder found \u2014 nothing to check.`);let d={status:"skipped",ok:!0,...n};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}}if(!jh(Fh.join(r,_e))){u.error(`\u274C Missing ${X}/${_e}. Re-run the vendor sync to generate it.`);let d={status:"missing-manifest",ok:!1,...n};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}}let o=Do(r);if(pd(o)){u.error(`\u274C ${X}/${_e} has a newer schemaVersion (${String(o.schemaVersion)}) than this CLI supports. Upgrade infra-kit.`);let d={status:"unknown-schema",ok:!1,...n};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}}let{modified:s,added:i,removed:a}=fd(r,o),c=s.length>0||i.length>0||a.length>0;c?(u.error(`\u274C ${X}/ has drifted from ${X}/${_e}.`),u.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),hd("Modified",s),hd("Added (not in manifest)",i),hd("Removed (in manifest, now missing)",a)):u.info(`\u2705 ${X}/ matches manifest (${o.fileCount} files).`);let l={status:c?"drift":"clean",ok:!c,fileCount:o.fileCount,modified:s,added:i,removed:a};return{content:k(JSON.stringify(l,null,2)),structuredContent:l}},PC={status:ut.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:ut.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:ut.number(),modified:ut.array(ut.string()),added:ut.array(ut.string()),removed:ut.array(ut.string())},yd=S({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:PC,handler:()=>Ti({cwd:SC.cwd()})});import Lh from"node:process";import{z as No}from"zod";var Bh=async e=>{try{return await e()}catch{return null}},Ci=async()=>{let e=G.version;u.info(e);let t=await Bh(E),r=t===null?null:await Bh(()=>je(t)),n={version:e,cwd:Lh.cwd(),repoRoot:t,mainRepoRoot:r,projectDir:Lh.env.CLAUDE_PROJECT_DIR||null};return{content:k(JSON.stringify(n,null,2)),structuredContent:n}},vd=S({name:"version",description:"Print the installed infra-kit CLI version and where this process runs (cwd, repo root, main repo root, CLAUDE_PROJECT_DIR)",inputSchema:{},outputSchema:{version:No.string().describe("Installed infra-kit CLI version (from package.json)"),cwd:No.string().describe("The working directory of this process"),repoRoot:No.string().nullable().describe("git toplevel of cwd \u2014 the worktree itself in a linked worktree; null when git cannot answer"),mainRepoRoot:No.string().nullable().describe("The main checkout a linked worktree belongs to (equals repoRoot outside worktrees); null with repoRoot"),projectDir:No.string().nullable().describe("CLAUDE_PROJECT_DIR as Claude Code set it for this process, or null")},handler:Ci});import Wh from"@inquirer/confirm";import EC from"node:path";import{z as W}from"zod";import{$ as _o}from"zx";var $i="create worktrees",xC=["already_open","orca_unreachable","orca_absent","orca_worktree_not_selectable","orca_error"],wd=()=>({orcaOpened:[],orcaSkipped:[],orcaHidden:[]}),Ai=async e=>{let{confirmedCommand:t,all:r,versions:n,githubDesktop:o,orca:s}=e,i=e.ide??e.cursor;await be({operation:$i});try{let a=await Te("release"),c=await E(),l=`${c}${pe}`;await Vh(`${l}/${vr.release}`),await Vh(`${l}/${vr.feature}`);let d=[];if(n)d=n.split(",").map(ue=>xe(ye(ue.trim())));else{let ue=await F(),pt=ue.map(Be=>Be.branch);if(pt.length===0){u.info("\u2139\uFE0F No open release branches found"),h.print();let Be={createdWorktrees:[],count:0,...wd()};return{content:k(JSON.stringify(Be,null,2)),structuredContent:Be}}if(r)d=pt;else{h.setInteractive();let Be=new Map(ue.map(du=>[du.branch,du.type])),iv=await ne();d=await xt(oe({branches:pt,descriptions:iv,types:Be}),{required:!0})}}r?h.addOption("--all",!0):h.addOption("--versions",zt(d));let p=await M(),m=i??(yt(p).length>0?"workspace":"none");h.addOption("--ide",m);let g=await TC(o,p),y=await CC(s,p),R=await je(c),v=EC.basename(R),$=y?await $C({explicit:s!==void 0,mainRepoRoot:R}):null;await B(t,AC($,v)),t||h.addOption("--yes",!0);let D=$?await OC($,R):null,{branchesToCreate:A}=_C({selectedReleaseBranches:d,currentWorktrees:a}),P=await MC(A,l);if(jC(P),m==="workspace"&&await Zl({projectRoot:c,worktreeDir:l,branches:P}),g)for(let ue of P)await _o`github ${l}/${ue}`,await _o`sleep 5`;let q=D?await DC({registration:D,createdWorktrees:P,worktreeDir:l,mainRepoRoot:R,repoName:v,config:p}):wd();NC(q),h.print();let U={createdWorktrees:P,count:P.length,...q};return{content:k(JSON.stringify(U,null,2)),structuredContent:U}}catch(a){throw ve(a)||a instanceof x?a:(u.debug({err:a},"Error managing worktrees"),new f(a,{operation:$i,remediation:"verify branches don't already exist as worktrees: 'git worktree list'"}))}},TC=async(e,t)=>{let r=t.worktrees?.openInGithubDesktop,n=e??r??await O(o=>Wh({message:"Open created worktrees in GitHub Desktop?"},o),{whenHeadless:{value:!1}});return e===void 0&&r===void 0&&h.setInteractive(),h.addOption(n?"--github-desktop":"--no-github-desktop",!0),n},CC=async(e,t)=>{let r=t.worktrees?.openInOrca,n=e??r??await O(o=>Wh({message:"Open created worktrees in Orca?",default:!0},o),{whenHeadless:{value:!1}});return e===void 0&&r===void 0&&h.setInteractive(),h.addOption(n?"--orca":"--no-orca",!0),n},Uh=e=>e==="absent"?{reason:"orca_absent",text:"the orca CLI is not installed (Orca \u2192 Settings \u2192 Experimental \u2192 CLI)"}:{reason:"orca_unreachable",text:"Orca is not running"},$C=async e=>{let{explicit:t,mainRepoRoot:r}=e,n=await Rr();if(n!=="ready"){let{reason:s,text:i}=Uh(n);if(t)throw u.warn({operation:$i},`\u26D4 --orca was passed but ${i}`),new x({status:"refused",reason:s,agentMode:I.source},2,{operation:$i,remediation:n==="absent"?"install Orca (brew install --cask stablyai/orca/orca) and register its CLI from Settings \u2192 Experimental \u2192 CLI, or re-run with --no-orca":"open Orca (`orca open`) and re-run, or re-run with --no-orca",stderrExcerpt:`--orca was passed but ${i}; no worktree was created`});return u.warn(`\u26A0\uFE0F ${i} \u2014 worktrees will be created but not opened in Orca`),{probe:n,registered:!1,visibility:void 0}}let o=await xp(r);return{probe:n,registered:o.registered,visibility:o.visibility}},AC=(e,t)=>{let r=["Are you sure you want to proceed with these worktree changes?"];return e?.probe==="ready"&&!e.registered&&r.push(` \u2022 will register ${t} in Orca (orca repo add); its worktrees start hidden in Orca's sidebar until you choose Show`),r.join(`
417
+ `)},OC=async(e,t)=>{if(e.probe!=="ready")return{kind:"skip",reason:Uh(e.probe).reason};if(e.registered)return{kind:"ready",visibility:e.visibility};try{let{visibility:r}=await Tp(t);return{kind:"ready",visibility:r}}catch(r){return u.warn({error:r},"\u26A0\uFE0F orca repo add failed \u2014 worktrees will be created but not opened in Orca"),{kind:"skip",reason:"orca_error",code:r instanceof as?r.code:void 0}}},IC=e=>`Orca \u2192 ${e} \u2192 "hidden worktrees" card \u2192 Show, or Settings \u2192 General \u2192 Workspace \u2192 external-worktree sources`,DC=async e=>{let{registration:t,createdWorktrees:r,worktreeDir:n,mainRepoRoot:o,repoName:s,config:i}=e,a=wd();if(t.kind==="skip"){for(let p of r)a.orcaSkipped.push({branch:p,reason:t.reason,code:t.code});return a}let c=np(i),l=r.length===1&&t.visibility!=="hide",d=$p();for(let p of r){let m=`${n}/${p}`;try{let{layout:g}=await Ap({cwd:m,title:Op({branch:p}),focus:l,layout:"full",panes:c,poll:d});await Cp(o,m)?a.orcaOpened.push({branch:p,layout:g}):a.orcaHidden.push({branch:p,path:m,fix:IC(s)})}catch(g){u.warn({error:g,branch:p},`\u26A0\uFE0F Failed to open Orca terminals for ${p}`),g instanceof as&&g.code==="orca_worktree_not_selectable"?a.orcaSkipped.push({branch:p,reason:"orca_worktree_not_selectable"}):a.orcaSkipped.push({branch:p,reason:"orca_error",code:g instanceof as?g.code:void 0})}}return a},NC=e=>{for(let t of e.orcaOpened)u.info(`\u{1FA9F} Opened ${t.branch} in Orca (${t.layout})`);for(let t of e.orcaHidden)u.info(`\u{1F648} ${t.branch} opened in Orca but its row is hidden (${t.path}) \u2014 ${t.fix}`);for(let t of e.orcaSkipped){let r=t.code?` (${t.code})`:"";u.info(`\u21A9\uFE0F ${t.branch} not opened in Orca: ${t.reason}${r}`)}},Vh=async e=>{await _o`mkdir -p ${e}`},_C=e=>{let{selectedReleaseBranches:t,currentWorktrees:r}=e,n=r.filter(s=>Qo(s));return{branchesToCreate:t.filter(s=>!n.includes(s))}},MC=async(e,t)=>{let r=await Promise.allSettled(e.map(async o=>{let s=`${t}/${o}`;return await _o`git worktree add ${s} ${o}`,await _o({cwd:s})`pnpm install`,o})),n=[];for(let[o,s]of r.entries())if(s.status==="fulfilled")n.push(s.value);else{let i=e[o],a=new f(s.reason,{operation:`git worktree add for ${i}`,remediation:"check the branch name and that the parent dir is writable"});u.error({error:s.reason,msg:a.message})}return n},jC=e=>{if(e.length>0){u.info("\u2705 Created git worktrees:");for(let t of e)u.info(t);u.info("")}else u.info("\u2139\uFE0F No new git worktrees to create")},kd=S({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 / Orca" follow-up prompts are unreachable without a TTY, and the CLI confirmation is auto-skipped for MCP calls. With "orca" true each created worktree gets an Orca terminal tab laid out per "worktrees.orca.layout"; the result reports orcaOpened, orcaSkipped (with a reason) and orcaHidden (a worktree Orca's sidebar hides, with the UI steps to reveal it). An unregistered repo is registered in Orca first (orca repo add).`,inputSchema:{all:W.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:W.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:W.enum(ur).optional().describe('Editor open mode for created worktrees, applied to the configured editor (Cursor, per the "ide" config). "workspace" (the only attach style) adds each worktree to the Cursor workspace and opens it. "none" skips the editor. Resolution order: this flag \u2192 "workspace" when an "ide" is configured \u2192 "none" otherwise.'),cursor:W.enum(ur).optional().describe('Deprecated alias for "ide". Prefer "ide". Ignored when "ide" is provided.'),githubDesktop:W.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).'),orca:W.boolean().optional().describe('Open each created worktree in Orca: one terminal tab per worktree, laid out per "worktrees.orca.layout" (default "two-columns": left | right; or "three-pane": left split top/bottom + full-height right). Resolution order: this flag \u2192 "worktrees.openInOrca" from infra-kit config \u2192 interactive prompt (CLI, default yes) / false (MCP, no TTY). Passed explicitly, an Orca that is absent or not running is refused before any worktree is created (orca_absent / orca_unreachable); resolved from config it degrades to orcaSkipped with that reason.')},outputSchema:{createdWorktrees:W.array(W.string()).describe("List of created git worktree branches"),count:W.number().describe("Number of git worktrees created"),orcaOpened:W.array(W.object({branch:W.string(),layout:W.enum(["full","single-pane"])})).describe("Created worktrees that got an Orca terminal tab on a row the sidebar shows, with the layout applied"),orcaSkipped:W.array(W.object({branch:W.string(),reason:W.enum(xC),code:W.string().optional()})).describe("Created worktrees NOT opened in Orca and why: orca_absent / orca_unreachable (config-derived ask, Orca down), orca_worktree_not_selectable (Orca had not scanned the fresh worktree yet), orca_error (code carries the Orca error code)"),orcaHidden:W.array(W.object({branch:W.string(),path:W.string(),fix:W.string()})).describe("Created worktrees whose Orca terminals opened on a row the sidebar HIDES (the repo hides external worktrees); fix names the in-app steps to reveal it")},handler:Ai});import{z as dn}from"zod";var Oi=async()=>{await M();let e=await Te("release");if(e.length===0)return u.info("\u2139\uFE0F No active worktrees found"),{content:k(JSON.stringify({worktrees:[],count:0},null,2)),structuredContent:{worktrees:[],count:0}};let[t,r]=await Promise.all([F(),ne()]),n=new Map(t.map(c=>[c.branch,c.type])),o=e.flatMap(c=>{let l=J(c);if(!l)return[];let d=Y(l),p=n.get(c)||"regular",m=r.get(te(l))||null;return[{version:d,type:p,description:m}]}),s=Math.max(...o.map(c=>c.version.length)),i=o.map(c=>{let l=qn(c.version,c.type,s);return c.description?`${l} ${c.description}`:l});u.info(`\u{1F33F} Active worktrees:
415
418
 
416
419
  ${i.join(`
417
- `)}`);let a={worktrees:o,count:o.length};return{content:k(JSON.stringify(a,null,2)),structuredContent:a}},Ud=R({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:Tn.array(Tn.object({version:Tn.string().describe("Release version"),type:Tn.enum(["regular","hotfix"]).describe("Release type"),description:Tn.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:Tn.number().describe("Number of worktrees")},handler:zi});import{z as Pr}from"zod";var b$=e=>{if(ee()){if(e.all)throw new E({status:"refused",agentMode:A.source},2,{operation:"remove worktrees",remediation:"name targets explicitly via --versions <refs>; bulk --all removal is disabled under agent mode",stderrExcerpt:"--all is not permitted for worktrees remove under agent mode"});if(!e.versions)throw new E({status:"argument_required",argument:"versions",agentMode:A.source},2,{operation:"remove worktrees",remediation:"pass --versions <refs> (comma-separated release versions/names) on the re-run \u2014 `infra-kit worktrees list --json` lists them",stderrExcerpt:"worktrees remove under agent mode requires --versions"})}},R$=(e,t)=>{let r=e.filter(n=>!t.includes(n));if(r.length>0)throw new f(void 0,{operation:"remove worktrees",remediation:`no active worktree for: ${r.join(", ")}. Run 'infra-kit worktrees list' to see current worktrees`,stderrExcerpt:`unmatched worktree target(s): ${r.join(", ")}`})},S$=async(e,t)=>{let r=await Rs(t.map(n=>`${e}/${n}`));if(r!==null)throw new E({status:"refused",reason:"orca_caller_inside_target",agentMode:A.source},2,{operation:"remove worktrees",remediation:`re-run from a terminal that is not an Orca pane of ${r} (a non-Orca terminal, or another worktree's row)`,stderrExcerpt:`this command runs inside an Orca terminal of ${r}, which the removal would close`})},Yi=async e=>{let{confirmedCommand:t,all:r,versions:n}=e;await be({operation:"remove worktrees"}),await D(),b$({all:r,versions:n});try{let o=await Ce("release");if(o.length===0){p.info("\u2139\uFE0F No active worktrees to remove"),h.print();let d={removedWorktrees:[],failedWorktrees:[],count:0};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}}let s=await x(),i=`${s}${ge}`,a=[];if(r)a=o;else if(n)a=n.split(",").map(d=>Te(ve(d.trim())));else{h.setInteractive();let[d,u]=await Promise.all([oe(),F()]),m=new Map(u.map(g=>[g.branch,g.type]));a=await Nt(se({branches:o,descriptions:d,types:m}),{required:!0})}R$(a,o);let c=a.length===o.length;c?h.addOption("--all",!0):h.addOption("--versions",nr(a)),await S$(i,a),await W(t,"Are you sure you want to proceed with these worktree changes?"),t||h.addOption("--yes",!0);let l=await yr({branches:a,worktreeDir:i,projectRoot:s,pruneFolder:c});return await kr({projectRoot:s,worktreeDir:i,removedWorktrees:l.removed}),$o(l),h.print(),Ao({result:l,operation:"remove worktrees"})}catch(o){throw we(o)||o instanceof f?o:(p.error({error:o},"\u274C Error managing worktrees"),new f(o,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"}))}},Gd=R({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". A branch git refuses to remove is listed in failedWorktrees and the result carries isError; a leftover that git already unregistered and that holds only tool state (.omc/state, .omc/sessions, .DS_Store) is swept automatically. Every Orca terminal open in a removed worktree is closed first; a call made from an Orca terminal INSIDE one of the targets is refused (orca_caller_inside_target) before anything is removed \u2014 re-run it from a terminal that is not an Orca pane of that worktree.',requiresHumanConfirm:!0,inputSchema:{versions:Pr.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.'),confirm:Pr.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{removedWorktrees:Pr.array(Pr.string()).describe("List of removed git worktree branches"),failedWorktrees:Pr.array(Pr.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:Pr.number().describe("Number of git worktrees removed")},handler:Yi});import{z as zo}from"zod";var Xi=async e=>{let{confirmedCommand:t}=e;await be({operation:"sync worktrees"}),await D();try{let r=await Ce("release"),n=await x(),o=`${n}${ge}`,s=await Fs();await W(t,"Are you sure you want to proceed with these worktree changes?"),t||h.addOption("--yes",!0);let{branchesToRemove:i}=P$({releasePRsList:s,currentWorktrees:r}),a=await yr({branches:i,worktreeDir:o,projectRoot:n});return await kr({projectRoot:n,worktreeDir:o,removedWorktrees:a.removed}),$o(a),h.print(),Ao({result:a,operation:"sync worktrees"})}catch(r){throw we(r)||r instanceof f?r:(p.error({error:r},"\u274C Error managing worktrees"),new f(r,{operation:"sync worktrees with remote",remediation:"ensure 'gh auth status' is ok and you can reach origin"}))}},P$=e=>{let{releasePRsList:t,currentWorktrees:r}=e;return{branchesToRemove:r.filter(s=>us(s)).filter(s=>!t.includes(s))}},Kd=R({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. A branch git refuses to remove is listed in failedWorktrees and the result carries isError; a leftover that git already unregistered and that holds only tool state (.omc/state, .omc/sessions, .DS_Store) is swept automatically.",inputSchema:{},outputSchema:{removedWorktrees:zo.array(zo.string()).describe("List of removed worktree branches"),failedWorktrees:zo.array(zo.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:zo.number().describe("Number of worktrees removed during sync")},handler:Xi});var Hd=[{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"}],fr=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["dev"],longRunning:!0},{cliName:"dev-status",menuGroup:"develop",mcpTool:yc,mcpExposed:!0,mutating:!1,groupPath:["dev-status"]},{cliName:"e2e",menuGroup:"develop",mcpTool:Cl,mcpExposed:!1,mutating:!0,groupPath:["e2e"]},{cliName:"merge-dev",menuGroup:"release",mcpTool:Ll,mcpExposed:!0,mutating:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:td,mcpExposed:!0,mutating:!1,groupPath:["release","list"]},{cliName:"release-create",menuGroup:"release",mcpTool:gd,mcpExposed:!0,mutating:!0,groupPath:["release","create"]},{cliName:"release-edit",menuGroup:"release",mcpTool:yd,mcpExposed:!0,mutating:!0,groupPath:["release","edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:Zl,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:ed,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:Bl,mcpExposed:!1,mutating:!0,humanOnly:!0,groupPath:["release","deliver"]},{cliName:"release-remove",menuGroup:"release",mcpTool:Pd,mcpExposed:!0,mutating:!0,groupPath:["release","remove"]},{cliName:"local-deploy-all",menuGroup:null,mcpTool:dd,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-all"]},{cliName:"local-deploy-selected",menuGroup:null,mcpTool:pd,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-selected"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:Jd,mcpExposed:!0,mutating:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:Ud,mcpExposed:!0,mutating:!1,groupPath:["worktrees","list"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:Gd,mcpExposed:!0,mutating:!0,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:Kd,mcpExposed:!0,mutating:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:_l,mcpExposed:!0,mutating:!1,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:Ol,mcpExposed:!0,mutating:!1,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:Nl,mcpExposed:!0,mutating:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:Al,mcpExposed:!0,mutating:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:Ml,mcpExposed:!0,mutating:!1,groupPath:["env-token-list"]},{cliName:"config-get",menuGroup:"configuration",mcpTool:fc,mcpExposed:!0,mutating:!1,groupPath:["config-get"]},{cliName:"config-path",menuGroup:"configuration",mcpTool:null,mcpExposed:!1,mutating:!1,groupPath:["config","path"]},{cliName:"config-edit",menuGroup:"configuration",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["config","edit"],entersAltScreen:!0},{cliName:"vendor-check",menuGroup:"vendor",mcpTool:Vd,mcpExposed:!0,mutating:!1,groupPath:["vendor","check"]},{cliName:"vendor-config",menuGroup:"vendor",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["vendor","config"]},{cliName:"vendor-sync",menuGroup:"vendor",mcpTool:null,mcpExposed:!1,mutating:!0,humanOnly:!0,groupPath:["vendor","sync"]},{cliName:"setup",menuGroup:"setup",mcpTool:Od,mcpExposed:!0,mutating:!0,groupPath:["setup"]},{cliName:"doctor",menuGroup:"setup",mcpTool:Sl,mcpExposed:!0,mutating:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:mc,mcpExposed:!0,mutating:!1,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:Bd,mcpExposed:!0,mutating:!1,groupPath:["version"]},{cliName:"vendor",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!1,groupPath:["vendor"]},{cliName:"config",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!1,groupPath:["config"]},{cliName:"env-token-set",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["env-token-set"]},{cliName:"env-token-remove",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["env-token-remove"]}];var qd=e=>fr.filter(t=>t.menuGroup===e),zd=e=>fr.some(t=>t.longRunning===!0&&t.groupPath.join(" ")===e);var E$=(e,t)=>{let r=e,n;for(let o of t){if(n=r.find(s=>s.name()===o),!n)return;r=n.commands}return n},uy=e=>Hd.flatMap(({key:t,label:r})=>qd(t).flatMap(n=>{let o=E$(e,n.groupPath);return o?[{name:n.groupPath.join(" "),description:o.description(),group:r}]:[]}));import Yd from"node:process";var x$="MODULE_TYPELESS_PACKAGE_JSON",T$=(e,t)=>typeof e=="object"&&e!==null?e.code:t,my=!1,Xd=()=>{if(my)return;my=!0;let e=Yd.emitWarning.bind(Yd);Yd.emitWarning=((t,...r)=>{T$(r[0],r[1])!==x$&&e(t,...r)})};import{Command as XA,InvalidArgumentError as ZA}from"commander";import{resolve as QA}from"node:path";import Fe from"node:process";import{cd as eO}from"zx";import fy from"node:process";import{$ as C$}from"zx";var Zd=async()=>{let e=await te(),t=await Promise.all([{label:"project (committed)",path:e.main},{label:"user global",path:e.userGlobal},{label:"user project",path:e.userProject}].map(async i=>({...i,exists:await X(i.path)}))),r=t.at(-1)?.exists===!0,n=await fo(e.userProject,r),o=r?go(n):"";p.info(`Project name: ${e.projectName}
418
- `),p.info(`Config merge chain (later overrides earlier):
419
- `);for(let i of t){let a=i.exists?" [\u2713]":" [ ]",c=i.path===e.userProject&&o!==""?` ${o}`:"";p.info(`${a} ${i.label.padEnd(22)} ${w(i.path)}${c}`)}let s={projectName:e.projectName,layers:t.map(i=>({label:i.label,path:i.path,exists:i.exists})),hasOverrides:n.hasOverrides,overrideKeys:n.overrideKeys};return{content:[{type:"text",text:JSON.stringify(s,null,2)}],structuredContent:s}},Qd=async()=>{let e=await te(),t=fy.env.EDITOR||fy.env.VISUAL||"vi",r=await Qr(e);r.createdConfig&&p.info(en(r)),p.info(`Opening ${w(e.userProject)} in ${t} (per-machine override \u2014 every key except "mcp")`),await C$({stdio:"inherit"})`${t} ${e.userProject}`,Ct();let n={path:e.userProject,editor:t};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}};var gy="https://dashboard.doppler.com/workplace/projects",$$=(e,t)=>["Removing it locally does NOT revoke it \u2014 the token still works anywhere else it is stored.",`Revoke it in Doppler (project "${e}", config "${t}"): ${gy}/${e}`],ep=async({env:e})=>{let r=!!(await ue())?.envs[e];await ju(e);let n=await We(),o=await lt();r?p.info(`Removed the "${e}" service token from ${w(o)}.`):p.info(`No "${e}" service token was stored in ${w(o)} \u2014 nothing to remove.`);for(let i of $$(n,e))p.warn(i);let s={env:e,removed:r,storePath:o,revokeUrl:`${gy}/${n}`};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}};import A$ from"@inquirer/password";import Qi from"node:process";import{$ as Zi}from"zx";var O$=async({stdin:e,fromEnv:t})=>{if(e)return{token:await I$(),source:"stdin"};if(t){let n=Qi.env[t];if(!n)throw new Error(`${t} is not set (or is empty) \u2014 nothing to store.`);return{token:n,source:"env"}}return h.setInteractive(),{token:(await I(n=>A$({message:"Paste the Doppler service token (input is hidden)",mask:!0},n),{output:Qi.stderr,whenHeadless:{refuse:"stdin"}})).trim(),source:"prompt"}},I$=async()=>{let e=[];Qi.stdin.setEncoding("utf8");for await(let t of Qi.stdin)e.push(t);return e.join("").trim()},tp="DOPPLER_CONFIG",D$=3e4,N$=async(e,t,r)=>{let n=Zi.quiet;Zi.quiet=!0;let o;try{o=(await Zi({env:bn(e)})`doppler secrets download --no-file --format json --project ${t} --config ${r}`.timeout(D$)).stdout}catch(s){throw _$(s,r)}finally{Zi.quiet=n}return yi(o)},_$=(e,t)=>{let r=$r(e)??(e instanceof Error?e.message:String(e));if(ir(r)!=="auth")return e instanceof Error?e:new Error(String(e));let n=ar(r)==="mis-scoped"?"it is scoped to a DIFFERENT config (pasting another environment's token here is the mistake this check exists to catch).":"it is invalid or has been revoked.";return new Error([`Doppler refused this token for config "${t}" \u2014 ${n}`,"Nothing was written. Issue a service token scoped to that config and try again."].join(`
420
- `))},M$=e=>[`Could not verify this token's scope: the Doppler payload for "${e}" carries no ${tp}.`,"Refusing to store a credential whose scope is unknown (a token for the wrong environment would load","the wrong secrets into every shell).","Re-run with --force if you are certain the token is scoped to this config."].join(`
421
- `),rp=async({env:e,stdin:t,fromEnv:r,force:n})=>{let o=await We(),{token:s,source:i}=await O$({stdin:t,fromEnv:r});if(!s)throw new Error("No token provided \u2014 nothing was written.");let a=await N$(s,o,e);hi(a,e);let c=a.some(([u])=>u===tp);if(!c&&!n)throw new Error(M$(e));await Mu(e,s);let l=await lt();p.info(`Stored the "${e}" service token (${Sn(s)}) in ${w(l)} (mode 0600).`),c||p.warn(`Scope was NOT verified (no ${tp} in the payload) \u2014 written because --force was given.`);let d={env:e,source:i,redactedToken:Sn(s),storePath:l,scopeVerified:c};return h.print(),{content:k(JSON.stringify(d,null,2)),structuredContent:d}};var np=async(e,t,r=!0)=>{let{from:n,version:o,env:s,services:i,skipTerraform:a,yes:c,dryRun:l,printEnv:d}=e,u=await Yl(n);if(r&&h.addOption("--from",u),zl(u,{"--version":o,"--skip-terraform":a,"--dry-run":l,"--print-env":d}),u==="local")throw new f(void 0,{operation:"deploy --from local",remediation:"use --from ci to dispatch the release workflow",stderrExcerpt:"local deploys are disabled for now \u2014 deploys run in CI only"});return t==="all"?Pi({version:o,env:s,skipTerraform:a,confirmedCommand:c}):Ei({version:o,env:s,services:i,skipTerraform:a,confirmedCommand:c})},op=async e=>np(e,"all"),sp=async e=>np(e,"selected"),ea=async(e,t)=>{let r=`release deploy-${t} --from local`;return p.warn(`\`local deploy-${t}\` is deprecated and will be removed \u2014 use \`${r}\` instead.`),np({...e,from:"local"},t,!1)};import{VENDOR_CONFIG_FILE as yy}from"@slip-stream-kit/config/internal";import ip from"node:fs/promises";import Cn from"node:path";import hy from"node:process";import{pathToFileURL as j$}from"node:url";var vy="~/projects",ap=async(e={})=>{if(e.init){await L$(e.cwd);return}await F$()},F$=async()=>{let e=rn(),t=await X(e);if(p.info(`Factory config: ${w(e)} ${t?"[\u2713]":"[ ]"}`),!t){p.info("\nNot found \u2014 run `infra-kit vendor config --init` to scaffold it."),hy.exitCode=1;return}let{workspaceDir:r,source:n,targets:o}=await Qs(),s=nn(r),i=await X(s),a=Cn.join(s,n),c=await X(a);p.info(`workspaceDir: ${r} (resolved: ${s}) ${i?"[\u2713 exists]":"[ ] not found"}`),p.info(`Source: ${c?"[\u2713]":"[ ]"} ${n} ${w(a)}${c?"":" (not found \u2014 clone it)"}`),p.info("Targets:");let l=i&&c;for(let d of o){let u=Cn.join(s,d),m=await X(u);m||(l=!1);let g=m?"[\u2713]":"[ ]",y=m?"":" (not found \u2014 clone or remove)";p.info(` ${g} ${d} ${w(u)}${y}`)}l||(hy.exitCode=1)},L$=async e=>{let t=rn();if(await X(t)){p.info(`Factory config already exists at ${w(t)} \u2014 leaving it untouched.`);return}let r=e??await x(),n=await V$(r);await ip.mkdir(Cn.dirname(t),{recursive:!0}),await ip.writeFile(t,B$(Cn.basename(r),n),"utf-8"),p.info(`\u2713 Created ${w(t)}`),n.length>0&&p.info(` Seeded ${n.length} target(s) from the source ${yy}.`),p.info(` Edit \`workspaceDir\` (placeholder: ${vy}) to point at where your repos live.`),p.info(` \`source\` is seeded with ${Cn.basename(r)} (this repo); change it if the source is another repo.`),n.length===0&&p.info(" Add at least one repo name to `targets` before running vendor sync/manifest/diff.")},V$=async e=>{try{let t=Cn.join(e,yy),r=await ip.stat(t),s=(await import(`${j$(t).href}?mtime=${Number(r.mtimeMs)}`)).default,i=typeof s=="function"?await s():s;if(i&&typeof i=="object"&&"targets"in i){let a=i.targets;if(Array.isArray(a)&&a.every(c=>typeof c=="string"))return a}}catch{}return[]},B$=(e,t)=>`${JSON.stringify({workspaceDir:vy,source:e,targets:t},null,2)}
422
- `;import{existsSync as FA}from"node:fs";import LA from"node:fs/promises";import Vy from"node:path";import kp from"node:process";import{z as VA}from"zod";import{chmodSync as z$,copyFileSync as Y$,lstatSync as X$,mkdirSync as Cy,readdirSync as Z$,readlinkSync as Q$,rmdirSync as $y,symlinkSync as eA,unlinkSync as tA,writeFileSync as rA}from"node:fs";import ye from"node:path";import{lstatSync as W$,readlinkSync as wy}from"node:fs";import J$ from"node:path";var U$=new Set(["ENOENT","ENOTDIR"]),ta=e=>{let t;try{t=W$(e)}catch(r){if(U$.has(r.code??""))return null;throw r}return t.isSymbolicLink()?{kind:"link",text:wy(e)}:t.isFile()?{kind:"file",executable:(t.mode&64)!==0,sha:Sr(e)}:{kind:"other"}},ky=(e,t)=>{let r=J$.join(e,t.path),n=t.mode==="120000"?{kind:"link",text:wy(r)}:{kind:"file",executable:t.mode==="100755",sha:Sr(r)};return{...t,fingerprint:n}},by=(e,t)=>t===null||e.kind!==t.kind?!1:e.kind==="link"&&t.kind==="link"?e.text===t.text:e.kind==="file"&&t.kind==="file"?e.executable===t.executable&&e.sha===t.sha:!1;import{$ as G$}from"zx";var Q=async(e,t,r={})=>{let{input:n,allowFailure:o=!1}=r,s=await G$({cwd:e,quiet:!0,input:n,nothrow:o})`git ${t}`;return s.exitCode===0?s.stdout:""},ra=e=>e.slice(0,7),Gt=e=>e.split("\0").filter(t=>t.length>0);import K$ from"node:path";var cp=`${Z}/`,Kt=`${Z}/README.md`,Yo=`${Z}/${je}`,Sy=e=>e.startsWith(cp),Ry=e=>{let t=K$.posix.normalize(e);return t.endsWith("/")?t.slice(0,-1):t},Py=e=>{let t=Ry(e.path),r=e.target===void 0?t:Ry(e.target);return{path:t,target:r,vendored:Sy(r)}},Ey=e=>e.copy.map(Py),Xo=(e,t)=>t.length===0?!1:e.split("/").some(r=>t.includes(r)),Zo=(e,t)=>e.filter(r=>!Xo(r.path,t)),na=(e,t)=>e===t.path?t.target:`${t.target}${e.slice(t.path.length)}`,$n=e=>[...new Set(e)].sort(),xy=e=>e.startsWith(cp)?e.slice(cp.length):null;var oa=e=>`# vendor/ \u2014 mirrored from ${e}
420
+ `)}`);let a={worktrees:o,count:o.length};return{content:k(JSON.stringify(a,null,2)),structuredContent:a}},bd=S({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:dn.array(dn.object({version:dn.string().describe("Release version"),type:dn.enum(["regular","hotfix"]).describe("Release type"),description:dn.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:dn.number().describe("Number of worktrees")},handler:Oi});import{z as fr}from"zod";var FC=e=>{if(fe()){if(e.all)throw new x({status:"refused",agentMode:I.source},2,{operation:"remove worktrees",remediation:"name targets explicitly via --versions <refs>; bulk --all removal is disabled under agent mode",stderrExcerpt:"--all is not permitted for worktrees remove under agent mode"});if(!e.versions)throw new x({status:"argument_required",argument:"versions",agentMode:I.source},2,{operation:"remove worktrees",remediation:"pass --versions <refs> (comma-separated release versions/names) on the re-run \u2014 `infra-kit worktrees list --json` lists them",stderrExcerpt:"worktrees remove under agent mode requires --versions"})}},LC=(e,t)=>{let r=e.filter(n=>!t.includes(n));if(r.length>0)throw new f(void 0,{operation:"remove worktrees",remediation:`no active worktree for: ${r.join(", ")}. Run 'infra-kit worktrees list' to see current worktrees`,stderrExcerpt:`unmatched worktree target(s): ${r.join(", ")}`})},BC=async(e,t)=>{let r=await cs(t.map(n=>`${e}/${n}`));if(r!==null)throw new x({status:"refused",reason:"orca_caller_inside_target",agentMode:I.source},2,{operation:"remove worktrees",remediation:`re-run from a terminal that is not an Orca pane of ${r} (a non-Orca terminal, or another worktree's row)`,stderrExcerpt:`this command runs inside an Orca terminal of ${r}, which the removal would close`})},Ii=async e=>{let{confirmedCommand:t,all:r,versions:n}=e;await be({operation:"remove worktrees"}),await M(),FC({all:r,versions:n});try{let o=await Te("release");if(o.length===0){u.info("\u2139\uFE0F No active worktrees to remove"),h.print();let d={removedWorktrees:[],failedWorktrees:[],count:0};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}}let s=await E(),i=`${s}${pe}`,a=[];if(r)a=o;else if(n)a=n.split(",").map(d=>xe(ye(d.trim())));else{h.setInteractive();let[d,p]=await Promise.all([ne(),F()]),m=new Map(p.map(g=>[g.branch,g.type]));a=await xt(oe({branches:o,descriptions:d,types:m}),{required:!0})}LC(a,o);let c=a.length===o.length;c?h.addOption("--all",!0):h.addOption("--versions",zt(a)),await BC(i,a),await B(t,"Are you sure you want to proceed with these worktree changes?"),t||h.addOption("--yes",!0);let l=await ar({branches:a,worktreeDir:i,projectRoot:s,pruneFolder:c});return await dr({projectRoot:s,worktreeDir:i,removedWorktrees:l.removed}),ho(l),h.print(),yo({result:l,operation:"remove worktrees"})}catch(o){throw ve(o)||o instanceof f?o:(u.error({error:o},"\u274C Error managing worktrees"),new f(o,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"}))}},Rd=S({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". A branch git refuses to remove is listed in failedWorktrees and the result carries isError; a leftover that git already unregistered and that holds only tool state (.omc/state, .omc/sessions, .DS_Store) is swept automatically. Every Orca terminal open in a removed worktree is closed first; a call made from an Orca terminal INSIDE one of the targets is refused (orca_caller_inside_target) before anything is removed \u2014 re-run it from a terminal that is not an Orca pane of that worktree.',requiresHumanConfirm:!0,inputSchema:{versions:fr.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.'),confirm:fr.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{removedWorktrees:fr.array(fr.string()).describe("List of removed git worktree branches"),failedWorktrees:fr.array(fr.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:fr.number().describe("Number of git worktrees removed")},handler:Ii});import{z as Mo}from"zod";var Di=async e=>{let{confirmedCommand:t}=e;await be({operation:"sync worktrees"}),await M();try{let r=await Te("release"),n=await E(),o=`${n}${pe}`,s=await xs();await B(t,"Are you sure you want to proceed with these worktree changes?"),t||h.addOption("--yes",!0);let{branchesToRemove:i}=VC({releasePRsList:s,currentWorktrees:r}),a=await ar({branches:i,worktreeDir:o,projectRoot:n});return await dr({projectRoot:n,worktreeDir:o,removedWorktrees:a.removed}),ho(a),h.print(),yo({result:a,operation:"sync worktrees"})}catch(r){throw ve(r)||r instanceof f?r:(u.error({error:r},"\u274C Error managing worktrees"),new f(r,{operation:"sync worktrees with remote",remediation:"ensure 'gh auth status' is ok and you can reach origin"}))}},VC=e=>{let{releasePRsList:t,currentWorktrees:r}=e;return{branchesToRemove:r.filter(s=>Qo(s)).filter(s=>!t.includes(s))}},Sd=S({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. A branch git refuses to remove is listed in failedWorktrees and the result carries isError; a leftover that git already unregistered and that holds only tool state (.omc/state, .omc/sessions, .DS_Store) is swept automatically.",inputSchema:{},outputSchema:{removedWorktrees:Mo.array(Mo.string()).describe("List of removed worktree branches"),failedWorktrees:Mo.array(Mo.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:Mo.number().describe("Number of worktrees removed during sync")},handler:Di});var Pd=[{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"}],nr=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["dev"],longRunning:!0},{cliName:"dev-status",menuGroup:"develop",mcpTool:rc,mcpExposed:!0,mutating:!1,groupPath:["dev-status"]},{cliName:"e2e",menuGroup:"develop",mcpTool:ll,mcpExposed:!1,mutating:!0,groupPath:["e2e"]},{cliName:"merge-dev",menuGroup:"release",mcpTool:hl,mcpExposed:!0,mutating:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:Il,mcpExposed:!0,mutating:!1,groupPath:["release","list"]},{cliName:"release-create",menuGroup:"release",mcpTool:Kl,mcpExposed:!0,mutating:!0,groupPath:["release","create"]},{cliName:"release-edit",menuGroup:"release",mcpTool:ql,mcpExposed:!0,mutating:!0,groupPath:["release","edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:$l,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:Ol,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:vl,mcpExposed:!1,mutating:!0,humanOnly:!0,groupPath:["release","deliver"]},{cliName:"release-remove",menuGroup:"release",mcpTool:td,mcpExposed:!0,mutating:!0,groupPath:["release","remove"]},{cliName:"local-deploy-all",menuGroup:null,mcpTool:Vl,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-all"]},{cliName:"local-deploy-selected",menuGroup:null,mcpTool:Wl,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-selected"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:kd,mcpExposed:!0,mutating:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:bd,mcpExposed:!0,mutating:!1,groupPath:["worktrees","list"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:Rd,mcpExposed:!0,mutating:!0,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:Sd,mcpExposed:!0,mutating:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:pl,mcpExposed:!0,mutating:!1,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:_p,mcpExposed:!0,mutating:!1,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:fa,mcpExposed:!0,mutating:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:ul,mcpExposed:!0,mutating:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:ml,mcpExposed:!0,mutating:!1,groupPath:["env-token-list"]},{cliName:"config-get",menuGroup:"configuration",mcpTool:Qa,mcpExposed:!0,mutating:!1,groupPath:["config-get"]},{cliName:"config-path",menuGroup:"configuration",mcpTool:null,mcpExposed:!1,mutating:!1,groupPath:["config","path"]},{cliName:"config-edit",menuGroup:"configuration",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["config","edit"],entersAltScreen:!0},{cliName:"vendor-check",menuGroup:"vendor",mcpTool:yd,mcpExposed:!0,mutating:!1,groupPath:["vendor","check"]},{cliName:"vendor-config",menuGroup:"vendor",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["vendor","config"]},{cliName:"vendor-sync",menuGroup:"vendor",mcpTool:null,mcpExposed:!1,mutating:!0,humanOnly:!0,groupPath:["vendor","sync"]},{cliName:"setup",menuGroup:"setup",mcpTool:cd,mcpExposed:!0,mutating:!0,groupPath:["setup"]},{cliName:"doctor",menuGroup:"setup",mcpTool:ol,mcpExposed:!0,mutating:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:Za,mcpExposed:!0,mutating:!1,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:vd,mcpExposed:!0,mutating:!1,groupPath:["version"]},{cliName:"vendor",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!1,groupPath:["vendor"]},{cliName:"config",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!1,groupPath:["config"]},{cliName:"env-token-set",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["env-token-set"]},{cliName:"env-token-remove",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["env-token-remove"]}];var Ed=e=>nr.filter(t=>t.menuGroup===e),xd=e=>nr.some(t=>t.longRunning===!0&&t.groupPath.join(" ")===e);var WC=(e,t)=>{let r=e,n;for(let o of t){if(n=r.find(s=>s.name()===o),!n)return;r=n.commands}return n},Jh=e=>Pd.flatMap(({key:t,label:r})=>Ed(t).flatMap(n=>{let o=WC(e,n.groupPath);return o?[{name:n.groupPath.join(" "),description:o.description(),group:r}]:[]}));import Td from"node:process";var UC="MODULE_TYPELESS_PACKAGE_JSON",JC=(e,t)=>typeof e=="object"&&e!==null?e.code:t,Gh=!1,Cd=()=>{if(Gh)return;Gh=!0;let e=Td.emitWarning.bind(Td);Td.emitWarning=((t,...r)=>{JC(r[0],r[1])!==UC&&e(t,...r)})};import{Command as fA,InvalidArgumentError as gA}from"commander";import{resolve as hA}from"node:path";import Me from"node:process";import{cd as yA}from"zx";import Kh from"node:process";import{$ as GC}from"zx";var $d=async()=>{let e=await Q(),t=await Promise.all([{label:"project (committed)",path:e.main},{label:"user global",path:e.userGlobal},{label:"user project",path:e.userProject}].map(async i=>({...i,exists:await z(i.path)}))),r=t.at(-1)?.exists===!0,n=await to(e.userProject,r),o=r?ro(n):"";u.info(`Project name: ${e.projectName}
421
+ `),u.info(`Config merge chain (later overrides earlier):
422
+ `);for(let i of t){let a=i.exists?" [\u2713]":" [ ]",c=i.path===e.userProject&&o!==""?` ${o}`:"";u.info(`${a} ${i.label.padEnd(22)} ${w(i.path)}${c}`)}let s={projectName:e.projectName,layers:t.map(i=>({label:i.label,path:i.path,exists:i.exists})),hasOverrides:n.hasOverrides,overrideKeys:n.overrideKeys};return{content:[{type:"text",text:JSON.stringify(s,null,2)}],structuredContent:s}},Ad=async()=>{let e=await Q(),t=Kh.env.EDITOR||Kh.env.VISUAL||"vi",r=await Gr(e);r.createdConfig&&u.info(Kr(r)),u.info(`Opening ${w(e.userProject)} in ${t} (per-machine override \u2014 every key except "mcp")`),await GC({stdio:"inherit"})`${t} ${e.userProject}`,vt();let n={path:e.userProject,editor:t};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}};var Hh="https://dashboard.doppler.com/workplace/projects",KC=(e,t)=>["Removing it locally does NOT revoke it \u2014 the token still works anywhere else it is stored.",`Revoke it in Doppler (project "${e}", config "${t}"): ${Hh}/${e}`],Od=async({env:e})=>{let r=!!(await Bt())?.envs[e];await Rp(e);let n=await br(),o=await Lt();r?u.info(`Removed the "${e}" service token from ${w(o)}.`):u.info(`No "${e}" service token was stored in ${w(o)} \u2014 nothing to remove.`);for(let i of KC(n,e))u.warn(i);let s={env:e,removed:r,storePath:o,revokeUrl:`${Hh}/${n}`};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}};import HC from"@inquirer/password";import _i from"node:process";import{$ as Ni}from"zx";var qC=async({stdin:e,fromEnv:t})=>{if(e)return{token:await YC(),source:"stdin"};if(t){let n=_i.env[t];if(!n)throw new Error(`${t} is not set (or is empty) \u2014 nothing to store.`);return{token:n,source:"env"}}return h.setInteractive(),{token:(await O(n=>HC({message:"Paste the Doppler service token (input is hidden)",mask:!0},n),{output:_i.stderr,whenHeadless:{refuse:"stdin"}})).trim(),source:"prompt"}},YC=async()=>{let e=[];_i.stdin.setEncoding("utf8");for await(let t of _i.stdin)e.push(t);return e.join("").trim()},Id="DOPPLER_CONFIG",zC=3e4,XC=async(e,t,r)=>{let n=Ni.quiet;Ni.quiet=!0;let o;try{o=(await Ni({env:Pn(e)})`doppler secrets download --no-file --format json --project ${t} --config ${r}`.timeout(zC)).stdout}catch(s){throw ZC(s,r)}finally{Ni.quiet=n}return ma(o)},ZC=(e,t)=>{let r=Lu(e)??(e instanceof Error?e.message:String(e));if(vp(r)!=="auth")return e instanceof Error?e:new Error(String(e));let n=wp(r)==="mis-scoped"?"it is scoped to a DIFFERENT config (pasting another environment's token here is the mistake this check exists to catch).":"it is invalid or has been revoked.";return new Error([`Doppler refused this token for config "${t}" \u2014 ${n}`,"Nothing was written. Issue a service token scoped to that config and try again."].join(`
423
+ `))},QC=e=>[`Could not verify this token's scope: the Doppler payload for "${e}" carries no ${Id}.`,"Refusing to store a credential whose scope is unknown (a token for the wrong environment would load","the wrong secrets into every shell).","Re-run with --force if you are certain the token is scoped to this config."].join(`
424
+ `),Dd=async({env:e,stdin:t,fromEnv:r,force:n})=>{let o=await br(),{token:s,source:i}=await qC({stdin:t,fromEnv:r});if(!s)throw new Error("No token provided \u2014 nothing was written.");let a=await XC(s,o,e);pa(a,e);let c=a.some(([p])=>p===Id);if(!c&&!n)throw new Error(QC(e));await bp(e,s);let l=await Lt();u.info(`Stored the "${e}" service token (${sn(s)}) in ${w(l)} (mode 0600).`),c||u.warn(`Scope was NOT verified (no ${Id} in the payload) \u2014 written because --force was given.`);let d={env:e,source:i,redactedToken:sn(s),storePath:l,scopeVerified:c};return h.print(),{content:k(JSON.stringify(d,null,2)),structuredContent:d}};var Nd=async(e,t,r=!0)=>{let{from:n,version:o,env:s,services:i,skipTerraform:a,yes:c,dryRun:l,printEnv:d}=e,p=await Tl(n);if(r&&h.addOption("--from",p),xl(p,{"--version":o,"--skip-terraform":a,"--dry-run":l,"--print-env":d}),p==="local")throw new f(void 0,{operation:"deploy --from local",remediation:"use --from ci to dispatch the release workflow",stderrExcerpt:"local deploys are disabled for now \u2014 deploys run in CI only"});return t==="all"?ii({version:o,env:s,skipTerraform:a,confirmedCommand:c}):ai({version:o,env:s,services:i,skipTerraform:a,confirmedCommand:c})},_d=async e=>Nd(e,"all"),Md=async e=>Nd(e,"selected"),Mi=async(e,t)=>{let r=`release deploy-${t} --from local`;return u.warn(`\`local deploy-${t}\` is deprecated and will be removed \u2014 use \`${r}\` instead.`),Nd({...e,from:"local"},t,!1)};import{VENDOR_CONFIG_FILE as Yh}from"@slip-stream-kit/config/internal";import jd from"node:fs/promises";import un from"node:path";import qh from"node:process";import{pathToFileURL as e$}from"node:url";var zh="~/projects",Fd=async(e={})=>{if(e.init){await r$(e.cwd);return}await t$()},t$=async()=>{let e=qr(),t=await z(e);if(u.info(`Factory config: ${w(e)} ${t?"[\u2713]":"[ ]"}`),!t){u.info("\nNot found \u2014 run `infra-kit vendor config --init` to scaffold it."),qh.exitCode=1;return}let{workspaceDir:r,source:n,targets:o}=await Vs(),s=Yr(r),i=await z(s),a=un.join(s,n),c=await z(a);u.info(`workspaceDir: ${r} (resolved: ${s}) ${i?"[\u2713 exists]":"[ ] not found"}`),u.info(`Source: ${c?"[\u2713]":"[ ]"} ${n} ${w(a)}${c?"":" (not found \u2014 clone it)"}`),u.info("Targets:");let l=i&&c;for(let d of o){let p=un.join(s,d),m=await z(p);m||(l=!1);let g=m?"[\u2713]":"[ ]",y=m?"":" (not found \u2014 clone or remove)";u.info(` ${g} ${d} ${w(p)}${y}`)}l||(qh.exitCode=1)},r$=async e=>{let t=qr();if(await z(t)){u.info(`Factory config already exists at ${w(t)} \u2014 leaving it untouched.`);return}let r=e??await E(),n=await n$(r);await jd.mkdir(un.dirname(t),{recursive:!0}),await jd.writeFile(t,o$(un.basename(r),n),"utf-8"),u.info(`\u2713 Created ${w(t)}`),n.length>0&&u.info(` Seeded ${n.length} target(s) from the source ${Yh}.`),u.info(` Edit \`workspaceDir\` (placeholder: ${zh}) to point at where your repos live.`),u.info(` \`source\` is seeded with ${un.basename(r)} (this repo); change it if the source is another repo.`),n.length===0&&u.info(" Add at least one repo name to `targets` before running vendor sync/manifest/diff.")},n$=async e=>{try{let t=un.join(e,Yh),r=await jd.stat(t),s=(await import(`${e$(t).href}?mtime=${Number(r.mtimeMs)}`)).default,i=typeof s=="function"?await s():s;if(i&&typeof i=="object"&&"targets"in i){let a=i.targets;if(Array.isArray(a)&&a.every(c=>typeof c=="string"))return a}}catch{}return[]},o$=(e,t)=>`${JSON.stringify({workspaceDir:zh,source:e,targets:t},null,2)}
425
+ `;import{existsSync as tA}from"node:fs";import rA from"node:fs/promises";import wy from"node:path";import Xd from"node:process";import{z as nA}from"zod";import{chmodSync as p$,copyFileSync as m$,lstatSync as f$,mkdirSync as iy,readdirSync as g$,readlinkSync as h$,rmdirSync as ay,symlinkSync as y$,unlinkSync as v$,writeFileSync as w$}from"node:fs";import he from"node:path";import{lstatSync as s$,readlinkSync as Xh}from"node:fs";import i$ from"node:path";var a$=new Set(["ENOENT","ENOTDIR"]),ji=e=>{let t;try{t=s$(e)}catch(r){if(a$.has(r.code??""))return null;throw r}return t.isSymbolicLink()?{kind:"link",text:Xh(e)}:t.isFile()?{kind:"file",executable:(t.mode&64)!==0,sha:mr(e)}:{kind:"other"}},Zh=(e,t)=>{let r=i$.join(e,t.path),n=t.mode==="120000"?{kind:"link",text:Xh(r)}:{kind:"file",executable:t.mode==="100755",sha:mr(r)};return{...t,fingerprint:n}},Qh=(e,t)=>t===null||e.kind!==t.kind?!1:e.kind==="link"&&t.kind==="link"?e.text===t.text:e.kind==="file"&&t.kind==="file"?e.executable===t.executable&&e.sha===t.sha:!1;import{$ as c$}from"zx";var Z=async(e,t,r={})=>{let{input:n,allowFailure:o=!1}=r,s=await c$({cwd:e,quiet:!0,input:n,nothrow:o})`git ${t}`;return s.exitCode===0?s.stdout:""},Fi=e=>e.slice(0,7),_t=e=>e.split("\0").filter(t=>t.length>0);import l$ from"node:path";var Ld=`${X}/`,Mt=`${X}/README.md`,jo=`${X}/${_e}`,ty=e=>e.startsWith(Ld),ey=e=>{let t=l$.posix.normalize(e);return t.endsWith("/")?t.slice(0,-1):t},ry=e=>{let t=ey(e.path),r=e.target===void 0?t:ey(e.target);return{path:t,target:r,vendored:ty(r)}},ny=e=>e.copy.map(ry),Fo=(e,t)=>t.length===0?!1:e.split("/").some(r=>t.includes(r)),Lo=(e,t)=>e.filter(r=>!Fo(r.path,t)),Li=(e,t)=>e===t.path?t.target:`${t.target}${e.slice(t.path.length)}`,pn=e=>[...new Set(e)].sort(),oy=e=>e.startsWith(Ld)?e.slice(Ld.length):null;var Bi=e=>`# vendor/ \u2014 mirrored from ${e}
423
426
 
424
427
  **DO NOT EDIT files in this folder here.**
425
428
 
@@ -430,19 +433,19 @@ fail \`ik vendor check\` in CI.
430
433
  To change a vendored package, edit it in \`${e}\` and re-run the sync there.
431
434
 
432
435
  See \`.sync-manifest.json\` for the source commit and per-file checksums.
433
- `;var H$=new Set(["100644","100755","120000"]),q$=(e,t)=>{let r=new Map;for(let n of Gt(e)){let o=n.indexOf(" "),s=n.slice(0,n.indexOf(" ")),i=n.slice(o+1);o<0||!H$.has(s)||Xo(i,t)||r.set(i,{path:i,mode:s})}return[...r.values()]},lp=async(e,t,r)=>{let n=await Q(e,["--literal-pathspecs","ls-files","-z","-s","--",t]);return q$(n,r)},Ty=async e=>Gt(await Q(e,["--literal-pathspecs","ls-files","-z","--",Z]));var An=e=>["git","-C",e.root,"--literal-pathspecs","checkout","HEAD","--",...e.recoveryPaths],Ay=e=>{let t=ta(e);t!==null&&(t.kind==="other"?$y(e):tA(e))},nA=(e,t,r)=>{let n=ye.join(e,r.source),o=ye.join(t,r.target);if(Cy(ye.dirname(o),{recursive:!0}),Ay(o),r.mode==="120000"){eA(Q$(n),o);return}Y$(n,o),z$(o,r.mode==="100755"?493:420)},oA=async(e,t)=>{let r=new Set;for(let n of Gt(await Q(e,["ls-files","-z"]))){if(t.has(n))continue;let o=ye.posix.dirname(n);for(;o!==".";)r.add(o),o=ye.posix.dirname(o)}return r},sA=async(e,t)=>{if(t.length===0)return;let r=await oA(e,new Set(t)),n=[...new Set(t.map(o=>ye.dirname(ye.join(e,o))))];n.sort((o,s)=>s.length-o.length);for(let o of n){let s=o;for(;s!==e&&s.startsWith(e)&&!(!X$(s,{throwIfNoEntry:!1})?.isDirectory()||Z$(s).length>0||r.has(ye.relative(e,s).split(ye.sep).join("/")));)$y(s),s=ye.dirname(s)}},Oy=(e,t,r)=>{let n=new Set(r),o=e.filter(a=>a.vendored).flatMap(a=>a.targetPaths),s=t.filter(a=>!n.has(a)),i=[...o,Kt,...s].map(xy).filter(a=>a!==null&&!Bi(a));return $n(i)},Iy=async(e,t,r,n)=>{let o=ye.join(e,Z);Cy(o,{recursive:!0}),rA(ye.join(e,Kt),oa(t.name));let s=Oy(r,await Ty(e),n);Md(o,{source:t.name,commit:t.headSha},s)},dp=async({source:e,plan:t,onBeforeFirstWrite:r})=>{if(t.status!=="changed")return{touched:[],manifestWritten:!1};r?.(An(t));let n=ye.resolve(t.root),o=t.entries.flatMap(a=>a.deletes);for(let a of o)Ay(ye.join(n,a));await sA(n,o);let s=t.entries.flatMap(a=>a.writes);for(let a of s)nA(e.root,n,a);let i=s.map(a=>a.target);return t.writeVendorMeta?(await Iy(n,e,t.entries,o),{touched:$n([...o,...i,Kt,Yo]),manifestWritten:!0}):{touched:$n([...o,...i]),manifestWritten:!1}},pp=async(e,t)=>(await Iy(e,t,[],[]),[Kt,Yo]);var up=(e,t)=>`[ROOT] vendor: sync from ${e}@${ra(t)}`,iA=e=>{let{stdout:t,stderr:r}=e;return[t,r].filter(o=>typeof o=="string"&&o.trim().length>0).join(`
434
- `).trim()||String(e)},mp=async(e,t,r)=>{if(t.length===0)return{ok:!0};let n=t.join("\0"),o=["--pathspec-from-file=-","--pathspec-file-nul"];try{return await Q(e,["--literal-pathspecs","add","-A",...o],{input:n}),await Q(e,["--literal-pathspecs","commit","--only","-m",r,...o],{input:n}),{ok:!0}}catch(s){return{ok:!1,output:iA(s)}}};var aA=20,cA=20,Dy=(e,t)=>e.length<=t?[...e]:[...e.slice(0,t),`\u2026and ${e.length-t} more`],Ny=(e,t,r)=>{let{entry:n}=e,o=new Set(t.tracked),s=[],i=[];for(let d of Zo(e.files,r)){let u=na(d.path,n);if(s.push(u),by(d.fingerprint,t.onDisk[u]??null))continue;let m=o.has(u)?"modified":"added";i.push({source:d.path,target:u,mode:d.mode,change:m})}let a=new Set(s),c=Zo(t.tracked.map(d=>({path:d})),r).map(d=>d.path).filter(d=>!a.has(d)),l=i.filter(d=>d.change==="added").length;return{...n,targetPaths:s,writes:i,deletes:c,counts:{added:l,modified:i.length-l,removed:c.length}}},Qo=(e,t,r,n=[])=>({name:e.name,root:e.root,status:t,message:r,notes:n,warnings:[],entries:[],writeVendorMeta:!1,recoveryPaths:[]}),fp=e=>e.entries.map(t=>t.entry.target),lA=(e,t,r)=>{let n=["git","-C",t.root,"--literal-pathspecs","status","--",...fp(e)];return Qo(t,"fail",`blocked: ${r.length} uncommitted path(s) under synced paths`,[...Dy(r,aA),Rt(n)])},dA=(e,t)=>{if(e.kind==="unknown-sha")return{notes:[],warnings:["no manifest commit recorded, so the source commits since the last sync are unknown"]};let r=ra(e.sha);return e.kind==="unresolvable"?{notes:[],warnings:[`manifest commit ${r} is not in ${t}, so the changelog is unknown`]}:{notes:[`${e.lines.length} ${t} commit(s) since ${r}`,...Dy(e.lines,cA)],warnings:[]}},pA=e=>{let{added:t,modified:r,removed:n}=e.counts;return t+r+n===0?null:`${e.target}: ${t} added, ${r} modified, ${n} removed`},uA=e=>{let t=r=>e.reduce((n,o)=>n+o.counts[r],0);return`${t("added")} added, ${t("modified")} modified, ${t("removed")} removed`},mA=(e,t,r)=>{let n=e.flatMap(o=>[...o.writes.filter(i=>i.change==="modified").map(i=>i.target),...o.deletes]);return $n([...n,...r?t.headVendorMeta:[]])},fA=(e,t)=>{if(t.dirty.length>0)return lA(e,t,t.dirty);let r=e.entries.map((d,u)=>{let m=t.entries[u]??{target:d.entry.target,tracked:[],onDisk:{}};return Ny(d,m,e.exclude)}),n=r.some(d=>d.vendored),o=r.some(d=>d.writes.length+d.deletes.length>0),s=n&&(!t.readmeCurrent||!t.manifestPresent),i={...Qo(t,"ok","up to date"),branch:t.branch,entries:r,writeVendorMeta:n};if(!o&&!s)return i;let a=dA(t.changelog,e.name),c=t.manifestSource!==null&&t.manifestSource!==e.name?[`vendor/ was last synced from ${t.manifestSource}, not ${e.name}: this sync replaces it`]:[],l=r.map(pA).filter(d=>d!==null);return{...i,status:"changed",message:`${uA(r)} on ${t.branch}`,notes:[...l,...s?["vendor/README.md and manifest rewritten"]:[],...a.notes],warnings:[...c,...a.warnings],recoveryPaths:mA(r,t,n)}},sa=(e,t)=>{switch(t.kind){case"missing":return Qo(t,"skipped",`not checked out at ${t.root}`);case"source":return Qo(t,"skipped","this is the source repo");case"not-git":return Qo(t,"fail",`not a git repo: ${t.reason}`);case"repo":return fA(e,t)}};import{existsSync as gA,readFileSync as hA,realpathSync as ia}from"node:fs";import aa from"node:path";var gp=async(e,t)=>{let r=t.exclude??[],n=(await Q(e,["rev-parse","HEAD"])).trim(),o=await Le(e),s=await Promise.all(Ey(t).map(async i=>{let a=await lp(e,i.path,r);return{entry:i,files:a.map(c=>ky(e,c))}}));return{root:e,selfRoots:[...new Set([ia(e),ia(o)])],name:aa.basename(o),headSha:n,entries:s,exclude:r}},ca=e=>{let t=Gt(e)[Symbol.iterator](),r=[];for(let n of t)r.push(n.slice(3)),/^[RC]|^.[RC]/u.test(n)&&t.next();return r},yA=async(e,t)=>{let r=await Q(t,["--literal-pathspecs","status","--porcelain","-z","--untracked-files=all","--",...fp(e)]);return ca(r).filter(n=>!Xo(n,e.exclude))},vA=async(e,t)=>Promise.all(e.entries.map(async({entry:r,files:n})=>{let o=await lp(t,r.target,e.exclude),s={};for(let i of Zo(n,e.exclude)){let a=na(i.path,r);s[a]=ta(aa.join(t,a))}return{target:r.target,tracked:o.map(i=>i.path),onDisk:s}})),wA=async e=>{try{return Gt(await Q(e,["--literal-pathspecs","ls-tree","-z","--name-only","HEAD","--",Kt,Yo]))}catch{return[]}},kA=e=>{try{let{commit:t,source:r}=Ko(aa.join(e,Z));return{commit:t,source:r}}catch{return null}},bA=async(e,t)=>{if(t===null)return{kind:"unknown-sha"};if(await $e(e.root,t)===null)return{kind:"unresolvable",sha:t};let r=e.entries.map(({entry:s})=>s.path),o=(await Q(e.root,["--literal-pathspecs","log","--oneline",`${t}..HEAD`,"--",...r])).split(`
435
- `).filter(s=>s.length>0);return{kind:"log",sha:t,lines:o}},RA=(e,t)=>{try{return hA(aa.join(e,Kt),"utf8")===oa(t)}catch{return!1}},SA=async e=>{try{return{toplevel:(await Q(e,["rev-parse","--show-toplevel"])).trim()}}catch(t){return{reason:String(t.stderr??t).trim().split(`
436
- `)[0]??"git rev-parse failed"}}},PA=async e=>{try{return(await Q(e,["rev-parse","--abbrev-ref","HEAD"])).trim()}catch{return"HEAD"}},la=async(e,t)=>{if(!gA(t.root))return{...t,kind:"missing"};let r=ia(t.root);if(e.selfRoots.includes(r))return{...t,kind:"source"};let n=await SA(t.root);if("reason"in n)return{...t,kind:"not-git",reason:n.reason};if(ia(n.toplevel)!==r)return{...t,kind:"not-git",reason:`it sits inside the repo at ${n.toplevel}`};let o=kA(t.root),s=o?.commit??null,[i,a,c,l,d]=await Promise.all([PA(t.root),yA(e,t.root),vA(e,t.root),wA(t.root),bA(e,s)]);return{...t,kind:"repo",branch:i,dirty:a,entries:c,headVendorMeta:l,readmeCurrent:RA(t.root,e.name),manifestPresent:o!==null,manifestSource:o?.source??null,changelog:d}};var EA=20,xA=(e,t)=>!t.commit||e.status!=="changed"||e.branch===void 0?e.notes:[...e.notes,`--commit lands on ${e.branch}`],TA=(e,t)=>{let{plan:r}=e,n=t.manifestOnly?"manifest":"sync";if(e.error!==void 0)return{name:n,status:"fail",message:`apply failed: ${e.error}`,notes:["restore the tracked paths with:",Rt(An(r))]};let o=e.applied?`wrote ${r.message}`:r.message;return{name:n,status:r.status,message:o,notes:t.mode==="applied"?r.notes:xA(r,t)}},CA=e=>e.ok?{name:"commit",status:"ok",message:"committed the synced paths"}:{name:"commit",status:"fail",message:"git refused the commit; the files stay written",notes:e.output.split(`
437
- `).slice(0,EA)},$A=(e,t)=>{let r=e.plan.warnings.map(n=>({name:"changelog",status:"warn",message:n}));return{label:e.plan.name,rows:[TA(e,t),...r,...e.commit?[CA(e.commit)]:[]]}},AA={preview:"infra-kit vendor sync (preview)",check:"infra-kit vendor sync --check",applied:"infra-kit vendor sync"},hp=(e,t,r)=>{let n=r.mode==="preview"?["re-run with --yes from a real terminal to apply"]:[];return{title:AA[r.mode],sections:[{label:"source",rows:[...e]},...t.map(o=>$A(o,r))],hints:n}},_y=e=>e.sections.some(t=>t.rows.some(r=>r.status==="fail"));var OA=20,yp=async(e,t)=>(await Q(e,t,{allowFailure:!0})).trim(),IA=async e=>ca(await Q(e,["status","--porcelain","-z","--untracked-files=normal"])),DA=async e=>(await yp(e,["for-each-ref","--contains","HEAD","--format=%(refname)","refs/remotes/origin/"])).length>0?null:{name:"HEAD pushed",status:"warn",message:"HEAD is on no origin/* ref, so every target will record a commit nobody else can resolve",notes:["git push"]},NA=async e=>{let[t,r]=await Promise.all([yp(e,["symbolic-ref","--quiet","--short","refs/remotes/origin/HEAD"]),yp(e,["rev-parse","--abbrev-ref","HEAD"])]);if(t.length===0)return{name:"default branch",status:"warn",message:"origin has no default branch recorded (origin/HEAD)"};let n=t.replace(/^origin\//u,"");return r===n?null:{name:"default branch",status:"warn",message:`syncing from ${r||"a detached HEAD"}, not the origin default branch ${n}`}},My=async e=>{let t=await IA(e);if(t.length>0){let n=t.slice(0,OA),o=t.length>n.length?`, and ${t.length-n.length} more`:"";throw new E({status:"refused",reason:"source-dirty",paths:t},1,{operation:`sync vendored files from ${e}`,stderrExcerpt:`the source has ${t.length} uncommitted path(s)`,remediation:`commit or stash them first, so every target records a commit holding exactly the files it got: ${n.join(", ")}${o}`})}let r=await Promise.all([DA(e),NA(e)]);return[{name:"working tree",status:"ok",message:"clean"},...r.filter(n=>n!==null)]};import _A from"node:path";var jy=(e,t)=>{let r=t.filter(s=>!e.targets.includes(s));if(r.length>0)throw new E({status:"refused",reason:"unknown-target",unknown:r,valid:e.targets},2,{operation:`sync vendored files to ${r.join(", ")}`,stderrExcerpt:`not a target in ~/.infra-kit/vendor.json: ${r.join(", ")}`,remediation:`name one of: ${e.targets.join(", ")}`});let n=nn(e.workspaceDir);return(t.length>0?e.targets.filter(s=>t.includes(s)):e.targets).map(s=>({name:s,root:_A.join(n,s)}))},MA="rewrite vendor/README.md and vendor/.sync-manifest.json from the tracked vendor/ files",jA=async(e,t)=>{let r=await la(e,t),n=sa(e,r);return r.kind!=="repo"||n.status==="fail"?n:{...n,status:"changed",message:`${MA} on ${r.branch}`,notes:[],warnings:[],branch:r.branch,entries:[],writeVendorMeta:!0,recoveryPaths:r.headVendorMeta}},Fy=async(e,t,r)=>Promise.all(t.map(async n=>r?jA(e,n):sa(e,await la(e,n))));var da="sync vendored files",BA=()=>{if(ee())throw new E({status:"refused",agentMode:A.source},2,{operation:da,stderrExcerpt:"vendor sync is human-only: refused in agent mode regardless of --yes",remediation:"ask a human to run `infra-kit vendor sync` from their own shell \u2014 a sync is never confirmed by an agent"})},WA=()=>{if(!kp.stdin.isTTY)throw new E({status:"refused",reason:"no-tty"},2,{operation:da,stderrExcerpt:"the apply needs a real terminal on stdin",remediation:"run `infra-kit vendor sync --yes` from a real terminal; Claude Code's `!` prefix is not one"})},JA=e=>{let t=Vy.join(nn(e.workspaceDir),e.source);if(FA(t))return t;throw new E({status:"refused",reason:"source-missing",source:t},1,{operation:da,stderrExcerpt:`the source repo ${e.source} is not checked out at ${t}`,remediation:'clone it there, or fix "source" / "workspaceDir" in ~/.infra-kit/vendor.json'})},vp=(e,t)=>new E({status:"refused",reason:"not-a-vendor-source"},1,{operation:da,stderrExcerpt:`${e} ${t}`,remediation:`add a vendorSource block to the source repo's committed infra-kit.json, or point "source" at the repo that has one`}),UA=async e=>{let t=Vy.join(e,"infra-kit.json"),r;try{r=JSON.parse(await LA.readFile(t,"utf8"))}catch(s){throw vp(t,`is unreadable: ${s instanceof Error?s.message:String(s)}`)}let n=r?.vendorSource;if(n==null)throw vp(t,"has no vendorSource block");let o=ku.safeParse(n);if(!o.success)throw vp(t,`has an invalid vendorSource: ${VA.prettifyError(o.error)}`);return o.data},Ly=(e,t)=>{kp.stderr.write(`${e.name}: if this run dies, restore the tracked paths with:
438
- ${Rt(t)}
439
- `)},GA=async(e,t,r)=>r?(Ly(t,An(t)),pp(t.root,e)):(await dp({source:e,plan:t,onBeforeFirstWrite:o=>{Ly(t,o)}})).touched,KA=async(e,t,r)=>{if(t.status!=="changed")return{plan:t,applied:!1};let n;try{n=await GA(e,t,!!r.manifestOnly)}catch(s){return{plan:t,applied:!1,error:s instanceof Error?s.message:String(s)}}if(!r.commit)return{plan:t,applied:!0};let o=await mp(t.root,n,up(e.name,e.headSha));return{plan:t,applied:!0,commit:o}},HA=async(e,t,r)=>{let n=[];for(let o of t)n.push(await KA(e,o,r));return n},By=e=>e.map(t=>({name:t.name,root:t.root,status:t.status,message:t.message,notes:t.notes,warnings:t.warnings,branch:t.branch})),wp=({mode:e,report:t,outcomes:r,source:n,print:o})=>{o&&It(t);let s=r.map(a=>a.plan);return{structuredContent:{mode:e,source:{root:n.root,name:n.name,headSha:n.headSha},targets:By(s).map((a,c)=>{let l=r[c];return{...a,applied:l.applied,error:l.error,commit:l.commit}}),changed:s.some(a=>a.status==="changed"),failed:_y(t),report:t.sections}}},qA=async e=>{let t=await Qs(),r=JA(t),n=await My(r),o=await UA(r),s=jy(t,e.targets??[]),i=await gp(r,o),a=await Fy(i,s,!!e.manifestOnly);return{source:i,sourceRows:n,plans:a}},bp=async(e={})=>{BA();let{source:t,sourceRows:r,plans:n}=await qA(e),o=n.map(m=>({plan:m,applied:!1})),s={commit:e.commit,manifestOnly:e.manifestOnly},i=e.check?"check":"preview",a=hp(r,o,{...s,mode:i}),c=!n.some(m=>m.status==="changed");if(e.check||c)return wp({mode:i,report:a,outcomes:o,source:t,print:!0});let l=!e.confirmedCommand&&!at.enabled;if(l&&It(a),l&&!kp.stdin.isTTY)return wp({mode:"preview",report:a,outcomes:o,source:t,print:!1});await W(e.confirmedCommand,`Sync vendored files from ${t.name} into these targets?`,{plan:By(n),throwOnDecline:!0}),WA();let d=await HA(t,n,e),u=hp(r,d,{...s,mode:"applied"});return wp({mode:"applied",report:u,outcomes:d,source:t,print:!0})};var pa=(e,t=!0)=>({line:e,reproducible:t});import ua from"node:fs";import zA from"node:os";import YA from"node:path";import Gy from"node:process";var ma="INFRA_KIT_SESSION_REPORT",Rp=null,Wy=!1,Jy=[],Ky=(e=Gy.env)=>{Wy||(Rp=e[ma]??null,Wy=!0,delete e[ma])};var Hy=(e,t)=>{if(!Rp)return;let r=e.summary??(Jy.length>0?[...Jy]:void 0),n={...e,...r?{summary:r}:{}},o=t?.write??((s,i)=>{ua.writeFileSync(s,i)});try{o(Rp,JSON.stringify(n))}catch{}},Uy=0,qy=e=>{let t=e?.tmpdir?.()??zA.tmpdir(),r=e?.pid??Gy.pid;return Uy+=1,YA.join(t,`infra-kit-session-${r}-${Uy}.json`)},zy=(e,t)=>{if(!(t?.exists??(i=>ua.existsSync(i)))(e))return null;let n=t?.read??(i=>ua.readFileSync(i,"utf-8")),o=t?.unlink??(i=>ua.unlinkSync(i)),s;try{s=n(e)}catch{return null}finally{try{o(e)}catch{}}try{return JSON.parse(s)}catch{return null}};var Sp=e=>{e.options.some(r=>r.long==="--agent")||e.option("--agent","Run as an agent: never prompt; refuse with a structured payload (under --json) naming what to pass instead"),e.commands.forEach(Sp)};var Pp=e=>{e.options.some(r=>r.long==="--debug")||e.option("--debug","Raise the log level to debug (logs stay on stderr)"),e.commands.forEach(Pp)};var tO=(e,t)=>[...t,e],Yy=(e,t)=>{if(!(typeof e>"u")){if(e===!0)return"workspace";if(e===!1)return"none";if(typeof e=="string"&&br.includes(e))return e;throw new Error(`Invalid ${t} value "${String(e)}". Expected one of: ${br.join(", ")}.`)}},rO=e=>e.description("Merge dev branch into every release branch").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-y, --yes","Skip confirmation prompt").option("--dry-run","Compute and print the merge plan without pushing anything").option("--verify [command]","Check each merge before pushing it. Bare runs `pnpm install --frozen-lockfile`; pass a command to run that instead. A branch that fails is dropped from the push, never rolled back").option("--keep-conflicts","On the confirmed run, leave each conflicted branch mid-merge in <root>-worktrees/merge-dev/ for resolution").option("--continue","Check, preview, then commit and push the selected resolutions left by --keep-conflicts").option("--abort","Discard the selected resolutions left by --keep-conflicts").option("--tree <branch=sha>","With --continue --yes: the approved tree per branch, as a --continue preview prints it (repeatable)",(t,r)=>[...r??[],t]).action(async t=>{let r=await nf(()=>ki({all:t.all,versions:t.versions,dryRun:t.dryRun,verify:t.verify,keepConflicts:t.keepConflicts,continue:t.continue,abort:t.abort,tree:t.tree,confirmedCommand:t.yes}));$(r),r.structuredContent.failedMerges>0&&(Fe.exitCode=1)}),Xy=e=>(Fe.stdout.write(`${e.structuredContent.filePath}
440
- `),$(e)),nO=e=>e.description("List all release branches").action(async()=>{$(await xi())}),oO=e=>e.description("Create one or more release branches (each entry can mix regular/hotfix and its own description)").option("-r, --release <spec>",'Release spec "<version|next|name>[@yyyy-mm-dd][:type[:description]]" (repeatable). The token is a semver ("1.2.5"), the literal "next", or a kebab-case name ("checkout-redesign"); "@yyyy-mm-dd" is the planned release date, written to the Jira fix version. Type is regular|hotfix (default regular). Examples: "1.2.5", "1.2.5:hotfix", "1.64.0@2026-10-28", "next:regular:Holiday backend", "checkout-redesign:regular:Q3 redesign".',tO,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let n=t.release.map(yl),o=n.length>0?n:void 0;$(await Oi({releases:o,confirmedCommand:t.yes}))}),sO=e=>{if(e==="")return e;try{return ur(e)}catch(t){throw t instanceof gn?new ZA(t.message):t}},iO=e=>e.description("Edit a release's description and/or release date in Jira (description also in the matching GitHub PR body)").option("-v, --version <version>","Release version (e.g. 1.2.5) or release name (e.g. checkout-redesign)").option("-d, --description <description>",'New description (use "" to clear)').option("--release-date <yyyy-mm-dd>",'New planned release date (use "" to clear)',sO).option("-y, --yes","Skip confirmation prompt").action(async t=>{$(await Ii({version:t.version,description:t.description,releaseDate:t.releaseDate,confirmedCommand:t.yes}))}),Zy=e=>e.option("-f, --from <where>",`Where the deploy runs: ${Jt.join(" | ")} (required)`).option("-v, --version <version>",'With --from ci: version (e.g. 1.2.5) or release name to deploy; "dev" deploys from the dev branch. Prompts when omitted').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("-y, --yes","Skip confirmation prompt").option("--skip-terraform","With --from ci: skip the terraform deployment step").option("--dry-run","With --from local: resolve target, contract and commands without deploying").option("--print-env","With --from local: print the resolved build contract"),aO=e=>Zy(e).description("Deploy every service to any environment, in CI or from this machine").action(async t=>{$(await op({from:t.from,version:t.version,env:t.env,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),cO=e=>Zy(e).description("Deploy selected services to any environment, in CI or from this machine").option("-s, --services <services...>","Specify services to deploy, e.g. client-be client-fe").action(async t=>{$(await sp({from:t.from,version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),lO=e=>e.description("Release a new version to production").option("-v, --version <version>","Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deliver").option("-y, --yes","Skip confirmation prompt").action(async t=>{$(await Si({version:t.version,confirmedCommand:t.yes}))}),dO=e=>e.description("Tear down a release: worktree, PR, branches, and the Jira fix version").option("-v, --version <version>","Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to remove").option("--move-issues-to <version>","Reassign issues carrying the fix version to this version before removing it").option("--skip-jira","Remove everything except the Jira fix version").option("-y, --yes","Skip confirmation prompt").action(async t=>{$(await Fi({version:t.version,moveIssuesTo:t.moveIssuesTo,skipJira:t.skipJira,confirmedCommand:t.yes}))}),pO=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{$(await Xi({confirmedCommand:t.yes}))}),uO=e=>e.description("Add git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-i, --ide [mode]","Editor mode for created worktrees: workspace (default) | none").option("--no-ide","Skip the editor (alias for --ide none)").option("-c, --cursor [mode]","Deprecated alias for --ide").option("--no-cursor","Deprecated alias for --no-ide").option("-g, --github-desktop","Open created worktrees in GitHub Desktop").option("--no-github-desktop","Skip GitHub Desktop prompt").option("--orca","Open created worktrees in Orca (pane layout from worktrees.orca.layout)").option("--no-orca","Skip the Orca prompt").action(async t=>{let r=Yy(t.ide,"--ide")??Yy(t.cursor,"--cursor");$(await qi({confirmedCommand:t.yes,all:t.all,versions:t.versions,ide:r,githubDesktop:t.githubDesktop,orca:t.orca}))}),mO=e=>e.description("List all git worktrees with detailed information").action(async()=>{$(await zi())}),fO=e=>e.description("Remove git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").action(async t=>{$(await Yi({confirmedCommand:t.yes,all:t.all,versions:t.versions}))}),gO=e=>e.description("Show the machine-local factory config (~/.infra-kit/vendor.json) or scaffold it with --init").option("--init","Scaffold ~/.infra-kit/vendor.json (skips if it already exists)").action(async t=>{$(await ap({init:t.init}))}),hO=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await Gi();$(t),t.structuredContent.ok||(Fe.exitCode=1)}),yO=e=>e.description("Mirror vendorSource files from the ~/.infra-kit/vendor.json source into every target, from any directory (human-only)").argument("[targets...]","Narrow to these target names from ~/.infra-kit/vendor.json").option("-y, --yes","Apply the previewed plan (needs a real terminal on stdin)").option("--check","Preview only; exit 1 when any target would change").option("--commit","Commit exactly the synced paths in each target after it syncs").option("--manifest-only","Rewrite vendor/README.md and vendor/.sync-manifest.json only; copy nothing").action(async(t,r)=>{let n;try{n=await bp({targets:t,confirmedCommand:r.yes,check:r.check,commit:r.commit,manifestOnly:r.manifestOnly})}catch(a){if(!ct(a))throw a;p.info("Operation cancelled.");return}$(n);let{failed:o,changed:s,mode:i}=n.structuredContent;(o||i==="check"&&s)&&(Fe.exitCode=1)}),vO=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{$(await Zd())}),wO=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{$(await Qd())}),kO=new Set(["version"]),fa=e=>{let t=[];for(let r=e;r&&r.parent;r=r.parent)t.unshift(r.name());return t.join(" ")},Ep=()=>{let e=new XA().option("-C <dir>","Run as if infra-kit was started in <dir> instead of the current working directory"),t=e.command("release").description("Release management commands");rO(t.command("merge-dev")),nO(t.command("list")),oO(t.command("create")),iO(t.command("edit")),aO(t.command("deploy-all")),cO(t.command("deploy-selected")),lO(t.command("deliver")),dO(t.command("remove"));let r=e.command("worktrees").description("Git worktree management commands");uO(r.command("add")),mO(r.command("list")),fO(r.command("remove")),pO(r.command("sync"));let n=e.command("config").description("Manage infra-kit configuration files");vO(n.command("path")),wO(n.command("edit")),e.command("config-get").description("Print the fully merged infra-kit config (project + user-global + per-project override layers)").action(async()=>{$(await _s())});let o=e.command("local").description("Deprecated \u2014 use `release deploy-all|deploy-selected --from local`"),s=a=>a.option("-e, --env <name>","Target environment (prompts when omitted)").option("-y, --yes","Skip the confirmation prompt").option("--dry-run","Resolve target, contract and commands without deploying").option("--print-env","Print the resolved build contract");s(o.command("deploy-all")).description("Deprecated \u2014 use `release deploy-all --from local`").action(async a=>{$(await ea({env:a.env,yes:a.yes,dryRun:a.dryRun,printEnv:a.printEnv},"all"))}),s(o.command("deploy-selected")).description("Deprecated \u2014 use `release deploy-selected --from local`").option("-s, --service <name...>","Service name(s), as in deploy-<name>.sh (prompts when omitted)").action(async a=>{$(await ea({env:a.env,services:a.service,yes:a.yes,dryRun:a.dryRun,printEnv:a.printEnv},"selected"))}),e.command("audit").description("Audit against infra-kit.config.ts rules (--all for every package, --root for the monorepo root)").option("-a, --all","Audit every non-vendor workspace package").option("-r, --root","Audit the monorepo root (turbo pipeline + root commands)").option("--fix","Write the infra-kit guidance block into CLAUDE.md for the audited scope before checking (CLI-only)").option("--design","With --fix: scaffold DESIGN.md for frontend/mobile packages that lack one").action(async a=>{if(a.design&&!a.fix){p.error("--design requires --fix (it scaffolds DESIGN.md; there is nothing to scaffold without a fix run)"),Fe.exitCode=1;return}let c=await Ns({all:a.all,root:a.root,fix:a.fix,design:a.design});$(c);let{allPassed:l,fixed:d}=c.structuredContent,u=(d??[]).some(m=>m.action==="failed");(!l||u)&&(Fe.exitCode=1)});let i=e.command("vendor").description("Mirror and verify the vendored starter files");return hO(i.command("check")),gO(i.command("config")),yO(i.command("sync")),e.command("doctor").description("Check installation and authentication status of gh and doppler CLIs").option("--fix","Remove portless routes left behind by a dev-server that was killed (kill -9, OOM, force-quit). Refuses while a dev session is running, when a booting UI is indistinguishable from a dead route.").option("--ascii","Render the report with ASCII markers instead of unicode glyphs (check messages are unchanged)").action(async a=>{let c=await li({fix:!!a.fix});at.enabled||Pc(c.structuredContent.checks,{ascii:!!a.ascii}),c.structuredContent.checks.some(d=>d.name==="plugin installed"&&d.status==="fail")&&(Fe.exitCode=1),$(c)}),e.command("dev").description("Run local dev servers for a named devServersPresets preset (or all apps); api + ui").argument("[preset]","Named preset from devServersPresets (omit to run every app)").option("-w, --watch","Rebuild and restart on file save (the default)").option("--no-watch","Build once and never restart on save").option("--app <names>","Further narrow to these app folder names (comma-separated)").option("--target <keys>","Run exactly these <app>/api|<app>/ui packages (comma-separated); part-level, unlike --app").option("--orca","Run each app in its own Orca pane (one tab, N panes; falls back to single terminal when Orca is not running)").option("--self","Run only the app of the current directory (infer from cwd; use inside apps/<app>/\u2026)").option("-V, --verbose","Print full boot narration (default: quiet; full detail always in the session log)").option("--routes","Print each app\u2019s registered METHOD /path routes at startup (default: off)").option("--no-ui-health","Do not probe the frontends\u2019 liveness (vite\u2019s HMR ping); their rows carry no health dot (also: INFRA_KIT_NO_UI_HEALTH=1)").action(async(a,c)=>{let{runDevServerCli:l}=await import("./dev-server.js"),d=!!(Fe.stdout.isTTY&&Fe.stdin.isTTY);await l({...c,preset:a},d,at.enabled)}),e.command("dev-status").description("Show what `infra-kit dev` currently has running (reads dev-context fragments; starts nothing)").action(async()=>{$(await js())}),e.command("e2e").description("Run an app\u2019s Playwright e2e against this worktree\u2019s dev server, else the deployed app at INFRA_KIT_ENV").argument("[playwrightArgs...]","Passed to `playwright test` (put them after `--`)").option("--app <name>","App folder whose apps/<app>/tests package to run (inferred from cwd when omitted)").option("--dry-run","Resolve and print the target and proxy topology without running").option("-y, --yes","Skip the confirmation a cloud run asks for").action(async(a,c)=>{$(await di({app:c.app,dryRun:c.dryRun,yes:c.yes,playwrightArgs:a}))}),e.command("setup").description("Set this machine up: shell integration, agent files, the Claude Code skills plugin, then the external tools").option("--tools <ids...>","Limit to these tools (brew, git, aws, gh, doppler, portless)").option("--update [ids...]","Update what is already installed; never install a missing tool").option("--skip-tools","Do the local setup only, then REPORT what each tool needs \u2014 installs nothing").option("--ascii","Render the report with ASCII markers instead of unicode glyphs (row messages are unchanged)").action(async a=>{$(await Vi({tools:a.tools,update:a.update,skipTools:a.skipTools,ascii:!!a.ascii}))}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{$(await Ki())}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{$(await vi())}),e.command("env-list").description("List available Doppler configs for the detected project, and whether a service token resolves for each").action(async()=>{$(await mi())}),e.command("env-load").description("Load Doppler env vars for a config. Source the returned file path to apply.").option("-c, --config <config>","Environment config name to load (e.g. dev, arthur)").action(async a=>{Xy(await gi({config:a.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{Xy(await pi())}),e.command("env-token-set").description("Store the Doppler service token for an env (masked prompt; validated against Doppler before writing)").argument("<env>","Environment / Doppler config the token is scoped to (e.g. dev)").option("--stdin","Read the token from stdin instead of prompting (e.g. from a password manager)").option("--from-env <var>","Read the token from the named environment variable (the NAME, never the value)").option("--force","Store even when the token\u2019s scope could not be verified. Never overrides a real mismatch.").action(async(a,c)=>{$(await rp({env:a,stdin:c.stdin,fromEnv:c.fromEnv,force:c.force}))}),e.command("env-token-list").description("Show which envs have a Doppler service token (redacted), and where it came from").option("--check","Also ask Doppler whether each token is valid and correctly scoped").action(async a=>{$(await wi({check:!!a.check}))}),e.command("env-token-remove").description("Delete an env\u2019s Doppler service token from the local store (does NOT revoke it in Doppler)").argument("<env>","Environment / Doppler config whose token to remove").action(async a=>{$(await ep({env:a}))}),e.commands.forEach(ou),Sp(e),Pp(e),e.hook("preAction",async(a,c)=>{let{C:l}=e.opts();l!==void 0&&eO(QA(Fe.cwd(),l)),h.start(fa(c)),at.enabled=!!c.optsWithGlobals().json,at.enabled&&(p.level="warn"),A.source=ds({env:Fe.env,stdinIsTTY:Fe.stdin.isTTY===!0,flag:!!c.optsWithGlobals().agent}),kO.has(fa(c))||await Kc()}),e.hook("postAction",(a,c)=>{let l=fa(c);if(zd(l))return;let u=h.snapshot()?.formattedOptions??"",m=u?` ${u}`:"",g=`infra-kit ${l}${m}`;Hy({equivalent:pa(g,!0)})}),e};import bO from"node:process";var RO={exit:bO.exit,emit:$,logger:p},Qy=(e,t=RO)=>we(e)?(t.logger.info("Operation cancelled."),t.exit(0)):e instanceof E?(t.emit({structuredContent:e.structuredContent}),t.logger.error(e.message),t.exit(e.exitCode)):(t.logger.error(e instanceof Error?e.message:String(e)),t.exit(1));var xp=(e,t=" ")=>{let r=e.reduce((n,[o])=>Math.max(n,o.length),0);return e.map(([n,o])=>`${n.padEnd(r)}${t}${o}`)};import SO from"node:fs";import ev from"node:path";import es from"node:process";var nv=new Set([...wu,He,"XDG_CACHE_HOME","CLAUDE_PROJECT_DIR","CLAUDE_PLUGIN_ROOT"]),ov=null,ga=new Set,Tp=null,tv=!1;var rv=e=>{try{return SO.statSync(e)}catch{return null}},PO=()=>{if(tv)return null;try{return bt()}catch{return tv=!0,p.debug(`session-env: ${He} unset \u2014 no overlay`),null}},EO=e=>{let t=ev.join(e,kt),r=ev.join(e,rs),n=rv(t),o=rv(r);return n&&!(o&&o.mtimeMs>n.mtimeMs)?{kind:"load",file:t,signature:`load:${n.ino}:${n.mtimeMs}:${n.size}`}:o?{kind:"clear",file:r,signature:`clear:${o.ino}:${o.mtimeMs}`}:{kind:"none",signature:"none"}},xO=e=>e.kind==="load"?{kind:"load",vars:Np(e.file),signature:e.signature}:e.kind==="clear"?{kind:"clear",unset:_p(e.file),signature:e.signature}:e;var TO=()=>{let e=PO();if(e===null)return{kind:"no-session"};let t=EO(e);return t.signature===Tp?null:xO(t)},CO=()=>{for(let e of ga){let t=ov[e];t===void 0?delete es.env[e]:es.env[e]=t}ga.clear()},$O=(e,t,r)=>{if(nv.has(t)){e.skipped.push(t);return}es.env[t]=r,ga.add(t),e.set.push(t)},AO=(e,t)=>{if(nv.has(t)){e.skipped.push(t);return}delete es.env[t],ga.add(t),e.unset.push(t)},OO=e=>{let t={set:[],unset:[],skipped:[]};if(e.kind==="load")for(let[r,n]of Object.entries(e.vars))$O(t,r,n);if(e.kind==="clear")for(let r of e.unset)AO(t,r);return t},IO=e=>e.kind==="load"?`load, ${Object.keys(e.vars).length} vars`:e.kind,Cp=(e=TO())=>{if(ov??={...es.env},e===null||e.kind==="no-session"||e.signature===Tp)return{set:[],unset:[],changed:!1};CO();let{set:t,unset:r,skipped:n}=OO(e);return Tp=e.signature,n.length>0&&p.warn(`session-env: skipped protected names [${n.join(", ")}]`),p.debug(`session-env applied: set [${t.join(", ")}] unset [${r.join(", ")}] (${IO(e)})`),{set:t,unset:r,changed:!0}};import{chalkStderr as QO}from"chalk";import{spawn as eI}from"node:child_process";import Pe from"node:process";import{Chalk as DO}from"chalk";var On=new DO({level:1}),Ge={ok:"ok",findingsPlain:"completed with findings",failed:"failed",cancelled:"cancelled",findingsSuffix:"findings",sep:" \xB7 ",reproPrefix:"$ ",nonReproPrefix:"\u2248 ",envNotice:"Applies to infra-kit commands in this terminal and to new shells; this zsh prompt itself needs the env-load function."},NO={suspend:{unicode:"any key commands \xB7 Esc / Ctrl-C quit \xB7 Ctrl-Z suspend",ascii:"any key commands - Esc / Ctrl-C quit - Ctrl-Z suspend"},plain:{unicode:"any key commands \xB7 Esc / Ctrl-C quit",ascii:"any key commands - Esc / Ctrl-C quit"}},sv={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},iv={unicode:"\u2500",ascii:"-"},_O=3,$p=e=>e,MO={ok:e=>On.green(e),findings:e=>On.yellow(e),failed:e=>On.red(e),cancelled:e=>On.gray(e)},Op=e=>e?{dim:t=>On.dim(t),bold:t=>On.bold(t)}:{dim:$p,bold:$p},jO=(e,t)=>e?MO[t]:$p,Ap=e=>[...e].length,FO=(e,t)=>{if(t==null)return e;let r=Math.max(0,t-1);return Ap(e)<=r?e:[...e].slice(0,r).join("")},av=e=>{let t=Op(e.color===!0).dim,r=NO[e.canSuspend?"suspend":"plain"],n=e.ascii===!0?r.ascii:r.unicode;return t(FO(n,e.width))},cv=(e,t={})=>{let r=Op(t.color===!0);return`${r.dim(Ge.reproPrefix.trim())} ${r.bold(e)}`},LO=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,VO=(e,t)=>e==="findings"?t!=null?`${t} ${Ge.findingsSuffix}`:Ge.findingsPlain:{ok:Ge.ok,failed:Ge.failed,cancelled:Ge.cancelled}[e],BO=(e,t,r,n)=>{if(t==null)return"";let o=t-2-e;return o<_O?"":` ${n(r.repeat(o))}`},lv=e=>{let t=e.color===!0,r=Op(t),n=jO(t,e.outcome),o=e.ascii===!0,s=e.equivalent.reproducible?Ge.reproPrefix:Ge.nonReproPrefix,i=o?sv[e.outcome].ascii:sv[e.outcome].unicode,a=VO(e.outcome,e.findingsCount),c=[LO(e.durationMs)],l=e.summary?.[0]?.split(`
441
- `)[0];l!=null&&l.length>0&&c.push(l);let d=`${i} ${a}`,u=`${Ge.sep}${c.join(Ge.sep)}`,m=Ap(d)+Ap(u),g=BO(m,e.width,o?iv.ascii:iv.unicode,r.dim),y=[`${n(d)}${r.dim(u)}${g}`];return e.showEquivalent!==!1&&y.unshift(`${r.dim(s.trim())} ${r.bold(e.equivalent.line)}`),e.envNotice===!0&&y.push(r.dim(Ge.envNotice)),y.join(`
442
- `)};var WO=new Set([130,143]),dv=(e,t,r,n=!1)=>r?t!=null||e===0?"ok":"findings":n&&e!=null&&WO.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import JO from"node:process";var UO={3:"quit",4:"quit",26:"suspend",27:"quit"},GO=e=>{if(e.length!==1)return"continue";let t=typeof e=="string"?e.charCodeAt(0):e[0];return t===void 0||Number.isNaN(t)?"continue":UO[t]??"continue"},KO=150,HO="\r\x1B[2K",qO=`\r
443
- `,pv=(e,t)=>{uv(e),e.stdin.on("data",t),e.listener=t},uv=e=>{e.listener!==null&&(e.stdin.off("data",e.listener),e.listener=null)},mv=(e,t)=>{Iu(),e.stdin.setRawMode(!0),e.stdin.isPaused()&&e.stdin.resume(),pv(e,t)},fv=e=>{e.hintOnScreen&&(e.hintOnScreen=!1,e.deps.write(HO)),uv(e),e.stdin.isTTY===!0&&e.stdin.isRaw===!0&&e.stdin.setRawMode(!1),Du()},zO=e=>{e.settled||(e.settled=!0,fv(e))},gv=(e,t)=>{let r=av({canSuspend:e.deps.suspend!==void 0,ascii:e.deps.ascii,color:e.deps.color,width:e.deps.columns()});e.deps.write(t+r),e.hintOnScreen=!0},YO=async e=>{await new Promise(t=>{setTimeout(t,e)})},XO=(e,t,r)=>{fv(e),t(),mv(e,r),gv(e,qO)},ZO=async e=>new Promise(t=>{let r=n=>{let o=GO(n),s=e.deps.suspend;if(o==="quit"){t("quit");return}if(o==="suspend"&&s!==void 0){XO(e,s,r);return}t("palette")};pv(e,r),gv(e,"")}),hv=async(e,t)=>{if(e.quitRequested())return"quit";let r=t.stdin??JO.stdin;if(r.isTTY!==!0)return"palette";let n={deps:t,stdin:r,listener:null,hintOnScreen:!1,settled:!1};try{return mv(n,()=>{}),e.armed(),await YO(t.drainMs??KO),await ZO(n)}finally{zO(n)}};import yv from"node:process";var Ht={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},vv=(e,t)=>{let r=t?.write??(s=>{yv.stderr.write(s)}),n=t?.stdin??yv.stdin,o=[Ht.saveCursor,Ht.scrollRegion,Ht.restoreCursor,Ht.column,Ht.sgr,Ht.cursor,Ht.wrap];e.entersAltScreen===!0&&o.push(Ht.primaryBuffer),r(o.join("")),n.isTTY===!0&&n.isRaw===!0&&n.setRawMode?.(!1)};var wv=e=>`infra-kit ${e.groupPath.join(" ")}`,tI=()=>{rI();let e=Pe.stderr.columns;return e!=null&&e>0?e:void 0},rI=()=>{let e=Pe.stderr;typeof e._refreshSize=="function"&&e._refreshSize()},nI=e=>new Promise(t=>{e.on("exit",(r,n)=>{t({code:r,signal:n})}),e.on("error",()=>{t({code:1,signal:null})})}),oI=async(e,t,r)=>{let n=qy(),o={...t.env,[ma]:n,INFRA_KIT_NO_AUTO_UPDATE:"1"},s=t.now(),i={code:1,signal:null};r();try{let u=t.spawn(Pe.execPath,[t.cliPath,...e.groupPath],{stdio:"inherit",env:o});i=await nI(u)}catch{i={code:1,signal:null}}finally{t.resetTerminal({entersAltScreen:e.entersAltScreen})}let a=zy(n),c=dv(i.code,i.signal,a!=null,e.longRunning),l=wv(e),d=a?.equivalent??pa(l,!0);return lv({equivalent:d,outcome:c,durationMs:t.now()-s,summary:a?.summary,envNotice:e.sessionEnvNotice,ascii:t.ascii,color:t.color,width:t.columns(),showEquivalent:!(d.reproducible&&d.line===l)})},sI=1e3,iI=(e,t)=>e!=null&&t-e<=sI,Ip=e=>{e.resetTerminal(),e.exit(0)},aI=(e,t)=>{let r=null,n=!1,o=()=>{let c=e();if(c==="child"){r=t.now();return}c!=="pause"&&Ip(t)},s=()=>{let c=e();if(c==="palette"){Ip(t);return}if(!iI(r,t.now())){if(c==="pause"){Ip(t);return}n=!0}},i=()=>{t.exit(129)},a=()=>{e()==="child"&&t.raise("SIGSTOP")};return t.register("SIGINT",o),t.register("SIGTERM",s),t.register("SIGHUP",i),t.register("SIGTSTP",a),{dispose:()=>{t.unregister("SIGINT",o),t.unregister("SIGTERM",s),t.unregister("SIGHUP",i),t.unregister("SIGTSTP",a)},childStarted:()=>{r=null},quitRequested:()=>n}},kv=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),cI=Pe.platform==="win32"?void 0:()=>{Nu()},lI=(e,t)=>r=>hv(r,{write:e,columns:t.columns,ascii:t.ascii,color:t.color,suspend:cI}),bv=async(e,t)=>{let r={spawn:t.spawn??eI,now:t.now??(()=>Date.now()),env:t.env??Pe.env,cliPath:t.cliPath,ascii:t.ascii??!(Pe.stdout.isTTY&&Pe.env.TERM!=="dumb"),color:t.color??QO.level>0,columns:t.columns??tI,resetTerminal:t.resetTerminal??(d=>{vv(d)})},n=t.write??(d=>Pe.stderr.write(d)),o="palette",s=t.signals??{register:(d,u)=>{Pe.on(d,u)},unregister:(d,u)=>{Pe.off(d,u)},exit:d=>{Pe.exit(d)},raise:d=>{Pe.kill(Pe.pid,d)},now:()=>Date.now(),resetTerminal:()=>{o==="pause"&&n("\r\x1B[2K"),r.resetTerminal({entersAltScreen:!1})}},i={dispose:()=>{},childStarted:()=>{},quitRequested:()=>!1},a=t.installSignals===!1?i:aI(()=>o,s),c={armed:()=>{o="pause"},quitRequested:()=>a.quitRequested()},l=t.afterRun??lI(n,r);try{for(;;){if(a.quitRequested())return;o="palette";let d=await t.renderPalette(e);if(d==null)return;let u=t.resolveCommand(d);if(!u)continue;let m=cv(wv(u),{color:r.color});n(`
436
+ `;var d$=new Set(["100644","100755","120000"]),u$=(e,t)=>{let r=new Map;for(let n of _t(e)){let o=n.indexOf(" "),s=n.slice(0,n.indexOf(" ")),i=n.slice(o+1);o<0||!d$.has(s)||Fo(i,t)||r.set(i,{path:i,mode:s})}return[...r.values()]},Bd=async(e,t,r)=>{let n=await Z(e,["--literal-pathspecs","ls-files","-z","-s","--",t]);return u$(n,r)},sy=async e=>_t(await Z(e,["--literal-pathspecs","ls-files","-z","--",X]));var mn=e=>["git","-C",e.root,"--literal-pathspecs","checkout","HEAD","--",...e.recoveryPaths],cy=e=>{let t=ji(e);t!==null&&(t.kind==="other"?ay(e):v$(e))},k$=(e,t,r)=>{let n=he.join(e,r.source),o=he.join(t,r.target);if(iy(he.dirname(o),{recursive:!0}),cy(o),r.mode==="120000"){y$(h$(n),o);return}m$(n,o),p$(o,r.mode==="100755"?493:420)},b$=async(e,t)=>{let r=new Set;for(let n of _t(await Z(e,["ls-files","-z"]))){if(t.has(n))continue;let o=he.posix.dirname(n);for(;o!==".";)r.add(o),o=he.posix.dirname(o)}return r},R$=async(e,t)=>{if(t.length===0)return;let r=await b$(e,new Set(t)),n=[...new Set(t.map(o=>he.dirname(he.join(e,o))))];n.sort((o,s)=>s.length-o.length);for(let o of n){let s=o;for(;s!==e&&s.startsWith(e)&&!(!f$(s,{throwIfNoEntry:!1})?.isDirectory()||g$(s).length>0||r.has(he.relative(e,s).split(he.sep).join("/")));)ay(s),s=he.dirname(s)}},ly=(e,t,r)=>{let n=new Set(r),o=e.filter(a=>a.vendored).flatMap(a=>a.targetPaths),s=t.filter(a=>!n.has(a)),i=[...o,Mt,...s].map(oy).filter(a=>a!==null&&!Si(a));return pn(i)},dy=async(e,t,r,n)=>{let o=he.join(e,X);iy(o,{recursive:!0}),w$(he.join(e,Mt),Bi(t.name));let s=ly(r,await sy(e),n);md(o,{source:t.name,commit:t.headSha},s)},Vd=async({source:e,plan:t,onBeforeFirstWrite:r})=>{if(t.status!=="changed")return{touched:[],manifestWritten:!1};r?.(mn(t));let n=he.resolve(t.root),o=t.entries.flatMap(a=>a.deletes);for(let a of o)cy(he.join(n,a));await R$(n,o);let s=t.entries.flatMap(a=>a.writes);for(let a of s)k$(e.root,n,a);let i=s.map(a=>a.target);return t.writeVendorMeta?(await dy(n,e,t.entries,o),{touched:pn([...o,...i,Mt,jo]),manifestWritten:!0}):{touched:pn([...o,...i]),manifestWritten:!1}},Wd=async(e,t)=>(await dy(e,t,[],[]),[Mt,jo]);var Ud=(e,t)=>`[ROOT] vendor: sync from ${e}@${Fi(t)}`,S$=e=>{let{stdout:t,stderr:r}=e;return[t,r].filter(o=>typeof o=="string"&&o.trim().length>0).join(`
437
+ `).trim()||String(e)},Jd=async(e,t,r)=>{if(t.length===0)return{ok:!0};let n=t.join("\0"),o=["--pathspec-from-file=-","--pathspec-file-nul"];try{return await Z(e,["--literal-pathspecs","add","-A",...o],{input:n}),await Z(e,["--literal-pathspecs","commit","--only","-m",r,...o],{input:n}),{ok:!0}}catch(s){return{ok:!1,output:S$(s)}}};var P$=20,E$=20,uy=(e,t)=>e.length<=t?[...e]:[...e.slice(0,t),`\u2026and ${e.length-t} more`],py=(e,t,r)=>{let{entry:n}=e,o=new Set(t.tracked),s=[],i=[];for(let d of Lo(e.files,r)){let p=Li(d.path,n);if(s.push(p),Qh(d.fingerprint,t.onDisk[p]??null))continue;let m=o.has(p)?"modified":"added";i.push({source:d.path,target:p,mode:d.mode,change:m})}let a=new Set(s),c=Lo(t.tracked.map(d=>({path:d})),r).map(d=>d.path).filter(d=>!a.has(d)),l=i.filter(d=>d.change==="added").length;return{...n,targetPaths:s,writes:i,deletes:c,counts:{added:l,modified:i.length-l,removed:c.length}}},Bo=(e,t,r,n=[])=>({name:e.name,root:e.root,status:t,message:r,notes:n,warnings:[],entries:[],writeVendorMeta:!1,recoveryPaths:[]}),Gd=e=>e.entries.map(t=>t.entry.target),x$=(e,t,r)=>{let n=["git","-C",t.root,"--literal-pathspecs","status","--",...Gd(e)];return Bo(t,"fail",`blocked: ${r.length} uncommitted path(s) under synced paths`,[...uy(r,P$),mt(n)])},T$=(e,t)=>{if(e.kind==="unknown-sha")return{notes:[],warnings:["no manifest commit recorded, so the source commits since the last sync are unknown"]};let r=Fi(e.sha);return e.kind==="unresolvable"?{notes:[],warnings:[`manifest commit ${r} is not in ${t}, so the changelog is unknown`]}:{notes:[`${e.lines.length} ${t} commit(s) since ${r}`,...uy(e.lines,E$)],warnings:[]}},C$=e=>{let{added:t,modified:r,removed:n}=e.counts;return t+r+n===0?null:`${e.target}: ${t} added, ${r} modified, ${n} removed`},$$=e=>{let t=r=>e.reduce((n,o)=>n+o.counts[r],0);return`${t("added")} added, ${t("modified")} modified, ${t("removed")} removed`},A$=(e,t,r)=>{let n=e.flatMap(o=>[...o.writes.filter(i=>i.change==="modified").map(i=>i.target),...o.deletes]);return pn([...n,...r?t.headVendorMeta:[]])},O$=(e,t)=>{if(t.dirty.length>0)return x$(e,t,t.dirty);let r=e.entries.map((d,p)=>{let m=t.entries[p]??{target:d.entry.target,tracked:[],onDisk:{}};return py(d,m,e.exclude)}),n=r.some(d=>d.vendored),o=r.some(d=>d.writes.length+d.deletes.length>0),s=n&&(!t.readmeCurrent||!t.manifestPresent),i={...Bo(t,"ok","up to date"),branch:t.branch,entries:r,writeVendorMeta:n};if(!o&&!s)return i;let a=T$(t.changelog,e.name),c=t.manifestSource!==null&&t.manifestSource!==e.name?[`vendor/ was last synced from ${t.manifestSource}, not ${e.name}: this sync replaces it`]:[],l=r.map(C$).filter(d=>d!==null);return{...i,status:"changed",message:`${$$(r)} on ${t.branch}`,notes:[...l,...s?["vendor/README.md and manifest rewritten"]:[],...a.notes],warnings:[...c,...a.warnings],recoveryPaths:A$(r,t,n)}},Vi=(e,t)=>{switch(t.kind){case"missing":return Bo(t,"skipped",`not checked out at ${t.root}`);case"source":return Bo(t,"skipped","this is the source repo");case"not-git":return Bo(t,"fail",`not a git repo: ${t.reason}`);case"repo":return O$(e,t)}};import{existsSync as I$,readFileSync as D$,realpathSync as Wi}from"node:fs";import Ui from"node:path";var Kd=async(e,t)=>{let r=t.exclude??[],n=(await Z(e,["rev-parse","HEAD"])).trim(),o=await je(e),s=await Promise.all(ny(t).map(async i=>{let a=await Bd(e,i.path,r);return{entry:i,files:a.map(c=>Zh(e,c))}}));return{root:e,selfRoots:[...new Set([Wi(e),Wi(o)])],name:Ui.basename(o),headSha:n,entries:s,exclude:r}},Ji=e=>{let t=_t(e)[Symbol.iterator](),r=[];for(let n of t)r.push(n.slice(3)),/^[RC]|^.[RC]/u.test(n)&&t.next();return r},N$=async(e,t)=>{let r=await Z(t,["--literal-pathspecs","status","--porcelain","-z","--untracked-files=all","--",...Gd(e)]);return Ji(r).filter(n=>!Fo(n,e.exclude))},_$=async(e,t)=>Promise.all(e.entries.map(async({entry:r,files:n})=>{let o=await Bd(t,r.target,e.exclude),s={};for(let i of Lo(n,e.exclude)){let a=Li(i.path,r);s[a]=ji(Ui.join(t,a))}return{target:r.target,tracked:o.map(i=>i.path),onDisk:s}})),M$=async e=>{try{return _t(await Z(e,["--literal-pathspecs","ls-tree","-z","--name-only","HEAD","--",Mt,jo]))}catch{return[]}},j$=e=>{try{let{commit:t,source:r}=Do(Ui.join(e,X));return{commit:t,source:r}}catch{return null}},F$=async(e,t)=>{if(t===null)return{kind:"unknown-sha"};if(await Ce(e.root,t)===null)return{kind:"unresolvable",sha:t};let r=e.entries.map(({entry:s})=>s.path),o=(await Z(e.root,["--literal-pathspecs","log","--oneline",`${t}..HEAD`,"--",...r])).split(`
438
+ `).filter(s=>s.length>0);return{kind:"log",sha:t,lines:o}},L$=(e,t)=>{try{return D$(Ui.join(e,Mt),"utf8")===Bi(t)}catch{return!1}},B$=async e=>{try{return{toplevel:(await Z(e,["rev-parse","--show-toplevel"])).trim()}}catch(t){return{reason:String(t.stderr??t).trim().split(`
439
+ `)[0]??"git rev-parse failed"}}},V$=async e=>{try{return(await Z(e,["rev-parse","--abbrev-ref","HEAD"])).trim()}catch{return"HEAD"}},Gi=async(e,t)=>{if(!I$(t.root))return{...t,kind:"missing"};let r=Wi(t.root);if(e.selfRoots.includes(r))return{...t,kind:"source"};let n=await B$(t.root);if("reason"in n)return{...t,kind:"not-git",reason:n.reason};if(Wi(n.toplevel)!==r)return{...t,kind:"not-git",reason:`it sits inside the repo at ${n.toplevel}`};let o=j$(t.root),s=o?.commit??null,[i,a,c,l,d]=await Promise.all([V$(t.root),N$(e,t.root),_$(e,t.root),M$(t.root),F$(e,s)]);return{...t,kind:"repo",branch:i,dirty:a,entries:c,headVendorMeta:l,readmeCurrent:L$(t.root,e.name),manifestPresent:o!==null,manifestSource:o?.source??null,changelog:d}};var W$=20,U$=(e,t)=>!t.commit||e.status!=="changed"||e.branch===void 0?e.notes:[...e.notes,`--commit lands on ${e.branch}`],J$=(e,t)=>{let{plan:r}=e,n=t.manifestOnly?"manifest":"sync";if(e.error!==void 0)return{name:n,status:"fail",message:`apply failed: ${e.error}`,notes:["restore the tracked paths with:",mt(mn(r))]};let o=e.applied?`wrote ${r.message}`:r.message;return{name:n,status:r.status,message:o,notes:t.mode==="applied"?r.notes:U$(r,t)}},G$=e=>e.ok?{name:"commit",status:"ok",message:"committed the synced paths"}:{name:"commit",status:"fail",message:"git refused the commit; the files stay written",notes:e.output.split(`
440
+ `).slice(0,W$)},K$=(e,t)=>{let r=e.plan.warnings.map(n=>({name:"changelog",status:"warn",message:n}));return{label:e.plan.name,rows:[J$(e,t),...r,...e.commit?[G$(e.commit)]:[]]}},H$={preview:"infra-kit vendor sync (preview)",check:"infra-kit vendor sync --check",applied:"infra-kit vendor sync"},Hd=(e,t,r)=>{let n=r.mode==="preview"?["re-run with --yes from a real terminal to apply"]:[];return{title:H$[r.mode],sections:[{label:"source",rows:[...e]},...t.map(o=>K$(o,r))],hints:n}},my=e=>e.sections.some(t=>t.rows.some(r=>r.status==="fail")),fy=(e,t,r)=>{let n=new Set(e.sections.flatMap(s=>s.rows.map(i=>`${s.label}\0${i.name}\0${i.status}`))),o=t.sections.map(s=>({label:s.label,rows:s.rows.filter(i=>!n.has(`${s.label}\0${i.name}\0${i.status}`))}));return{...t,sections:o,emptyMessage:`synced ${r.join(", ")}`}};var q$=20,qd=async(e,t)=>(await Z(e,t,{allowFailure:!0})).trim(),Y$=async e=>Ji(await Z(e,["status","--porcelain","-z","--untracked-files=normal"])),z$=async e=>(await qd(e,["for-each-ref","--contains","HEAD","--format=%(refname)","refs/remotes/origin/"])).length>0?null:{name:"HEAD pushed",status:"warn",message:"HEAD is on no origin/* ref, so every target will record a commit nobody else can resolve",notes:["git push"]},X$=async e=>{let[t,r]=await Promise.all([qd(e,["symbolic-ref","--quiet","--short","refs/remotes/origin/HEAD"]),qd(e,["rev-parse","--abbrev-ref","HEAD"])]);if(t.length===0)return{name:"default branch",status:"warn",message:"origin has no default branch recorded (origin/HEAD)"};let n=t.replace(/^origin\//u,"");return r===n?null:{name:"default branch",status:"warn",message:`syncing from ${r||"a detached HEAD"}, not the origin default branch ${n}`}},gy=async e=>{let t=await Y$(e);if(t.length>0){let n=t.slice(0,q$),o=t.length>n.length?`, and ${t.length-n.length} more`:"";throw new x({status:"refused",reason:"source-dirty",paths:t},1,{operation:`sync vendored files from ${e}`,stderrExcerpt:`the source has ${t.length} uncommitted path(s)`,remediation:`commit or stash them first, so every target records a commit holding exactly the files it got: ${n.join(", ")}${o}`})}let r=await Promise.all([z$(e),X$(e)]);return[{name:"working tree",status:"ok",message:"clean"},...r.filter(n=>n!==null)]};import Z$ from"node:path";var hy=(e,t)=>{let r=t.filter(s=>!e.targets.includes(s));if(r.length>0)throw new x({status:"refused",reason:"unknown-target",unknown:r,valid:e.targets},2,{operation:`sync vendored files to ${r.join(", ")}`,stderrExcerpt:`not a target in ~/.infra-kit/vendor.json: ${r.join(", ")}`,remediation:`name one of: ${e.targets.join(", ")}`});let n=Yr(e.workspaceDir);return(t.length>0?e.targets.filter(s=>t.includes(s)):e.targets).map(s=>({name:s,root:Z$.join(n,s)}))},Q$="rewrite vendor/README.md and vendor/.sync-manifest.json from the tracked vendor/ files",eA=async(e,t)=>{let r=await Gi(e,t),n=Vi(e,r);return r.kind!=="repo"||n.status==="fail"?n:{...n,status:"changed",message:`${Q$} on ${r.branch}`,notes:[],warnings:[],branch:r.branch,entries:[],writeVendorMeta:!0,recoveryPaths:r.headVendorMeta}},yy=async(e,t,r)=>Promise.all(t.map(async n=>r?eA(e,n):Vi(e,await Gi(e,n))));var Ki="sync vendored files",oA=()=>{if(fe())throw new x({status:"refused",agentMode:I.source},2,{operation:Ki,stderrExcerpt:"vendor sync is human-only: refused in agent mode regardless of --yes",remediation:"ask a human to run `infra-kit vendor sync` from their own shell \u2014 a sync is never confirmed by an agent"})},sA=()=>{if(!Xd.stdin.isTTY)throw new x({status:"refused",reason:"no-tty"},2,{operation:Ki,stderrExcerpt:"the apply needs a real terminal on stdin",remediation:"run `infra-kit vendor sync --yes` from a real terminal; Claude Code's `!` prefix is not one"})},iA=e=>{let t=wy.join(Yr(e.workspaceDir),e.source);if(tA(t))return t;throw new x({status:"refused",reason:"source-missing",source:t},1,{operation:Ki,stderrExcerpt:`the source repo ${e.source} is not checked out at ${t}`,remediation:'clone it there, or fix "source" / "workspaceDir" in ~/.infra-kit/vendor.json'})},Yd=(e,t)=>new x({status:"refused",reason:"not-a-vendor-source"},1,{operation:Ki,stderrExcerpt:`${e} ${t}`,remediation:`add a vendorSource block to the source repo's committed infra-kit.json, or point "source" at the repo that has one`}),aA=async e=>{let t=wy.join(e,"infra-kit.json"),r;try{r=JSON.parse(await rA.readFile(t,"utf8"))}catch(s){throw Yd(t,`is unreadable: ${s instanceof Error?s.message:String(s)}`)}let n=r?.vendorSource;if(n==null)throw Yd(t,"has no vendorSource block");let o=tp.safeParse(n);if(!o.success)throw Yd(t,`has an invalid vendorSource: ${nA.prettifyError(o.error)}`);return o.data},vy=(e,t)=>{Xd.stderr.write(`${e.name}: if this run dies, restore the tracked paths with:
441
+ ${mt(t)}
442
+ `)},cA=async(e,t,r)=>r?(vy(t,mn(t)),Wd(t.root,e)):(await Vd({source:e,plan:t,onBeforeFirstWrite:o=>{vy(t,o)}})).touched,lA=async(e,t,r)=>{if(t.status!=="changed")return{plan:t,applied:!1};let n;try{n=await cA(e,t,!!r.manifestOnly)}catch(s){return{plan:t,applied:!1,error:s instanceof Error?s.message:String(s)}}if(!r.commit)return{plan:t,applied:!0};let o=await Jd(t.root,n,Ud(e.name,e.headSha));return{plan:t,applied:!0,commit:o}},dA=async(e,t,r)=>{let n=[];for(let o of t)n.push(await lA(e,o,r));return n},ky=e=>e.map(t=>({name:t.name,root:t.root,status:t.status,message:t.message,notes:t.notes,warnings:t.warnings,branch:t.branch})),zd=({mode:e,report:t,outcomes:r,source:n,print:o})=>{o&&qe(t);let s=r.map(a=>a.plan);return{structuredContent:{mode:e,source:{root:n.root,name:n.name,headSha:n.headSha},targets:ky(s).map((a,c)=>{let l=r[c];return{...a,applied:l.applied,error:l.error,commit:l.commit}}),changed:s.some(a=>a.status==="changed"),failed:my(t),report:t.sections}}},uA=async e=>{let t=await Vs(),r=iA(t),n=await gy(r),o=await aA(r),s=hy(t,e.targets??[]),i=await Kd(r,o),a=await yy(i,s,!!e.manifestOnly);return{source:i,sourceRows:n,plans:a}},Zd=async(e={})=>{oA();let{source:t,sourceRows:r,plans:n}=await uA(e),o=n.map(m=>({plan:m,applied:!1})),s={commit:e.commit,manifestOnly:e.manifestOnly},i=e.check?"check":"preview",a=Hd(r,o,{...s,mode:i}),c=!n.some(m=>m.status==="changed");if(e.check||c)return zd({mode:i,report:a,outcomes:o,source:t,print:!0});let l=!e.confirmedCommand&&!rt.enabled;if(l&&!Xd.stdin.isTTY)return qe(a),zd({mode:"preview",report:a,outcomes:o,source:t,print:!1});l&&qe({...a,hints:[]}),await B(e.confirmedCommand,`Sync vendored files from ${t.name} into these targets?`,{plan:ky(n),throwOnDecline:!0}),sA();let d=await dA(t,n,e),p=Hd(r,d,{...s,mode:"applied"});if(l){let m=d.filter(g=>g.applied).map(g=>g.plan.name);qe(fy(a,p,m))}return zd({mode:"applied",report:p,outcomes:d,source:t,print:!l})};var Hi=(e,t=!0)=>({line:e,reproducible:t});import qi from"node:fs";import pA from"node:os";import mA from"node:path";import Py from"node:process";var Yi="INFRA_KIT_SESSION_REPORT",Qd=null,by=!1,Ry=[],Ey=(e=Py.env)=>{by||(Qd=e[Yi]??null,by=!0,delete e[Yi])};var xy=(e,t)=>{if(!Qd)return;let r=e.summary??(Ry.length>0?[...Ry]:void 0),n={...e,...r?{summary:r}:{}},o=t?.write??((s,i)=>{qi.writeFileSync(s,i)});try{o(Qd,JSON.stringify(n))}catch{}},Sy=0,Ty=e=>{let t=e?.tmpdir?.()??pA.tmpdir(),r=e?.pid??Py.pid;return Sy+=1,mA.join(t,`infra-kit-session-${r}-${Sy}.json`)},Cy=(e,t)=>{if(!(t?.exists??(i=>qi.existsSync(i)))(e))return null;let n=t?.read??(i=>qi.readFileSync(i,"utf-8")),o=t?.unlink??(i=>qi.unlinkSync(i)),s;try{s=n(e)}catch{return null}finally{try{o(e)}catch{}}try{return JSON.parse(s)}catch{return null}};var eu=e=>{e.options.some(r=>r.long==="--agent")||e.option("--agent","Run as an agent: never prompt; refuse with a structured payload (under --json) naming what to pass instead"),e.commands.forEach(eu)};var tu=e=>{e.options.some(r=>r.long==="--debug")||e.option("--debug","Raise the log level to debug (logs stay on stderr)"),e.commands.forEach(tu)};var vA=(e,t)=>[...t,e],$y=(e,t)=>{if(!(typeof e>"u")){if(e===!0)return"workspace";if(e===!1)return"none";if(typeof e=="string"&&ur.includes(e))return e;throw new Error(`Invalid ${t} value "${String(e)}". Expected one of: ${ur.join(", ")}.`)}},wA=e=>e.description("Merge dev branch into every release branch").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-y, --yes","Skip confirmation prompt").option("--dry-run","Compute and print the merge plan without pushing anything").option("--verify [command]","Check each merge before pushing it. Bare runs `pnpm install --frozen-lockfile`; pass a command to run that instead. A branch that fails is dropped from the push, never rolled back").option("--keep-conflicts","On the confirmed run, leave each conflicted branch mid-merge in <root>-worktrees/merge-dev/ for resolution").option("--continue","Check, preview, then commit and push the selected resolutions left by --keep-conflicts").option("--abort","Discard the selected resolutions left by --keep-conflicts").option("--tree <branch=sha>","With --continue --yes: the approved tree per branch, as a --continue preview prints it (repeatable)",(t,r)=>[...r??[],t]).action(async t=>{let r=await Ym(()=>ri({all:t.all,versions:t.versions,dryRun:t.dryRun,verify:t.verify,keepConflicts:t.keepConflicts,continue:t.continue,abort:t.abort,tree:t.tree,confirmedCommand:t.yes}));C(r),r.structuredContent.failedMerges>0&&(Me.exitCode=1)}),Ay=e=>(Me.stdout.write(`${e.structuredContent.filePath}
443
+ `),C(e)),kA=e=>e.description("List all release branches").action(async()=>{C(await ci())}),bA=e=>e.description("Create one or more release branches (each entry can mix regular/hotfix and its own description)").option("-r, --release <spec>",'Release spec "<version|next|name>[@yyyy-mm-dd][:type[:description]]" (repeatable). The token is a semver ("1.2.5"), the literal "next", or a kebab-case name ("checkout-redesign"); "@yyyy-mm-dd" is the planned release date, written to the Jira fix version. Type is regular|hotfix (default regular). Examples: "1.2.5", "1.2.5:hotfix", "1.64.0@2026-10-28", "next:regular:Holiday backend", "checkout-redesign:regular:Q3 redesign".',vA,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let n=t.release.map(Zc),o=n.length>0?n:void 0;C(await mi({releases:o,confirmedCommand:t.yes}))}),RA=e=>{if(e==="")return e;try{return tr(e)}catch(t){throw t instanceof tn?new gA(t.message):t}},SA=e=>e.description("Edit a release's description and/or release date in Jira (description also in the matching GitHub PR body)").option("-v, --version <version>","Release version (e.g. 1.2.5) or release name (e.g. checkout-redesign)").option("-d, --description <description>",'New description (use "" to clear)').option("--release-date <yyyy-mm-dd>",'New planned release date (use "" to clear)',RA).option("-y, --yes","Skip confirmation prompt").action(async t=>{C(await fi({version:t.version,description:t.description,releaseDate:t.releaseDate,confirmedCommand:t.yes}))}),Oy=e=>e.option("-f, --from <where>",`Where the deploy runs: ${Dt.join(" | ")} (required)`).option("-v, --version <version>",'With --from ci: version (e.g. 1.2.5) or release name to deploy; "dev" deploys from the dev branch. Prompts when omitted').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("-y, --yes","Skip confirmation prompt").option("--skip-terraform","With --from ci: skip the terraform deployment step").option("--dry-run","With --from local: resolve target, contract and commands without deploying").option("--print-env","With --from local: print the resolved build contract"),PA=e=>Oy(e).description("Deploy every service to any environment, in CI or from this machine").action(async t=>{C(await _d({from:t.from,version:t.version,env:t.env,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),EA=e=>Oy(e).description("Deploy selected services to any environment, in CI or from this machine").option("-s, --services <services...>","Specify services to deploy, e.g. client-be client-fe").action(async t=>{C(await Md({from:t.from,version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),xA=e=>e.description("Release a new version to production").option("-v, --version <version>","Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deliver").option("-y, --yes","Skip confirmation prompt").action(async t=>{C(await si({version:t.version,confirmedCommand:t.yes}))}),TA=e=>e.description("Tear down a release: worktree, PR, branches, and the Jira fix version").option("-v, --version <version>","Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to remove").option("--move-issues-to <version>","Reassign issues carrying the fix version to this version before removing it").option("--skip-jira","Remove everything except the Jira fix version").option("-y, --yes","Skip confirmation prompt").action(async t=>{C(await ki({version:t.version,moveIssuesTo:t.moveIssuesTo,skipJira:t.skipJira,confirmedCommand:t.yes}))}),CA=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{C(await Di({confirmedCommand:t.yes}))}),$A=e=>e.description("Add git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-i, --ide [mode]","Editor mode for created worktrees: workspace (default) | none").option("--no-ide","Skip the editor (alias for --ide none)").option("-c, --cursor [mode]","Deprecated alias for --ide").option("--no-cursor","Deprecated alias for --no-ide").option("-g, --github-desktop","Open created worktrees in GitHub Desktop").option("--no-github-desktop","Skip GitHub Desktop prompt").option("--orca","Open created worktrees in Orca (pane layout from worktrees.orca.layout)").option("--no-orca","Skip the Orca prompt").action(async t=>{let r=$y(t.ide,"--ide")??$y(t.cursor,"--cursor");C(await Ai({confirmedCommand:t.yes,all:t.all,versions:t.versions,ide:r,githubDesktop:t.githubDesktop,orca:t.orca}))}),AA=e=>e.description("List all git worktrees with detailed information").action(async()=>{C(await Oi())}),OA=e=>e.description("Remove git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").action(async t=>{C(await Ii({confirmedCommand:t.yes,all:t.all,versions:t.versions}))}),IA=e=>e.description("Show the machine-local factory config (~/.infra-kit/vendor.json) or scaffold it with --init").option("--init","Scaffold ~/.infra-kit/vendor.json (skips if it already exists)").action(async t=>{C(await Fd({init:t.init}))}),DA=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await Ti();C(t),t.structuredContent.ok||(Me.exitCode=1)}),NA=e=>e.description("Mirror vendorSource files from the ~/.infra-kit/vendor.json source into every target, from any directory (human-only)").argument("[targets...]","Narrow to these target names from ~/.infra-kit/vendor.json").option("-y, --yes","Apply the previewed plan (needs a real terminal on stdin)").option("--check","Preview only; exit 1 when any target would change").option("--commit","Commit exactly the synced paths in each target after it syncs").option("--manifest-only","Rewrite vendor/README.md and vendor/.sync-manifest.json only; copy nothing").action(async(t,r)=>{let n;try{n=await Zd({targets:t,confirmedCommand:r.yes,check:r.check,commit:r.commit,manifestOnly:r.manifestOnly})}catch(a){if(!nt(a))throw a;u.info("Operation cancelled.");return}C(n);let{failed:o,changed:s,mode:i}=n.structuredContent;(o||i==="check"&&s)&&(Me.exitCode=1)}),_A=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{C(await $d())}),MA=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{C(await Ad())}),jA=new Set(["version"]),zi=e=>{let t=[];for(let r=e;r&&r.parent;r=r.parent)t.unshift(r.name());return t.join(" ")},ru=()=>{let e=new fA().option("-C <dir>","Run as if infra-kit was started in <dir> instead of the current working directory"),t=e.command("release").description("Release management commands");wA(t.command("merge-dev")),kA(t.command("list")),bA(t.command("create")),SA(t.command("edit")),PA(t.command("deploy-all")),EA(t.command("deploy-selected")),xA(t.command("deliver")),TA(t.command("remove"));let r=e.command("worktrees").description("Git worktree management commands");$A(r.command("add")),AA(r.command("list")),OA(r.command("remove")),CA(r.command("sync"));let n=e.command("config").description("Manage infra-kit configuration files");_A(n.command("path")),MA(n.command("edit")),e.command("config-get").description("Print the fully merged infra-kit config (project + user-global + per-project override layers)").action(async()=>{C(await Ss())});let o=e.command("local").description("Deprecated \u2014 use `release deploy-all|deploy-selected --from local`"),s=a=>a.option("-e, --env <name>","Target environment (prompts when omitted)").option("-y, --yes","Skip the confirmation prompt").option("--dry-run","Resolve target, contract and commands without deploying").option("--print-env","Print the resolved build contract");s(o.command("deploy-all")).description("Deprecated \u2014 use `release deploy-all --from local`").action(async a=>{C(await Mi({env:a.env,yes:a.yes,dryRun:a.dryRun,printEnv:a.printEnv},"all"))}),s(o.command("deploy-selected")).description("Deprecated \u2014 use `release deploy-selected --from local`").option("-s, --service <name...>","Service name(s), as in deploy-<name>.sh (prompts when omitted)").action(async a=>{C(await Mi({env:a.env,services:a.service,yes:a.yes,dryRun:a.dryRun,printEnv:a.printEnv},"selected"))}),e.command("audit").description("Audit against infra-kit.config.ts rules (--all for every package, --root for the monorepo root)").option("-a, --all","Audit every non-vendor workspace package").option("-r, --root","Audit the monorepo root (turbo pipeline + root commands)").option("--fix","Write the infra-kit guidance block into CLAUDE.md for the audited scope before checking (CLI-only)").option("--design","With --fix: scaffold DESIGN.md for frontend/mobile packages that lack one").action(async a=>{if(a.design&&!a.fix){u.error("--design requires --fix (it scaffolds DESIGN.md; there is nothing to scaffold without a fix run)"),Me.exitCode=1;return}let c=await Rs({all:a.all,root:a.root,fix:a.fix,design:a.design});C(c);let{allPassed:l,fixed:d}=c.structuredContent,p=(d??[]).some(m=>m.action==="failed");(!l||p)&&(Me.exitCode=1)});let i=e.command("vendor").description("Mirror and verify the vendored starter files");return DA(i.command("check")),IA(i.command("config")),NA(i.command("sync")),e.command("doctor").description("Check installation and authentication status of gh and doppler CLIs").option("--fix","Remove portless routes left behind by a dev-server that was killed (kill -9, OOM, force-quit). Refuses while a dev session is running, when a booting UI is indistinguishable from a dead route.").option("--ascii","Render the report with ASCII markers instead of unicode glyphs (check messages are unchanged)").action(async a=>{let c=await zs({fix:!!a.fix});rt.enabled||lc(c.structuredContent.checks,{ascii:!!a.ascii}),c.structuredContent.checks.some(d=>d.name==="plugin installed"&&d.status==="fail")&&(Me.exitCode=1),C(c)}),e.command("dev").description("Run local dev servers for a preset or an app (or every app); api + ui").argument("[preset]","A devServersPresets name, or an app \u2014 its api/ui plus the backends its routes can run locally (omit to run every app)").option("-w, --watch","Rebuild and restart on file save (the default)").option("--no-watch","Build once and never restart on save").option("--app <names>","Further narrow to these app folder names (comma-separated)").option("--target <keys>","Run exactly these <app>/api|<app>/ui packages (comma-separated); part-level, unlike --app").option("--orca","Run each app in its own Orca pane (one tab, N panes; falls back to single terminal when Orca is not running)").option("--self","Run only the app of the current directory (infer from cwd; use inside apps/<app>/\u2026)").option("-V, --verbose","Print full boot narration (default: quiet; full detail always in the session log)").option("--routes","Print each app\u2019s registered METHOD /path routes at startup (default: off)").option("--reuse","For test runners: start nothing when this worktree already serves one of these apps, exit on a boot failure").option("--no-ui-health","Do not probe the frontends\u2019 liveness (vite\u2019s HMR ping); their rows carry no health dot (also: INFRA_KIT_NO_UI_HEALTH=1)").action(async(a,c)=>{let{runDevServerCli:l}=await import("./dev-server.js"),d=!!(Me.stdout.isTTY&&Me.stdin.isTTY);await l({...c,preset:a},d,rt.enabled)}),e.command("dev-status").description("Show what `infra-kit dev` currently has running (reads dev-context fragments; starts nothing)").action(async()=>{C(await Es())}),e.command("e2e").description("Run an app\u2019s Playwright e2e against this worktree (dev reused or started), or --cloud").argument("[playwrightArgs...]","Passed to `playwright test` (put them after `--`)").option("--app <name>","App folder whose apps/<app>/tests package to run (inferred from cwd when omitted)").option("--dry-run","Resolve and print the target and proxy topology without running").option("--cloud","Run against the deployed app at INFRA_KIT_ENV instead of this worktree").option("-y, --yes","Skip the confirmation a cloud run asks for").action(async(a,c)=>{C(await Zs({app:c.app,dryRun:c.dryRun,yes:c.yes,cloud:c.cloud,playwrightArgs:a}))}),e.command("setup").description("Set this machine up: shell integration, agent files, the Claude Code skills plugin, then the external tools").option("--tools <ids...>","Limit to these tools (brew, git, aws, gh, doppler, portless)").option("--update [ids...]","Update what is already installed; never install a missing tool").option("--skip-tools","Do the local setup only, then REPORT what each tool needs \u2014 installs nothing").option("--ascii","Render the report with ASCII markers instead of unicode glyphs (row messages are unchanged)").action(async a=>{C(await Ri({tools:a.tools,update:a.update,skipTools:a.skipTools,ascii:!!a.ascii}))}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{C(await Ci())}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{C(await ei())}),e.command("env-list").description("List available Doppler configs for the detected project, and whether a service token resolves for each").action(async()=>{C(await Np())}),e.command("env-load").description("Load Doppler env vars for a config. Source the returned file path to apply.").option("-c, --config <config>","Environment config name to load (e.g. dev, arthur)").action(async a=>{Ay(await ua({config:a.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{Ay(await Qs())}),e.command("env-token-set").description("Store the Doppler service token for an env (masked prompt; validated against Doppler before writing)").argument("<env>","Environment / Doppler config the token is scoped to (e.g. dev)").option("--stdin","Read the token from stdin instead of prompting (e.g. from a password manager)").option("--from-env <var>","Read the token from the named environment variable (the NAME, never the value)").option("--force","Store even when the token\u2019s scope could not be verified. Never overrides a real mismatch.").action(async(a,c)=>{C(await Dd({env:a,stdin:c.stdin,fromEnv:c.fromEnv,force:c.force}))}),e.command("env-token-list").description("Show which envs have a Doppler service token (redacted), and where it came from").option("--check","Also ask Doppler whether each token is valid and correctly scoped").action(async a=>{C(await ti({check:!!a.check}))}),e.command("env-token-remove").description("Delete an env\u2019s Doppler service token from the local store (does NOT revoke it in Doppler)").argument("<env>","Environment / Doppler config whose token to remove").action(async a=>{C(await Od({env:a}))}),e.commands.forEach(Fu),eu(e),tu(e),e.hook("preAction",async(a,c)=>{let{C:l}=e.opts();l!==void 0&&yA(hA(Me.cwd(),l)),h.start(zi(c)),rt.enabled=!!c.optsWithGlobals().json,rt.enabled&&(u.level="warn"),I.source=Xo({env:Me.env,stdinIsTTY:Me.stdin.isTTY===!0,flag:!!c.optsWithGlobals().agent}),jA.has(zi(c))||await Oc()}),e.hook("postAction",(a,c)=>{let l=zi(c);if(xd(l))return;let p=h.snapshot()?.formattedOptions??"",m=p?` ${p}`:"",g=`infra-kit ${l}${m}`;xy({equivalent:Hi(g,!0)})}),e};import FA from"node:process";var LA={exit:FA.exit,emit:C,logger:u},Iy=(e,t=LA)=>ve(e)?(t.logger.info("Operation cancelled."),t.exit(0)):e instanceof x?(t.emit({structuredContent:e.structuredContent}),t.logger.error(e.message),t.exit(e.exitCode)):(t.logger.error(e instanceof Error?e.message:String(e)),t.exit(1));var nu=(e,t=" ")=>{let r=e.reduce((n,[o])=>Math.max(n,o.length),0);return e.map(([n,o])=>`${n.padEnd(r)}${t}${o}`)};import BA from"node:fs";import Dy from"node:path";import Vo from"node:process";var My=new Set([...ep,gn,"XDG_CACHE_HOME","CLAUDE_PROJECT_DIR","CLAUDE_PLUGIN_ROOT"]),jy=null,Xi=new Set,ou=null,Ny=!1;var _y=e=>{try{return BA.statSync(e)}catch{return null}},VA=()=>{if(Ny)return null;try{return yr()}catch{return Ny=!0,u.debug(`session-env: ${gn} unset \u2014 no overlay`),null}},WA=e=>{let t=Dy.join(e,gr),r=Dy.join(e,Wo),n=_y(t),o=_y(r);return n&&!(o&&o.mtimeMs>n.mtimeMs)?{kind:"load",file:t,signature:`load:${n.ino}:${n.mtimeMs}:${n.size}`}:o?{kind:"clear",file:r,signature:`clear:${o.ino}:${o.mtimeMs}`}:{kind:"none",signature:"none"}},UA=e=>e.kind==="load"?{kind:"load",vars:mu(e.file),signature:e.signature}:e.kind==="clear"?{kind:"clear",unset:fu(e.file),signature:e.signature}:e;var JA=()=>{let e=VA();if(e===null)return{kind:"no-session"};let t=WA(e);return t.signature===ou?null:UA(t)},GA=()=>{for(let e of Xi){let t=jy[e];t===void 0?delete Vo.env[e]:Vo.env[e]=t}Xi.clear()},KA=(e,t,r)=>{if(My.has(t)){e.skipped.push(t);return}Vo.env[t]=r,Xi.add(t),e.set.push(t)},HA=(e,t)=>{if(My.has(t)){e.skipped.push(t);return}delete Vo.env[t],Xi.add(t),e.unset.push(t)},qA=e=>{let t={set:[],unset:[],skipped:[]};if(e.kind==="load")for(let[r,n]of Object.entries(e.vars))KA(t,r,n);if(e.kind==="clear")for(let r of e.unset)HA(t,r);return t},YA=e=>e.kind==="load"?`load, ${Object.keys(e.vars).length} vars`:e.kind,su=(e=JA())=>{if(jy??={...Vo.env},e===null||e.kind==="no-session"||e.signature===ou)return{set:[],unset:[],changed:!1};GA();let{set:t,unset:r,skipped:n}=qA(e);return ou=e.signature,n.length>0&&u.warn(`session-env: skipped protected names [${n.join(", ")}]`),u.debug(`session-env applied: set [${t.join(", ")}] unset [${r.join(", ")}] (${YA(e)})`),{set:t,unset:r,changed:!0}};import{chalkStderr as hO}from"chalk";import{spawn as yO}from"node:child_process";import Pe from"node:process";import{Chalk as zA}from"chalk";var fn=new zA({level:1}),Le={ok:"ok",findingsPlain:"completed with findings",failed:"failed",cancelled:"cancelled",findingsSuffix:"findings",sep:" \xB7 ",reproPrefix:"$ ",nonReproPrefix:"\u2248 ",envNotice:"Applies to infra-kit commands in this terminal and to new shells; this zsh prompt itself needs the env-load function."},XA={suspend:{unicode:"any key commands \xB7 Esc / Ctrl-C quit \xB7 Ctrl-Z suspend",ascii:"any key commands - Esc / Ctrl-C quit - Ctrl-Z suspend"},plain:{unicode:"any key commands \xB7 Esc / Ctrl-C quit",ascii:"any key commands - Esc / Ctrl-C quit"}},Fy={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},Ly={unicode:"\u2500",ascii:"-"},ZA=3,iu=e=>e,QA={ok:e=>fn.green(e),findings:e=>fn.yellow(e),failed:e=>fn.red(e),cancelled:e=>fn.gray(e)},cu=e=>e?{dim:t=>fn.dim(t),bold:t=>fn.bold(t)}:{dim:iu,bold:iu},eO=(e,t)=>e?QA[t]:iu,au=e=>[...e].length,tO=(e,t)=>{if(t==null)return e;let r=Math.max(0,t-1);return au(e)<=r?e:[...e].slice(0,r).join("")},By=e=>{let t=cu(e.color===!0).dim,r=XA[e.canSuspend?"suspend":"plain"],n=e.ascii===!0?r.ascii:r.unicode;return t(tO(n,e.width))},Vy=(e,t={})=>{let r=cu(t.color===!0);return`${r.dim(Le.reproPrefix.trim())} ${r.bold(e)}`},rO=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,nO=(e,t)=>e==="findings"?t!=null?`${t} ${Le.findingsSuffix}`:Le.findingsPlain:{ok:Le.ok,failed:Le.failed,cancelled:Le.cancelled}[e],oO=(e,t,r,n)=>{if(t==null)return"";let o=t-2-e;return o<ZA?"":` ${n(r.repeat(o))}`},Wy=e=>{let t=e.color===!0,r=cu(t),n=eO(t,e.outcome),o=e.ascii===!0,s=e.equivalent.reproducible?Le.reproPrefix:Le.nonReproPrefix,i=o?Fy[e.outcome].ascii:Fy[e.outcome].unicode,a=nO(e.outcome,e.findingsCount),c=[rO(e.durationMs)],l=e.summary?.[0]?.split(`
444
+ `)[0];l!=null&&l.length>0&&c.push(l);let d=`${i} ${a}`,p=`${Le.sep}${c.join(Le.sep)}`,m=au(d)+au(p),g=oO(m,e.width,o?Ly.ascii:Ly.unicode,r.dim),y=[`${n(d)}${r.dim(p)}${g}`];return e.showEquivalent!==!1&&y.unshift(`${r.dim(s.trim())} ${r.bold(e.equivalent.line)}`),e.envNotice===!0&&y.push(r.dim(Le.envNotice)),y.join(`
445
+ `)};var sO=new Set([130,143]),Uy=(e,t,r,n=!1)=>r?t!=null||e===0?"ok":"findings":n&&e!=null&&sO.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import iO from"node:process";var aO={3:"quit",4:"quit",26:"suspend",27:"quit"},cO=e=>{if(e.length!==1)return"continue";let t=typeof e=="string"?e.charCodeAt(0):e[0];return t===void 0||Number.isNaN(t)?"continue":aO[t]??"continue"},lO=150,dO="\r\x1B[2K",uO=`\r
446
+ `,Jy=(e,t)=>{Gy(e),e.stdin.on("data",t),e.listener=t},Gy=e=>{e.listener!==null&&(e.stdin.off("data",e.listener),e.listener=null)},Ky=(e,t)=>{fp(),e.stdin.setRawMode(!0),e.stdin.isPaused()&&e.stdin.resume(),Jy(e,t)},Hy=e=>{e.hintOnScreen&&(e.hintOnScreen=!1,e.deps.write(dO)),Gy(e),e.stdin.isTTY===!0&&e.stdin.isRaw===!0&&e.stdin.setRawMode(!1),gp()},pO=e=>{e.settled||(e.settled=!0,Hy(e))},qy=(e,t)=>{let r=By({canSuspend:e.deps.suspend!==void 0,ascii:e.deps.ascii,color:e.deps.color,width:e.deps.columns()});e.deps.write(t+r),e.hintOnScreen=!0},mO=async e=>{await new Promise(t=>{setTimeout(t,e)})},fO=(e,t,r)=>{Hy(e),t(),Ky(e,r),qy(e,uO)},gO=async e=>new Promise(t=>{let r=n=>{let o=cO(n),s=e.deps.suspend;if(o==="quit"){t("quit");return}if(o==="suspend"&&s!==void 0){fO(e,s,r);return}t("palette")};Jy(e,r),qy(e,"")}),Yy=async(e,t)=>{if(e.quitRequested())return"quit";let r=t.stdin??iO.stdin;if(r.isTTY!==!0)return"palette";let n={deps:t,stdin:r,listener:null,hintOnScreen:!1,settled:!1};try{return Ky(n,()=>{}),e.armed(),await mO(t.drainMs??lO),await gO(n)}finally{pO(n)}};import zy from"node:process";var jt={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},Xy=(e,t)=>{let r=t?.write??(s=>{zy.stderr.write(s)}),n=t?.stdin??zy.stdin,o=[jt.saveCursor,jt.scrollRegion,jt.restoreCursor,jt.column,jt.sgr,jt.cursor,jt.wrap];e.entersAltScreen===!0&&o.push(jt.primaryBuffer),r(o.join("")),n.isTTY===!0&&n.isRaw===!0&&n.setRawMode?.(!1)};var Zy=e=>`infra-kit ${e.groupPath.join(" ")}`,vO=()=>{wO();let e=Pe.stderr.columns;return e!=null&&e>0?e:void 0},wO=()=>{let e=Pe.stderr;typeof e._refreshSize=="function"&&e._refreshSize()},kO=e=>new Promise(t=>{e.on("exit",(r,n)=>{t({code:r,signal:n})}),e.on("error",()=>{t({code:1,signal:null})})}),bO=async(e,t,r)=>{let n=Ty(),o={...t.env,[Yi]:n,INFRA_KIT_NO_AUTO_UPDATE:"1"},s=t.now(),i={code:1,signal:null};r();try{let p=t.spawn(Pe.execPath,[t.cliPath,...e.groupPath],{stdio:"inherit",env:o});i=await kO(p)}catch{i={code:1,signal:null}}finally{t.resetTerminal({entersAltScreen:e.entersAltScreen})}let a=Cy(n),c=Uy(i.code,i.signal,a!=null,e.longRunning),l=Zy(e),d=a?.equivalent??Hi(l,!0);return Wy({equivalent:d,outcome:c,durationMs:t.now()-s,summary:a?.summary,envNotice:e.sessionEnvNotice,ascii:t.ascii,color:t.color,width:t.columns(),showEquivalent:!(d.reproducible&&d.line===l)})},RO=1e3,SO=(e,t)=>e!=null&&t-e<=RO,lu=e=>{e.resetTerminal(),e.exit(0)},PO=(e,t)=>{let r=null,n=!1,o=()=>{let c=e();if(c==="child"){r=t.now();return}c!=="pause"&&lu(t)},s=()=>{let c=e();if(c==="palette"){lu(t);return}if(!SO(r,t.now())){if(c==="pause"){lu(t);return}n=!0}},i=()=>{t.exit(129)},a=()=>{e()==="child"&&t.raise("SIGSTOP")};return t.register("SIGINT",o),t.register("SIGTERM",s),t.register("SIGHUP",i),t.register("SIGTSTP",a),{dispose:()=>{t.unregister("SIGINT",o),t.unregister("SIGTERM",s),t.unregister("SIGHUP",i),t.unregister("SIGTSTP",a)},childStarted:()=>{r=null},quitRequested:()=>n}},Qy=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),EO=Pe.platform==="win32"?void 0:()=>{hp()},xO=(e,t)=>r=>Yy(r,{write:e,columns:t.columns,ascii:t.ascii,color:t.color,suspend:EO}),ev=async(e,t)=>{let r={spawn:t.spawn??yO,now:t.now??(()=>Date.now()),env:t.env??Pe.env,cliPath:t.cliPath,ascii:t.ascii??!(Pe.stdout.isTTY&&Pe.env.TERM!=="dumb"),color:t.color??hO.level>0,columns:t.columns??vO,resetTerminal:t.resetTerminal??(d=>{Xy(d)})},n=t.write??(d=>Pe.stderr.write(d)),o="palette",s=t.signals??{register:(d,p)=>{Pe.on(d,p)},unregister:(d,p)=>{Pe.off(d,p)},exit:d=>{Pe.exit(d)},raise:d=>{Pe.kill(Pe.pid,d)},now:()=>Date.now(),resetTerminal:()=>{o==="pause"&&n("\r\x1B[2K"),r.resetTerminal({entersAltScreen:!1})}},i={dispose:()=>{},childStarted:()=>{},quitRequested:()=>!1},a=t.installSignals===!1?i:PO(()=>o,s),c={armed:()=>{o="pause"},quitRequested:()=>a.quitRequested()},l=t.afterRun??xO(n,r);try{for(;;){if(a.quitRequested())return;o="palette";let d=await t.renderPalette(e);if(d==null)return;let p=t.resolveCommand(d);if(!p)continue;let m=Vy(Zy(p),{color:r.color});n(`
444
447
  ${m}
445
- `),a.childStarted();let g=await oI(u,r,()=>{o="child"});if(n(`
448
+ `),a.childStarted();let g=await bO(p,r,()=>{o="child"});if(n(`
446
449
  ${g}
447
- `),await l(c)==="quit")return}}finally{a.dispose()}};Xd();Ky();var Ev=Ep(),Sv=async(e=Ee.argv)=>{Cp(),Au(e);try{await Ev.parseAsync(e)}catch(t){Qy(t)}},fI=()=>{try{if(Ee.env.INFRA_KIT_NO_LOCATION_WARN||Ee.argv.includes("--json"))return;Vp({selfRealPath:uI(Pv(import.meta.url)),cwd:Ee.cwd(),env:Ee.env,realpath:he,home:mI(),exists:pI})&&p.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};fI();nu((e,t)=>{p.debug(e,t)});qc(q.version);var xv=()=>uy(Ev.commands),gI=async()=>{let e=xv(),t=null;try{if(Ee.stdout.isTTY&&Ee.stdin.isTTY){let{runCommandPalette:r}=await import("./boot-XLDVLQEG.js");t=await r(e)}else{let r=xp(e.map(o=>[o.name,o.description])),n=e.flatMap((o,s)=>[...e[s-1]?.group===o.group?[]:[new Rv(" "),new Rv(`\u2014 ${o.group} \u2014`)],{name:r[s]??o.name,value:o.name}]);t=await I(o=>dI({message:"Select a command to run",choices:n},o),{output:Ee.stderr})}}catch(r){if(!we(r))throw r}return t},hI=async()=>{let{runCommandPalette:e}=await import("./boot-XLDVLQEG.js"),t=Pv(import.meta.url),r=new Map(fr.map(n=>[n.groupPath.join(" "),n]));await bv(xv(),{renderPalette:e,resolveCommand:n=>{let o=r.get(n);return o?{groupPath:o.groupPath,entersAltScreen:o.entersAltScreen,sessionEnvNotice:o.sessionEnvNotice,longRunning:o.longRunning}:void 0},cliPath:t})};if(Ee.argv.length<=2){let e={stdoutIsTTY:!!Ee.stdout.isTTY,stdinIsTTY:!!Ee.stdin.isTTY,stderrIsTTY:!!Ee.stderr.isTTY};if(kv(Ee.env,e))await hI();else{let t=await gI();t&&await Sv(["node","infra-kit",...t.split(" ")])}}else await Sv();
450
+ `),await l(c)==="quit")return}}finally{a.dispose()}};Cd();Ey();var ov=ru(),rv=async(e=Ee.argv)=>{su(),pp(e);try{await ov.parseAsync(e)}catch(t){Iy(t)}},OO=()=>{try{if(Ee.env.INFRA_KIT_NO_LOCATION_WARN||Ee.argv.includes("--json"))return;ku({selfRealPath:$O(nv(import.meta.url)),cwd:Ee.cwd(),env:Ee.env,realpath:me,home:AO(),exists:CO})&&u.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};OO();ju((e,t)=>{u.debug(e,t)});Dc(G.version);var sv=()=>Jh(ov.commands),IO=async()=>{let e=sv(),t=null;try{if(Ee.stdout.isTTY&&Ee.stdin.isTTY){let{runCommandPalette:r}=await import("./boot-LC2ESPY6.js");t=await r(e)}else{let r=nu(e.map(o=>[o.name,o.description])),n=e.flatMap((o,s)=>[...e[s-1]?.group===o.group?[]:[new tv(" "),new tv(`\u2014 ${o.group} \u2014`)],{name:r[s]??o.name,value:o.name}]);t=await O(o=>TO({message:"Select a command to run",choices:n},o),{output:Ee.stderr})}}catch(r){if(!ve(r))throw r}return t},DO=async()=>{let{runCommandPalette:e}=await import("./boot-LC2ESPY6.js"),t=nv(import.meta.url),r=new Map(nr.map(n=>[n.groupPath.join(" "),n]));await ev(sv(),{renderPalette:e,resolveCommand:n=>{let o=r.get(n);return o?{groupPath:o.groupPath,entersAltScreen:o.entersAltScreen,sessionEnvNotice:o.sessionEnvNotice,longRunning:o.longRunning}:void 0},cliPath:t})};if(Ee.argv.length<=2){let e={stdoutIsTTY:!!Ee.stdout.isTTY,stdinIsTTY:!!Ee.stdin.isTTY,stderrIsTTY:!!Ee.stderr.isTTY};if(Qy(Ee.env,e))await DO();else{let t=await IO();t&&await rv(["node","infra-kit",...t.split(" ")])}}else await rv();
448
451
  //# sourceMappingURL=cli.js.map