infra-kit 0.27.0 → 0.28.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{c as Sm,e as Ir,f as Om,g as Ct,h as js,i as Im,j as Dm,k as Nm,l as _m,m as Mm,n as jm,o as Fm,p as Lm,s as za,t as Vm,u as Se}from"./chunk-JZ7P52FQ.js";import{a as Op,b as Ie,c as Ip,d as Ma,e as Dp,f as Np,g as _p,h as Mp,i as Nn,j as jp,k as Fp,l as Lp,m as Bp,n as Up,o as _n,p as Vp,q as Wp,r as Gp,s as Jp,t as ja,u as xs,v as St,w as Kp,x as Ts,y as Hp}from"./chunk-XES5EOEE.js";import{a as oe,b as G,c as xt,d as Fn,e as Va,f as Ds,g as Ns,h as Wa,i as Ln,j as Xt,k as Ga,l as _s,m as ym,n as Bn,o as Un,p as Ka,q as Ha,r as qa,s as xm,u as Ya}from"./chunk-7A4LVTRJ.js";import{b as Dn,c as Es,d as _a,e as xp,f as Ps,g as Tp,i as Cp,k as $p,m as ye,o as Ap}from"./chunk-AWFGP6GY.js";import{a as Rm}from"./chunk-TVG47UHG.js";import{A as Wn,C as Za,G as Qa,H as ec,a as k,b as E,c as Tm,d as Cm,e as Zt,f as $m,g as Qt,h as Am,i as Bm,j as Vn,k as $t,l as Dr,m as Ye,n as Fs,o as At,p as Um,q as Ls,r as Wm,s as Gm,t as ze,x as Xa}from"./chunk-L6NGDZWU.js";import{a as h,b as pt,c as vm,d as wm,e as I,f as Ms,g as L,i as Tt,j as Je,k as Em,l as Ja,m as Pm}from"./chunk-Q32KHZHK.js";import{$ as fm,A as em,B as tm,C as rm,D as As,E as Os,F as De,G as Mn,H as Or,I as Is,J as nm,K as om,L as sm,M as La,N as Ba,O as im,P as d,Q as Ne,R as Z,S as v,T as Ge,U as am,V as cm,W as lm,X as dm,Y as pm,Z as mm,_ as Et,a as zt,aa as Ua,b as $,ba as gm,c as qp,ca as hm,d as _,da as Y,e as ve,ea as W,f as K,fa as jn,g as Cs,ga as Pt,h as Yp,ha as C,i as g,j as zp,k as $s,l as q,m as me,n as we,o as Xp,p as Fa,q as ne,r as X,s as $r,t as Zp,u as qe,v as fe,w as P,x as Re,y as Ar,z as Qp}from"./chunk-MUYD4QA4.js";import{a as um}from"./chunk-MFAFQVTW.js";import{a as U}from"./chunk-53KLNCP2.js";import{a as Pr,b as vs,c as ws,d as In,e as bp,f as xr,g as ks,h as bs,i as Rp,j as Rs,k as Ss,l as Sp,m as Ep,n as dt,o as Tr,p as Rt,q as le,r as Pp,s as Cr}from"./chunk-I23MDR4X.js";import{a as km,b as bm}from"./chunk-QWVLAZ6N.js";import sM,{Separator as gk}from"@inquirer/select";import{existsSync as iM,realpathSync as aM}from"node:fs";import{homedir as cM}from"node:os";import Oe from"node:process";import{fileURLToPath as yk}from"node:url";import Mf from"node:process";import{z as je}from"zod";import Qm from"node:fs";import _r from"node:path";import{packageConfigSchema as Hm}from"@slip-stream-kit/config/internal";import qm from"node:fs/promises";import Bs from"node:path";import{pathToFileURL as xk}from"node:url";import{z as Ym}from"zod";import Jm from"node:path";var Gn=["frontend","backend","lib","e2e","mobile"],kk={ui:"frontend",api:"backend",tests:"e2e"},bk="mobile-app",Rk=[{type:"e2e",packages:["@playwright/test"]},{type:"mobile",packages:["@capacitor/core","@capacitor/cli"]},{type:"backend",packages:["serverless"]}],Sk=(e,t)=>{let r=Jm.relative(t,e).split(Jm.sep).filter(s=>s!==""&&s!=="."),[n,,o]=r;if(r.length===3&&n==="apps"&&o!==void 0){let s=kk[o];if(s)return s}return r.at(-1)===bk?"mobile":null},Ek=e=>{let t=new Set([...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{}),...Object.keys(e.peerDependencies??{})]);for(let n of Rk)if(n.packages.some(o=>t.has(o)))return n.type;return t.has("vite")&&t.has("react")&&!!e.scripts?.dev?"frontend":null},Jn=({packageDir:e,repoRoot:t,pkgJson:r,declaredType:n})=>n??Sk(e,t)??Ek(r)??"lib";var Ot={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},Km=2e3,tc={"e2e-test":"pnpm exec playwright test","e2e-test-ui":"pnpm exec playwright test --ui","e2e-test-ui-demo":`E2E_SLOW_MO=\${E2E_SLOW_MO:-${Km}} 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"},Kn={requiredScripts:["build","test","qa","infra-kit-check","fix"],requiredFiles:["turbo.json","pnpm-workspace.yaml"],turboTasks:["build","test","ts-check","eslint-check","prettier-check","infra-kit-check"]},Hn=(e,t=Ot)=>({requiredScripts:e.requiredScripts??[...t.requiredScripts],requiredFiles:e.requiredFiles??[...t.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...t.turboTasks]});import Pk from"node:fs/promises";var Ee=async e=>{try{return await Pk.access(e),!0}catch{return!1}};var se="infra-kit.config.ts",er=async e=>{try{let t=await qm.readFile(Bs.join(e,"package.json"),"utf-8");return JSON.parse(t)}catch{return{}}},rc=async e=>{let t=await qm.stat(e),o=(await import(`${xk(e).href}?mtime=${Number(t.mtimeMs)}`)).default;if(o===void 0)throw new Error(`${se} at ${e} has no default export`);return typeof o=="function"?await o():o},tr=async e=>{let t=Bs.join(e,se);if(await Ee(t))try{let n=(await rc(t))?.type;return Gn.find(o=>o===n)}catch{return}},zm=e=>e,qn=async(e,t=Ot)=>{let r=Bs.join(e,se);if(!await Ee(r))throw new Error(`${se} not found at ${r}`);let n=await rc(r),o=Hm.safeParse(n);if(!o.success)throw new Error(`Invalid ${se} at ${r}: ${Ym.prettifyError(o.error)}`);return Hn(zm(o.data),t)},It=async e=>{let t=Bs.join(e,se);if(!await Ee(t))return;let r=Hm.safeParse(await rc(t));if(!r.success)throw new Error(`Invalid ${se} at ${t}: ${Ym.prettifyError(r.error)}`);return zm(r.data)};import Xm from"node:fs/promises";import Us from"node:path";import Tk from"yaml";var Ck="pnpm-workspace.yaml",$k=async e=>(await Xm.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(r=>r.isDirectory()).map(r=>Us.join(e,r.name)),Ak=async(e,t)=>{let r=[];for(let n of e){if(t==="*"){r.push(...await $k(n));continue}let o=Us.join(n,t);await Ee(o)&&r.push(o)}return r},Ok=async(e,t)=>{let r=[e];for(let n of t.split("/"))r=await Ak(r,n);return r},Pe=async e=>{let t=await Xm.readFile(Us.join(e,Ck),"utf-8"),n=((Tk.parse(t)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),o=new Set;for(let s of n){let i=await Ok(e,s);for(let a of i)await Ee(Us.join(a,"package.json"))&&o.add(a)}return[...o].sort()};import Yn from"node:path";var zn=async e=>{let t=Yn.resolve(e);for(;t!==Yn.dirname(t);){if(await Ee(Yn.join(t,"package.json")))return t;t=Yn.dirname(t)}if(await Ee(Yn.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 Xe=(e,t,r)=>{let n=e.indexOf(t),o=e.indexOf(r);return n!==-1&&o!==-1&&o>=n},Dt=(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}`:"")},nc=(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},Zm=(e,t,r)=>`${e}
2
+ import{c as Em,e as Ir,f as Im,g as Ct,h as js,i as Dm,j as Nm,k as _m,l as Mm,m as jm,n as Fm,o as Lm,p as Bm,s as za,t as Wm,u as Se}from"./chunk-QJCOLFRN.js";import{a as Ip,b as Ie,c as Dp,d as Ma,e as Np,f as _p,g as Mp,h as jp,i as _n,j as Fp,k as Lp,l as Bp,m as Up,n as Vp,o as Mn,p as Wp,q as Gp,r as Jp,s as Kp,t as ja,u as xs,v as St,w as Hp,x as Ts,y as qp}from"./chunk-XES5EOEE.js";import{a as oe,b as G,c as xt,d as Ln,e as Va,f as Ds,g as Ns,h as Wa,i as Bn,j as Xt,k as Ga,l as _s,m as vm,n as Un,o as Vn,p as Ka,q as Ha,r as qa,s as Tm,u as Ya}from"./chunk-7A4LVTRJ.js";import{b as Nn,c as Es,d as _a,e as Tp,f as Ps,g as Cp,i as $p,k as Ap,m as ve,o as Op}from"./chunk-AWFGP6GY.js";import{a as Sm}from"./chunk-TVG47UHG.js";import{A as Gn,C as Za,G as Qa,H as ec,a as k,b as E,c as Cm,d as $m,e as Zt,f as Am,g as Qt,h as Om,i as Um,j as Wn,k as $t,l as Dr,m as ze,n as Fs,o as At,p as Vm,q as Ls,r as Gm,s as Jm,t as Xe,x as Xa}from"./chunk-W4CZUPXZ.js";import{a as h,b as pt,c as wm,d as km,e as I,f as Ms,g as L,i as Tt,j as Je,k as Pm,l as Ja,m as xm}from"./chunk-STVQOKMC.js";import{$ as gm,A as tm,B as rm,C as nm,D as As,E as Os,F as De,G as jn,H as Or,I as Is,J as om,K as sm,L as im,M as La,N as Ba,O as am,P as d,Q as Ne,R as Z,S as v,T as Ge,U as cm,V as lm,W as um,X as pm,Y as mm,Z as fm,_ as Et,a as zt,aa as Ua,b as $,ba as hm,c as Yp,ca as ym,d as _,da as Y,e as we,ea as W,f as H,fa as Fn,g as Cs,ga as Pt,h as zp,ha as C,i as g,j as Xp,k as $s,l as q,m as me,n as ke,o as Zp,p as Fa,q as ne,r as X,s as $r,t as Qp,u as Ye,v as fe,w as P,x as Re,y as Ar,z as em}from"./chunk-MDZSYRGS.js";import{a as dm}from"./chunk-MFAFQVTW.js";import{a as U}from"./chunk-WTS3O3LM.js";import{a as Pr,b as vs,c as ws,d as Dn,e as Rp,f as xr,g as ks,h as bs,i as Sp,j as Rs,k as Ss,l as Ep,m as Pp,n as dt,o as Tr,p as Rt,q as le,r as xp,s as Cr}from"./chunk-I23MDR4X.js";import{a as bm,b as Rm}from"./chunk-QWVLAZ6N.js";import uM,{Separator as yk}from"@inquirer/select";import{existsSync as dM,realpathSync as pM}from"node:fs";import{homedir as mM}from"node:os";import Oe from"node:process";import{fileURLToPath as wk}from"node:url";import jf from"node:process";import{z as je}from"zod";import ef from"node:fs";import _r from"node:path";import{packageConfigSchema as qm}from"@slip-stream-kit/config/internal";import Ym from"node:fs/promises";import Bs from"node:path";import{pathToFileURL as Ck}from"node:url";import{z as zm}from"zod";import Km from"node:path";var Jn=["frontend","backend","lib","e2e","mobile"],Rk={ui:"frontend",api:"backend",tests:"e2e"},Sk="mobile-app",Ek=[{type:"e2e",packages:["@playwright/test"]},{type:"mobile",packages:["@capacitor/core","@capacitor/cli"]},{type:"backend",packages:["serverless"]}],Pk=(e,t)=>{let r=Km.relative(t,e).split(Km.sep).filter(s=>s!==""&&s!=="."),[n,,o]=r;if(r.length===3&&n==="apps"&&o!==void 0){let s=Rk[o];if(s)return s}return r.at(-1)===Sk?"mobile":null},xk=e=>{let t=new Set([...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{}),...Object.keys(e.peerDependencies??{})]);for(let n of Ek)if(n.packages.some(o=>t.has(o)))return n.type;return t.has("vite")&&t.has("react")&&!!e.scripts?.dev?"frontend":null},Kn=({packageDir:e,repoRoot:t,pkgJson:r,declaredType:n})=>n??Pk(e,t)??xk(r)??"lib";var Ot={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},Hm=2e3,tc={"e2e-test":"pnpm exec playwright test","e2e-test-ui":"pnpm exec playwright test --ui","e2e-test-ui-demo":`E2E_SLOW_MO=\${E2E_SLOW_MO:-${Hm}} 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"},Hn={requiredScripts:["build","test","qa","infra-kit-check","fix"],requiredFiles:["turbo.json","pnpm-workspace.yaml"],turboTasks:["build","test","ts-check","eslint-check","prettier-check","infra-kit-check"]},qn=(e,t=Ot)=>({requiredScripts:e.requiredScripts??[...t.requiredScripts],requiredFiles:e.requiredFiles??[...t.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...t.turboTasks]});import Tk from"node:fs/promises";var Ee=async e=>{try{return await Tk.access(e),!0}catch{return!1}};var se="infra-kit.config.ts",er=async e=>{try{let t=await Ym.readFile(Bs.join(e,"package.json"),"utf-8");return JSON.parse(t)}catch{return{}}},rc=async e=>{let t=await Ym.stat(e),o=(await import(`${Ck(e).href}?mtime=${Number(t.mtimeMs)}`)).default;if(o===void 0)throw new Error(`${se} at ${e} has no default export`);return typeof o=="function"?await o():o},tr=async e=>{let t=Bs.join(e,se);if(await Ee(t))try{let n=(await rc(t))?.type;return Jn.find(o=>o===n)}catch{return}},Xm=e=>e,Yn=async(e,t=Ot)=>{let r=Bs.join(e,se);if(!await Ee(r))throw new Error(`${se} not found at ${r}`);let n=await rc(r),o=qm.safeParse(n);if(!o.success)throw new Error(`Invalid ${se} at ${r}: ${zm.prettifyError(o.error)}`);return qn(Xm(o.data),t)},It=async e=>{let t=Bs.join(e,se);if(!await Ee(t))return;let r=qm.safeParse(await rc(t));if(!r.success)throw new Error(`Invalid ${se} at ${t}: ${zm.prettifyError(r.error)}`);return Xm(r.data)};import Zm from"node:fs/promises";import Us from"node:path";import $k from"yaml";var Ak="pnpm-workspace.yaml",Ok=async e=>(await Zm.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(r=>r.isDirectory()).map(r=>Us.join(e,r.name)),Ik=async(e,t)=>{let r=[];for(let n of e){if(t==="*"){r.push(...await Ok(n));continue}let o=Us.join(n,t);await Ee(o)&&r.push(o)}return r},Dk=async(e,t)=>{let r=[e];for(let n of t.split("/"))r=await Ik(r,n);return r},Pe=async e=>{let t=await Zm.readFile(Us.join(e,Ak),"utf-8"),n=(($k.parse(t)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),o=new Set;for(let s of n){let i=await Dk(e,s);for(let a of i)await Ee(Us.join(a,"package.json"))&&o.add(a)}return[...o].sort()};import zn from"node:path";var Xn=async e=>{let t=zn.resolve(e);for(;t!==zn.dirname(t);){if(await Ee(zn.join(t,"package.json")))return t;t=zn.dirname(t)}if(await Ee(zn.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},Dt=(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}`:"")},nc=(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},Qm=(e,t,r)=>`${e}
4
4
  ${t}
5
- ${r}`,Nr=({content:e,body:t,startMarker:r,endMarker:n,placement:o="replace-in-place"})=>{let s=Zm(r,t,n),i=Xe(e,r,n);if(o==="replace-in-place"&&i){let l=e.indexOf(r),u=e.indexOf(n)+n.length;return e.slice(0,l)+s+e.slice(u)}let c=(i?Dt(e,r,n)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
5
+ ${r}`,Nr=({content:e,body:t,startMarker:r,endMarker:n,placement:o="replace-in-place"})=>{let s=Qm(r,t,n),i=Ze(e,r,n);if(o==="replace-in-place"&&i){let l=e.indexOf(r),u=e.indexOf(n)+n.length;return e.slice(0,l)+s+e.slice(u)}let c=(i?Dt(e,r,n)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
6
6
  ${s}
7
7
  `:`${s}
8
- `};var _e="<!-- infra-kit:begin -->",Ze="<!-- infra-kit:end -->",oc="<!-- infra-kit:version ",Qe="<!-- infra-kit:package:begin -->",mt="<!-- infra-kit:package:end -->",rr="<!-- infra-kit:package:version ";var Ik=e=>{let t=e.indexOf(Qe)+Qe.length;return e.slice(t,e.indexOf(mt))},Dk=e=>{let t=e.indexOf(rr);if(t===-1)return null;let r=e.slice(t+rr.length).match(/^\S+\s+([^\s>]+)/)?.[1];return Gn.find(n=>n===r)??null},nr=e=>{if(e===null)return{state:"missing"};if(!Xe(e,Qe,mt))return e.includes(Qe)||e.includes(mt)?{state:"malformed"}:Xe(e,_e,Ze)?{state:"foreign-block"}:{state:"no-block"};let t=Ik(e);if(t.trim()==="")return{state:"malformed"};let r={state:"ok"},n=nc(t,rr),o=Dk(t);return n!==null&&(r.version=n),o!==null&&(r.type=o),r};import Nk from"node:fs";var or=e=>{try{return Nk.readFileSync(e,"utf-8")}catch{return null}};var ef="pnpm-workspace.yaml",_k="CLAUDE.md",ic=e=>{let t=_r.resolve(e);for(;t!==_r.dirname(t);){if(Qm.existsSync(_r.join(t,ef)))return t;t=_r.dirname(t)}return Qm.existsSync(_r.join(t,ef))?t:null},sc=new Map,Vs=()=>{sc.clear()},Mk=async e=>{let t;try{t=await Pe(e)}catch{return{adopted:!1,workspaceRoot:e}}for(let r of t){let n=_r.join(r,_k),o=or(n);if(o!==null&&nr(o).state==="ok")return{adopted:!0,workspaceRoot:e,evidencePath:n}}return{adopted:!1,workspaceRoot:e}},Mr=async e=>{if(e===null)return{adopted:!1,workspaceRoot:null};let t=sc.get(e);if(t)return t;let r=await Mk(e);return sc.set(e,r),r};import sr from"node:fs";import Nt from"node:path";var tf=`---
8
+ `};var _e="<!-- infra-kit:begin -->",Qe="<!-- infra-kit:end -->",oc="<!-- infra-kit:version ",et="<!-- infra-kit:package:begin -->",mt="<!-- infra-kit:package:end -->",rr="<!-- infra-kit:package:version ";var Nk=e=>{let t=e.indexOf(et)+et.length;return e.slice(t,e.indexOf(mt))},_k=e=>{let t=e.indexOf(rr);if(t===-1)return null;let r=e.slice(t+rr.length).match(/^\S+\s+([^\s>]+)/)?.[1];return Jn.find(n=>n===r)??null},nr=e=>{if(e===null)return{state:"missing"};if(!Ze(e,et,mt))return e.includes(et)||e.includes(mt)?{state:"malformed"}:Ze(e,_e,Qe)?{state:"foreign-block"}:{state:"no-block"};let t=Nk(e);if(t.trim()==="")return{state:"malformed"};let r={state:"ok"},n=nc(t,rr),o=_k(t);return n!==null&&(r.version=n),o!==null&&(r.type=o),r};import Mk from"node:fs";var or=e=>{try{return Mk.readFileSync(e,"utf-8")}catch{return null}};var tf="pnpm-workspace.yaml",jk="CLAUDE.md",ic=e=>{let t=_r.resolve(e);for(;t!==_r.dirname(t);){if(ef.existsSync(_r.join(t,tf)))return t;t=_r.dirname(t)}return ef.existsSync(_r.join(t,tf))?t:null},sc=new Map,Vs=()=>{sc.clear()},Fk=async e=>{let t;try{t=await Pe(e)}catch{return{adopted:!1,workspaceRoot:e}}for(let r of t){let n=_r.join(r,jk),o=or(n);if(o!==null&&nr(o).state==="ok")return{adopted:!0,workspaceRoot:e,evidencePath:n}}return{adopted:!1,workspaceRoot:e}},Mr=async e=>{if(e===null)return{adopted:!1,workspaceRoot:null};let t=sc.get(e);if(t)return t;let r=await Fk(e);return sc.set(e,r),r};import sr from"node:fs";import Nt from"node:path";var rf=`---
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 rf=`# {{packageName}}
77
+ `;var nf=`# {{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 nf="# {{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- {{checksBullet}}\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- HTTP Basic Auth credentials are `E2E__BASIC_AUTH_USERNAME` / `E2E__BASIC_AUTH_PASSWORD` (double underscore) in every suite \u2014 the names the dev proxy injects and the shared CI job exports. Pass them to `use.httpCredentials`; never invent a per-app name (`E2E_CLIENT_BASIC_AUTH_*`) or fall back to one. `infra-kit audit` fails the package otherwise.\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. The one exception is a suite that must run against a production build it serves itself: it declares `e2e: { server: 'static' }` in `infra-kit.config.ts` and sets `baseURL` and `webServer` itself.\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 once a person approves (see Repair).\n\nLint enforces the mechanical part: `@wl/e2e-file-layout` the Structure folders and the `.spec.ts` suffix, `@wl/e2e-file-order` imports first and then the class, the `extend` call, the `test.*` calls, the mock function or a `lib/` file's exports \u2014 constants and helpers below, `@wl/e2e-page-object-member-order` fields \u2192 constructor \u2192 getters \u2192 public \u2192 private methods, `@wl/e2e-top-level-describe` one top-level describe holding the setup, hooks and tests, `@wl/e2e-describe-order` setup \u2192 hooks \u2192 tests inside it, `@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\n## Repair\n\nFor a failing spec, before editing anything:\n\n- Classify the failure: product defect, intentional product change, test defect, test data or environment, or flake. Say which, and why, in the change.\n- Diagnose from `infra-kit e2e --json`: read `failures[]` (title, `file:line`, error) and open its `tracePath` with `pnpm exec playwright show-trace`, rather than reading the full log. Re-run one test with `infra-kit e2e --json -- <spec> --grep \"<title>\"`.\n- Never take the expected behaviour from what the UI shows now. It comes from the spec's intent, the ticket, or a person; when it is unclear, stop and report instead of editing.\n- Never without a person's explicit approval: delete or weaken an assertion, add `test.skip` / `test.fixme` / `test.fail`, update a snapshot or visual baseline, widen a timeout, or add retries. A product defect is reported, not tested around.\n";var of="# {{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- {{checksBullet}}\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- A loaded env var that breaks local dev \u2014 one meant for another build mode, e.g. a mobile-only absolute origin that bypasses the proxy \u2014 goes in `dev.env.unset` (or `dev.env.set` to override it) in `infra-kit.config.ts`. Never remove it from Doppler or patch it out in `vite.config.ts`.\n- Use the tokens in `DESIGN.md` rather than ad-hoc colors, spacing, or type scales.\n";var sf=`# {{packageName}}
98
+ `;var of="# {{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- {{checksBullet}}\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- HTTP Basic Auth credentials are `E2E__BASIC_AUTH_USERNAME` / `E2E__BASIC_AUTH_PASSWORD` (double underscore) in every suite \u2014 the names the dev proxy injects and the shared CI job exports. Pass them to `use.httpCredentials`; never invent a per-app name (`E2E_CLIENT_BASIC_AUTH_*`) or fall back to one. `infra-kit audit` fails the package otherwise.\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. The one exception is a suite that must run against a production build it serves itself: it declares `e2e: { server: 'static' }` in `infra-kit.config.ts` and sets `baseURL` and `webServer` itself.\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 once a person approves (see Repair).\n\nLint enforces the mechanical part: `@wl/e2e-file-layout` the Structure folders and the `.spec.ts` suffix, `@wl/e2e-file-order` imports first and then the class, the `extend` call, the `test.*` calls, the mock function or a `lib/` file's exports \u2014 constants and helpers below, `@wl/e2e-page-object-member-order` fields \u2192 constructor \u2192 getters \u2192 public \u2192 private methods, `@wl/e2e-top-level-describe` one top-level describe holding the setup, hooks and tests, `@wl/e2e-describe-order` setup \u2192 hooks \u2192 tests inside it, `@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\n## Repair\n\nFor a failing spec, before editing anything:\n\n- Classify the failure: product defect, intentional product change, test defect, test data or environment, or flake. Say which, and why, in the change.\n- Diagnose from `infra-kit e2e --json`: read `failures[]` (title, `file:line`, error) and open its `tracePath` with `pnpm exec playwright show-trace`, rather than reading the full log. Re-run one test with `infra-kit e2e --json -- <spec> --grep \"<title>\"`.\n- Never take the expected behaviour from what the UI shows now. It comes from the spec's intent, the ticket, or a person; when it is unclear, stop and report instead of editing.\n- Never without a person's explicit approval: delete or weaken an assertion, add `test.skip` / `test.fixme` / `test.fail`, update a snapshot or visual baseline, widen a timeout, or add retries. A product defect is reported, not tested around.\n";var sf="# {{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- {{checksBullet}}\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- A loaded env var that breaks local dev \u2014 one meant for another build mode, e.g. a mobile-only absolute origin that bypasses the proxy \u2014 goes in `dev.env.unset` (or `dev.env.set` to override it) in `infra-kit.config.ts`. Never remove it from Doppler or patch it out in `vite.config.ts`.\n- Use the tokens in `DESIGN.md` rather than ad-hoc colors, spacing, or type scales.\n";var af=`# {{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.
@@ -116,7 +116,7 @@ This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_
116
116
  - {{surfaceBullet}}
117
117
  - {{buildBullet}}
118
118
  - No app-specific logic belongs here.
119
- `;var af=`# {{packageName}}
119
+ `;var cf=`# {{packageName}}
120
120
 
121
121
  Workspace package at \`{{relDir}}\` \u2014 type: **{{type}}**.
122
122
  This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_ the markers, never inside.
@@ -138,42 +138,42 @@ This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_
138
138
  - The native shell is Capacitor; its settings live in \`capacitor.config.*\`.
139
139
  - The web build feeds the native shell, so a device run needs a rebuild first.
140
140
  - Use the tokens in \`DESIGN.md\` rather than ad-hoc colors, spacing, or type scales.
141
- `;var cf="# 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` = `infra-kit`, the global CLI)\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. Without `-c`, an agent loads the project's `defaultEnv` (set yours with `ik config-set defaultEnv <env>`); with none set it is refused and must ask the human.\n- `ik dev [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; no name runs every app. App names are per-repo: an unknown one is refused with the 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. `ik worktrees add --feature <name> [--base <dev|main|release>]` creates `feature/<name>` at `<root>-worktrees/feature/<name>`, cut from `dev` by default (the default branch in a repo without `dev`); `worktrees remove --feature <name>` removes it. To close the worktree a session runs in (\"close this worktree\"), run `infra-kit worktrees remove --self` from inside it: it previews, and its `--yes` re-run hands the removal to an Orca tab of the main checkout, which closes every tab of the worktree \u2014 this session included. The `/infra-kit:worktrees` skill is the agent entry point for feature worktrees \u2014 never create one with raw `git worktree add` or Claude Code's `EnterWorktree`, which skip `pnpm install`, the editor/Orca wiring and the `feature/` layout.\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`. 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`, `vendor 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` is human-only and is 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 jr={"root/body":cf.trimEnd(),"package/frontend":of.trimEnd(),"package/backend":rf.trimEnd(),"package/lib":sf.trimEnd(),"package/e2e":nf.trimEnd(),"package/mobile":af.trimEnd(),"design/skeleton":tf.trimEnd()};var ac=/\{\{(\w+)\}\}/g,Gk=/^- \{\{(\w+)\}\}$/,Jk=e=>new Set([...e.matchAll(ac)].map(t=>t[1])),Kk=(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(", ")}`)},Hk=(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(", ")}`)},qk=(e,t)=>e.filter(r=>{let n=Gk.exec(r);return n===null||t[n[1]]!==""}),Yk=(e,t)=>{for(let r of e)for(let n of r.matchAll(ac)){let o=t[n[1]];if(o!==void 0&&o.includes(`
142
- `)&&n.index!==0)throw new Error(`renderTemplate: multi-line value for {{${n[1]}}} must start its line (found at column ${n.index})`)}},Fr=(e,t)=>{let r=Jk(e);Hk(r,t),Kk(r,t);let n=qk(e.split(`
143
- `),t);return Yk(n,t),n.join(`
144
- `).replace(ac,(o,s)=>t[s])};var zk="name: TODO",cc=e=>{let t=Fr(jr["design/skeleton"],{packageName:e}),r=`name: ${e}`;return`${t.replace(zk,()=>r)}
145
- `};var Xk=(e,t)=>`${rr}${e} ${t} -->`,Zk="`README.md` \u2014 what this package is and how to run it.",lc="docs/e2e-playwright.md",Qk=`\`${lc}\` at the repo root \u2014 env setup, run modes, \`E2E_SLOW_MO\`, traces after a failure.`,eb=["ts-check","eslint-check","test"],tb="The public surface is what `package.json` exposes \u2014 its `exports` map, or `bin` for a CLI; changing it is a breaking change for every dependent package.",rb="Run `pnpm run build` before a dependent package can see a change.",lf=(e,t)=>e?.includes(t)??!0,nb=e=>{let t=eb.filter(r=>lf(e,r)).map(r=>`pnpm run ${r}`);return t.length===0?"":`\`${t.join(" && ")}\` \u2014 this package only.`},uc=e=>{let{version:t,type:r,packageName:n,relDir:o,hasReadme:s,hasE2eDoc:i,scripts:a,hasPublicSurface:c=!0}=e,l=Fr(jr[`package/${r}`],{packageName:n,relDir:o,type:r,readmeBullet:s?Zk:"",checksBullet:nb(a),...r==="e2e"?{e2eDocBullet:i?Qk:""}:{},...r==="lib"?{surfaceBullet:c?tb:"",buildBullet:lf(a,"build")?rb:""}:{}});return[Xk(t,r),"",l,""].join(`
146
- `)};var ob=e=>`${oc}${e} -->`,dc=e=>{let t=Fr(jr["root/body"],{});return[ob(e),"",t,""].join(`
147
- `)};import Lr from"node:fs";import sb from"node:path";var Ws=e=>{let t;try{t=Lr.lstatSync(e)}catch{return}if(t.isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},Xn=(e,t)=>{let r=Zn(e,t);return r!=="unchanged"&&(Lr.mkdirSync(sb.dirname(e),{recursive:!0}),Lr.writeFileSync(e,t,"utf-8")),r},Zn=(e,t)=>{Ws(e);let r=Lr.existsSync(e)?Lr.readFileSync(e,"utf-8"):null;return r===t?"unchanged":r===null?"created":"updated"},pc=(e,t,r)=>{let n=Lr.readFileSync(e,"utf-8");if(!Xe(n,t,r))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},uf=(e,t,r)=>Xe(e,t,r)?{before:e.slice(0,e.indexOf(t)),after:e.slice(e.indexOf(r)+r.length)}:null,mc=(e,t,r,n)=>{let o=uf(e,r,n),s=uf(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 Js="<!-- infra-kit:import:begin -->",Ks="<!-- infra-kit:import:end -->",ib="AGENTS.md",df="CLAUDE.md",ab="README.md",fc="DESIGN.md",cb=["frontend","mobile"],lb=e=>sr.existsSync(e)?sr.readFileSync(e,"utf-8"):null,gc=(e,t)=>{try{return sr.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},pf=({filePath:e,body:t,startMarker:r,endMarker:n,prepare:o,dryRun:s})=>{let i=lb(e),a=i===null?"":o?.(i)??i,c=Nr({content:a,body:t,startMarker:r,endMarker:n,placement:"replace-in-place"});if(s)return Zn(e,c);let l=Xn(e,c);return pc(e,r,n),i!==null&&mc(a,c,r,n),l},ub=(e,t)=>{if(!sr.existsSync(e))return"unchanged";Ws(e);let r=sr.readFileSync(e,"utf-8"),n=Dt(r,_e,Ze);return n===null?"unchanged":n.trim()===""?(t||sr.rmSync(e),"removed"):t?Zn(e,n):Xn(e,n)},db=(e,t,r)=>pf({filePath:e,dryRun:r,body:dc(t),startMarker:_e,endMarker:Ze,prepare:n=>Dt(n,Js,Ks)??n}),Qn=async(e,{version:t,dryRun:r=!1})=>{let n=Nt.join(e,df),o=Nt.join(e,ib),s=[];try{s.push({path:n,action:db(n,t,r)})}catch(i){s.push(Gs(n,i))}try{s.push({path:o,action:ub(o,r)})}catch(i){s.push(Gs(o,i))}return s},pb=(e,t,r,n)=>{if(!cb.includes(r)||gc(e,fc))return null;let o=Nt.join(e,fc),s=cc(t);try{return{path:o,action:n?Zn(o,s):Xn(o,s),type:r}}catch(i){return Gs(o,i,r)}},eo=async(e,{repoRoot:t,version:r,design:n,declaredType:o,dryRun:s=!1})=>{let i=Nt.join(e,df),a=await er(e),c=a.name??Nt.basename(e),l=Jn({packageDir:e,repoRoot:t,pkgJson:a,declaredType:o}),u=uc({version:r,type:l,packageName:c,relDir:Nt.relative(t,e).split(Nt.sep).join("/"),hasReadme:gc(e,ab),hasDesign:gc(e,fc),hasE2eDoc:sr.existsSync(Nt.join(t,lc)),scripts:Object.keys(a.scripts??{}),hasPublicSurface:a.exports!==void 0||a.bin!==void 0}),p=[];try{p.push({path:i,action:pf({filePath:i,body:u,startMarker:Qe,endMarker:mt,dryRun:s}),type:l})}catch(m){p.push(Gs(i,m,l))}if(n){let m=pb(e,c,l,s);m&&p.push(m)}return p};import Nb from"node:path";import mf from"node:path";var hc="agent-guidance",to="CLAUDE.md",mb="\u2014 run: infra-kit audit --fix",fb={missing:`${to} missing`,"no-block":`${to} has no infra-kit block (expected ${Qe} \u2026 ${mt})`,malformed:`${to} block is malformed (end marker precedes start, or body is empty)`,"foreign-block":`${to} carries the ROOT infra-kit block (${_e}); a package needs the package block`},gb=e=>e.adopted?` (workspace adopted: ${mf.relative(e.workspaceRoot,e.evidencePath)} carries a package block)`:"",yc=(e,t)=>{let r=nr(or(mf.join(e,to)));if(r.state==="ok"){let s=r.version??"unknown",i=r.type??"unknown";return{name:hc,status:"pass",message:`present (block from infra-kit ${s}, type ${i})`}}let n=`${fb[r.state]} ${mb}`,o=r.state==="missing"?`${n}${gb(t)}`:n;return t.adopted?{name:hc,status:"fail",message:o}:{name:hc,status:"pass",message:`not yet adopted \u2014 ${o}`}};import hb from"node:path";var vc=async(e,t=Ot)=>{try{let r=await qn(e,t);return{check:{name:se,status:"pass",message:"present and valid"},rules:r}}catch(r){return{check:{name:se,status:"fail",message:r.message},rules:null}}},ff="infra-kit.json",yb=async e=>await Ee(hb.join(e,se))?{name:se,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,wc=async(e,t=Kn)=>{let r=await yb(e),n=r?[r]:[];try{let{audit:o={}}=await W();return{checks:[{name:ff,status:"pass",message:"present and valid"},...n],rules:Hn(o,t)}}catch(o){return{checks:[{name:ff,status:"fail",message:o.message},...n],rules:null}}};import Hs from"node:fs/promises";import Br from"node:path";import{$ as vb}from"zx";var ro="playwright.config.ts",wb=[{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'"},{name:"infra-kit-e2e",pattern:/\binfraKitE2e\b/u,expected:"baseURL, ignoreHTTPSErrors and webServer from infraKitE2e() ('@slip-stream-kit/config/playwright')"}],gf=e=>Object.entries(tc).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"}}),kb="infra-kit-e2e",hf=async(e,t={})=>{let r=Br.join(e,ro),n=await Hs.readFile(r,"utf-8").catch(()=>null);return n===null?[{name:`e2e-config:${ro}`,status:"fail",message:`missing ${ro}`}]:wb.map(o=>{let s=`e2e-config:${o.name}`;return t.staticServer&&o.name===kb?{name:s,status:"pass",message:"not required \u2014 e2e.server is 'static', the suite serves its own build"}:o.pattern.test(n)?{name:s,status:"pass",message:"present"}:{name:s,status:"fail",message:`${ro} lacks the shared e2e convention \u2014 expected: ${o.expected}`}})},bb=/['"`](?:[^'"`\n]*\/)?\.auth['"/`]/u,Rb=/\.[cm]?[jt]sx?$/u,kc=async(e,t)=>(await Hs.readdir(e,{recursive:t,withFileTypes:!0}).catch(()=>[])).filter(n=>n.isFile()&&Rb.test(n.name)).map(n=>Br.join(n.parentPath,n.name)),Sb=async e=>{let t=await kc(Br.join(e,"src"),!0);for(let r of[Br.join(e,ro),...t]){let n=await Hs.readFile(r,"utf-8").catch(()=>"");if(bb.test(n))return!0}return!1},yf=async e=>{let t="e2e-auth:gitignored";if(!await Sb(e))return{name:t,status:"pass",message:"no saved auth state referenced"};let r=await vb({cwd:e,quiet:!0,nothrow:!0})`git -c core.excludesFile=/dev/null check-ignore -q .auth/storage-state.json`;if(r.exitCode===0)return{name:t,status:"pass",message:".auth/ is gitignored"};if(r.exitCode===1)return{name:t,status:"fail",message:"the suite saves auth state under .auth/, which git would commit \u2014 add `.auth/` to .gitignore"};let n=r.stderr.trim()||`exit ${r.exitCode}`;return{name:t,status:"fail",message:`could not ask git whether .auth/ is ignored: ${n}`}},bc="E2E__BASIC_AUTH_USERNAME",Rc="E2E__BASIC_AUTH_PASSWORD",Eb=/\bE2E_\w*BASIC_AUTH_\w+/gu,Pb=/_(?:USER(?:NAME)?|PASS(?:WORD)?)$/u,xb=/\/\*[\s\S]*?\*\//gu,Tb=/(^|[^:])\/\/[^\n]*/gu,Cb=e=>/USER(?:NAME)?$/u.test(e)?bc:Rc,$b=e=>e.replace(xb,"").replace(Tb,"$1"),vf=async e=>{let t="e2e-env:basic-auth",r=[...await kc(e,!1),...await kc(Br.join(e,"src"),!0)],n=[];for(let o of r){let s=await Hs.readFile(o,"utf-8").catch(()=>""),i=new Set([...$b(s).matchAll(Eb)].map(a=>a[0]).filter(a=>Pb.test(a)&&a!==bc&&a!==Rc));for(let a of i)n.push(`${a} \u2192 ${Cb(a)} (${Br.relative(e,o)})`)}return n.length===0?{name:t,status:"pass",message:`basic auth read only from ${bc} / ${Rc}`}:{name:t,status:"fail",message:`basic auth has one name pair in every suite \u2014 rename, with no fallback to the old name: ${n.join("; ")}`}},Sc=async(e,t,r={})=>[...gf(t),...await hf(e,r),await yf(e),await vf(e)];import Ab from"node:fs/promises";import Ob from"node:path";var Ec=async(e,t)=>Promise.all(t.map(async r=>{let n=await Ab.stat(Ob.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 Pc=(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 Ib from"node:fs/promises";import Db from"node:path";var Ur="turbo.json",xc=async(e,t)=>{if(t.length===0)return[];let r;try{let o=await Ib.readFile(Db.join(e,Ur),"utf-8");r=JSON.parse(o)}catch(o){return[{name:Ur,status:"fail",message:`cannot read/parse ${Ur}: ${o.message}`}]}let n=r.tasks;return n===null||typeof n!="object"?[{name:Ur,status:"fail",message:`no "tasks" object defined in ${Ur}`}]: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 ${Ur}`}})};var _b=async(e,t)=>{let{check:r,rules:n}=await vc(e,t);return{checks:[r],rules:n}},Mb={adopted:!1,workspaceRoot:null},jb=async(e,t,r)=>Jn({packageDir:e,repoRoot:r??e,pkgJson:t,declaredType:await tr(e)}),Fb=async e=>(await It(e).catch(()=>{}))?.e2e?.server==="static",Tc=async(e,t=Ot,r={})=>{let n=await er(e),o=n.name??Nb.basename(e),{checks:s,rules:i}=r.isRoot?await wc(e,t):await _b(e,t);r.isRoot||s.push(yc(e,r.adoption??Mb)),i&&(s.push(...Pc(n.scripts??{},i.requiredScripts)),s.push(...await Ec(e,i.requiredFiles)),s.push(...await xc(e,i.turboTasks))),!r.isRoot&&await jb(e,n,r.repoRoot)==="e2e"&&s.push(...await Sc(e,n.scripts??{},{staticServer:await Fb(e)}));let a=s.every(c=>c.status==="pass");return{packageDir:e,packageName:o,checks:s,passed:a}};var Cc=["plugin","marketplace","add",xt],$c=["plugin","install",G,"--scope","project"],wf=(e,t)=>Xt({projectPath:e,home:t}).kind==="installed",qs=e=>((e??"").split(`
148
- `).find(r=>r.trim().length>0)??"").trim(),Lb=(e,t)=>{if(Ln(t))return null;d.debug({msg:`Running: ${Fn} ${Cc.join(" ")}`});let r=e({args:Cc});return r.ok?null:{step:"marketplace",error:qs(r.output)}},Bb=(e,t)=>{d.debug({msg:`Running: ${Fn} ${Ns.join(" ")}`});let r=e({args:Ns});if(!r.ok)return{status:"update-failed",error:qs(r.output)};d.debug({msg:`Running: ${Fn} ${Ds.join(" ")}`});let n=e({args:Ds,cwd:t});return n.ok?{status:"updated"}:{status:"update-failed",error:qs(n.output)}},Ac=e=>{let{projectRoot:t,home:r}=e,n=e.run??Wa;if(!n({args:Va}).ok)return{status:"claude-missing"};if(wf(t,r))return e.cliIsStale?.()===!0?{status:"skipped-cli-stale"}:Bb(n,t);let o=Lb(n,r);if(o!==null)return{status:"failed",...o};d.debug({msg:`Running: ${Fn} ${$c.join(" ")}`});let s=n({args:$c,cwd:t});return s.ok?wf(t,r)?{status:"installed"}:{status:"unverified"}:{status:"failed",step:"install",error:qs(s.output)}};import Ub from"node:fs";import Vb from"node:path";var Me=".mcp.json",et="mcpServers",Wb="infra-kit",Gb=["mcp"],Jb="/infra-kit/dist/mcp.js",Oc=" ",ir=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),kf=e=>{if(!ir(e))return!1;let{command:t,args:r}=e;return Array.isArray(r)?t===Wb&&r[0]===Gb[0]?!0:r.some(n=>typeof n=="string"&&n.endsWith(Jb)):!1},bf=e=>/\n([ \t]+)"/.exec(e)?.[1]??Oc,Ic=e=>{try{return{kind:"raw",raw:Ub.readFileSync(e,"utf-8")}}catch(t){return t.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable",error:t}}},Dc=e=>{try{return JSON.parse(e)}catch{return}},Nc=e=>e instanceof Error?e.message:String(e),Vr=e=>{let t=Ic(Vb.join(e,Me));if(t.kind==="absent")return{kind:"missing-file"};if(t.kind==="unreadable")return{kind:"unparseable"};let r=Dc(t.raw);if(!ir(r)||!ir(r[et]))return{kind:"unparseable"};let n=r[et];if(oe in n)return{kind:"stale"};let o=Object.keys(n).find(s=>kf(n[s]));return o===void 0?{kind:"absent"}:{kind:"wrong-key",key:o}};import Ys from"node:fs";import Kb from"node:path";var ft=`claude plugin install ${G} --scope project`,Wr=`claude plugin marketplace update ${oe} && claude plugin update ${G} --scope project`,_c=`claude plugin marketplace add ${xt}`,Ef=" ",Pf=()=>({source:{source:"github",repo:xt}}),Hb=()=>({extraKnownMarketplaces:{[oe]:Pf()},enabledPlugins:{[G]:!0}}),xf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),qb=e=>/\n([ \t]+)"/.exec(e)?.[1]??Ef,Rf=(e,t,r,n)=>{let o=e[t];return o===void 0?(e[t]={[r]:n},`${t}.${r}`):!xf(o)||r in o?null:(o[r]=n,`${t}.${r}`)},Sf=e=>[Rf(e,"extraKnownMarketplaces",oe,Pf()),Rf(e,"enabledPlugins",G,!0)].filter(r=>r!==null),Yb=e=>{try{return Ys.readFileSync(e,"utf-8")}catch{return null}},zb=e=>(Ys.mkdirSync(Kb.dirname(e),{recursive:!0}),Ys.writeFileSync(e,`${JSON.stringify(Hb(),null,Ef)}
149
- `,"utf-8"),{status:"created",path:e,added:[`extraKnownMarketplaces.${oe}`,`enabledPlugins.${G}`]}),Mc=(e,{write:t=!0}={})=>{let r=Yb(e);if(r===null)return t?zb(e):{status:"withheld",path:e,added:Sf({})};let n;try{n=JSON.parse(r)}catch{n=void 0}if(!xf(n))return d.warn(`Could not parse ${e} \u2014 left it untouched. Add "${G}" to enabledPlugins by hand, or fix the JSON and re-run: infra-kit setup --skip-tools`),{status:"unparseable",path:e,added:[]};let o=Sf(n);if(o.length===0)return{status:"unchanged",path:e,added:[]};if(!t)return{status:"withheld",path:e,added:o};let s=qb(r),i=r.endsWith(`
141
+ `;var lf="# 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` = `infra-kit`, the global CLI)\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. Without `-c`, an agent loads the project's `defaultEnv` (set yours with `ik config-set defaultEnv <env>`); with none set it is refused and must ask the human.\n- `ik dev [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; no name runs every app. App names are per-repo: an unknown one is refused with the 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. `ik worktrees add --feature <name> [--base <dev|main|release>]` creates `feature/<name>` at `<root>-worktrees/feature/<name>`, cut from `dev` by default (the default branch in a repo without `dev`); `worktrees remove --feature <name>` removes it. To close the worktree a session runs in (\"close this worktree\"), run `infra-kit worktrees remove --self` from inside it: it previews, and its `--yes` re-run hands the removal to an Orca tab of the main checkout, which closes every tab of the worktree \u2014 this session included. The `/infra-kit:worktrees` skill is the agent entry point for feature worktrees \u2014 never create one with raw `git worktree add` or Claude Code's `EnterWorktree`, which skip `pnpm install`, the editor/Orca wiring and the `feature/` layout.\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`. 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`, `vendor 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` is human-only and is 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 jr={"root/body":lf.trimEnd(),"package/frontend":sf.trimEnd(),"package/backend":nf.trimEnd(),"package/lib":af.trimEnd(),"package/e2e":of.trimEnd(),"package/mobile":cf.trimEnd(),"design/skeleton":rf.trimEnd()};var ac=/\{\{(\w+)\}\}/g,Kk=/^- \{\{(\w+)\}\}$/,Hk=e=>new Set([...e.matchAll(ac)].map(t=>t[1])),qk=(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(", ")}`)},Yk=(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(", ")}`)},zk=(e,t)=>e.filter(r=>{let n=Kk.exec(r);return n===null||t[n[1]]!==""}),Xk=(e,t)=>{for(let r of e)for(let n of r.matchAll(ac)){let o=t[n[1]];if(o!==void 0&&o.includes(`
142
+ `)&&n.index!==0)throw new Error(`renderTemplate: multi-line value for {{${n[1]}}} must start its line (found at column ${n.index})`)}},Fr=(e,t)=>{let r=Hk(e);Yk(r,t),qk(r,t);let n=zk(e.split(`
143
+ `),t);return Xk(n,t),n.join(`
144
+ `).replace(ac,(o,s)=>t[s])};var Zk="name: TODO",cc=e=>{let t=Fr(jr["design/skeleton"],{packageName:e}),r=`name: ${e}`;return`${t.replace(Zk,()=>r)}
145
+ `};var Qk=(e,t)=>`${rr}${e} ${t} -->`,eb="`README.md` \u2014 what this package is and how to run it.",lc="docs/e2e-playwright.md",tb=`\`${lc}\` at the repo root \u2014 env setup, run modes, \`E2E_SLOW_MO\`, traces after a failure.`,rb=["ts-check","eslint-check","test"],nb="The public surface is what `package.json` exposes \u2014 its `exports` map, or `bin` for a CLI; changing it is a breaking change for every dependent package.",ob="Run `pnpm run build` before a dependent package can see a change.",uf=(e,t)=>e?.includes(t)??!0,sb=e=>{let t=rb.filter(r=>uf(e,r)).map(r=>`pnpm run ${r}`);return t.length===0?"":`\`${t.join(" && ")}\` \u2014 this package only.`},uc=e=>{let{version:t,type:r,packageName:n,relDir:o,hasReadme:s,hasE2eDoc:i,scripts:a,hasPublicSurface:c=!0}=e,l=Fr(jr[`package/${r}`],{packageName:n,relDir:o,type:r,readmeBullet:s?eb:"",checksBullet:sb(a),...r==="e2e"?{e2eDocBullet:i?tb:""}:{},...r==="lib"?{surfaceBullet:c?nb:"",buildBullet:uf(a,"build")?ob:""}:{}});return[Qk(t,r),"",l,""].join(`
146
+ `)};var ib=e=>`${oc}${e} -->`,dc=e=>{let t=Fr(jr["root/body"],{});return[ib(e),"",t,""].join(`
147
+ `)};import Lr from"node:fs";import ab from"node:path";var Ws=e=>{let t;try{t=Lr.lstatSync(e)}catch{return}if(t.isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},Zn=(e,t)=>{let r=Qn(e,t);return r!=="unchanged"&&(Lr.mkdirSync(ab.dirname(e),{recursive:!0}),Lr.writeFileSync(e,t,"utf-8")),r},Qn=(e,t)=>{Ws(e);let r=Lr.existsSync(e)?Lr.readFileSync(e,"utf-8"):null;return r===t?"unchanged":r===null?"created":"updated"},pc=(e,t,r)=>{let n=Lr.readFileSync(e,"utf-8");if(!Ze(n,t,r))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},df=(e,t,r)=>Ze(e,t,r)?{before:e.slice(0,e.indexOf(t)),after:e.slice(e.indexOf(r)+r.length)}:null,mc=(e,t,r,n)=>{let o=df(e,r,n),s=df(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 Js="<!-- infra-kit:import:begin -->",Ks="<!-- infra-kit:import:end -->",cb="AGENTS.md",pf="CLAUDE.md",lb="README.md",fc="DESIGN.md",ub=["frontend","mobile"],db=e=>sr.existsSync(e)?sr.readFileSync(e,"utf-8"):null,gc=(e,t)=>{try{return sr.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},mf=({filePath:e,body:t,startMarker:r,endMarker:n,prepare:o,dryRun:s})=>{let i=db(e),a=i===null?"":o?.(i)??i,c=Nr({content:a,body:t,startMarker:r,endMarker:n,placement:"replace-in-place"});if(s)return Qn(e,c);let l=Zn(e,c);return pc(e,r,n),i!==null&&mc(a,c,r,n),l},pb=(e,t)=>{if(!sr.existsSync(e))return"unchanged";Ws(e);let r=sr.readFileSync(e,"utf-8"),n=Dt(r,_e,Qe);return n===null?"unchanged":n.trim()===""?(t||sr.rmSync(e),"removed"):t?Qn(e,n):Zn(e,n)},mb=(e,t,r)=>mf({filePath:e,dryRun:r,body:dc(t),startMarker:_e,endMarker:Qe,prepare:n=>Dt(n,Js,Ks)??n}),eo=async(e,{version:t,dryRun:r=!1})=>{let n=Nt.join(e,pf),o=Nt.join(e,cb),s=[];try{s.push({path:n,action:mb(n,t,r)})}catch(i){s.push(Gs(n,i))}try{s.push({path:o,action:pb(o,r)})}catch(i){s.push(Gs(o,i))}return s},fb=(e,t,r,n)=>{if(!ub.includes(r)||gc(e,fc))return null;let o=Nt.join(e,fc),s=cc(t);try{return{path:o,action:n?Qn(o,s):Zn(o,s),type:r}}catch(i){return Gs(o,i,r)}},to=async(e,{repoRoot:t,version:r,design:n,declaredType:o,dryRun:s=!1})=>{let i=Nt.join(e,pf),a=await er(e),c=a.name??Nt.basename(e),l=Kn({packageDir:e,repoRoot:t,pkgJson:a,declaredType:o}),u=uc({version:r,type:l,packageName:c,relDir:Nt.relative(t,e).split(Nt.sep).join("/"),hasReadme:gc(e,lb),hasDesign:gc(e,fc),hasE2eDoc:sr.existsSync(Nt.join(t,lc)),scripts:Object.keys(a.scripts??{}),hasPublicSurface:a.exports!==void 0||a.bin!==void 0}),p=[];try{p.push({path:i,action:mf({filePath:i,body:u,startMarker:et,endMarker:mt,dryRun:s}),type:l})}catch(m){p.push(Gs(i,m,l))}if(n){let m=fb(e,c,l,s);m&&p.push(m)}return p};import Mb from"node:path";import ff from"node:path";var hc="agent-guidance",ro="CLAUDE.md",gb="\u2014 run: infra-kit audit --fix",hb={missing:`${ro} missing`,"no-block":`${ro} has no infra-kit block (expected ${et} \u2026 ${mt})`,malformed:`${ro} block is malformed (end marker precedes start, or body is empty)`,"foreign-block":`${ro} carries the ROOT infra-kit block (${_e}); a package needs the package block`},yb=e=>e.adopted?` (workspace adopted: ${ff.relative(e.workspaceRoot,e.evidencePath)} carries a package block)`:"",yc=(e,t)=>{let r=nr(or(ff.join(e,ro)));if(r.state==="ok"){let s=r.version??"unknown",i=r.type??"unknown";return{name:hc,status:"pass",message:`present (block from infra-kit ${s}, type ${i})`}}let n=`${hb[r.state]} ${gb}`,o=r.state==="missing"?`${n}${yb(t)}`:n;return t.adopted?{name:hc,status:"fail",message:o}:{name:hc,status:"pass",message:`not yet adopted \u2014 ${o}`}};import vb from"node:path";var vc=async(e,t=Ot)=>{try{let r=await Yn(e,t);return{check:{name:se,status:"pass",message:"present and valid"},rules:r}}catch(r){return{check:{name:se,status:"fail",message:r.message},rules:null}}},gf="infra-kit.json",wb=async e=>await Ee(vb.join(e,se))?{name:se,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,wc=async(e,t=Hn)=>{let r=await wb(e),n=r?[r]:[];try{let{audit:o={}}=await W();return{checks:[{name:gf,status:"pass",message:"present and valid"},...n],rules:qn(o,t)}}catch(o){return{checks:[{name:gf,status:"fail",message:o.message},...n],rules:null}}};import Hs from"node:fs/promises";import Br from"node:path";import{$ as kb}from"zx";var no="playwright.config.ts",bb=[{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'"},{name:"infra-kit-e2e",pattern:/\binfraKitE2e\b/u,expected:"baseURL, ignoreHTTPSErrors and webServer from infraKitE2e() ('@slip-stream-kit/config/playwright')"}],hf=e=>Object.entries(tc).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"}}),Rb="infra-kit-e2e",yf=async(e,t={})=>{let r=Br.join(e,no),n=await Hs.readFile(r,"utf-8").catch(()=>null);return n===null?[{name:`e2e-config:${no}`,status:"fail",message:`missing ${no}`}]:bb.map(o=>{let s=`e2e-config:${o.name}`;return t.staticServer&&o.name===Rb?{name:s,status:"pass",message:"not required \u2014 e2e.server is 'static', the suite serves its own build"}:o.pattern.test(n)?{name:s,status:"pass",message:"present"}:{name:s,status:"fail",message:`${no} lacks the shared e2e convention \u2014 expected: ${o.expected}`}})},Sb=/['"`](?:[^'"`\n]*\/)?\.auth['"/`]/u,Eb=/\.[cm]?[jt]sx?$/u,kc=async(e,t)=>(await Hs.readdir(e,{recursive:t,withFileTypes:!0}).catch(()=>[])).filter(n=>n.isFile()&&Eb.test(n.name)).map(n=>Br.join(n.parentPath,n.name)),Pb=async e=>{let t=await kc(Br.join(e,"src"),!0);for(let r of[Br.join(e,no),...t]){let n=await Hs.readFile(r,"utf-8").catch(()=>"");if(Sb.test(n))return!0}return!1},vf=async e=>{let t="e2e-auth:gitignored";if(!await Pb(e))return{name:t,status:"pass",message:"no saved auth state referenced"};let r=await kb({cwd:e,quiet:!0,nothrow:!0})`git -c core.excludesFile=/dev/null check-ignore -q .auth/storage-state.json`;if(r.exitCode===0)return{name:t,status:"pass",message:".auth/ is gitignored"};if(r.exitCode===1)return{name:t,status:"fail",message:"the suite saves auth state under .auth/, which git would commit \u2014 add `.auth/` to .gitignore"};let n=r.stderr.trim()||`exit ${r.exitCode}`;return{name:t,status:"fail",message:`could not ask git whether .auth/ is ignored: ${n}`}},bc="E2E__BASIC_AUTH_USERNAME",Rc="E2E__BASIC_AUTH_PASSWORD",xb=/\bE2E_\w*BASIC_AUTH_\w+/gu,Tb=/_(?:USER(?:NAME)?|PASS(?:WORD)?)$/u,Cb=/\/\*[\s\S]*?\*\//gu,$b=/(^|[^:])\/\/[^\n]*/gu,Ab=e=>/USER(?:NAME)?$/u.test(e)?bc:Rc,Ob=e=>e.replace(Cb,"").replace($b,"$1"),wf=async e=>{let t="e2e-env:basic-auth",r=[...await kc(e,!1),...await kc(Br.join(e,"src"),!0)],n=[];for(let o of r){let s=await Hs.readFile(o,"utf-8").catch(()=>""),i=new Set([...Ob(s).matchAll(xb)].map(a=>a[0]).filter(a=>Tb.test(a)&&a!==bc&&a!==Rc));for(let a of i)n.push(`${a} \u2192 ${Ab(a)} (${Br.relative(e,o)})`)}return n.length===0?{name:t,status:"pass",message:`basic auth read only from ${bc} / ${Rc}`}:{name:t,status:"fail",message:`basic auth has one name pair in every suite \u2014 rename, with no fallback to the old name: ${n.join("; ")}`}},Sc=async(e,t,r={})=>[...hf(t),...await yf(e,r),await vf(e),await wf(e)];import Ib from"node:fs/promises";import Db from"node:path";var Ec=async(e,t)=>Promise.all(t.map(async r=>{let n=await Ib.stat(Db.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 Pc=(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 Nb from"node:fs/promises";import _b from"node:path";var Ur="turbo.json",xc=async(e,t)=>{if(t.length===0)return[];let r;try{let o=await Nb.readFile(_b.join(e,Ur),"utf-8");r=JSON.parse(o)}catch(o){return[{name:Ur,status:"fail",message:`cannot read/parse ${Ur}: ${o.message}`}]}let n=r.tasks;return n===null||typeof n!="object"?[{name:Ur,status:"fail",message:`no "tasks" object defined in ${Ur}`}]: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 ${Ur}`}})};var jb=async(e,t)=>{let{check:r,rules:n}=await vc(e,t);return{checks:[r],rules:n}},Fb={adopted:!1,workspaceRoot:null},Lb=async(e,t,r)=>Kn({packageDir:e,repoRoot:r??e,pkgJson:t,declaredType:await tr(e)}),Bb=async e=>(await It(e).catch(()=>{}))?.e2e?.server==="static",Tc=async(e,t=Ot,r={})=>{let n=await er(e),o=n.name??Mb.basename(e),{checks:s,rules:i}=r.isRoot?await wc(e,t):await jb(e,t);r.isRoot||s.push(yc(e,r.adoption??Fb)),i&&(s.push(...Pc(n.scripts??{},i.requiredScripts)),s.push(...await Ec(e,i.requiredFiles)),s.push(...await xc(e,i.turboTasks))),!r.isRoot&&await Lb(e,n,r.repoRoot)==="e2e"&&s.push(...await Sc(e,n.scripts??{},{staticServer:await Bb(e)}));let a=s.every(c=>c.status==="pass");return{packageDir:e,packageName:o,checks:s,passed:a}};var Cc=["plugin","marketplace","add",xt],$c=["plugin","install",G,"--scope","project"],kf=(e,t)=>Xt({projectPath:e,home:t}).kind==="installed",qs=e=>((e??"").split(`
148
+ `).find(r=>r.trim().length>0)??"").trim(),Ub=(e,t)=>{if(Bn(t))return null;d.debug({msg:`Running: ${Ln} ${Cc.join(" ")}`});let r=e({args:Cc});return r.ok?null:{step:"marketplace",error:qs(r.output)}},Vb=(e,t)=>{d.debug({msg:`Running: ${Ln} ${Ns.join(" ")}`});let r=e({args:Ns});if(!r.ok)return{status:"update-failed",error:qs(r.output)};d.debug({msg:`Running: ${Ln} ${Ds.join(" ")}`});let n=e({args:Ds,cwd:t});return n.ok?{status:"updated"}:{status:"update-failed",error:qs(n.output)}},Ac=e=>{let{projectRoot:t,home:r}=e,n=e.run??Wa;if(!n({args:Va}).ok)return{status:"claude-missing"};if(kf(t,r))return e.cliIsStale?.()===!0?{status:"skipped-cli-stale"}:Vb(n,t);let o=Ub(n,r);if(o!==null)return{status:"failed",...o};d.debug({msg:`Running: ${Ln} ${$c.join(" ")}`});let s=n({args:$c,cwd:t});return s.ok?kf(t,r)?{status:"installed"}:{status:"unverified"}:{status:"failed",step:"install",error:qs(s.output)}};import Wb from"node:fs";import Gb from"node:path";var Me=".mcp.json",tt="mcpServers",Jb="infra-kit",Kb=["mcp"],Hb="/infra-kit/dist/mcp.js",Oc=" ",ir=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),bf=e=>{if(!ir(e))return!1;let{command:t,args:r}=e;return Array.isArray(r)?t===Jb&&r[0]===Kb[0]?!0:r.some(n=>typeof n=="string"&&n.endsWith(Hb)):!1},Rf=e=>/\n([ \t]+)"/.exec(e)?.[1]??Oc,Ic=e=>{try{return{kind:"raw",raw:Wb.readFileSync(e,"utf-8")}}catch(t){return t.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable",error:t}}},Dc=e=>{try{return JSON.parse(e)}catch{return}},Nc=e=>e instanceof Error?e.message:String(e),Vr=e=>{let t=Ic(Gb.join(e,Me));if(t.kind==="absent")return{kind:"missing-file"};if(t.kind==="unreadable")return{kind:"unparseable"};let r=Dc(t.raw);if(!ir(r)||!ir(r[tt]))return{kind:"unparseable"};let n=r[tt];if(oe in n)return{kind:"stale"};let o=Object.keys(n).find(s=>bf(n[s]));return o===void 0?{kind:"absent"}:{kind:"wrong-key",key:o}};import Ys from"node:fs";import qb from"node:path";var ft=`claude plugin install ${G} --scope project`,Wr=`claude plugin marketplace update ${oe} && claude plugin update ${G} --scope project`,_c=`claude plugin marketplace add ${xt}`,Pf=" ",xf=()=>({source:{source:"github",repo:xt}}),Yb=()=>({extraKnownMarketplaces:{[oe]:xf()},enabledPlugins:{[G]:!0}}),Tf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),zb=e=>/\n([ \t]+)"/.exec(e)?.[1]??Pf,Sf=(e,t,r,n)=>{let o=e[t];return o===void 0?(e[t]={[r]:n},`${t}.${r}`):!Tf(o)||r in o?null:(o[r]=n,`${t}.${r}`)},Ef=e=>[Sf(e,"extraKnownMarketplaces",oe,xf()),Sf(e,"enabledPlugins",G,!0)].filter(r=>r!==null),Xb=e=>{try{return Ys.readFileSync(e,"utf-8")}catch{return null}},Zb=e=>(Ys.mkdirSync(qb.dirname(e),{recursive:!0}),Ys.writeFileSync(e,`${JSON.stringify(Yb(),null,Pf)}
149
+ `,"utf-8"),{status:"created",path:e,added:[`extraKnownMarketplaces.${oe}`,`enabledPlugins.${G}`]}),Mc=(e,{write:t=!0}={})=>{let r=Xb(e);if(r===null)return t?Zb(e):{status:"withheld",path:e,added:Ef({})};let n;try{n=JSON.parse(r)}catch{n=void 0}if(!Tf(n))return d.warn(`Could not parse ${e} \u2014 left it untouched. Add "${G}" to enabledPlugins by hand, or fix the JSON and re-run: infra-kit setup --skip-tools`),{status:"unparseable",path:e,added:[]};let o=Ef(n);if(o.length===0)return{status:"unchanged",path:e,added:[]};if(!t)return{status:"withheld",path:e,added:o};let s=zb(r),i=r.endsWith(`
150
150
  `)?`
151
- `:"";return Ys.writeFileSync(e,`${JSON.stringify(n,null,s)}${i}`,"utf-8"),{status:"added",path:e,added:o}};import Qb from"node:path";import eR from"node:process";import jc from"node:fs/promises";import Tf from"node:path";var Xb="infra-kit.json",Cf=["requiredScripts","requiredFiles","turbo"],no=(e,t)=>[{path:e,action:"failed",message:t}],Zb=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),$f=async e=>{let t=Tf.join(e,se),r=Tf.join(e,Xb),n;try{n=await It(e)}catch(c){return no(t,c.message)}if(!n)return[];let o={...n},s=Object.keys(o).filter(c=>!Cf.includes(c));if(s.length>0)return no(t,`declares ${s.join(", ")}, which mean nothing at the repo root \u2014 remove them, then re-run`);let i=Object.fromEntries(Cf.filter(c=>o[c]!==void 0).map(c=>[c,o[c]])),a=[];if(Object.keys(i).length>0)try{let c=await jc.stat(r),l=await jc.readFile(r,"utf8"),u=JSON.parse(l);if(!Zb(u))return no(r,"is not a JSON object");if("audit"in u)return no(r,`already has an "audit" block \u2014 merge ${se}'s rules into it by hand, then delete ${se}`);await cm({path:r,raw:l,migrated:{...u,audit:i},expectedMtimeMs:c.mtimeMs}),a.push({path:r,action:"updated"})}catch(c){return no(r,c.message)}try{await jc.rm(t),a.push({path:t,action:"removed"})}catch(c){a.push({path:t,action:"failed",message:c.message})}return a};var tR=["unchanged","created"],rR=["unchanged","created","updated","removed","failed"],Af=async(e,t,r)=>{let n=await tr(e);return eo(e,{repoRoot:t,version:U.version,design:r,declaredType:n})},nR=async(e,t)=>{if(e.root)return[...await $f(t),...await Qn(t,{version:U.version})];if(e.all){let n=[];for(let o of await Pe(t))n.push(...await Af(o,t,e.design));return n}let r=await zn(e.cwd??eR.cwd());return Af(r,t,e.design)},oR=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 ${rR.filter(n=>tR.includes(n)||(t.get(n)??0)>0).map(n=>`${t.get(n)??0} ${n}`).join(", ")} (infra-kit ${U.version})`},sR=(e,t)=>{for(let r of e){if(r.action==="unchanged")continue;let n=Qb.relative(t,r.path),o=r.type?` (${r.type})`:"",s=r.action==="failed"&&r.message?` \u2014 ${r.message}`:"";d.info(` ${r.action.padEnd(9)} ${n}${o}${s}`)}d.info(oR(e))},iR=e=>{let t={path:e.path,action:e.action};return e.type&&(t.type=e.type),t},Of=async(e,t)=>{let r=await P();Vs();let n=await Mr(t),o=await nR(e,r);sR(o,r),Vs();let s=await Mr(t),i=!e.all&&!e.root;return{fixed:o.map(iR),adoptionFlipped:i&&!n.adopted&&s.adopted}};import Df from"node:fs";import Nf from"node:path";var Fc="ik-mcp",If=(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:Fc,args:r}};var zs="run `infra-kit setup` (or `infra-kit audit --root --fix`)",aR=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((r,n)=>r===t[n]),Lc=e=>ir(e)&&e.command===Fc,cR=(e,t)=>({...e??{},type:t.type,command:t.command,args:t.args}),lR=(e,t,r)=>{let n=[],o={...e},s=!1;for(let[i,a]of Object.entries(t)){let c=If(i,a),l=e[i];if(l!==void 0&&!Lc(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 ${zs}, or drop mcp.${i} from infra-kit.json`});continue}if(Lc(l)&&l.type===c.type&&aR(l.args,c.args)){n.push({name:i,status:"unchanged",message:""});continue}if(r){o[i]=cR(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: ${zs}`:`"${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: ${zs}`})}for(let[i,a]of Object.entries(e))Object.hasOwn(t,i)||!Lc(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}},uR=(e,t,r)=>{let n=r===null?Oc:bf(r),o=r===null||r.endsWith(`
151
+ `:"";return Ys.writeFileSync(e,`${JSON.stringify(n,null,s)}${i}`,"utf-8"),{status:"added",path:e,added:o}};import tR from"node:path";import rR from"node:process";import jc from"node:fs/promises";import Cf from"node:path";var Qb="infra-kit.json",$f=["requiredScripts","requiredFiles","turbo"],oo=(e,t)=>[{path:e,action:"failed",message:t}],eR=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Af=async e=>{let t=Cf.join(e,se),r=Cf.join(e,Qb),n;try{n=await It(e)}catch(c){return oo(t,c.message)}if(!n)return[];let o={...n},s=Object.keys(o).filter(c=>!$f.includes(c));if(s.length>0)return oo(t,`declares ${s.join(", ")}, which mean nothing at the repo root \u2014 remove them, then re-run`);let i=Object.fromEntries($f.filter(c=>o[c]!==void 0).map(c=>[c,o[c]])),a=[];if(Object.keys(i).length>0)try{let c=await jc.stat(r),l=await jc.readFile(r,"utf8"),u=JSON.parse(l);if(!eR(u))return oo(r,"is not a JSON object");if("audit"in u)return oo(r,`already has an "audit" block \u2014 merge ${se}'s rules into it by hand, then delete ${se}`);await lm({path:r,raw:l,migrated:{...u,audit:i},expectedMtimeMs:c.mtimeMs}),a.push({path:r,action:"updated"})}catch(c){return oo(r,c.message)}try{await jc.rm(t),a.push({path:t,action:"removed"})}catch(c){a.push({path:t,action:"failed",message:c.message})}return a};var nR=["unchanged","created"],oR=["unchanged","created","updated","removed","failed"],Of=async(e,t,r)=>{let n=await tr(e);return to(e,{repoRoot:t,version:U.version,design:r,declaredType:n})},sR=async(e,t)=>{if(e.root)return[...await Af(t),...await eo(t,{version:U.version})];if(e.all){let n=[];for(let o of await Pe(t))n.push(...await Of(o,t,e.design));return n}let r=await Xn(e.cwd??rR.cwd());return Of(r,t,e.design)},iR=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 ${oR.filter(n=>nR.includes(n)||(t.get(n)??0)>0).map(n=>`${t.get(n)??0} ${n}`).join(", ")} (infra-kit ${U.version})`},aR=(e,t)=>{for(let r of e){if(r.action==="unchanged")continue;let n=tR.relative(t,r.path),o=r.type?` (${r.type})`:"",s=r.action==="failed"&&r.message?` \u2014 ${r.message}`:"";d.info(` ${r.action.padEnd(9)} ${n}${o}${s}`)}d.info(iR(e))},cR=e=>{let t={path:e.path,action:e.action};return e.type&&(t.type=e.type),t},If=async(e,t)=>{let r=await P();Vs();let n=await Mr(t),o=await sR(e,r);aR(o,r),Vs();let s=await Mr(t),i=!e.all&&!e.root;return{fixed:o.map(cR),adoptionFlipped:i&&!n.adopted&&s.adopted}};import Nf from"node:fs";import _f from"node:path";var Fc="ik-mcp",Df=(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:Fc,args:r}};var zs="run `infra-kit setup` (or `infra-kit audit --root --fix`)",lR=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((r,n)=>r===t[n]),Lc=e=>ir(e)&&e.command===Fc,uR=(e,t)=>({...e??{},type:t.type,command:t.command,args:t.args}),dR=(e,t,r)=>{let n=[],o={...e},s=!1;for(let[i,a]of Object.entries(t)){let c=Df(i,a),l=e[i];if(l!==void 0&&!Lc(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 ${zs}, or drop mcp.${i} from infra-kit.json`});continue}if(Lc(l)&&l.type===c.type&&lR(l.args,c.args)){n.push({name:i,status:"unchanged",message:""});continue}if(r){o[i]=uR(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: ${zs}`:`"${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: ${zs}`})}for(let[i,a]of Object.entries(e))Object.hasOwn(t,i)||!Lc(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}},pR=(e,t,r)=>{let n=r===null?Oc:Rf(r),o=r===null||r.endsWith(`
152
152
  `)?`
153
- `:"";try{return Df.mkdirSync(Nf.dirname(e),{recursive:!0}),Df.writeFileSync(e,`${JSON.stringify(t,null,n)}${o}`,"utf-8"),!0}catch(s){return d.warn(`Could not write ${e} (${Nc(s)}) \u2014 the ik-mcp entries were not updated.`),!1}},oo=({projectRoot:e,proxies:t,write:r})=>{let n=Nf.join(e,Me),o=Ic(n);if(o.kind==="unreadable")return d.warn(`Could not read ${n} (${Nc(o.error)}) \u2014 left it untouched.`),{status:"unreadable",path:n,entries:[],wrote:!1};let s=o.kind==="raw"?o.raw:null,i=s===null?{}:Dc(s);if(!ir(i))return d.warn(`Could not parse ${n} \u2014 left it untouched. Fix the JSON, then ${zs}.`),{status:"unparseable",path:n,entries:[],wrote:!1};let a=i[et];if(a!==void 0&&!ir(a))return d.warn(`${n} has a "${et}" that is not an object \u2014 left it untouched.`),{status:"unparseable",path:n,entries:[],wrote:!1};let c=lR(a??{},t,r);if(!c.changed)return{status:"ok",path:n,entries:c.entries,wrote:!1};let l=uR(n,{...i,[et]:c.servers},s);return{status:l?"ok":"failed",path:n,entries:c.entries,wrote:l}};var _f=async(e,t)=>{let r;try{r=(await W()).mcp}catch{return null}if(!r||Object.keys(r).length===0)return null;let n=oo({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 dR="workspace adopted \u2014 every other package now needs a CLAUDE.md: run infra-kit audit --fix --all",pR=async e=>e.root?[{dir:await P(),baseline:Kn,isRoot:!0}]:e.all?(await Pe(await P())).map(r=>({dir:r})):[{dir:await zn(e.cwd??Mf.cwd())}],mR=async e=>e.root||e.all?await P():e.cwd??Mf.cwd(),fR=async()=>{try{return await P()}catch{return}},gR=e=>{let t=0,r=0;for(let i of e)for(let a of i.checks)t+=1,a.status!=="pass"&&(r+=1,d.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 d.info(n?`\u2705 audit passed \u2014 ${s}`:`\u274C audit failed \u2014 ${r}/${s}`),n},hR=async(e,t)=>{let{fixed:r,adoptionFlipped:n}=await Of(e,t);return n&&d.info(dR),r},yR=e=>{if(Vr(e).kind!=="stale")return null;let t=`${Me} still registers "${oe}" \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 "${oe}" entry by hand in a PR, keeping its siblings`;return d.info(`[INFO] mcp mcp:legacy-key: ${t}`),{packageDir:e,packageName:"mcp",checks:[{name:"mcp:legacy-key",status:"pass",message:t}],passed:!0}},Xs=async(e={})=>{let t=ic(await mR(e)),r=e.fix?await hR(e,t):void 0,n=await pR(e),o=await Mr(t),s=await fR(),i=[];for(let l of n)i.push(await Tc(l.dir,l.baseline,{adoption:o,isRoot:l.isRoot,repoRoot:s}));if(e.root){let l=await _f(n[0].dir,e.fix===!0);l&&i.push(l);let u=yR(n[0].dir);u&&i.push(u)}let c={allPassed:gR(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}},vR={all:je.boolean().optional().describe("Audit every non-vendor workspace package"),root:je.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},wR={allPassed:je.boolean().describe("Whether every audited package passed all checks"),packages:je.array(je.object({name:je.string(),passed:je.boolean(),checks:je.array(je.object({name:je.string(),status:je.enum(["pass","fail"]),message:je.string()}))})).describe("Per-package check results")},Bc=E({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:vR,outputSchema:wR,handler:e=>Xs({all:e.all,root:e.root})});import{z as _t}from"zod";import Uc from"node:fs/promises";import kR from"node:path";var Gr=()=>Object.keys(mm.shape),bR=new Set(["protectedEnvs"]),so={project:"per-project override",global:"user-global override"},Zs=(e,t)=>{if(ve()&&bR.has(e))throw new C({status:"refused",agentMode:_.source},2,{operation:t,remediation:`ask the human to run \`infra-kit ${t} ${e} \u2026\` in their own terminal`,stderrExcerpt:`"${e}" decides what an agent may reach, so an agent may not change it`});if(!Gr().includes(e)){if(e.includes(".")){let r=e.split(".")[0]??e;throw new Error(`Nested keys are not supported: override layers merge per top-level key, so "${e}" would replace the whole "${r}" section. Set "${r}" to its full JSON value instead, or use \`infra-kit config edit\`.`)}throw new Error(`Unknown config key "${e}". Top-level keys: ${Gr().join(", ")}.`)}},jf=e=>{try{return JSON.parse(e)}catch{return e}},RR=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),SR=async e=>{let t;try{t=await Uc.readFile(e,"utf-8")}catch{return{raw:null,data:{}}}let r;try{r=t.trim()===""?{}:JSON.parse(t)}catch(n){throw new Error(`Invalid JSON in ${v(e)}: ${n.message} \u2014 fix it with \`infra-kit config edit\`.`)}if(!RR(r))throw new Error(`${v(e)} is not a JSON object \u2014 fix it with \`infra-kit config edit\`.`);return{raw:t,data:r}},ER=async(e,t)=>{t===null?await Uc.rm(e,{force:!0}):Rt(e,t,420),jn()},Qs=async(e,t,r)=>{let n=await Y(),o=e==="global"?n.userGlobal:n.userProject,{raw:s,data:i}=await SR(o),a=i[t],c=r({...i});if(c===null)return{file:o,previous:a,changed:!1};await Uc.mkdir(kR.dirname(o),{recursive:!0}),Rt(o,`${JSON.stringify(c,null,2)}
154
- `,420),jn();try{await W({autoMigrate:"off"})}catch(l){throw await ER(o,s),new Error(`${l.message}
155
- ${v(o)} was left unchanged.`)}return{file:o,previous:a,changed:!0}},Vc=async({key:e,value:t,global:r})=>{Zs(e,"config-set");let n=r?"global":"project",o=jf(t),{file:s,previous:i}=await Qs(n,e,c=>({...c,[e]:o}));d.info(`Set ${e} = ${JSON.stringify(o)} in the ${so[n]} (${v(s)})`);let a={key:e,value:o,previous:i??null,scope:n,path:s};return{content:k(JSON.stringify(a,null,2)),structuredContent:a}};var ei=async({key:e}={})=>{let[t,r]=await Promise.all([W(),Y()]),n=t;if(e===void 0){let s=Object.keys(t).sort();d.info(`Merged config for ${r.projectName} \u2014 ${s.length} section(s): ${s.join(", ")}`),d.info(` source: ${r.main}`)}else{if(!Gr().includes(e))throw new Error(`Unknown config key "${e}". Top-level keys: ${Gr().join(", ")}.`);d.info(`${e} = ${JSON.stringify(n[e]??null,null,2)}`)}let o={config:n,configPath:r.main,projectName:r.projectName,...e===void 0?{}:{key:e,value:n[e]??null}};return{content:k(JSON.stringify(o,null,2)),structuredContent:o}},PR={config:_t.record(_t.string(),_t.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, worktrees, and protectedEnvs."),configPath:_t.string().describe("Absolute path to the project-level infra-kit.json (the base layer / committed source of truth)."),key:_t.string().optional().describe("The top-level key asked for, when one was."),value:_t.unknown().optional().describe("The merged value of `key` (null when no layer sets it)."),projectName:_t.string().describe("Repository name the config is keyed to (the main-repo basename; shared across all worktrees of the repo).")},Wc=E({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-set` / `config-unset` (top-level keys) or `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:{key:_t.string().optional().describe("Report only this top-level key as `value` (e.g. `ide`).")},outputSchema:PR,handler:e=>ei(e)});import OR from"node:fs";import{z as ie}from"zod";import ao from"node:fs";import Jr from"node:path";import xR from"node:process";var TR=Jr.join(".infra-kit","dev-context"),CR=".infra-kit",Ff=(e,t)=>{let r=Jr.resolve(e);for(;;){let n=Jr.join(r,t);if(ao.existsSync(n))return n;let o=Jr.dirname(r);if(o===r)return;r=o}},$R=e=>{let t=Ff(e,TR);if(t)return t;let r=Ff(e,CR);return r?Jr.join(r,"dev-context"):void 0},Gc=e=>typeof e=="number"&&Number.isFinite(e)?e:0,io=e=>typeof e=="string"?e:"",AR=(e,t,r)=>{let n=Jr.join(e,t);try{let o=ao.statSync(n),s=JSON.parse(ao.readFileSync(n,"utf-8"));if(typeof s!="object"||s===null)return null;let i=s;return{app:t.replace(/\.json$/,""),package:io(i.package),port:Gc(i.port),alias:io(i.alias),origin:io(i.origin),release:io(i.release),env:io(i.env),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}},co=(e=xR.cwd())=>{let t=Date.now(),r=$R(e);if(!r||!ao.existsSync(r))return{session:"none",fragmentDir:r,readAt:t,apps:[]};let n;try{n=ao.readdirSync(r).filter(s=>s.endsWith(".json"))}catch{return{session:"none",fragmentDir:r,readAt:t,apps:[]}}let o=n.map(s=>AR(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 ti=async(e={})=>{let t=e.now??Date.now,r=e.isListening??Nn,n=co(e.cwd),o=t(),s=await Promise.all(n.apps.map(async p=>{let m=Math.max(0,Math.round((o-p.mtimeMs)/1e3)),f=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,env:p.env||null,writtenAt:p.writtenAt>0?new Date(p.writtenAt).toISOString():null,fragmentMtime:new Date(p.mtimeMs).toISOString(),ageSeconds:m,live:f}})),i=s.length>0,a=n.fragmentDir??null,c=a!==null&&(OR.statSync(a,{throwIfNoEntry:!1})?.isDirectory()??!1),l=a===null?"nothing (no .infra-kit anchor exists up-tree)":a;if(i){d.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",f=`written ${p.ageSeconds}s ago`;d.info(` ${p.app} (${p.package}) \u2192 ${p.origin} on :${p.port} \u2014 ${m}, ${f}`)}}else{let p=c?"no readable fragment found there":"that directory does not exist";d.info(`No active infra-kit dev session \u2014 searched ${l} (${p}).`)}let u={active:i,apps:s,contextDir:a,contextDirExists:c};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}},IR={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."),env:ie.string().nullable().describe("INFRA_KIT_ENV the dev session runs with \u2014 where its UIs proxy cloud routes. Null when none was loaded, or the fragment predates the field."),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.")},Jc=E({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:IR,handler:()=>ti()});import{spawnSync as jh}from"node:child_process";import te from"node:fs";import Fh from"node:os";import de from"node:path";import it from"node:process";import{z as ge}from"zod";import{execFileSync as DR}from"node:child_process";var Lf=(e,t)=>{let r=e.filter(n=>!n.live).map(n=>n.name);return t?{prunable:[],withheld:r}:{prunable:r,withheld:[]}},NR=[/\binfra-kit\s+dev\b/,/cli\.js\s+dev\b/,/dev-server\.(?:js|ts)\b/],_R=e=>NR.some(t=>t.test(e)),MR="/bin/ps",jR=()=>DR(MR,["-eo","command="],{encoding:"utf8",maxBuffer:8<<20}).split(`
156
- `),Bf=(e=jR)=>{try{return e().some(_R)}catch{return!0}};import{Chalk as FR}from"chalk";import Kc from"node:process";var Hc={unicode:{ok:"\u2713",changed:"+",skipped:"-",manual:">",warn:"!",fail:"\u2717",separator:"\xB7",rule:"\u2500"},ascii:{ok:"ok",changed:"++",skipped:"--",manual:">>",warn:"!?",fail:"!!",separator:"-",rule:"-"}},LR=new Set(["warn","fail"]),BR=24,Kr=" ",Uf=" ",UR=(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:[""]},Vf=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},VR=e=>{let t=new FR({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)}},Wf=(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),WR=(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=Wf(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}},GR=(e,t,r,n)=>{let o=WR(Vf(e.rows),e.rows.length,t,r),s=Math.max(1,n-Kr.length-e.label.length-o.plainWidth);return`${Kr}${t.header(e.label)}${" ".repeat(s)}${o.text}`},JR=(e,t,r,n,o)=>{let s=LR.has(e.status),i=n.ok.length,a=e.name.padEnd(t),c=r[e.status],l=s?c(a):a,u=Uf.length+i+1+t+2,p=Math.max(BR,o-u),[m,...f]=UR(e.message,p),y=" ".repeat(u),b=x=>s?x:r.dim(x);return[`${Uf}${c(n[e.status])} ${l} ${b(m??"")}`.trimEnd(),...f.map(x=>`${y}${b(x)}`),...(e.notes??[]).map(x=>`${y}${x}`.trimEnd())]},KR=(e,t,r,n,o)=>{let s=Vf(t),i=n.rule.repeat(Math.max(12,Math.min(o-Kr.length,56))),a=Wf(s,()=>"warned"),c=[r.ok(`${s.ok} passed`),...a.map(u=>r[u.status](u.plain))].join(` ${n.separator} `),l=(e.hints??[]).map(u=>` ${r.dim(u)}`);return[`${Kr}${r.dim(i)}`,`${Kr}${c}${l.join("")}`]},qc=(e,t={})=>{let r=t.width??80,n=VR(t.color??!1),o=t.unicode??!0?Hc.unicode:Hc.ascii,s=e.sections.filter(u=>u.rows.length>0),i=s.flatMap(u=>u.rows),a=n.bold(e.title);if(i.length===0)return[a,"",`${Kr}${n.dim(e.emptyMessage??"Nothing ran.")}`];let c=Math.max(...i.map(u=>u.name.length)),l=s.flatMap(u=>[GR(u,n,o,r),...u.rows.flatMap(p=>JR(p,c,n,o,r)),""]);return[a,"",...l,...KR(e,i,n,o,r)]},HR=new Set(["","0","false","none"]),qR=["LC_ALL","LC_CTYPE","LANG"],YR=(e,t)=>e.NO_COLOR!==void 0&&e.NO_COLOR!==""?!1:e.FORCE_COLOR!==void 0?!HR.has(e.FORCE_COLOR.toLowerCase()):!!t.isTTY,zR=(e,t)=>{if(t)return!1;let r=qR.map(n=>e[n]).find(n=>n!==void 0&&n!=="");return r===void 0?!0:/UTF-?8/i.test(r)},Yc=(e={})=>{let t=e.env??Kc.env,r=e.stream??Kc.stderr;return{color:YR(t,r),unicode:zR(t,e.ascii??!1),width:r.columns??80}},tt=(e,t={})=>{(t.write??(n=>{Kc.stderr.write(n)}))(`${qc(e,Yc(t)).join(`
153
+ `:"";try{return Nf.mkdirSync(_f.dirname(e),{recursive:!0}),Nf.writeFileSync(e,`${JSON.stringify(t,null,n)}${o}`,"utf-8"),!0}catch(s){return d.warn(`Could not write ${e} (${Nc(s)}) \u2014 the ik-mcp entries were not updated.`),!1}},so=({projectRoot:e,proxies:t,write:r})=>{let n=_f.join(e,Me),o=Ic(n);if(o.kind==="unreadable")return d.warn(`Could not read ${n} (${Nc(o.error)}) \u2014 left it untouched.`),{status:"unreadable",path:n,entries:[],wrote:!1};let s=o.kind==="raw"?o.raw:null,i=s===null?{}:Dc(s);if(!ir(i))return d.warn(`Could not parse ${n} \u2014 left it untouched. Fix the JSON, then ${zs}.`),{status:"unparseable",path:n,entries:[],wrote:!1};let a=i[tt];if(a!==void 0&&!ir(a))return d.warn(`${n} has a "${tt}" that is not an object \u2014 left it untouched.`),{status:"unparseable",path:n,entries:[],wrote:!1};let c=dR(a??{},t,r);if(!c.changed)return{status:"ok",path:n,entries:c.entries,wrote:!1};let l=pR(n,{...i,[tt]:c.servers},s);return{status:l?"ok":"failed",path:n,entries:c.entries,wrote:l}};var Mf=async(e,t)=>{let r;try{r=(await W()).mcp}catch{return null}if(!r||Object.keys(r).length===0)return null;let n=so({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 mR="workspace adopted \u2014 every other package now needs a CLAUDE.md: run infra-kit audit --fix --all",fR=async e=>e.root?[{dir:await P(),baseline:Hn,isRoot:!0}]:e.all?(await Pe(await P())).map(r=>({dir:r})):[{dir:await Xn(e.cwd??jf.cwd())}],gR=async e=>e.root||e.all?await P():e.cwd??jf.cwd(),hR=async()=>{try{return await P()}catch{return}},yR=e=>{let t=0,r=0;for(let i of e)for(let a of i.checks)t+=1,a.status!=="pass"&&(r+=1,d.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 d.info(n?`\u2705 audit passed \u2014 ${s}`:`\u274C audit failed \u2014 ${r}/${s}`),n},vR=async(e,t)=>{let{fixed:r,adoptionFlipped:n}=await If(e,t);return n&&d.info(mR),r},wR=e=>{if(Vr(e).kind!=="stale")return null;let t=`${Me} still registers "${oe}" \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 "${oe}" entry by hand in a PR, keeping its siblings`;return d.info(`[INFO] mcp mcp:legacy-key: ${t}`),{packageDir:e,packageName:"mcp",checks:[{name:"mcp:legacy-key",status:"pass",message:t}],passed:!0}},Xs=async(e={})=>{let t=ic(await gR(e)),r=e.fix?await vR(e,t):void 0,n=await fR(e),o=await Mr(t),s=await hR(),i=[];for(let l of n)i.push(await Tc(l.dir,l.baseline,{adoption:o,isRoot:l.isRoot,repoRoot:s}));if(e.root){let l=await Mf(n[0].dir,e.fix===!0);l&&i.push(l);let u=wR(n[0].dir);u&&i.push(u)}let c={allPassed:yR(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}},kR={all:je.boolean().optional().describe("Audit every non-vendor workspace package"),root:je.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},bR={allPassed:je.boolean().describe("Whether every audited package passed all checks"),packages:je.array(je.object({name:je.string(),passed:je.boolean(),checks:je.array(je.object({name:je.string(),status:je.enum(["pass","fail"]),message:je.string()}))})).describe("Per-package check results")},Bc=E({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:kR,outputSchema:bR,handler:e=>Xs({all:e.all,root:e.root})});import{z as _t}from"zod";import Uc from"node:fs/promises";import RR from"node:path";var Gr=()=>Object.keys(fm.shape),SR=new Set(["protectedEnvs"]),io={project:"per-project override",global:"user-global override"},Zs=(e,t)=>{if(we()&&SR.has(e))throw new C({status:"refused",agentMode:_.source},2,{operation:t,remediation:`ask the human to run \`infra-kit ${t} ${e} \u2026\` in their own terminal`,stderrExcerpt:`"${e}" decides what an agent may reach, so an agent may not change it`});if(!Gr().includes(e)){if(e.includes(".")){let r=e.split(".")[0]??e;throw new Error(`Nested keys are not supported: override layers merge per top-level key, so "${e}" would replace the whole "${r}" section. Set "${r}" to its full JSON value instead, or use \`infra-kit config edit\`.`)}throw new Error(`Unknown config key "${e}". Top-level keys: ${Gr().join(", ")}.`)}},Ff=e=>{try{return JSON.parse(e)}catch{return e}},ER=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),PR=async e=>{let t;try{t=await Uc.readFile(e,"utf-8")}catch{return{raw:null,data:{}}}let r;try{r=t.trim()===""?{}:JSON.parse(t)}catch(n){throw new Error(`Invalid JSON in ${v(e)}: ${n.message} \u2014 fix it with \`infra-kit config edit\`.`)}if(!ER(r))throw new Error(`${v(e)} is not a JSON object \u2014 fix it with \`infra-kit config edit\`.`);return{raw:t,data:r}},xR=async(e,t)=>{t===null?await Uc.rm(e,{force:!0}):Rt(e,t,420),Fn()},Qs=async(e,t,r)=>{let n=await Y(),o=e==="global"?n.userGlobal:n.userProject,{raw:s,data:i}=await PR(o),a=i[t],c=r({...i});if(c===null)return{file:o,previous:a,changed:!1};await Uc.mkdir(RR.dirname(o),{recursive:!0}),Rt(o,`${JSON.stringify(c,null,2)}
154
+ `,420),Fn();try{await W({autoMigrate:"off"})}catch(l){throw await xR(o,s),new Error(`${l.message}
155
+ ${v(o)} was left unchanged.`)}return{file:o,previous:a,changed:!0}},Vc=async({key:e,value:t,global:r})=>{Zs(e,"config-set");let n=r?"global":"project",o=Ff(t),{file:s,previous:i}=await Qs(n,e,c=>({...c,[e]:o}));d.info(`Set ${e} = ${JSON.stringify(o)} in the ${io[n]} (${v(s)})`);let a={key:e,value:o,previous:i??null,scope:n,path:s};return{content:k(JSON.stringify(a,null,2)),structuredContent:a}};var ei=async({key:e}={})=>{let[t,r]=await Promise.all([W(),Y()]),n=t;if(e===void 0){let s=Object.keys(t).sort();d.info(`Merged config for ${r.projectName} \u2014 ${s.length} section(s): ${s.join(", ")}`),d.info(` source: ${r.main}`)}else{if(!Gr().includes(e))throw new Error(`Unknown config key "${e}". Top-level keys: ${Gr().join(", ")}.`);d.info(`${e} = ${JSON.stringify(n[e]??null,null,2)}`)}let o={config:n,configPath:r.main,projectName:r.projectName,...e===void 0?{}:{key:e,value:n[e]??null}};return{content:k(JSON.stringify(o,null,2)),structuredContent:o}},TR={config:_t.record(_t.string(),_t.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, worktrees, and protectedEnvs."),configPath:_t.string().describe("Absolute path to the project-level infra-kit.json (the base layer / committed source of truth)."),key:_t.string().optional().describe("The top-level key asked for, when one was."),value:_t.unknown().optional().describe("The merged value of `key` (null when no layer sets it)."),projectName:_t.string().describe("Repository name the config is keyed to (the main-repo basename; shared across all worktrees of the repo).")},Wc=E({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-set` / `config-unset` (top-level keys) or `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:{key:_t.string().optional().describe("Report only this top-level key as `value` (e.g. `ide`).")},outputSchema:TR,handler:e=>ei(e)});import DR from"node:fs";import{z as ie}from"zod";import co from"node:fs";import Jr from"node:path";import CR from"node:process";var $R=Jr.join(".infra-kit","dev-context"),AR=".infra-kit",Lf=(e,t)=>{let r=Jr.resolve(e);for(;;){let n=Jr.join(r,t);if(co.existsSync(n))return n;let o=Jr.dirname(r);if(o===r)return;r=o}},OR=e=>{let t=Lf(e,$R);if(t)return t;let r=Lf(e,AR);return r?Jr.join(r,"dev-context"):void 0},Gc=e=>typeof e=="number"&&Number.isFinite(e)?e:0,ao=e=>typeof e=="string"?e:"",IR=(e,t,r)=>{let n=Jr.join(e,t);try{let o=co.statSync(n),s=JSON.parse(co.readFileSync(n,"utf-8"));if(typeof s!="object"||s===null)return null;let i=s;return{app:t.replace(/\.json$/,""),package:ao(i.package),port:Gc(i.port),alias:ao(i.alias),origin:ao(i.origin),release:ao(i.release),env:ao(i.env),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}},lo=(e=CR.cwd())=>{let t=Date.now(),r=OR(e);if(!r||!co.existsSync(r))return{session:"none",fragmentDir:r,readAt:t,apps:[]};let n;try{n=co.readdirSync(r).filter(s=>s.endsWith(".json"))}catch{return{session:"none",fragmentDir:r,readAt:t,apps:[]}}let o=n.map(s=>IR(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 ti=async(e={})=>{let t=e.now??Date.now,r=e.isListening??_n,n=lo(e.cwd),o=t(),s=await Promise.all(n.apps.map(async p=>{let m=Math.max(0,Math.round((o-p.mtimeMs)/1e3)),f=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,env:p.env||null,writtenAt:p.writtenAt>0?new Date(p.writtenAt).toISOString():null,fragmentMtime:new Date(p.mtimeMs).toISOString(),ageSeconds:m,live:f}})),i=s.length>0,a=n.fragmentDir??null,c=a!==null&&(DR.statSync(a,{throwIfNoEntry:!1})?.isDirectory()??!1),l=a===null?"nothing (no .infra-kit anchor exists up-tree)":a;if(i){d.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",f=`written ${p.ageSeconds}s ago`;d.info(` ${p.app} (${p.package}) \u2192 ${p.origin} on :${p.port} \u2014 ${m}, ${f}`)}}else{let p=c?"no readable fragment found there":"that directory does not exist";d.info(`No active infra-kit dev session \u2014 searched ${l} (${p}).`)}let u={active:i,apps:s,contextDir:a,contextDirExists:c};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}},NR={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."),env:ie.string().nullable().describe("INFRA_KIT_ENV the dev session runs with \u2014 where its UIs proxy cloud routes. Null when none was loaded, or the fragment predates the field."),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.")},Jc=E({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:NR,handler:()=>ti()});import{spawnSync as Fh}from"node:child_process";import te from"node:fs";import Lh from"node:os";import de from"node:path";import at from"node:process";import{z as ge}from"zod";import{execFileSync as _R}from"node:child_process";var Bf=(e,t)=>{let r=e.filter(n=>!n.live).map(n=>n.name);return t?{prunable:[],withheld:r}:{prunable:r,withheld:[]}},MR=[/\binfra-kit\s+dev\b/,/cli\.js\s+dev\b/,/dev-server\.(?:js|ts)\b/],jR=e=>MR.some(t=>t.test(e)),FR="/bin/ps",LR=()=>_R(FR,["-eo","command="],{encoding:"utf8",maxBuffer:8<<20}).split(`
156
+ `),Uf=(e=LR)=>{try{return e().some(jR)}catch{return!0}};import{Chalk as BR}from"chalk";import Kc from"node:process";var Hc={unicode:{ok:"\u2713",changed:"+",skipped:"-",manual:">",warn:"!",fail:"\u2717",separator:"\xB7",rule:"\u2500"},ascii:{ok:"ok",changed:"++",skipped:"--",manual:">>",warn:"!?",fail:"!!",separator:"-",rule:"-"}},UR=new Set(["warn","fail"]),VR=24,Kr=" ",Vf=" ",WR=(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:[""]},Wf=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},GR=e=>{let t=new BR({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)}},Gf=(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),JR=(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=Gf(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}},KR=(e,t,r,n)=>{let o=JR(Wf(e.rows),e.rows.length,t,r),s=Math.max(1,n-Kr.length-e.label.length-o.plainWidth);return`${Kr}${t.header(e.label)}${" ".repeat(s)}${o.text}`},HR=(e,t,r,n,o)=>{let s=UR.has(e.status),i=n.ok.length,a=e.name.padEnd(t),c=r[e.status],l=s?c(a):a,u=Vf.length+i+1+t+2,p=Math.max(VR,o-u),[m,...f]=WR(e.message,p),y=" ".repeat(u),b=x=>s?x:r.dim(x);return[`${Vf}${c(n[e.status])} ${l} ${b(m??"")}`.trimEnd(),...f.map(x=>`${y}${b(x)}`),...(e.notes??[]).map(x=>`${y}${x}`.trimEnd())]},qR=(e,t,r,n,o)=>{let s=Wf(t),i=n.rule.repeat(Math.max(12,Math.min(o-Kr.length,56))),a=Gf(s,()=>"warned"),c=[r.ok(`${s.ok} passed`),...a.map(u=>r[u.status](u.plain))].join(` ${n.separator} `),l=(e.hints??[]).map(u=>` ${r.dim(u)}`);return[`${Kr}${r.dim(i)}`,`${Kr}${c}${l.join("")}`]},qc=(e,t={})=>{let r=t.width??80,n=GR(t.color??!1),o=t.unicode??!0?Hc.unicode:Hc.ascii,s=e.sections.filter(u=>u.rows.length>0),i=s.flatMap(u=>u.rows),a=n.bold(e.title);if(i.length===0)return[a,"",`${Kr}${n.dim(e.emptyMessage??"Nothing ran.")}`];let c=Math.max(...i.map(u=>u.name.length)),l=s.flatMap(u=>[KR(u,n,o,r),...u.rows.flatMap(p=>HR(p,c,n,o,r)),""]);return[a,"",...l,...qR(e,i,n,o,r)]},YR=new Set(["","0","false","none"]),zR=["LC_ALL","LC_CTYPE","LANG"],XR=(e,t)=>e.NO_COLOR!==void 0&&e.NO_COLOR!==""?!1:e.FORCE_COLOR!==void 0?!YR.has(e.FORCE_COLOR.toLowerCase()):!!t.isTTY,ZR=(e,t)=>{if(t)return!1;let r=zR.map(n=>e[n]).find(n=>n!==void 0&&n!=="");return r===void 0?!0:/UTF-?8/i.test(r)},Yc=(e={})=>{let t=e.env??Kc.env,r=e.stream??Kc.stderr;return{color:XR(t,r),unicode:ZR(t,e.ascii??!1),width:r.columns??80}},rt=(e,t={})=>{(t.write??(n=>{Kc.stderr.write(n)}))(`${qc(e,Yc(t)).join(`
157
157
  `)}
158
- `)};var XR="Tools & CLIs",ZR="Shell & integration",QR="Project config",eS="Doppler env tokens",tS="Dev proxy (portless)",rS="Claude Code plugin",nS=`portless serving TLS on :${Et}`,zc=[[XR,["brew installed","git installed","gh installed","gh authenticated","doppler installed","aws installed","package manager installed","typescript-language-server installed","orca installed"]],[ZR,["zshrc init block","zshenv session block","pnpm enableGlobalVirtualStore","CLAUDE.md block"]],[QR,["infra-kit config valid","user override path","legacy user-global config","merge-dev resolutions"]],[eS,["tokens.json present","env tokens configured","tokens.json perms"]],[tS,["portless installed","portless node","portless service target",nS,"portless CA chain valid","portless CA trusted","portless routes"]],[rS,["claude CLI","marketplace registered","plugin installed","plugin version","plugin MCP server","CLI version","background setup","claude in chrome","Agent mode","Agent allowlist"]]],Gf="Other",oS=zc.map(([e])=>e),sS=new Map(zc.flatMap(([e,t])=>t.map(r=>[r,e]))),j0=zc.flatMap(([,e])=>e),Xc=new Set(["portless routes","tokens.json perms"]),iS=e=>{let t=new Map;for(let n of e){let o=sS.get(n.name)??Gf,s=t.get(o);s?s.push(n):t.set(o,[n])}return[...oS,Gf].flatMap(n=>{let o=t.get(n);return o&&o.length>0?[{label:n,checks:o}]:[]})};var aS=e=>{switch(e){case"pass":return"ok";case"fail":return"fail";case"warn":return"warn";case"skip":return"skipped";default:return Ne(e)}},cS=e=>{let t=e.filter(r=>r.status==="fail"&&Xc.has(r.name)).length;return{title:"infra-kit doctor",emptyMessage:"No checks ran.",sections:iS(e).map(r=>({label:r.label,rows:r.checks.map(n=>({name:n.name,status:aS(n.status),message:n.message}))})),hints:t>0?[`${t} fixable \u2014 run \`infra-kit doctor --fix\``]:[]}};var Zc=(e,t={})=>{tt(cS(e),t)};var lS=e=>e.replace(/&apos;/g,"'").replace(/&quot;/g,'"').replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&amp;/g,"&"),uS=e=>[...e.matchAll(/<string>([\s\S]*?)<\/string>/g)].map(t=>lS(t[1])),dS=e=>{let t=e.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/);return t===null?null:uS(t[1])},pS=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},mS=e=>{let t=e.split(`
159
- `).find(r=>r.startsWith("ExecStart="));return t===void 0?null:pS(t.slice(10))},Jf=(e,t)=>{try{return e==="darwin"?dS(t):e==="linux"?mS(t):null}catch{return null}};import{Buffer as ug}from"node:buffer";import Te from"node:fs/promises";import nt from"node:path";import dg from"node:process";import{$ as pi}from"zx";import fS from"node:process";var lo=class extends Error{name="PromptCancelledError";constructor(){super("Prompt cancelled")}};var Kf=e=>{let t={operation:"interactive branch selection",remediation:"pass the branch selection explicitly (`--version`/`--versions`/`--all`) for non-interactive, --json, or --agent runs"};if(K())throw new C({status:"argument_required",argument:e,agentMode:_.source},2,t);if(!fS.stdin.isTTY)throw new g(void 0,t)},Mt=async e=>{Kf("version");let{runBranchPicker:t}=await import("./boot-LC2ESPY6.js"),r=await t(e);if(r===null)throw new lo;return r},jt=async(e,t)=>{Kf("versions");let{runBranchMultiPicker:r}=await import("./boot-LC2ESPY6.js"),n=await r(e,t);if(n===null)throw new lo;return n};import{$ as Qf}from"zx";import{$ as q0}from"zx";import{$ as qr}from"zx";import{$ as Hf}from"zx";var Qc=async e=>{let{operation:t}=e;try{await Hf({quiet:!0})`git rev-parse --git-dir`}catch(r){throw new g(r,{operation:t,remediation:"run this from inside a git repository"})}try{await Hf({quiet:!0})`git remote get-url origin`}catch(r){throw new g(r,{operation:t,remediation:"this repository has no `origin` remote to fetch from or push to"})}},hS=4,Hr=async e=>{let{operation:t}=e,r=await Qp();if(r.length===0)return;d.error(`working tree has uncommitted changes:
158
+ `)};var QR="Tools & CLIs",eS="Shell & integration",tS="Project config",rS="Doppler env tokens",nS="Dev proxy (portless)",oS="Claude Code plugin",sS=`portless serving TLS on :${Et}`,zc=[[QR,["brew installed","git installed","gh installed","gh authenticated","doppler installed","aws installed","package manager installed","typescript-language-server installed","orca installed"]],[eS,["zshrc init block","zshenv session block","pnpm enableGlobalVirtualStore","CLAUDE.md block"]],[tS,["infra-kit config valid","user override path","legacy user-global config","merge-dev resolutions"]],[rS,["tokens.json present","env tokens configured","tokens.json perms"]],[nS,["portless installed","portless node","portless service target",sS,"portless CA chain valid","portless CA trusted","portless routes"]],[oS,["claude CLI","marketplace registered","plugin installed","plugin version","plugin MCP server","CLI version","background setup","claude in chrome","Agent mode","Agent allowlist"]]],Jf="Other",iS=zc.map(([e])=>e),aS=new Map(zc.flatMap(([e,t])=>t.map(r=>[r,e]))),V0=zc.flatMap(([,e])=>e),Xc=new Set(["portless routes","tokens.json perms"]),cS=e=>{let t=new Map;for(let n of e){let o=aS.get(n.name)??Jf,s=t.get(o);s?s.push(n):t.set(o,[n])}return[...iS,Jf].flatMap(n=>{let o=t.get(n);return o&&o.length>0?[{label:n,checks:o}]:[]})};var lS=e=>{switch(e){case"pass":return"ok";case"fail":return"fail";case"warn":return"warn";case"skip":return"skipped";default:return Ne(e)}},uS=e=>{let t=e.filter(r=>r.status==="fail"&&Xc.has(r.name)).length;return{title:"infra-kit doctor",emptyMessage:"No checks ran.",sections:cS(e).map(r=>({label:r.label,rows:r.checks.map(n=>({name:n.name,status:lS(n.status),message:n.message}))})),hints:t>0?[`${t} fixable \u2014 run \`infra-kit doctor --fix\``]:[]}};var Zc=(e,t={})=>{rt(uS(e),t)};var dS=e=>e.replace(/&apos;/g,"'").replace(/&quot;/g,'"').replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&amp;/g,"&"),pS=e=>[...e.matchAll(/<string>([\s\S]*?)<\/string>/g)].map(t=>dS(t[1])),mS=e=>{let t=e.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/);return t===null?null:pS(t[1])},fS=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},gS=e=>{let t=e.split(`
159
+ `).find(r=>r.startsWith("ExecStart="));return t===void 0?null:fS(t.slice(10))},Kf=(e,t)=>{try{return e==="darwin"?mS(t):e==="linux"?gS(t):null}catch{return null}};import{Buffer as dg}from"node:buffer";import Te from"node:fs/promises";import ot from"node:path";import pg from"node:process";import{$ as pi}from"zx";import hS from"node:process";var uo=class extends Error{name="PromptCancelledError";constructor(){super("Prompt cancelled")}};var Hf=e=>{let t={operation:"interactive branch selection",remediation:"pass the branch selection explicitly (`--version`/`--versions`/`--all`) for non-interactive, --json, or --agent runs"};if(H())throw new C({status:"argument_required",argument:e,agentMode:_.source},2,t);if(!hS.stdin.isTTY)throw new g(void 0,t)},Mt=async e=>{Hf("version");let{runBranchPicker:t}=await import("./boot-LC2ESPY6.js"),r=await t(e);if(r===null)throw new uo;return r},jt=async(e,t)=>{Hf("versions");let{runBranchMultiPicker:r}=await import("./boot-LC2ESPY6.js"),n=await r(e,t);if(n===null)throw new uo;return n};import{$ as eg}from"zx";import{$ as Q0}from"zx";import{$ as qr}from"zx";import{$ as qf}from"zx";var Qc=async e=>{let{operation:t}=e;try{await qf({quiet:!0})`git rev-parse --git-dir`}catch(r){throw new g(r,{operation:t,remediation:"run this from inside a git repository"})}try{await qf({quiet:!0})`git remote get-url origin`}catch(r){throw new g(r,{operation:t,remediation:"this repository has no `origin` remote to fetch from or push to"})}},vS=4,Hr=async e=>{let{operation:t}=e,r=await em();if(r.length===0)return;d.error(`working tree has uncommitted changes:
160
160
  ${r.join(`
161
- `)}`);let n=r.slice(0,hS),o=r.length-n.length,s=o>0?`${n.join(", ")} (+${o} more)`:n.join(", ");throw new g(void 0,{operation:t,remediation:"commit or stash your changes (`git stash -u`), then retry",stderrExcerpt:`working tree has uncommitted changes: ${s}`})},uo=async e=>{let{operation:t,base:r}=e;if(await Ar()===r)return;let n=(await qe(await P())).find(o=>o.branch===r);if(n)throw new g(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}`})},xe=async e=>{let{operation:t}=e;if(await tm())throw new g(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 Hr({operation:t})};var yS=e=>e.map(t=>({pr:t,id:q(t.headRefName)})).filter(t=>t.id!==null).sort((t,r)=>Zp(t.id,r.id,{a:t.pr.createdAt,b:r.pr.createdAt})).map(t=>t.pr),po=200,qf=(e,t)=>{e.length<po||d.warn({source:t,limit:po},`\u26A0\uFE0F ${t} returned ${po} PRs \u2014 the page is full, so older release PRs may be missing`)},vS=async()=>{let[e,t]=await Promise.all([qr`gh pr list --limit ${po} --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,qr`gh pr list --limit ${po} --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName,createdAt`]),r=JSON.parse(e.stdout),n=JSON.parse(t.stdout);qf(r,"release PR discovery (base dev)"),qf(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)}))},mo="find open release PRs",Yf=async()=>{try{let e=await vS();if(e.length===0)throw new g(void 0,{operation:mo,remediation:"open a release PR first, or check you are in the right repo"});return yS(e)}catch(e){throw e instanceof g?e:(d.debug({err:e},"Error fetching release PRs"),new g(e,{operation:"fetch release PRs"}))}},ri=async()=>(await Yf()).map(t=>t.headRefName),wS=e=>{let t=fo(e.baseRefName);if(t===null)throw new g(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=el(e.title)!==t;return(r||e.dualBase)&&d.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 Yf()).map(wS),ni=async e=>{let{branch:t,body:r}=e;try{await qr({quiet:!0})`gh pr edit ${t} --body ${r}`}catch(n){throw d.error({error:n,branch:t},`Error updating release PR body for ${t}`),n}},kS=async(e,t)=>{let r=qr({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){d.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&&d.error({branchName:e},`could not remove the local branch ${e} after a failed release \u2014 delete it with \`git branch -D ${e}\` before retrying`)},oi=async e=>{let{id:t,jiraVersionUrl:r,type:n,description:o,baseSha:s}=e,i=Xp(t,n),a=rt(n),c=qr({quiet:!0}),l=we(t),u=go(r,o);try{await Hr({operation:`create release branch ${l}`});let p=(await c`git rev-parse HEAD`).stdout.trim();if(p!==s)throw new g(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 ${u} --base ${a} --head ${l}`;return{branchName:l,prUrl:m.stdout.trim()}}catch(m){throw await kS(l,a),m}}catch(p){throw d.error({error:p,branchName:l},`Error creating release branch ${l}`),p}finally{await qr({quiet:!0,nothrow:!0})`git switch ${a}`}};import{$ as tl}from"zx";var Yr=async e=>{let t=await tl`gh pr list --head ${e} --state all --json number,state,title,baseRefName,headRefName --limit 1`;return JSON.parse(t.stdout)[0]??null},rl=async e=>{let t=await tl`gh pr list --head ${e} --state open --limit 5 --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)},nl=async e=>{try{let t=await tl`gh pr view ${e} --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)}catch(t){throw new g(t,{operation:`fetch PR #${e}`,remediation:`check it exists with \`gh pr view ${e}\``})}};import yo from"node:process";var bS="x-seraph-loginreason",RS="AUTHENTICATED_FAILED",SS=(e,t=160)=>{let r=e.split(`
162
- `,1)[0].trim();return r.length>t?`${r.slice(0,t)}\u2026`:r},Xf=(e,t)=>t===RS||e===401?"auth":e===403?"forbidden":e===404?"not-found-or-forbidden":"other",zf=(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}`,zr=class extends Error{status;kind;body;context;constructor(t){let r=Xf(t.status,t.seraphLoginReason),n=SS(t.body);super(n===""?`${t.context}: ${zf(r,t.status)}`:`${t.context}: ${zf(r,t.status)}. Jira said: ${n}`),this.name="JiraApiError",this.status=t.status,this.kind=r,this.body=t.body,this.context=t.context}},ho=e=>e instanceof zr,Zf=e=>e.headers.get(bS);var Xr=async(e,t)=>{if(e.ok)return;let r=await e.text(),n=new zr({status:e.status,seraphLoginReason:Zf(e),body:r,context:t});throw d.debug({status:e.status,kind:n.kind,body:r},t),n},ar=(e,t)=>`${e.baseUrl}/projects/${t.projectId}/versions/${t.id}/tab/release-report-all-issues`,ol=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 Xr(l,"Failed to create Jira version"),{success:!0,version:await l.json()}},Zr=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 Xr(a,"Failed to get Jira project versions"),await a.json()},gt=async(e,t)=>(await Zr(t)).find(o=>o.name===e)||null,Qr=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 Xr(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}},sl=async(e,t)=>{let{versionName:r}=e,n=await gt(r,t);if(!n)throw new Error(`Version "${r}" not found in Jira project`);return await Qr({versionId:n.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},t)},en=async()=>{let e=yo.env.JIRA_BASE_URL,t=yo.env.JIRA_TOKEN||yo.env.JIRA_API_TOKEN,r=yo.env.JIRA_PROJECT_ID,n=yo.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(`
163
- `);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}},ht=async()=>{try{return await en()}catch(e){return d.warn({err:e},"Jira configuration not available, skipping Jira integration"),null}};var si=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 Xr(a,"Failed to get Jira version issue counts");let c=await a.json();return{issuesFixedCount:c.issuesFixedCount,issuesAffectedCount:c.issuesAffectedCount}},il=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 Xr(c,"Failed to remove Jira version")};var eg="dev",tg={regular:"dev",hotfix:"main"},rt=e=>tg[e],fo=e=>{let t=Object.entries(tg).find(([,r])=>r===e);return t?t[0]:null},go=(e,t)=>(t??"").trim()!==""?`${e}
161
+ `)}`);let n=r.slice(0,vS),o=r.length-n.length,s=o>0?`${n.join(", ")} (+${o} more)`:n.join(", ");throw new g(void 0,{operation:t,remediation:"commit or stash your changes (`git stash -u`), then retry",stderrExcerpt:`working tree has uncommitted changes: ${s}`})},po=async e=>{let{operation:t,base:r}=e;if(await Ar()===r)return;let n=(await Ye(await P())).find(o=>o.branch===r);if(n)throw new g(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}`})},xe=async e=>{let{operation:t}=e;if(await rm())throw new g(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 Hr({operation:t})};var wS=e=>e.map(t=>({pr:t,id:q(t.headRefName)})).filter(t=>t.id!==null).sort((t,r)=>Qp(t.id,r.id,{a:t.pr.createdAt,b:r.pr.createdAt})).map(t=>t.pr),mo=200,Yf=(e,t)=>{e.length<mo||d.warn({source:t,limit:mo},`\u26A0\uFE0F ${t} returned ${mo} PRs \u2014 the page is full, so older release PRs may be missing`)},kS=async()=>{let[e,t]=await Promise.all([qr`gh pr list --limit ${mo} --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,qr`gh pr list --limit ${mo} --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName,createdAt`]),r=JSON.parse(e.stdout),n=JSON.parse(t.stdout);Yf(r,"release PR discovery (base dev)"),Yf(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)}))},fo="find open release PRs",zf=async()=>{try{let e=await kS();if(e.length===0)throw new g(void 0,{operation:fo,remediation:"open a release PR first, or check you are in the right repo"});return wS(e)}catch(e){throw e instanceof g?e:(d.debug({err:e},"Error fetching release PRs"),new g(e,{operation:"fetch release PRs"}))}},ri=async()=>(await zf()).map(t=>t.headRefName),bS=e=>{let t=go(e.baseRefName);if(t===null)throw new g(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=el(e.title)!==t;return(r||e.dualBase)&&d.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 zf()).map(bS),ni=async e=>{let{branch:t,body:r}=e;try{await qr({quiet:!0})`gh pr edit ${t} --body ${r}`}catch(n){throw d.error({error:n,branch:t},`Error updating release PR body for ${t}`),n}},RS=async(e,t)=>{let r=qr({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){d.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&&d.error({branchName:e},`could not remove the local branch ${e} after a failed release \u2014 delete it with \`git branch -D ${e}\` before retrying`)},oi=async e=>{let{id:t,jiraVersionUrl:r,type:n,description:o,baseSha:s}=e,i=Zp(t,n),a=nt(n),c=qr({quiet:!0}),l=ke(t),u=ho(r,o);try{await Hr({operation:`create release branch ${l}`});let p=(await c`git rev-parse HEAD`).stdout.trim();if(p!==s)throw new g(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 ${u} --base ${a} --head ${l}`;return{branchName:l,prUrl:m.stdout.trim()}}catch(m){throw await RS(l,a),m}}catch(p){throw d.error({error:p,branchName:l},`Error creating release branch ${l}`),p}finally{await qr({quiet:!0,nothrow:!0})`git switch ${a}`}};import{$ as tl}from"zx";var Yr=async e=>{let t=await tl`gh pr list --head ${e} --state all --json number,state,title,baseRefName,headRefName --limit 1`;return JSON.parse(t.stdout)[0]??null},rl=async e=>{let t=await tl`gh pr list --head ${e} --state open --limit 5 --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)},nl=async e=>{try{let t=await tl`gh pr view ${e} --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)}catch(t){throw new g(t,{operation:`fetch PR #${e}`,remediation:`check it exists with \`gh pr view ${e}\``})}};import vo from"node:process";var SS="x-seraph-loginreason",ES="AUTHENTICATED_FAILED",PS=(e,t=160)=>{let r=e.split(`
162
+ `,1)[0].trim();return r.length>t?`${r.slice(0,t)}\u2026`:r},Zf=(e,t)=>t===ES||e===401?"auth":e===403?"forbidden":e===404?"not-found-or-forbidden":"other",Xf=(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}`,zr=class extends Error{status;kind;body;context;constructor(t){let r=Zf(t.status,t.seraphLoginReason),n=PS(t.body);super(n===""?`${t.context}: ${Xf(r,t.status)}`:`${t.context}: ${Xf(r,t.status)}. Jira said: ${n}`),this.name="JiraApiError",this.status=t.status,this.kind=r,this.body=t.body,this.context=t.context}},yo=e=>e instanceof zr,Qf=e=>e.headers.get(SS);var Xr=async(e,t)=>{if(e.ok)return;let r=await e.text(),n=new zr({status:e.status,seraphLoginReason:Qf(e),body:r,context:t});throw d.debug({status:e.status,kind:n.kind,body:r},t),n},ar=(e,t)=>`${e.baseUrl}/projects/${t.projectId}/versions/${t.id}/tab/release-report-all-issues`,ol=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 Xr(l,"Failed to create Jira version"),{success:!0,version:await l.json()}},Zr=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 Xr(a,"Failed to get Jira project versions"),await a.json()},gt=async(e,t)=>(await Zr(t)).find(o=>o.name===e)||null,Qr=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 Xr(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}},sl=async(e,t)=>{let{versionName:r}=e,n=await gt(r,t);if(!n)throw new Error(`Version "${r}" not found in Jira project`);return await Qr({versionId:n.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},t)},en=async()=>{let e=vo.env.JIRA_BASE_URL,t=vo.env.JIRA_TOKEN||vo.env.JIRA_API_TOKEN,r=vo.env.JIRA_PROJECT_ID,n=vo.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(`
163
+ `);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}},ht=async()=>{try{return await en()}catch(e){return d.warn({err:e},"Jira configuration not available, skipping Jira integration"),null}};var si=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 Xr(a,"Failed to get Jira version issue counts");let c=await a.json();return{issuesFixedCount:c.issuesFixedCount,issuesAffectedCount:c.issuesAffectedCount}},il=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 Xr(c,"Failed to remove Jira version")};var tg="dev",rg={regular:"dev",hotfix:"main"},nt=e=>rg[e],go=e=>{let t=Object.entries(rg).find(([,r])=>r===e);return t?t[0]:null},ho=(e,t)=>(t??"").trim()!==""?`${e}
164
164
 
165
165
  ${t}`:`${e}
166
- `,al=async(e="regular")=>{let t=rt(e),r=Qf({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 Qf({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 g(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()},ES=async e=>{let{versionName:t,jiraConfig:r,description:n,releaseDate:o}=e,s=await gt(t,r);if(!s)return(await ol({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 g(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 Qr({versionId:s.id,...a},r);return{...s,...a,...a.releaseDate===void 0?{}:{releaseDate:c.version.releaseDate}}},cl=async e=>{let{id:t,jiraConfig:r,description:n,releaseDate:o,type:s="regular",baseSha:i}=e,a=ne(t),c=await ES({versionName:a,jiraConfig:r,description:n,...o===void 0?{}:{releaseDate:o}}),l=ar(r,c),u=await oi({id:t,jiraVersionUrl:l,type:s,description:n,baseSha:i});return{version:X(t),type:s,branchName:u.branchName,prUrl:u.prUrl,jiraVersionUrl:l,releaseDate:c.releaseDate||null}},ii=async()=>{let e=new Map,t=await ht();if(!t)return e;try{let r=await Zr(t);for(let n of r)e.set(n.name,{description:n.description||null,releaseDate:n.releaseDate||null})}catch(r){d.warn({err:r},"Jira descriptions unavailable \u2014 the release list will render without them. If this persists, check JIRA_EMAIL / JIRA_TOKEN.")}return e},ae=async()=>{let e=await ii();return new Map([...e].flatMap(([t,{description:r}])=>r?[[t,r]]:[]))},vo=(e,t,r)=>{let n=r?" ".repeat(r-e.length+3):" ",o=`[${t}]`.padEnd(11);return`${e}${n}${o}`},el=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",ai=e=>e.flatMap(t=>{let r=q(t);return r?[{branch:t,id:r,label:X(r)}]:[]}),yt=e=>{try{return we(me(e))}catch(t){throw new g(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)})}},wo=e=>{if(e===eg)return eg;let t=q(e);return t?X(t):e},vt=e=>e.flatMap(t=>{let r=q(t);return r?[X(r)]:[]}),PS=(e,t)=>t?t.get(e)||"regular":void 0,ce=e=>{let{branches:t,descriptions:r,types:n}=e;return ai(t).map(({branch:o,id:s,label:i})=>({value:o,label:i,description:r.get(ne(s)),type:PS(o,n)}))};import rg from"node:fs/promises";import xS from"node:path";import{$ as ll}from"zx";var B="pnpm-lock.yaml",TS=/^(?:<{7}|={7}|>{7})(?:\s|$)/m,og=async(e,t)=>{let r=xS.join(e,B),n=`${t}:${B}`;try{let o=await ll({cwd:e,quiet:!0})`git show ${n}`;await rg.writeFile(r,o.stdout)}catch(o){return{ok:!1,reason:`dev has no ${B} to start from: ${ng(o)}`}}try{await ll({cwd:e,quiet:!0})`pnpm install --lockfile-only --ignore-scripts --no-frozen-lockfile`}catch(o){return{ok:!1,reason:`pnpm could not merge ${B}: ${ng(o)}`}}return TS.test(await rg.readFile(r,"utf8"))?{ok:!1,reason:`${B} still carries conflict markers after pnpm ran`}:(await ll({cwd:e,quiet:!0})`git add -- ${B}`,{ok:!0})},ng=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim()};import{$ as cr}from"zx";var ul="Merge remote-tracking branch 'origin/dev' into ",CS=e=>{let{stderr:t,message:r}=e;return String(t?.trim()||r||e).trim()},$S=2048,AS=e=>{let{stderr:t,stdout:r,exitCode:n}=e;return[t,r].map(s=>(s??"").trim().slice(-$S)).filter(s=>s.length>0).join(`
167
- `)||`the verify command exited with code ${n??"unknown"} and printed nothing`},OS=async e=>{try{return(await cr({cwd:e,quiet:!0})`git diff --name-only --diff-filter=U`).stdout.split(`
168
- `).map(r=>r.trim()).filter(r=>r.length>0)}catch{return[]}},IS=async(e,t)=>{let r=CS(t),n=await OS(e);return n.length>0?{status:"conflict",conflictPaths:n,reason:r}:await sm(e)?{status:"hook-failed",reason:r}:{status:"error",reason:r}},sg=async e=>{let{cwd:t,worktreePath:r,branches:n}=e,o=[],s=await De(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 DS({cwd:t,worktreePath:r,branch:i,devSha:s});o.push({...c,durationMs:Date.now()-a})}return o},DS=async e=>{let{cwd:t,worktreePath:r,branch:n,devSha:o}=e,s=`origin/${n}`;if(!await De(t,s))return{branch:n,status:"error",reason:`${s} does not exist on origin`};if(await Mn(t,"origin/dev",s))return{branch:n,status:"up-to-date"};try{await La(r),await cr({cwd:r,quiet:!0})`git checkout --detach ${s}`;let i=`${ul}${n}`;await cr({cwd:r,quiet:!0})`git merge origin/dev --no-edit -m ${i}`;let a=(await cr({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 IS(r,i)}}finally{await Ba(r)}},ig=e=>e.flatMap(t=>t.mergeSha?[{branch:t.branch,sha:t.mergeSha}]:[]),ag="pnpm install --frozen-lockfile",cg=async e=>{let{worktreePath:t,refs:r,command:n}=e,o=[],s=new Map;for(let i of r)try{await La(t),await cr({cwd:t,quiet:!0})`git checkout --detach ${i.sha}`,await cr({cwd:t,quiet:!0})`sh -c ${n}`,o.push(i)}catch(a){s.set(i.branch,AS(a))}finally{await Ba(t)}return{kept:o,failed:s}},ko=async(e,t,r="origin/dev")=>{await cr({cwd:e,quiet:!0})`git fetch origin --prune`;let n=[],o=[];for(let s of t)await Mn(e,r,`origin/${s.branch}`)?o.push(s.branch):n.push(s);return{kept:n,nowUpToDate:o}};import dl from"node:process";var ci=new Set,li=e=>(ci.add(e),()=>{ci.delete(e)}),NS=async()=>{for(let e of[...ci])try{await e()}catch(t){d.warn({error:t,msg:"cleanup failed during shutdown"})}ci.clear()},_S=["SIGINT","SIGTERM"],lg=async(e,t={})=>{let{register:r=(i,a)=>{dl.on(i,a)},unregister:n=(i,a)=>{dl.off(i,a)},exit:o=i=>{dl.exit(i)}}=t,s=new Map;for(let i of _S){let a=()=>{NS().then(()=>{o(Sm(i))})};s.set(i,a),r(i,a)}try{return await e()}finally{for(let[i,a]of s)n(i,a)}};var MS="pnpm install --frozen-lockfile --ignore-scripts",jS="pnpm install --frozen-lockfile",pg=64*1024,yg=4096,Ro=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim().slice(-yg)},j=async(e,t)=>(await pi({cwd:e,quiet:!0})`git ${t}`).stdout,pl=e=>e.split(`
169
- `).map(t=>t.trim()).filter(t=>t.length>0),mi=e=>e.split("\0").filter(t=>t.length>0),ui=async(e,t)=>{try{return(await j(e,["rev-parse","-q","--verify",t])).trim()||null}catch{return null}},vg=async e=>nt.resolve(e,(await j(e,["rev-parse","--git-common-dir"])).trim()),ml=e=>e.then(()=>!0,()=>!1),bo=()=>({results:[],atomicPush:{attempted:!1,aborted:!1},declined:!1}),fl=e=>e?.length===1&&e[0]===B,wg=async e=>nt.join(await vg(e),"infra-kit","merge-dev-resolutions"),gl=async(e,t)=>nt.join(await wg(e),`${nm(t)}.json`),kg=async e=>{try{return JSON.parse(await Te.readFile(e,"utf8"))}catch{return null}},rn=async(e,t)=>{let r=await gl(e,t.branch);await Te.mkdir(nt.dirname(r),{recursive:!0}),await Te.writeFile(r,`${JSON.stringify(t,null,2)}
170
- `)},bg=async e=>{let t=await wg(e),r=await Te.readdir(t).catch(()=>[]);return(await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(o=>kg(nt.join(t,o))))).filter(o=>o!==null)},Rg=async e=>Promise.all((await bg(e)).map(async t=>({branch:t.branch,worktreePath:t.worktreePath,createdAt:t.createdAt,worktreeExists:await ml(Te.stat(t.worktreePath))}))),mg=(e,t)=>({worktreePath:e.worktreePath,baseSha:e.baseSha,devSha:e.devSha,conflictPaths:e.conflictPaths,lockfileOnly:e.lockfileOnly,rererePreResolved:e.rererePreResolved,state:t}),hl=async(e,t,r)=>{await j(e,["worktree","remove","--force",r]).catch(()=>Te.rm(r,{recursive:!0,force:!0})),await Te.rm(await gl(e,t),{force:!0}).catch(()=>{}),await j(e,["worktree","prune"]).catch(()=>{})},Sg=async e=>mi(await j(e,["diff","--name-only","-z","--diff-filter=U"])),di=async e=>mi(await j(e,["status","--porcelain","-z","--untracked-files=all","--ignored=matching"])).filter(r=>r.startsWith("!! ")).map(r=>r.slice(3)),FS=async(e,t)=>{let r=(await j(e,["config","--type=bool","--get","rerere.enabled"]).catch(()=>"")).trim(),n=await ml(Te.stat(nt.join(await vg(e),"rr-cache")));if(r==="false"||r===""&&!n)return[];let o=new Set(pl(await j(e,["rerere","remaining"])));return t.filter(s=>!o.has(s))},Eg=e=>e.split("/").includes("node_modules"),fi=async(e,t)=>{let r=new Set(t.conflictPaths),n=new Set([...t.ignoredAtHandoff,...t.ignoredByVerify??[]]),o=mi(await j(e,["diff","--cached","--name-only","-z","--no-renames",t.autoMergeTree])),s=[...await LS(e),...o].filter(a=>!r.has(a)),i=(await di(e)).filter(a=>!n.has(a)&&!Eg(a));return[...new Set([...s,...i,...await BS(e)])].sort()},LS=async e=>{let t=mi(await j(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},BS=async e=>(await j(e,["ls-files","-v"])).split(`
171
- `).filter(t=>{let r=t.charAt(0);return r==="S"||r!==""&&r!==r.toUpperCase()}).map(t=>t.slice(2)),US=async e=>{let t=`:(exclude)${B}`;try{return await j(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 g(r,{operation:"check the staged resolution for conflict markers"});let i=new Set;for(let a of n.split(`
172
- `)){let c=/^(.*):\d+: leftover conflict marker/.exec(a);c?.[1]&&i.add(c[1])}return[...i].sort()}},VS=async(e,t)=>{let r=[];for(let n of t)(await ml(Te.lstat(nt.join(e,n)))||(await j(e,["--literal-pathspecs","ls-files","--",n])).length>0)&&r.push(n);r.length>0&&await j(e,["--literal-pathspecs","add","-A","--",...r])},fg=async e=>(await j(e,["write-tree"])).trim(),Pg=async e=>(await j(e,["rev-list","--parents","-n","1","HEAD"])).trim().split(" ").slice(1),WS=e=>e?`${jS} && ${e}`:MS,GS=async(e,t)=>{try{return await pi({cwd:e,quiet:!0})`sh -c ${t}`,{command:t,ok:!0}}catch(r){return{command:t,ok:!1,reason:Ro(r)}}},xg=async(e,t)=>{let r=(await j(e,["diff","--cached","--stat",t.autoMergeTree])).trim(),n=async l=>(await j(e,["diff","--cached","--stat",l,"--",B])).trim(),o=t.conflictPaths.includes(B)?{vsDev:await n(t.devSha),vsBase:await n(t.baseSha)}:void 0,s=await j(e,["diff","--cached",t.autoMergeTree,"--",".",`:(exclude)${B}`]),i=new Set(t.rererePreResolved),a=s.split(/^(?=diff --git )/m).map(l=>{let u=/^diff --git a\/(.*) b\//.exec(l)?.[1];return u&&i.has(u)?`# rerere (recorded resolution)
173
- ${l}`:l}).join(""),c=ug.byteLength(a)>pg;return{diffStat:r,...o?{lockfileDiffStat:o}:{},resolutionDiff:c?ug.from(a).subarray(0,pg).toString():a,resolutionDiffTruncated:c}},Tg=async e=>{let{cwd:t,branches:r,devSha:n}=e,o=new Map;for(let s of r)o.set(s,await JS(t,s,n));return o},JS=async(e,t,r)=>{let n=await kg(await gl(e,t));if(n)return{resolution:mg(n,"exists"),reason:`resolution-exists: ${n.worktreePath} \u2014 finish it with --continue or drop it with --abort`};let o=await De(e,`origin/${t}`);if(!o)return{reason:`origin/${t} does not exist on origin`};let s=om(e,t),i=()=>hl(e,t,s),a=li(i);try{await j(e,["worktree","prune"]),await Te.mkdir(nt.dirname(s),{recursive:!0}),await j(e,["worktree","add","--detach",s,o]),await pi({cwd:s,quiet:!0})`git merge --no-commit ${r} -m ${ul+t}`.catch(()=>{});let c=await Sg(s);if(c.length===0)return await i(),{reason:"the merge no longer conflicts \u2014 re-run release merge-dev"};let l=await ui(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 j(e,["--version"])).trim()})`};let u=await FS(s,c),p=fl(c),m={branch:t,worktreePath:s,baseSha:o,devSha:r,conflictPaths:c,autoMergeTree:l,rererePreResolved:u,ignoredAtHandoff:await di(s),lockfileOnly:p,cliVersion:U.version,createdAt:new Date().toISOString()};return await rn(e,m),{resolution:mg(m,p?"lockfile-only":"needs-agent")}}catch(c){return await i(),{reason:Ro(c)}}finally{a()}},Cg=async e=>{let{cwd:t,versions:r,all:n}=e,o=await bg(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=we(me(c)),u=o.find(p=>p.branch===l);if(!u)throw new g(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 u});if(n||o.length===0)return o;let i=await jt(ce({branches:s,descriptions:new Map}),{required:!0});return o.filter(a=>i.includes(a.branch))},KS=async(e,t)=>{let r=await Te.realpath(t).catch(()=>null);if(!r)return!1;let n=await qe(e);for(let o of n)if(await Te.realpath(o.path).catch(()=>o.path)===r)return!0;return!1},tn=(e,t,r,n)=>({...e,blocked:{code:t,detail:r,...n&&n.length>0?{paths:n}:{}}}),$g=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 KS(e,n))return tn(o,"parents-mismatch",`the resolution worktree ${n} is gone \u2014 run --abort, then start again`);let s=await ui(n,"HEAD"),i=await ui(n,"MERGE_HEAD");return s===t.baseSha&&i===t.devSha?XS(e,t,o,r):HS(t,o,s,i)},HS=async(e,t,r,n)=>{let o=e.worktreePath;if(r!==null&&r===e.unapprovedCommit)return tn(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 Pg(o),i=n?null:await ui(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 tn(t,"parents-mismatch",`expected HEAD ${e.baseSha} merging ${e.devSha}, or an approved merge commit of the two; found ${l}`)}let c=await fi(o,e);return c.length>0?tn(t,"out-of-scope-edit","only the conflicted paths may change",c):{...t,committed:!0,mergeSha:r,treeSha:i,lockfileMerged:e.conflictPaths.includes(B),...await xg(o,e)}},gg=async(e,t)=>{let r=pl(await j(e,["--literal-pathspecs","ls-files","-s","--",t])),[n,o,s]=r.length===1?(r[0]??"").split(/\s+/):[];return n&&s==="0"?o??null:null},qS=async(e,t)=>{let r=t.worktreePath,n=await gg(r,B),o=t.lockfileBlob,s=await og(r,t.devSha);if(!s.ok)return{code:"verify-failed",detail:s.reason,paths:[B]};let i=await gg(r,B);if(i!==null&&i!==o&&(t.lockfileBlob=i,await rn(e,t)),n!==null&&n!==i)return n===o?{code:"tree-changed",detail:`rebuilding ${B} from dev resolved differently than the last preview (the registry moved) \u2014 preview again`,paths:[B]}:{code:"out-of-scope-edit",detail:`${B} was staged by something other than the CLI; it has been rebuilt from dev \u2014 preview again`,paths:[B]};let a=await fi(r,t);return a.length>0?{code:"out-of-scope-edit",detail:"merging the lockfile changed other paths",paths:a}:null},YS=async(e,t)=>{let r=t.worktreePath;await VS(r,t.conflictPaths.filter(i=>i!==B));let n=await fi(r,t);if(n.length>0)return{code:"out-of-scope-edit",detail:"only the conflicted paths may change",paths:n};let o=(await Sg(r)).filter(i=>i!==B);if(o.length>0)return{code:"unmerged-paths",detail:"these paths are still unmerged",paths:o};let s;try{s=await US(r)}catch(i){return{code:"markers-remaining",detail:`the marker check could not run: ${Ro(i)}`}}return s.length>0?{code:"markers-remaining",detail:"conflict markers are still staged",paths:s}:t.conflictPaths.includes(B)?qS(e,t):null},zS=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 di(o)),i=await GS(o,n),a=(await di(o)).filter(c=>!s.has(c)&&!Eg(c)&&nt.posix.basename(c)!==".gitignore");return t.ignoredByVerify=[...new Set([...t.ignoredByVerify??[],...a])],await rn(e,t),i},XS=async(e,t,r,n)=>{let o=t.worktreePath,s=await YS(e,t);if(s)return{...r,blocked:s};let i=t.conflictPaths.includes(B),a=await fg(o),c=await zS(e,t,a,WS(n)),l={...r,treeSha:a,lockfileMerged:i,verify:c};if(!c.ok)return tn(l,"verify-failed",c.reason??"the verify command failed");let u=await fi(o,t),p=pl(await j(o,["diff","--name-only"]));return u.length>0||p.length>0||await fg(o)!==a?tn(l,"verify-mutated-tree","the verify step changed the tree",[...new Set([...u,...p])]):(c.reused||(t.verified={treeSha:a,command:c.command},await rn(e,t)),{...l,...await xg(o,t)})},ZS=12e4,QS=async(e,t=ZS)=>{let r=pi({cwd:e,quiet:!0,detached:!0,stdio:["ignore","pipe","pipe"],env:{...dg.env,GIT_TERMINAL_PROMPT:"0"}})`git commit --no-edit --cleanup=strip`,n=!1,o=setTimeout(()=>{n=!0;let s=r.child?.pid;try{s&&dg.kill(-s,"SIGKILL")}catch{}},t);try{return await r,{ok:!0}}catch(s){if(!n)return{ok:!1,reason:Ro(s)};let i=(await j(e,["rev-parse","--git-path","index.lock"])).trim();return await Te.rm(nt.resolve(e,i),{force:!0}),{ok:!1,reason:`git commit timed out after ${t}ms`}}finally{clearTimeout(o)}},eE={"verify-failed":"verify-failed","tree-changed":"tree-changed"},tE=e=>{let t=e.blocked;return{branch:e.branch,status:eE[t.code]??"blocked",conflictPaths:e.conflictPaths,pushed:!1,reason:[`${t.code}: ${t.detail}`,...t.paths?[`(${t.paths.join(", ")})`]:[]].join(" "),blocked:t}},rE=async(e,t,r,n)=>{let o=r.worktreePath,s=(u,p,m={})=>({branch:t.branch,status:u,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 QS(o);if(!i.ok)return s("hook-failed",i.reason);let a=(await j(o,["rev-parse","HEAD"])).trim(),c=(await j(o,["rev-parse","HEAD^{tree}"])).trim();if(c!==t.treeSha)return r.unapprovedCommit=a,await rn(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 Pg(o);if(l.length!==2||l[0]!==r.baseSha||l[1]!==r.devSha){let u={code:"parents-mismatch",detail:`commit parents are ${l.join(" ")}, expected ${r.baseSha} ${r.devSha}`};return s("blocked",`parents-mismatch: ${u.detail}`,{mergeSha:a,blocked:u})}return{sha:a}},nE=async(e,t,r)=>{let n=(c,l,u)=>({branch:t.branch,status:c,mergeSha:r,conflictPaths:t.conflictPaths,pushed:!1,...l?{reason:l}:{},...u?{blocked:u}:{}}),o;try{o=(await ko(e,[{branch:t.branch,sha:r}],t.devSha)).nowUpToDate}catch(c){let l={code:"parents-mismatch",detail:`origin/${t.branch}: ${Ro(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 De(e,`origin/${t.branch}`);if(s===t.baseSha)return"keep";let i=s!==null&&await Mn(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)},oE=e=>{d.info(`
174
- \u{1F4CB} Resolution preview:`);for(let t of e)t.blocked?d.info(` ${t.branch} \u2014 BLOCKED ${t.blocked.code}: ${t.blocked.detail}`):d.info(` ${t.branch} \u2014 ready${t.committed?" (already committed)":""}: tree ${t.treeSha}`)},Ag=async e=>{let{cwd:t,versions:r,all:n,verify:o,trees:s=new Map,confirmedCommand:i}=e,a=await Cg({cwd:t,versions:r,all:n});if(a.length===0)return d.info("\u2139\uFE0F No merge-dev resolutions in progress"),bo();if(i)return hg(t,a,o,s);let c=[];for(let m of a){let f=await $g(t,m,o);!f.blocked&&!f.committed&&f.treeSha&&(m.previewedTree=f.treeSha,await rn(t,m)),c.push(f)}oE(c);let l={branches:c},u=c.filter(m=>!m.blocked&&m.treeSha!==void 0);if(u.length===0)throw new C({status:"refused",plan:l,agentMode:_.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(u.map(m=>[m.branch,m.treeSha]));try{await L(i,`Commit and push the resolved merges for: ${[...p.keys()].join(", ")}?`,{plan:l,throwOnDecline:!0,rerun:sE(p)})}catch(m){if(!pt(m))throw m;return{...bo(),declined:!0}}return hg(t,a,o,p)},Og=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 g(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},sE=e=>{let t=[],r=!1;for(let o of wm())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"]},iE=async(e,t,r,n)=>{let o=await $g(e,t,r);if(o.blocked)return tE(o);let s=await rE(e,o,t,n);if(!("sha"in s))return s;let i=await nE(e,t,s.sha);return i==="keep"?s:i},aE=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}));d.info(`
175
- \u2B06\uFE0F Pushing atomically: ${r.map(s=>s.branch).join(", ")}`);let n=await Is(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(-yg)}})}return{results:o,atomicPush:{attempted:!0,aborted:!n.pushed,abortedBy:n.stderr?.split(`
176
- `)[0]}}},hg=async(e,t,r,n)=>{let o=[],s=[];for(let u of t){let p=await iE(e,u,r,n.get(u.branch));"sha"in p?s.push({record:u,sha:p.sha}):o.push(p)}let i=await aE(e,s),a=[...o,...i.results],c=t.filter(u=>a.some(p=>p.branch===u.branch&&(p.pushed||p.status==="up-to-date")));for(let u of c)await hl(e,u.branch,u.worktreePath);let l=t.map(u=>u.branch);return a.sort((u,p)=>l.indexOf(u.branch)-l.indexOf(p.branch)),{results:a,atomicPush:i.atomicPush,declined:!1}},Ig=async e=>{let{cwd:t,versions:r,all:n,confirmedCommand:o}=e,s=await Cg({cwd:t,versions:r,all:n});if(s.length===0)return d.info("\u2139\uFE0F No merge-dev resolutions in progress"),bo();let i={branches:s.map(a=>({branch:a.branch,worktreePath:a.worktreePath}))};try{await L(o,`Discard the resolution worktrees for: ${s.map(a=>a.branch).join(", ")}?`,{plan:i,throwOnDecline:!0})}catch(a){if(!pt(a))throw a;return{...bo(),declined:!0}}for(let a of s)await hl(t,a.branch,a.worktreePath),d.info(`\u{1F5D1}\uFE0F Discarded the resolution for ${a.branch}`);return{...bo(),results:s.map(a=>({branch:a.branch,status:"aborted",conflictPaths:a.conflictPaths,pushed:!1}))}};import cE from"node:fs";import lE from"node:os";import uE from"node:path";var dE="infra-kit.json",pE="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)",mE="Skipped agent-instruction files \u2014 no infra-kit.json at the repo root (the plugin pointer, the plugin install and .mcp.json are unaffected)",So=async()=>{let e;try{e=await P()}catch{return null}let t=e.trim();return t===""||t===lE.homedir()?null:t},Dg=async()=>{let e=await So();return e===null&&d.info(pE),e},fE=async()=>{let e=await So();return e===null?null:cE.existsSync(uE.join(e,dE))?e:(d.info(mE),null)};var gE=async e=>{try{return await Pe(e)}catch(t){return d.debug({err:t,msg:"Skipped per-package agent guidance \u2014 no workspace packages could be discovered."}),[]}},Ng=async({dryRun:e=!1}={})=>{let t=await fE(),r=U.version;if(t===null)return{skipped:!0,root:null,version:r,written:[]};let n=[...await Qn(t,{version:r,dryRun:e})];for(let o of await gE(t)){let s=await tr(o);n.push(...await eo(o,{repoRoot:t,version:r,declaredType:s,dryRun:e}))}return{skipped:!1,root:t,version:r,written:n}};import ue from"node:fs";import bi from"node:os";import ee from"node:path";import Tl from"node:process";import yl from"node:fs";import _g from"node:os";import Mg from"node:path";import hE from"node:process";import{z as hi}from"zod";var jg=e=>{try{return yl.readFileSync(e,"utf-8")}catch{return null}},nn="claude in chrome",yE="com.anthropic.claude_code_browser_extension",gi="run `/chrome` inside Claude Code to set up Claude in Chrome",vE={darwin:["Library","Application Support","Google","Chrome","NativeMessagingHosts"],linux:[".config","google-chrome","NativeMessagingHosts"]},wE=e=>{try{return yl.accessSync(e,yl.constants.X_OK),!0}catch{return!1}},Fg=e=>{try{return JSON.parse(e)}catch{return null}},kE=/^exec\s+(?<target>\S+)\s+--chrome-native-host\b/m,Eo=(e={})=>{let t=e.platform??hE.platform,r=e.home??_g.homedir(),n=e.readText??jg,o=e.isExecutable??wE,s=vE[t];if(s===void 0)return{name:nn,status:"skip",message:`no Chrome native host location known for ${t}`};let i=Mg.join(r,...s,`${yE}.json`),a=n(i);if(a===null)return{name:nn,status:"warn",message:`Chrome native host not registered \u2014 ${gi}`};let c=hi.object({path:hi.string().min(1)}).safeParse(Fg(a));if(!c.success)return{name:nn,status:"fail",message:`${v(i)} has no host path \u2014 ${gi} again`};let l=c.data.path;if(!o(l))return{name:nn,status:"fail",message:`Chrome native host ${v(l)} is missing or not executable \u2014 ${gi} again`};let u=kE.exec(n(l)??"")?.groups?.target;return u!==void 0&&!o(u)?{name:nn,status:"fail",message:`Chrome native host runs ${v(u)}, which no longer exists \u2014 ${gi} again`}:{name:nn,status:"pass",message:`Native host registered (${v(l)}); /infra-kit:doctor checks the live connection`}},vl=(e={})=>{let t=e.home??_g.homedir(),r=e.readText??jg,n=hi.object({claudeInChromeDefaultEnabled:hi.boolean().optional()}).safeParse(Fg(r(Mg.join(t,".claude.json"))??""));return n.success&&n.data.claudeInChromeDefaultEnabled===!0};import vi from"node:fs/promises";import bE from"node:path";import RE from"node:process";var Lg=` // "envManagement": { // required in layer 1; provider-tagged
166
+ `,al=async(e="regular")=>{let t=nt(e),r=eg({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 eg({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 g(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()},xS=async e=>{let{versionName:t,jiraConfig:r,description:n,releaseDate:o}=e,s=await gt(t,r);if(!s)return(await ol({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 g(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 Qr({versionId:s.id,...a},r);return{...s,...a,...a.releaseDate===void 0?{}:{releaseDate:c.version.releaseDate}}},cl=async e=>{let{id:t,jiraConfig:r,description:n,releaseDate:o,type:s="regular",baseSha:i}=e,a=ne(t),c=await xS({versionName:a,jiraConfig:r,description:n,...o===void 0?{}:{releaseDate:o}}),l=ar(r,c),u=await oi({id:t,jiraVersionUrl:l,type:s,description:n,baseSha:i});return{version:X(t),type:s,branchName:u.branchName,prUrl:u.prUrl,jiraVersionUrl:l,releaseDate:c.releaseDate||null}},ii=async()=>{let e=new Map,t=await ht();if(!t)return e;try{let r=await Zr(t);for(let n of r)e.set(n.name,{description:n.description||null,releaseDate:n.releaseDate||null})}catch(r){d.warn({err:r},"Jira descriptions unavailable \u2014 the release list will render without them. If this persists, check JIRA_EMAIL / JIRA_TOKEN.")}return e},ae=async()=>{let e=await ii();return new Map([...e].flatMap(([t,{description:r}])=>r?[[t,r]]:[]))},wo=(e,t,r)=>{let n=r?" ".repeat(r-e.length+3):" ",o=`[${t}]`.padEnd(11);return`${e}${n}${o}`},el=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",ai=e=>e.flatMap(t=>{let r=q(t);return r?[{branch:t,id:r,label:X(r)}]:[]}),yt=e=>{try{return ke(me(e))}catch(t){throw new g(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)})}},ko=e=>{if(e===tg)return tg;let t=q(e);return t?X(t):e},vt=e=>e.flatMap(t=>{let r=q(t);return r?[X(r)]:[]}),TS=(e,t)=>t?t.get(e)||"regular":void 0,ce=e=>{let{branches:t,descriptions:r,types:n}=e;return ai(t).map(({branch:o,id:s,label:i})=>({value:o,label:i,description:r.get(ne(s)),type:TS(o,n)}))};import ng from"node:fs/promises";import CS from"node:path";import{$ as ll}from"zx";var B="pnpm-lock.yaml",$S=/^(?:<{7}|={7}|>{7})(?:\s|$)/m,sg=async(e,t)=>{let r=CS.join(e,B),n=`${t}:${B}`;try{let o=await ll({cwd:e,quiet:!0})`git show ${n}`;await ng.writeFile(r,o.stdout)}catch(o){return{ok:!1,reason:`dev has no ${B} to start from: ${og(o)}`}}try{await ll({cwd:e,quiet:!0})`pnpm install --lockfile-only --ignore-scripts --no-frozen-lockfile`}catch(o){return{ok:!1,reason:`pnpm could not merge ${B}: ${og(o)}`}}return $S.test(await ng.readFile(r,"utf8"))?{ok:!1,reason:`${B} still carries conflict markers after pnpm ran`}:(await ll({cwd:e,quiet:!0})`git add -- ${B}`,{ok:!0})},og=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim()};import{$ as cr}from"zx";var ul="Merge remote-tracking branch 'origin/dev' into ",AS=e=>{let{stderr:t,message:r}=e;return String(t?.trim()||r||e).trim()},OS=2048,IS=e=>{let{stderr:t,stdout:r,exitCode:n}=e;return[t,r].map(s=>(s??"").trim().slice(-OS)).filter(s=>s.length>0).join(`
167
+ `)||`the verify command exited with code ${n??"unknown"} and printed nothing`},DS=async e=>{try{return(await cr({cwd:e,quiet:!0})`git diff --name-only --diff-filter=U`).stdout.split(`
168
+ `).map(r=>r.trim()).filter(r=>r.length>0)}catch{return[]}},NS=async(e,t)=>{let r=AS(t),n=await DS(e);return n.length>0?{status:"conflict",conflictPaths:n,reason:r}:await im(e)?{status:"hook-failed",reason:r}:{status:"error",reason:r}},ig=async e=>{let{cwd:t,worktreePath:r,branches:n}=e,o=[],s=await De(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 _S({cwd:t,worktreePath:r,branch:i,devSha:s});o.push({...c,durationMs:Date.now()-a})}return o},_S=async e=>{let{cwd:t,worktreePath:r,branch:n,devSha:o}=e,s=`origin/${n}`;if(!await De(t,s))return{branch:n,status:"error",reason:`${s} does not exist on origin`};if(await jn(t,"origin/dev",s))return{branch:n,status:"up-to-date"};try{await La(r),await cr({cwd:r,quiet:!0})`git checkout --detach ${s}`;let i=`${ul}${n}`;await cr({cwd:r,quiet:!0})`git merge origin/dev --no-edit -m ${i}`;let a=(await cr({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 NS(r,i)}}finally{await Ba(r)}},ag=e=>e.flatMap(t=>t.mergeSha?[{branch:t.branch,sha:t.mergeSha}]:[]),cg="pnpm install --frozen-lockfile",lg=async e=>{let{worktreePath:t,refs:r,command:n}=e,o=[],s=new Map;for(let i of r)try{await La(t),await cr({cwd:t,quiet:!0})`git checkout --detach ${i.sha}`,await cr({cwd:t,quiet:!0})`sh -c ${n}`,o.push(i)}catch(a){s.set(i.branch,IS(a))}finally{await Ba(t)}return{kept:o,failed:s}},bo=async(e,t,r="origin/dev")=>{await cr({cwd:e,quiet:!0})`git fetch origin --prune`;let n=[],o=[];for(let s of t)await jn(e,r,`origin/${s.branch}`)?o.push(s.branch):n.push(s);return{kept:n,nowUpToDate:o}};import dl from"node:process";var ci=new Set,li=e=>(ci.add(e),()=>{ci.delete(e)}),MS=async()=>{for(let e of[...ci])try{await e()}catch(t){d.warn({error:t,msg:"cleanup failed during shutdown"})}ci.clear()},jS=["SIGINT","SIGTERM"],ug=async(e,t={})=>{let{register:r=(i,a)=>{dl.on(i,a)},unregister:n=(i,a)=>{dl.off(i,a)},exit:o=i=>{dl.exit(i)}}=t,s=new Map;for(let i of jS){let a=()=>{MS().then(()=>{o(Em(i))})};s.set(i,a),r(i,a)}try{return await e()}finally{for(let[i,a]of s)n(i,a)}};var FS="pnpm install --frozen-lockfile --ignore-scripts",LS="pnpm install --frozen-lockfile",mg=64*1024,vg=4096,So=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim().slice(-vg)},j=async(e,t)=>(await pi({cwd:e,quiet:!0})`git ${t}`).stdout,pl=e=>e.split(`
169
+ `).map(t=>t.trim()).filter(t=>t.length>0),mi=e=>e.split("\0").filter(t=>t.length>0),ui=async(e,t)=>{try{return(await j(e,["rev-parse","-q","--verify",t])).trim()||null}catch{return null}},wg=async e=>ot.resolve(e,(await j(e,["rev-parse","--git-common-dir"])).trim()),ml=e=>e.then(()=>!0,()=>!1),Ro=()=>({results:[],atomicPush:{attempted:!1,aborted:!1},declined:!1}),fl=e=>e?.length===1&&e[0]===B,kg=async e=>ot.join(await wg(e),"infra-kit","merge-dev-resolutions"),gl=async(e,t)=>ot.join(await kg(e),`${om(t)}.json`),bg=async e=>{try{return JSON.parse(await Te.readFile(e,"utf8"))}catch{return null}},rn=async(e,t)=>{let r=await gl(e,t.branch);await Te.mkdir(ot.dirname(r),{recursive:!0}),await Te.writeFile(r,`${JSON.stringify(t,null,2)}
170
+ `)},Rg=async e=>{let t=await kg(e),r=await Te.readdir(t).catch(()=>[]);return(await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(o=>bg(ot.join(t,o))))).filter(o=>o!==null)},Sg=async e=>Promise.all((await Rg(e)).map(async t=>({branch:t.branch,worktreePath:t.worktreePath,createdAt:t.createdAt,worktreeExists:await ml(Te.stat(t.worktreePath))}))),fg=(e,t)=>({worktreePath:e.worktreePath,baseSha:e.baseSha,devSha:e.devSha,conflictPaths:e.conflictPaths,lockfileOnly:e.lockfileOnly,rererePreResolved:e.rererePreResolved,state:t}),hl=async(e,t,r)=>{await j(e,["worktree","remove","--force",r]).catch(()=>Te.rm(r,{recursive:!0,force:!0})),await Te.rm(await gl(e,t),{force:!0}).catch(()=>{}),await j(e,["worktree","prune"]).catch(()=>{})},Eg=async e=>mi(await j(e,["diff","--name-only","-z","--diff-filter=U"])),di=async e=>mi(await j(e,["status","--porcelain","-z","--untracked-files=all","--ignored=matching"])).filter(r=>r.startsWith("!! ")).map(r=>r.slice(3)),BS=async(e,t)=>{let r=(await j(e,["config","--type=bool","--get","rerere.enabled"]).catch(()=>"")).trim(),n=await ml(Te.stat(ot.join(await wg(e),"rr-cache")));if(r==="false"||r===""&&!n)return[];let o=new Set(pl(await j(e,["rerere","remaining"])));return t.filter(s=>!o.has(s))},Pg=e=>e.split("/").includes("node_modules"),fi=async(e,t)=>{let r=new Set(t.conflictPaths),n=new Set([...t.ignoredAtHandoff,...t.ignoredByVerify??[]]),o=mi(await j(e,["diff","--cached","--name-only","-z","--no-renames",t.autoMergeTree])),s=[...await US(e),...o].filter(a=>!r.has(a)),i=(await di(e)).filter(a=>!n.has(a)&&!Pg(a));return[...new Set([...s,...i,...await VS(e)])].sort()},US=async e=>{let t=mi(await j(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},VS=async e=>(await j(e,["ls-files","-v"])).split(`
171
+ `).filter(t=>{let r=t.charAt(0);return r==="S"||r!==""&&r!==r.toUpperCase()}).map(t=>t.slice(2)),WS=async e=>{let t=`:(exclude)${B}`;try{return await j(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 g(r,{operation:"check the staged resolution for conflict markers"});let i=new Set;for(let a of n.split(`
172
+ `)){let c=/^(.*):\d+: leftover conflict marker/.exec(a);c?.[1]&&i.add(c[1])}return[...i].sort()}},GS=async(e,t)=>{let r=[];for(let n of t)(await ml(Te.lstat(ot.join(e,n)))||(await j(e,["--literal-pathspecs","ls-files","--",n])).length>0)&&r.push(n);r.length>0&&await j(e,["--literal-pathspecs","add","-A","--",...r])},gg=async e=>(await j(e,["write-tree"])).trim(),xg=async e=>(await j(e,["rev-list","--parents","-n","1","HEAD"])).trim().split(" ").slice(1),JS=e=>e?`${LS} && ${e}`:FS,KS=async(e,t)=>{try{return await pi({cwd:e,quiet:!0})`sh -c ${t}`,{command:t,ok:!0}}catch(r){return{command:t,ok:!1,reason:So(r)}}},Tg=async(e,t)=>{let r=(await j(e,["diff","--cached","--stat",t.autoMergeTree])).trim(),n=async l=>(await j(e,["diff","--cached","--stat",l,"--",B])).trim(),o=t.conflictPaths.includes(B)?{vsDev:await n(t.devSha),vsBase:await n(t.baseSha)}:void 0,s=await j(e,["diff","--cached",t.autoMergeTree,"--",".",`:(exclude)${B}`]),i=new Set(t.rererePreResolved),a=s.split(/^(?=diff --git )/m).map(l=>{let u=/^diff --git a\/(.*) b\//.exec(l)?.[1];return u&&i.has(u)?`# rerere (recorded resolution)
173
+ ${l}`:l}).join(""),c=dg.byteLength(a)>mg;return{diffStat:r,...o?{lockfileDiffStat:o}:{},resolutionDiff:c?dg.from(a).subarray(0,mg).toString():a,resolutionDiffTruncated:c}},Cg=async e=>{let{cwd:t,branches:r,devSha:n}=e,o=new Map;for(let s of r)o.set(s,await HS(t,s,n));return o},HS=async(e,t,r)=>{let n=await bg(await gl(e,t));if(n)return{resolution:fg(n,"exists"),reason:`resolution-exists: ${n.worktreePath} \u2014 finish it with --continue or drop it with --abort`};let o=await De(e,`origin/${t}`);if(!o)return{reason:`origin/${t} does not exist on origin`};let s=sm(e,t),i=()=>hl(e,t,s),a=li(i);try{await j(e,["worktree","prune"]),await Te.mkdir(ot.dirname(s),{recursive:!0}),await j(e,["worktree","add","--detach",s,o]),await pi({cwd:s,quiet:!0})`git merge --no-commit ${r} -m ${ul+t}`.catch(()=>{});let c=await Eg(s);if(c.length===0)return await i(),{reason:"the merge no longer conflicts \u2014 re-run release merge-dev"};let l=await ui(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 j(e,["--version"])).trim()})`};let u=await BS(s,c),p=fl(c),m={branch:t,worktreePath:s,baseSha:o,devSha:r,conflictPaths:c,autoMergeTree:l,rererePreResolved:u,ignoredAtHandoff:await di(s),lockfileOnly:p,cliVersion:U.version,createdAt:new Date().toISOString()};return await rn(e,m),{resolution:fg(m,p?"lockfile-only":"needs-agent")}}catch(c){return await i(),{reason:So(c)}}finally{a()}},$g=async e=>{let{cwd:t,versions:r,all:n}=e,o=await Rg(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=ke(me(c)),u=o.find(p=>p.branch===l);if(!u)throw new g(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 u});if(n||o.length===0)return o;let i=await jt(ce({branches:s,descriptions:new Map}),{required:!0});return o.filter(a=>i.includes(a.branch))},qS=async(e,t)=>{let r=await Te.realpath(t).catch(()=>null);if(!r)return!1;let n=await Ye(e);for(let o of n)if(await Te.realpath(o.path).catch(()=>o.path)===r)return!0;return!1},tn=(e,t,r,n)=>({...e,blocked:{code:t,detail:r,...n&&n.length>0?{paths:n}:{}}}),Ag=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 qS(e,n))return tn(o,"parents-mismatch",`the resolution worktree ${n} is gone \u2014 run --abort, then start again`);let s=await ui(n,"HEAD"),i=await ui(n,"MERGE_HEAD");return s===t.baseSha&&i===t.devSha?QS(e,t,o,r):YS(t,o,s,i)},YS=async(e,t,r,n)=>{let o=e.worktreePath;if(r!==null&&r===e.unapprovedCommit)return tn(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 xg(o),i=n?null:await ui(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 tn(t,"parents-mismatch",`expected HEAD ${e.baseSha} merging ${e.devSha}, or an approved merge commit of the two; found ${l}`)}let c=await fi(o,e);return c.length>0?tn(t,"out-of-scope-edit","only the conflicted paths may change",c):{...t,committed:!0,mergeSha:r,treeSha:i,lockfileMerged:e.conflictPaths.includes(B),...await Tg(o,e)}},hg=async(e,t)=>{let r=pl(await j(e,["--literal-pathspecs","ls-files","-s","--",t])),[n,o,s]=r.length===1?(r[0]??"").split(/\s+/):[];return n&&s==="0"?o??null:null},zS=async(e,t)=>{let r=t.worktreePath,n=await hg(r,B),o=t.lockfileBlob,s=await sg(r,t.devSha);if(!s.ok)return{code:"verify-failed",detail:s.reason,paths:[B]};let i=await hg(r,B);if(i!==null&&i!==o&&(t.lockfileBlob=i,await rn(e,t)),n!==null&&n!==i)return n===o?{code:"tree-changed",detail:`rebuilding ${B} from dev resolved differently than the last preview (the registry moved) \u2014 preview again`,paths:[B]}:{code:"out-of-scope-edit",detail:`${B} was staged by something other than the CLI; it has been rebuilt from dev \u2014 preview again`,paths:[B]};let a=await fi(r,t);return a.length>0?{code:"out-of-scope-edit",detail:"merging the lockfile changed other paths",paths:a}:null},XS=async(e,t)=>{let r=t.worktreePath;await GS(r,t.conflictPaths.filter(i=>i!==B));let n=await fi(r,t);if(n.length>0)return{code:"out-of-scope-edit",detail:"only the conflicted paths may change",paths:n};let o=(await Eg(r)).filter(i=>i!==B);if(o.length>0)return{code:"unmerged-paths",detail:"these paths are still unmerged",paths:o};let s;try{s=await WS(r)}catch(i){return{code:"markers-remaining",detail:`the marker check could not run: ${So(i)}`}}return s.length>0?{code:"markers-remaining",detail:"conflict markers are still staged",paths:s}:t.conflictPaths.includes(B)?zS(e,t):null},ZS=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 di(o)),i=await KS(o,n),a=(await di(o)).filter(c=>!s.has(c)&&!Pg(c)&&ot.posix.basename(c)!==".gitignore");return t.ignoredByVerify=[...new Set([...t.ignoredByVerify??[],...a])],await rn(e,t),i},QS=async(e,t,r,n)=>{let o=t.worktreePath,s=await XS(e,t);if(s)return{...r,blocked:s};let i=t.conflictPaths.includes(B),a=await gg(o),c=await ZS(e,t,a,JS(n)),l={...r,treeSha:a,lockfileMerged:i,verify:c};if(!c.ok)return tn(l,"verify-failed",c.reason??"the verify command failed");let u=await fi(o,t),p=pl(await j(o,["diff","--name-only"]));return u.length>0||p.length>0||await gg(o)!==a?tn(l,"verify-mutated-tree","the verify step changed the tree",[...new Set([...u,...p])]):(c.reused||(t.verified={treeSha:a,command:c.command},await rn(e,t)),{...l,...await Tg(o,t)})},eE=12e4,tE=async(e,t=eE)=>{let r=pi({cwd:e,quiet:!0,detached:!0,stdio:["ignore","pipe","pipe"],env:{...pg.env,GIT_TERMINAL_PROMPT:"0"}})`git commit --no-edit --cleanup=strip`,n=!1,o=setTimeout(()=>{n=!0;let s=r.child?.pid;try{s&&pg.kill(-s,"SIGKILL")}catch{}},t);try{return await r,{ok:!0}}catch(s){if(!n)return{ok:!1,reason:So(s)};let i=(await j(e,["rev-parse","--git-path","index.lock"])).trim();return await Te.rm(ot.resolve(e,i),{force:!0}),{ok:!1,reason:`git commit timed out after ${t}ms`}}finally{clearTimeout(o)}},rE={"verify-failed":"verify-failed","tree-changed":"tree-changed"},nE=e=>{let t=e.blocked;return{branch:e.branch,status:rE[t.code]??"blocked",conflictPaths:e.conflictPaths,pushed:!1,reason:[`${t.code}: ${t.detail}`,...t.paths?[`(${t.paths.join(", ")})`]:[]].join(" "),blocked:t}},oE=async(e,t,r,n)=>{let o=r.worktreePath,s=(u,p,m={})=>({branch:t.branch,status:u,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 tE(o);if(!i.ok)return s("hook-failed",i.reason);let a=(await j(o,["rev-parse","HEAD"])).trim(),c=(await j(o,["rev-parse","HEAD^{tree}"])).trim();if(c!==t.treeSha)return r.unapprovedCommit=a,await rn(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 xg(o);if(l.length!==2||l[0]!==r.baseSha||l[1]!==r.devSha){let u={code:"parents-mismatch",detail:`commit parents are ${l.join(" ")}, expected ${r.baseSha} ${r.devSha}`};return s("blocked",`parents-mismatch: ${u.detail}`,{mergeSha:a,blocked:u})}return{sha:a}},sE=async(e,t,r)=>{let n=(c,l,u)=>({branch:t.branch,status:c,mergeSha:r,conflictPaths:t.conflictPaths,pushed:!1,...l?{reason:l}:{},...u?{blocked:u}:{}}),o;try{o=(await bo(e,[{branch:t.branch,sha:r}],t.devSha)).nowUpToDate}catch(c){let l={code:"parents-mismatch",detail:`origin/${t.branch}: ${So(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 De(e,`origin/${t.branch}`);if(s===t.baseSha)return"keep";let i=s!==null&&await jn(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)},iE=e=>{d.info(`
174
+ \u{1F4CB} Resolution preview:`);for(let t of e)t.blocked?d.info(` ${t.branch} \u2014 BLOCKED ${t.blocked.code}: ${t.blocked.detail}`):d.info(` ${t.branch} \u2014 ready${t.committed?" (already committed)":""}: tree ${t.treeSha}`)},Og=async e=>{let{cwd:t,versions:r,all:n,verify:o,trees:s=new Map,confirmedCommand:i}=e,a=await $g({cwd:t,versions:r,all:n});if(a.length===0)return d.info("\u2139\uFE0F No merge-dev resolutions in progress"),Ro();if(i)return yg(t,a,o,s);let c=[];for(let m of a){let f=await Ag(t,m,o);!f.blocked&&!f.committed&&f.treeSha&&(m.previewedTree=f.treeSha,await rn(t,m)),c.push(f)}iE(c);let l={branches:c},u=c.filter(m=>!m.blocked&&m.treeSha!==void 0);if(u.length===0)throw new C({status:"refused",plan:l,agentMode:_.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(u.map(m=>[m.branch,m.treeSha]));try{await L(i,`Commit and push the resolved merges for: ${[...p.keys()].join(", ")}?`,{plan:l,throwOnDecline:!0,rerun:aE(p)})}catch(m){if(!pt(m))throw m;return{...Ro(),declined:!0}}return yg(t,a,o,p)},Ig=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 g(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},aE=e=>{let t=[],r=!1;for(let o of km())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"]},cE=async(e,t,r,n)=>{let o=await Ag(e,t,r);if(o.blocked)return nE(o);let s=await oE(e,o,t,n);if(!("sha"in s))return s;let i=await sE(e,t,s.sha);return i==="keep"?s:i},lE=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}));d.info(`
175
+ \u2B06\uFE0F Pushing atomically: ${r.map(s=>s.branch).join(", ")}`);let n=await Is(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(-vg)}})}return{results:o,atomicPush:{attempted:!0,aborted:!n.pushed,abortedBy:n.stderr?.split(`
176
+ `)[0]}}},yg=async(e,t,r,n)=>{let o=[],s=[];for(let u of t){let p=await cE(e,u,r,n.get(u.branch));"sha"in p?s.push({record:u,sha:p.sha}):o.push(p)}let i=await lE(e,s),a=[...o,...i.results],c=t.filter(u=>a.some(p=>p.branch===u.branch&&(p.pushed||p.status==="up-to-date")));for(let u of c)await hl(e,u.branch,u.worktreePath);let l=t.map(u=>u.branch);return a.sort((u,p)=>l.indexOf(u.branch)-l.indexOf(p.branch)),{results:a,atomicPush:i.atomicPush,declined:!1}},Dg=async e=>{let{cwd:t,versions:r,all:n,confirmedCommand:o}=e,s=await $g({cwd:t,versions:r,all:n});if(s.length===0)return d.info("\u2139\uFE0F No merge-dev resolutions in progress"),Ro();let i={branches:s.map(a=>({branch:a.branch,worktreePath:a.worktreePath}))};try{await L(o,`Discard the resolution worktrees for: ${s.map(a=>a.branch).join(", ")}?`,{plan:i,throwOnDecline:!0})}catch(a){if(!pt(a))throw a;return{...Ro(),declined:!0}}for(let a of s)await hl(t,a.branch,a.worktreePath),d.info(`\u{1F5D1}\uFE0F Discarded the resolution for ${a.branch}`);return{...Ro(),results:s.map(a=>({branch:a.branch,status:"aborted",conflictPaths:a.conflictPaths,pushed:!1}))}};import uE from"node:fs";import dE from"node:os";import pE from"node:path";var mE="infra-kit.json",fE="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)",gE="Skipped agent-instruction files \u2014 no infra-kit.json at the repo root (the plugin pointer, the plugin install and .mcp.json are unaffected)",Eo=async()=>{let e;try{e=await P()}catch{return null}let t=e.trim();return t===""||t===dE.homedir()?null:t},Ng=async()=>{let e=await Eo();return e===null&&d.info(fE),e},hE=async()=>{let e=await Eo();return e===null?null:uE.existsSync(pE.join(e,mE))?e:(d.info(gE),null)};var yE=async e=>{try{return await Pe(e)}catch(t){return d.debug({err:t,msg:"Skipped per-package agent guidance \u2014 no workspace packages could be discovered."}),[]}},_g=async({dryRun:e=!1}={})=>{let t=await hE(),r=U.version;if(t===null)return{skipped:!0,root:null,version:r,written:[]};let n=[...await eo(t,{version:r,dryRun:e})];for(let o of await yE(t)){let s=await tr(o);n.push(...await to(o,{repoRoot:t,version:r,declaredType:s,dryRun:e}))}return{skipped:!1,root:t,version:r,written:n}};import ue from"node:fs";import bi from"node:os";import ee from"node:path";import Tl from"node:process";import yl from"node:fs";import Mg from"node:os";import jg from"node:path";import vE from"node:process";import{z as hi}from"zod";var Fg=e=>{try{return yl.readFileSync(e,"utf-8")}catch{return null}},nn="claude in chrome",wE="com.anthropic.claude_code_browser_extension",gi="run `/chrome` inside Claude Code to set up Claude in Chrome",kE={darwin:["Library","Application Support","Google","Chrome","NativeMessagingHosts"],linux:[".config","google-chrome","NativeMessagingHosts"]},bE=e=>{try{return yl.accessSync(e,yl.constants.X_OK),!0}catch{return!1}},Lg=e=>{try{return JSON.parse(e)}catch{return null}},RE=/^exec\s+(?<target>\S+)\s+--chrome-native-host\b/m,Po=(e={})=>{let t=e.platform??vE.platform,r=e.home??Mg.homedir(),n=e.readText??Fg,o=e.isExecutable??bE,s=kE[t];if(s===void 0)return{name:nn,status:"skip",message:`no Chrome native host location known for ${t}`};let i=jg.join(r,...s,`${wE}.json`),a=n(i);if(a===null)return{name:nn,status:"warn",message:`Chrome native host not registered \u2014 ${gi}`};let c=hi.object({path:hi.string().min(1)}).safeParse(Lg(a));if(!c.success)return{name:nn,status:"fail",message:`${v(i)} has no host path \u2014 ${gi} again`};let l=c.data.path;if(!o(l))return{name:nn,status:"fail",message:`Chrome native host ${v(l)} is missing or not executable \u2014 ${gi} again`};let u=RE.exec(n(l)??"")?.groups?.target;return u!==void 0&&!o(u)?{name:nn,status:"fail",message:`Chrome native host runs ${v(u)}, which no longer exists \u2014 ${gi} again`}:{name:nn,status:"pass",message:`Native host registered (${v(l)}); /infra-kit:doctor checks the live connection`}},vl=(e={})=>{let t=e.home??Mg.homedir(),r=e.readText??Fg,n=hi.object({claudeInChromeDefaultEnabled:hi.boolean().optional()}).safeParse(Lg(r(jg.join(t,".claude.json"))??""));return n.success&&n.data.claudeInChromeDefaultEnabled===!0};import vi from"node:fs/promises";import SE from"node:path";import EE from"node:process";var Bg=` // "envManagement": { // required in layer 1; provider-tagged
177
177
  // "provider": "doppler",
178
178
  // "config": { "name": "my-doppler-project" }
179
179
  // },
@@ -299,7 +299,7 @@ ${l}`:l}).join(""),c=ug.byteLength(a)>pg;return{diffStat:r,...o?{lockfileDiffSta
299
299
  // the committed project infra-kit.json (layer 1) and is usually NOT set in this
300
300
  // user-global layer \u2014 it is shown here only to document the full, valid config shape.
301
301
  {
302
- ${Lg}
302
+ ${Bg}
303
303
  }
304
304
  `,kl=e=>`// infra-kit user override for ${e} \u2014 ~/.infra-kit/projects/${e}/infra-kit.json
305
305
  //
@@ -317,7 +317,7 @@ ${Lg}
317
317
  // the committed project infra-kit.json (layer 1) and is usually NOT set in this
318
318
  // override layer \u2014 it is shown here only to document the full, valid config shape.
319
319
  {
320
- ${Lg}
320
+ ${Bg}
321
321
  }
322
322
  `,bl=()=>`// infra-kit factory registry \u2014 ~/.infra-kit/vendor.json
323
323
  //
@@ -331,102 +331,102 @@ ${Lg}
331
331
  // "source": "starter-workspace", // string \u2014 the one repo \`vendor sync\` copies from (its infra-kit.json holds vendorSource)
332
332
  // "targets": ["my-repo-a", "my-repo-b"] // string[] (>=1) \u2014 repo dir names resolved under workspaceDir
333
333
  }
334
- `;var Bg=!1,SE=e=>e.replace(/\.json$/,".example.jsonc"),EE=async e=>{try{return await vi.readFile(e,"utf-8")}catch{return null}},on=async e=>{let t=e.userProject,r=SE(t);await vi.mkdir(bE.dirname(t),{recursive:!0});let n=!await Z(t);n&&await vi.writeFile(t,`{}
335
- `,"utf-8");let o=kl(e.projectName),s=await EE(r)!==o;return s&&await vi.writeFile(r,o,"utf-8"),n&&jn(),{configPath:t,examplePath:r,createdConfig:n,refreshedExample:s}},sn=e=>`Created ${v(e.configPath)} \u2014 see ${v(e.examplePath)} for the annotated reference.`,Rl=async()=>{if(RE.env.INFRA_KIT_NO_SEED||Bg)return;Bg=!0;let e;try{e=await Y()}catch{return}if(await Z(e.main))try{let t=await on(e);t.createdConfig?d.info(sn(t)):t.refreshedExample&&d.debug(`Refreshed ${v(t.examplePath)} to match the current schema.`)}catch(t){d.debug({err:t,msg:`Skipped seeding ${v(e.userProject)} (config bootstrap failed).`})}};import{spawn as _E}from"node:child_process";import Yg from"node:fs";import un from"node:process";import{fileURLToPath as zg}from"node:url";import wi from"node:fs";import an from"node:path";var Ug="auto-setup.json",PE="auto-setup.log",xE="auto-setup.lock",Vg="auto-setup.notified",TE=3,CE=3600*1e3,$E=()=>an.join(dt(),Ug),cn=()=>an.join(dt(),PE),Wg=()=>an.join(dt(),xE),AE=()=>an.join(dt(),Vg),OE=new Set(["ok","attention","failed"]),IE=e=>{if(typeof e!="object"||e===null)return!1;let{root:t,status:r,notes:n}=e;return(t===null||typeof t=="string")&&typeof r=="string"&&OE.has(r)&&Array.isArray(n)&&n.every(o=>typeof o=="string")},DE=e=>{if(typeof e!="object"||e===null)return!1;let{version:t,attempts:r,startedMs:n,finishedMs:o,runs:s}=e;return typeof t=="string"&&typeof r=="number"&&Number.isInteger(r)&&typeof n=="number"&&Number.isFinite(n)&&(o===null||typeof o=="number"&&Number.isFinite(o))&&Array.isArray(s)&&s.every(IE)},ln=(e=t=>wi.readFileSync(t,"utf8"))=>{try{let t=JSON.parse(e($E()));return DE(t)?t:null}catch{return null}},Gg=e=>{let t=dt();wi.mkdirSync(t,{recursive:!0}),Rt(an.join(t,Ug),JSON.stringify(e),384)},NE=e=>e.finishedMs===null||e.runs.some(t=>t.status==="failed"),Jg=(e=t=>wi.readFileSync(t,"utf8"))=>{try{let t=Number(e(AE()).trim());return Number.isFinite(t)?t:null}catch{return null}},Kg=e=>{let t=dt();wi.mkdirSync(t,{recursive:!0}),Rt(an.join(t,Vg),String(e),384)},Hg=(e,t,r)=>{if(e===null)return!0;let n=r-e.startedMs;return n>=0&&n<CE?!1:e.version!==t?!0:NE(e)&&e.attempts<TE};var qg=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],Sl=e=>{let{argv:t,env:r,isTty:n,selfRealPath:o,cwd:s,realpath:i}=e;return qg.some(c=>{let l=r[c];return l!=null&&l!==""})?"opt-out":t.includes("--json")?"json":n?Cp(o,s,i)?"local-install":null:"not-a-tty"};var ME=e=>{_E(un.execPath,[e,"--parent-pid",String(un.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},jE=()=>zg(new URL("./update-check.js",import.meta.url)),FE=()=>Yg.realpathSync(zg(new URL("./cli.js",import.meta.url))),LE=/^[\w@./+ -]+$/,BE=e=>LE.test(e),UE=(e,t,r)=>{!e?.latestVersion||!e.updateCommand||Bn(e.latestVersion,t)&&e.updateCommand.every(BE)&&r(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${Ps(e.updateCommand)}`)},VE=(e,t,r,n,o)=>{if(e===null||e.finishedMs===null||e.version!==t||r===e.finishedMs)return;let s=e.runs.filter(c=>c.status==="failed").length,i=e.runs.filter(c=>c.status==="attention").length;if(s+i===0)return;let a=[s>0?`${s} failed`:null,i>0?`${i} need you`:null].filter(Boolean);n(`infra-kit ${e.version} background setup: ${a.join(", ")} \u2014 see ${v(cn())}, or run: infra-kit setup`),o(e.finishedMs)},El=(e,t={})=>{try{let r=t.argv??un.argv,n=t.env??un.env,o=t.isTty??!!un.stdout.isTTY,s=t.cwd??un.cwd(),i=t.nowMs??Date.now(),a=t.selfRealPath??FE(),c=t.readCache??Un,l=t.spawnChild??ME,u=t.fileExists??(y=>Yg.existsSync(y)),p=t.notify??(y=>{d.info(y)});if(Sl({argv:r,env:n,isTty:o,selfRealPath:a,cwd:s,realpath:ye})!==null)return;let m=c();UE(m,e,p);try{VE((t.readAutoSetup??ln)(),e,(t.readNotified??Jg)(),p,t.writeNotified??Kg)}catch{}if(!Ka(m,i))return;let f=t.childPath??jE();if(!u(f))return;l(f)}catch{}};import st from"node:fs/promises";import ot from"node:path";import{pathToFileURL as JE}from"node:url";import KE from"yaml";import{z as mn}from"zod";import WE from"node:fs/promises";import Pl from"node:os";import xl from"node:path";import{z as GE}from"zod";import{z as Po}from"zod";var Xg="vendor.json",Zg=Po.object({workspaceDir:Po.string().min(1),source:Po.string().min(1),targets:Po.array(Po.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 dn=()=>xl.join(Pl.homedir(),bp,Xg),pn=e=>{if(e==="~")return Pl.homedir();if(e.startsWith("~/"))return xl.join(Pl.homedir(),e.slice(2));if(xl.isAbsolute(e))return e;throw new Error(`workspaceDir must be absolute or ~-prefixed, got: ${e}`)},ki=async()=>{let e=dn(),t;try{t=await WE.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:
334
+ `;var Ug=!1,PE=e=>e.replace(/\.json$/,".example.jsonc"),xE=async e=>{try{return await vi.readFile(e,"utf-8")}catch{return null}},on=async e=>{let t=e.userProject,r=PE(t);await vi.mkdir(SE.dirname(t),{recursive:!0});let n=!await Z(t);n&&await vi.writeFile(t,`{}
335
+ `,"utf-8");let o=kl(e.projectName),s=await xE(r)!==o;return s&&await vi.writeFile(r,o,"utf-8"),n&&Fn(),{configPath:t,examplePath:r,createdConfig:n,refreshedExample:s}},sn=e=>`Created ${v(e.configPath)} \u2014 see ${v(e.examplePath)} for the annotated reference.`,Rl=async()=>{if(EE.env.INFRA_KIT_NO_SEED||Ug)return;Ug=!0;let e;try{e=await Y()}catch{return}if(await Z(e.main))try{let t=await on(e);t.createdConfig?d.info(sn(t)):t.refreshedExample&&d.debug(`Refreshed ${v(t.examplePath)} to match the current schema.`)}catch(t){d.debug({err:t,msg:`Skipped seeding ${v(e.userProject)} (config bootstrap failed).`})}};import{spawn as jE}from"node:child_process";import zg from"node:fs";import un from"node:process";import{fileURLToPath as Xg}from"node:url";import wi from"node:fs";import an from"node:path";var Vg="auto-setup.json",TE="auto-setup.log",CE="auto-setup.lock",Wg="auto-setup.notified",$E=3,AE=3600*1e3,OE=()=>an.join(dt(),Vg),cn=()=>an.join(dt(),TE),Gg=()=>an.join(dt(),CE),IE=()=>an.join(dt(),Wg),DE=new Set(["ok","attention","failed"]),NE=e=>{if(typeof e!="object"||e===null)return!1;let{root:t,status:r,notes:n}=e;return(t===null||typeof t=="string")&&typeof r=="string"&&DE.has(r)&&Array.isArray(n)&&n.every(o=>typeof o=="string")},_E=e=>{if(typeof e!="object"||e===null)return!1;let{version:t,attempts:r,startedMs:n,finishedMs:o,runs:s}=e;return typeof t=="string"&&typeof r=="number"&&Number.isInteger(r)&&typeof n=="number"&&Number.isFinite(n)&&(o===null||typeof o=="number"&&Number.isFinite(o))&&Array.isArray(s)&&s.every(NE)},ln=(e=t=>wi.readFileSync(t,"utf8"))=>{try{let t=JSON.parse(e(OE()));return _E(t)?t:null}catch{return null}},Jg=e=>{let t=dt();wi.mkdirSync(t,{recursive:!0}),Rt(an.join(t,Vg),JSON.stringify(e),384)},ME=e=>e.finishedMs===null||e.runs.some(t=>t.status==="failed"),Kg=(e=t=>wi.readFileSync(t,"utf8"))=>{try{let t=Number(e(IE()).trim());return Number.isFinite(t)?t:null}catch{return null}},Hg=e=>{let t=dt();wi.mkdirSync(t,{recursive:!0}),Rt(an.join(t,Wg),String(e),384)},qg=(e,t,r)=>{if(e===null)return!0;let n=r-e.startedMs;return n>=0&&n<AE?!1:e.version!==t?!0:ME(e)&&e.attempts<$E};var Yg=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],Sl=e=>{let{argv:t,env:r,isTty:n,selfRealPath:o,cwd:s,realpath:i}=e;return Yg.some(c=>{let l=r[c];return l!=null&&l!==""})?"opt-out":t.includes("--json")?"json":n?$p(o,s,i)?"local-install":null:"not-a-tty"};var FE=e=>{jE(un.execPath,[e,"--parent-pid",String(un.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},LE=()=>Xg(new URL("./update-check.js",import.meta.url)),BE=()=>zg.realpathSync(Xg(new URL("./cli.js",import.meta.url))),UE=/^[\w@./+ -]+$/,VE=e=>UE.test(e),WE=(e,t,r)=>{!e?.latestVersion||!e.updateCommand||Un(e.latestVersion,t)&&e.updateCommand.every(VE)&&r(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${Ps(e.updateCommand)}`)},GE=(e,t,r,n,o)=>{if(e===null||e.finishedMs===null||e.version!==t||r===e.finishedMs)return;let s=e.runs.filter(c=>c.status==="failed").length,i=e.runs.filter(c=>c.status==="attention").length;if(s+i===0)return;let a=[s>0?`${s} failed`:null,i>0?`${i} need you`:null].filter(Boolean);n(`infra-kit ${e.version} background setup: ${a.join(", ")} \u2014 see ${v(cn())}, or run: infra-kit setup`),o(e.finishedMs)},El=(e,t={})=>{try{let r=t.argv??un.argv,n=t.env??un.env,o=t.isTty??!!un.stdout.isTTY,s=t.cwd??un.cwd(),i=t.nowMs??Date.now(),a=t.selfRealPath??BE(),c=t.readCache??Vn,l=t.spawnChild??FE,u=t.fileExists??(y=>zg.existsSync(y)),p=t.notify??(y=>{d.info(y)});if(Sl({argv:r,env:n,isTty:o,selfRealPath:a,cwd:s,realpath:ve})!==null)return;let m=c();WE(m,e,p);try{GE((t.readAutoSetup??ln)(),e,(t.readNotified??Kg)(),p,t.writeNotified??Hg)}catch{}if(!Ka(m,i))return;let f=t.childPath??LE();if(!u(f))return;l(f)}catch{}};import it from"node:fs/promises";import st from"node:path";import{pathToFileURL as HE}from"node:url";import qE from"yaml";import{z as mn}from"zod";import JE from"node:fs/promises";import Pl from"node:os";import xl from"node:path";import{z as KE}from"zod";import{z as xo}from"zod";var Zg="vendor.json",Qg=xo.object({workspaceDir:xo.string().min(1),source:xo.string().min(1),targets:xo.array(xo.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 dn=()=>xl.join(Pl.homedir(),Rp,Zg),pn=e=>{if(e==="~")return Pl.homedir();if(e.startsWith("~/"))return xl.join(Pl.homedir(),e.slice(2));if(xl.isAbsolute(e))return e;throw new Error(`workspaceDir must be absolute or ~-prefixed, got: ${e}`)},ki=async()=>{let e=dn(),t;try{t=await JE.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:
336
336
 
337
337
  {
338
338
  "workspaceDir": "~/projects",
339
339
  "source": "my-starter",
340
340
  "targets": ["my-repo"]
341
341
  }
342
- `)}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=Zg.safeParse(r);if(!n.success)throw new Error(`Invalid factory config at ${e}: ${GE.prettifyError(n.error)}`);return n.data};var Qg=e=>e.replace(/\.json$/,".yml"),eh=async()=>{let e;try{e=await Y()}catch{return}let t={label:"infra-kit.json",yml:Qg(e.main),json:e.main,schema:fm},r=[...Ge.withheld?[]:[t],{label:"~/.infra-kit/infra-kit.json",yml:ot.join(ot.dirname(e.userGlobal),"config.yml"),json:e.userGlobal,schema:Ua},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:Qg(e.userProject),json:e.userProject,schema:Ua}],n=0;for(let o of r){let[s,i]=await Promise.all([Z(o.yml),Z(o.json)]);if(s){if(i){d.info(`\u26A0 Skipped ${v(o.yml)} \u2014 ${v(o.json)} already exists (remove the stale .yml manually)`);continue}try{let a=await st.readFile(o.yml,"utf-8"),c=KE.parse(a)??{},l=o.schema.safeParse(c);if(!l.success){d.info(`\u26A0 Skipped ${v(o.yml)} \u2014 invalid config: ${mn.prettifyError(l.error)}`);continue}await st.mkdir(ot.dirname(o.json),{recursive:!0}),await st.writeFile(o.json,`${JSON.stringify(l.data,null,2)}
343
- `,"utf-8"),await st.rm(o.yml,{force:!0}),d.info(`\u2713 Migrated ${v(o.yml)} \u2192 ${v(o.json)}`),n++}catch(a){d.info(`\u26A0 Skipped ${v(o.yml)} \u2014 ${a.message}`)}}}n>0&&Pt()},th=async()=>{let e;try{e=await Y()}catch{return}let t=ot.dirname(e.userGlobal),r=[{from:ot.join(t,"config.json"),to:e.userGlobal},{from:ot.join(t,"config.example.jsonc"),to:ot.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){d.info(`\u26A0 Skipped ${v(o)} \u2014 ${v(s)} already exists (remove the stale file manually)`);continue}try{await st.mkdir(ot.dirname(s),{recursive:!0}),await st.rename(o,s),d.info(`\u2713 Renamed ${v(o)} \u2192 ${v(s)}`),n++}catch(c){d.info(`\u26A0 Skipped ${v(o)} \u2014 ${c.message}`)}}}n>0&&Pt()},HE=mn.object({workspaceDir:mn.string().min(1),targets:mn.array(mn.string()).min(1)}).strict(),rh=async()=>{let e=dn(),t=ot.dirname(e),r=ot.join(t,"vendor.config.ts"),[n,o]=await Promise.all([Z(r),Z(e)]);if(n){if(o){d.info(`\u26A0 Skipped ${v(r)} \u2014 ${v(e)} already exists (remove the stale vendor.config.ts manually)`);return}try{let s=await st.stat(r),c=(await import(`${JE(r).href}?mtime=${Number(s.mtimeMs)}`)).default,l=typeof c=="function",u=l?await c():c,p=HE.safeParse(u);if(!p.success){d.info(`\u26A0 Skipped ${v(r)} \u2014 invalid factory config: ${mn.prettifyError(p.error)}`);return}await st.mkdir(t,{recursive:!0}),await st.writeFile(e,`${JSON.stringify(p.data,null,2)}
344
- `,"utf-8"),await st.rm(r,{force:!0}),l?d.info(`\u26A0 Migrated ${v(r)} \u2192 ${v(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 ${v(e)} directly to change them.`):d.info(`\u2713 Migrated ${v(r)} \u2192 ${v(e)}`)}catch(s){d.info(`\u26A0 Skipped ${v(r)} \u2014 ${s.message}`)}}},nh=async()=>{let e=await qE(),t=0;for(let r of e)if(await Z(r))try{let n=await lm(r);if(!n.changed)continue;d.info(`\u2713 Migrated ${v(r)} (removed ${n.notes.join(" and ")})`),t++}catch(n){let o=n instanceof am?"changed while migrating":n.message;d.info(`\u26A0 Skipped ${v(r)} \u2014 ${o}`)}t>0&&Pt()},qE=async()=>{try{let e=await Y();return Ge.withheld?[e.userGlobal,e.userProject]:[e.main,e.userGlobal,e.userProject]}catch{return[hm()]}};var lr="# -- infra-kit:begin --",Ft="# -- infra-kit:end --",YE=[["# region infra-kit","# endregion infra-kit"]],zE="# infra-kit shell functions",fn=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},gn="Run `source ~/.zshrc` or open a new terminal to activate.",XE={step:"migrations",outcome:"unchanged",message:"Config migrations checked (legacy yml layers, user-global filename, ide structure, factory config, retired project cache)",level:"silent"},Fe=async(e,t)=>{try{return await t()}catch(r){throw new fn(e,r)}},Cl=async e=>{let t=[],r=(...s)=>{for(let i of s)t.push(i),e?.(i)};await Fe("zshrc",()=>{r(eP())}),await Fe("zshenv",()=>{r(tP())}),await Fe("migrations",async()=>{await nP(),rP(),r(XE)}),await Fe("user-config",()=>{r(sP())});let n=await Fe("guidance",async()=>{let{entries:s,root:i}=await lP();return r(...s),i}),o=await Fe("plugin-pointer",async()=>Dg());return r(...dP(o,n)),await Fe("worktrees",async()=>{r(...await hP(o))}),await Fe("plugin-pointer",async()=>{await vP(o,r)}),await Fe("mcp-proxies",async()=>{r(...await kP(o))}),await Fe("project-config",async()=>{r(...await iP(o))}),await Fe("token-perms",async()=>{r(await QE())}),await Fe("chrome",()=>{r(ZE())}),r(...oP()),t},ZE=()=>{let e=Eo();return e.status==="skip"?{step:"chrome",outcome:"skipped",message:e.message,level:"debug"}:e.status!=="pass"?{step:"chrome",outcome:"manual",message:`${e.message}, then choose "Enabled by default"`,level:"info"}:vl()?{step:"chrome",outcome:"unchanged",message:"Claude in Chrome is set up and enabled by default",level:"debug"}:{step:"chrome",outcome:"manual",message:'Claude in Chrome is set up but off by default \u2014 run `/chrome` inside Claude Code and choose "Enabled by default"',level:"info"}},QE=async()=>{let e=await Em();return e===null?{step:"token-perms",outcome:"skipped",message:"No token store to protect",level:"debug"}:e.length===0?{step:"token-perms",outcome:"unchanged",message:"Token store is 0600 (0700 dirs)",level:"debug"}:{step:"token-perms",outcome:"written",message:`Tightened the token store to 0600 (0700 dirs): ${e.join("; ")}`,level:"info"}};var sh=e=>{let t=ee.dirname(e);return ue.existsSync(ee.join(e,".git"))?e:t===e?null:sh(t)},ih=(e,t,r,n)=>{if(!Ge.withheld)return null;if(r===n)return{step:e,outcome:"unchanged",message:`Managed block in ${t} is up to date`,level:"debug"};let o=t;try{o=ue.realpathSync(t)}catch{}return sh(ee.dirname(o))===null?null:To(e,bi.homedir(),o,["the infra-kit block updated"])},ah=e=>ue.existsSync(e)?ue.readFileSync(e,"utf-8"):null,eP=()=>{let e=ee.join(bi.homedir(),".zshrc"),t=ah(e),r=t===null?"":RP(t),n=Nr({content:r,body:uh(),startMarker:lr,endMarker:Ft,placement:"append-end"}),o=ih("zshrc",e,t,n);return o!==null?o:(ue.writeFileSync(e,n),{step:"zshrc",outcome:"written",message:`Added infra-kit shell functions to ${e}`,level:"info"})},tP=()=>{let e=ee.join(bi.homedir(),".zshenv"),t=ah(e),r=Nr({content:t??"",body:$l(),startMarker:lr,endMarker:Ft}),n=ih("zshenv",e,t,r);return n!==null?n:(ue.writeFileSync(e,r),{step:"zshenv",outcome:"written",message:`Added infra-kit session-env block to ${e}`,level:"info"})},rP=()=>{ue.rmSync(ee.join(dt(),"projects"),{recursive:!0,force:!0})},nP=async()=>{await eh(),await th(),await nh(),await rh()},oP=()=>{let e=Tl.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:gn,level:"info"}),t},sP=()=>{let e=ee.join(bi.homedir(),".infra-kit"),t=ee.join(e,"infra-kit.json");return ue.mkdirSync(e,{recursive:!0}),ue.writeFileSync(ee.join(e,"infra-kit.example.jsonc"),wl(),"utf-8"),ue.writeFileSync(ee.join(e,"vendor.example.jsonc"),bl(),"utf-8"),ue.existsSync(t)?{step:"user-config",outcome:"unchanged",message:`User-global config already present at ${t} (refreshed reference examples)`,level:"info"}:(ue.writeFileSync(t,`{}
345
- `,"utf-8"),{step:"user-config",outcome:"written",message:`Wrote user-global config to ${t} (see the sibling .example.jsonc files for reference)`,level:"info"})},iP=async e=>{if(Tl.env.INFRA_KIT_NO_SEED)return[xo("skipped","INFRA_KIT_NO_SEED is set")];if(e===null)return[xo("skipped","not inside a git repository")];try{let t=await Y();if(!ue.existsSync(t.main))return[xo("skipped",`no project config at ${t.main}`)];let r=await on(t);return r.createdConfig?[{step:"project-config",outcome:"written",message:sn(r),level:"info"}]:[xo("unchanged","the user-project config was already present")]}catch(t){return d.debug({err:t,msg:"Skipped seeding the user-project config (init)."}),[xo("warned",t instanceof Error?t.message:String(t))]}},xo=(e,t)=>({step:"project-config",outcome:e,message:`Skipped seeding the user-project config \u2014 ${t}`,level:"silent"}),aP=e=>{let t=[];return e.some(r=>r.type===void 0)&&t.push("infra-kit audit --fix --root"),e.some(r=>r.type!==void 0)&&t.push("infra-kit audit --fix --all"),t},cP=(e,t)=>{let r=t.filter(s=>s.action==="failed"),n=t.filter(s=>s.action!=="unchanged"&&s.action!=="failed"),o=[];return n.length===0?o.push({step:"guidance",outcome:"unchanged",message:`Agent-instruction files current (infra-kit ${e})`,level:"info"}):o.push({step:"guidance",outcome:"skipped",message:`${n.length} agent-instruction files differ from infra-kit ${e} \u2014 setup does not rewrite them; run:`,level:"info"},...aP(n).map(s=>({step:"guidance",outcome:"manual",message:s,level:"info"}))),r.length>0&&o.push({step:"guidance",outcome:"warned",message:`${r.length} agent-instruction files could not be checked \u2014 run: infra-kit audit --root && infra-kit audit --all`,level:"warn"}),o},lP=async()=>{let{skipped:e,root:t,version:r,written:n}=await Ng({dryRun:!0});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:cP(r,n)}},Ri=e=>`cd ${Op(e)} && infra-kit setup --skip-tools`,To=(e,t,r,n)=>({step:e,outcome:"manual",message:`${r} needs ${n.join(", ")} \u2014 left for a human to commit; run: ${Ri(t)}`,level:"info"}),uP=(e,t)=>{let r=ee.relative(e,t.path);return t.status==="withheld"?To("plugin-pointer",e,r,t.added):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"}},oh=(e,t)=>{let r=Me;if(t.kind==="stale"||t.kind==="wrong-key"){let o=t.kind==="stale"?oe: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 ${et} from ${ee.join(e,Me)} \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 "${oe}" key`:`no ${r}`})`,level:"info"}},dP=(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 ${G} plugin for that project. If that is not the repo you meant to set up, revert that file and uninstall the plugin.`,level:"warn"}],pP=()=>[_c,ft].map(e=>({step:"plugin-pointer",outcome:"manual",message:e,level:"info"})),mP=e=>{let r={step:"plugin-pointer",outcome:"warned",message:`Claude Code plugin not updated \u2014 ${e.stale?`CLI ${U.version} is behind ${e.latestVersion}, update it first with the command below`:`CLI ${U.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:Ps(e.updateCommand),level:"info"}]:[r]},fP=(e,t)=>e.status==="skipped-cli-stale"?mP(t):e.status==="updated"?[{step:"plugin-pointer",outcome:"unchanged",message:`Claude Code plugin ${G} 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: ${Wr}`,level:"warn"}]:e.status==="installed"?[{step:"plugin-pointer",outcome:"written",message:`installed Claude Code plugin ${G} (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"},...pP()]:[{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: ${ft}`,level:"warn"}],ch={stale:!1},gP=async()=>{let e=Un(),t=e===null?await qa(Tl.env):e.latestVersion;return t===null||!Ya(t,U.version)?ch:{stale:!0,latestVersion:t,updateCommand:e?.updateCommand??Tp(t)}},hP=async e=>{if(e===null)return[];let r=`${await Re(e)}${le}`,n=Object.values(Cr).filter(o=>!ue.existsSync(ee.join(r,o)));for(let o of Object.values(Cr))ue.mkdirSync(ee.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"}]},yP=(e,t)=>t?[{step:"plugin-pointer",outcome:"skipped",message:`Claude Code plugin ${G} is installed; the update worker keeps it current`,level:"debug"}]:[To("plugin-pointer",e,".claude/settings.json",[`the ${G} plugin installed`])],vP=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(uP(e,Mc(ee.join(e,".claude","settings.json"),{write:!Ge.withheld})));let r=Xt({projectPath:e}).kind==="installed";if(Ge.withheld){t(...yP(e,r),oh(e,Vr(e)));return}let n=r?await gP():ch;t(...fP(Ac({projectRoot:e,cliIsStale:()=>n.stale}),n)),t(oh(e,Vr(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: ${ft}`,level:"warn"})}},lh=(e,t)=>{let r=ee.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},wP=(e,t)=>{let r=t.entries.filter(i=>i.status==="drifted"),n=t.entries.filter(i=>i.status!=="drifted"),o=lh(e,{...t,entries:n});if(t.status!=="ok"||r.length===0)return o;let s=r.map(i=>`ik-mcp "${i.name}"`);return[...o,To("mcp-proxies",e,ee.relative(e,t.path),s)]},kP=async e=>{if(e===null)return[];if(!ue.existsSync(ee.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 W()).mcp}catch(r){let n=r instanceof Error?r.message:String(r),o=n.split(`
346
- `)[0]??n;return Ge.withheld?[To("mcp-proxies",e,"infra-kit.json",[`a config fix or migration (${o})`])]:[{step:"mcp-proxies",outcome:"warned",message:` ik-mcp entries not synced \u2014 infra-kit.json could not be loaded (${o})`,level:"warn"}]}return!t||Object.keys(t).length===0?[]:Ge.withheld?wP(e,oo({projectRoot:e,proxies:t,write:!1})):lh(e,oo({projectRoot:e,proxies:t,write:!0}))},bP=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"),RP=e=>{let t=Dt(e,lr,Ft);if(t!==null)return t;for(let[a,c]of YE){let l=Dt(e,a,c);if(l!==null)return l}let r=e.indexOf(zE);if(r===-1)return e;let n=e.slice(0,r).replace(/\n+$/,""),o=e.slice(r).split(`
347
- `),s=0;for(;s<o.length&&bP(o[s]);)s++;let i=o.slice(s).join(`
342
+ `)}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=Qg.safeParse(r);if(!n.success)throw new Error(`Invalid factory config at ${e}: ${KE.prettifyError(n.error)}`);return n.data};var eh=e=>e.replace(/\.json$/,".yml"),th=async()=>{let e;try{e=await Y()}catch{return}let t={label:"infra-kit.json",yml:eh(e.main),json:e.main,schema:gm},r=[...Ge.withheld?[]:[t],{label:"~/.infra-kit/infra-kit.json",yml:st.join(st.dirname(e.userGlobal),"config.yml"),json:e.userGlobal,schema:Ua},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:eh(e.userProject),json:e.userProject,schema:Ua}],n=0;for(let o of r){let[s,i]=await Promise.all([Z(o.yml),Z(o.json)]);if(s){if(i){d.info(`\u26A0 Skipped ${v(o.yml)} \u2014 ${v(o.json)} already exists (remove the stale .yml manually)`);continue}try{let a=await it.readFile(o.yml,"utf-8"),c=qE.parse(a)??{},l=o.schema.safeParse(c);if(!l.success){d.info(`\u26A0 Skipped ${v(o.yml)} \u2014 invalid config: ${mn.prettifyError(l.error)}`);continue}await it.mkdir(st.dirname(o.json),{recursive:!0}),await it.writeFile(o.json,`${JSON.stringify(l.data,null,2)}
343
+ `,"utf-8"),await it.rm(o.yml,{force:!0}),d.info(`\u2713 Migrated ${v(o.yml)} \u2192 ${v(o.json)}`),n++}catch(a){d.info(`\u26A0 Skipped ${v(o.yml)} \u2014 ${a.message}`)}}}n>0&&Pt()},rh=async()=>{let e;try{e=await Y()}catch{return}let t=st.dirname(e.userGlobal),r=[{from:st.join(t,"config.json"),to:e.userGlobal},{from:st.join(t,"config.example.jsonc"),to:st.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){d.info(`\u26A0 Skipped ${v(o)} \u2014 ${v(s)} already exists (remove the stale file manually)`);continue}try{await it.mkdir(st.dirname(s),{recursive:!0}),await it.rename(o,s),d.info(`\u2713 Renamed ${v(o)} \u2192 ${v(s)}`),n++}catch(c){d.info(`\u26A0 Skipped ${v(o)} \u2014 ${c.message}`)}}}n>0&&Pt()},YE=mn.object({workspaceDir:mn.string().min(1),targets:mn.array(mn.string()).min(1)}).strict(),nh=async()=>{let e=dn(),t=st.dirname(e),r=st.join(t,"vendor.config.ts"),[n,o]=await Promise.all([Z(r),Z(e)]);if(n){if(o){d.info(`\u26A0 Skipped ${v(r)} \u2014 ${v(e)} already exists (remove the stale vendor.config.ts manually)`);return}try{let s=await it.stat(r),c=(await import(`${HE(r).href}?mtime=${Number(s.mtimeMs)}`)).default,l=typeof c=="function",u=l?await c():c,p=YE.safeParse(u);if(!p.success){d.info(`\u26A0 Skipped ${v(r)} \u2014 invalid factory config: ${mn.prettifyError(p.error)}`);return}await it.mkdir(t,{recursive:!0}),await it.writeFile(e,`${JSON.stringify(p.data,null,2)}
344
+ `,"utf-8"),await it.rm(r,{force:!0}),l?d.info(`\u26A0 Migrated ${v(r)} \u2192 ${v(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 ${v(e)} directly to change them.`):d.info(`\u2713 Migrated ${v(r)} \u2192 ${v(e)}`)}catch(s){d.info(`\u26A0 Skipped ${v(r)} \u2014 ${s.message}`)}}},oh=async()=>{let e=await zE(),t=0;for(let r of e)if(await Z(r))try{let n=await um(r);if(!n.changed)continue;d.info(`\u2713 Migrated ${v(r)} (removed ${n.notes.join(" and ")})`),t++}catch(n){let o=n instanceof cm?"changed while migrating":n.message;d.info(`\u26A0 Skipped ${v(r)} \u2014 ${o}`)}t>0&&Pt()},zE=async()=>{try{let e=await Y();return Ge.withheld?[e.userGlobal,e.userProject]:[e.main,e.userGlobal,e.userProject]}catch{return[ym()]}};var lr="# -- infra-kit:begin --",Ft="# -- infra-kit:end --",XE=[["# region infra-kit","# endregion infra-kit"]],ZE="# infra-kit shell functions",fn=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},gn="Run `source ~/.zshrc` or open a new terminal to activate.",QE={step:"migrations",outcome:"unchanged",message:"Config migrations checked (legacy yml layers, user-global filename, ide structure, factory config, retired project cache)",level:"silent"},Fe=async(e,t)=>{try{return await t()}catch(r){throw new fn(e,r)}},Cl=async e=>{let t=[],r=(...s)=>{for(let i of s)t.push(i),e?.(i)};await Fe("zshrc",()=>{r(rP())}),await Fe("zshenv",()=>{r(nP())}),await Fe("migrations",async()=>{await sP(),oP(),r(QE)}),await Fe("user-config",()=>{r(aP())});let n=await Fe("guidance",async()=>{let{entries:s,root:i}=await dP();return r(...s),i}),o=await Fe("plugin-pointer",async()=>Ng());return r(...mP(o,n)),await Fe("worktrees",async()=>{r(...await vP(o))}),await Fe("plugin-pointer",async()=>{await kP(o,r)}),await Fe("mcp-proxies",async()=>{r(...await RP(o))}),await Fe("project-config",async()=>{r(...await cP(o))}),await Fe("token-perms",async()=>{r(await tP())}),await Fe("chrome",()=>{r(eP())}),r(...iP()),t},eP=()=>{let e=Po();return e.status==="skip"?{step:"chrome",outcome:"skipped",message:e.message,level:"debug"}:e.status!=="pass"?{step:"chrome",outcome:"manual",message:`${e.message}, then choose "Enabled by default"`,level:"info"}:vl()?{step:"chrome",outcome:"unchanged",message:"Claude in Chrome is set up and enabled by default",level:"debug"}:{step:"chrome",outcome:"manual",message:'Claude in Chrome is set up but off by default \u2014 run `/chrome` inside Claude Code and choose "Enabled by default"',level:"info"}},tP=async()=>{let e=await Pm();return e===null?{step:"token-perms",outcome:"skipped",message:"No token store to protect",level:"debug"}:e.length===0?{step:"token-perms",outcome:"unchanged",message:"Token store is 0600 (0700 dirs)",level:"debug"}:{step:"token-perms",outcome:"written",message:`Tightened the token store to 0600 (0700 dirs): ${e.join("; ")}`,level:"info"}};var ih=e=>{let t=ee.dirname(e);return ue.existsSync(ee.join(e,".git"))?e:t===e?null:ih(t)},ah=(e,t,r,n)=>{if(!Ge.withheld)return null;if(r===n)return{step:e,outcome:"unchanged",message:`Managed block in ${t} is up to date`,level:"debug"};let o=t;try{o=ue.realpathSync(t)}catch{}return ih(ee.dirname(o))===null?null:Co(e,bi.homedir(),o,["the infra-kit block updated"])},ch=e=>ue.existsSync(e)?ue.readFileSync(e,"utf-8"):null,rP=()=>{let e=ee.join(bi.homedir(),".zshrc"),t=ch(e),r=t===null?"":EP(t),n=Nr({content:r,body:dh(),startMarker:lr,endMarker:Ft,placement:"append-end"}),o=ah("zshrc",e,t,n);return o!==null?o:(ue.writeFileSync(e,n),{step:"zshrc",outcome:"written",message:`Added infra-kit shell functions to ${e}`,level:"info"})},nP=()=>{let e=ee.join(bi.homedir(),".zshenv"),t=ch(e),r=Nr({content:t??"",body:$l(),startMarker:lr,endMarker:Ft}),n=ah("zshenv",e,t,r);return n!==null?n:(ue.writeFileSync(e,r),{step:"zshenv",outcome:"written",message:`Added infra-kit session-env block to ${e}`,level:"info"})},oP=()=>{ue.rmSync(ee.join(dt(),"projects"),{recursive:!0,force:!0})},sP=async()=>{await th(),await rh(),await oh(),await nh()},iP=()=>{let e=Tl.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:gn,level:"info"}),t},aP=()=>{let e=ee.join(bi.homedir(),".infra-kit"),t=ee.join(e,"infra-kit.json");return ue.mkdirSync(e,{recursive:!0}),ue.writeFileSync(ee.join(e,"infra-kit.example.jsonc"),wl(),"utf-8"),ue.writeFileSync(ee.join(e,"vendor.example.jsonc"),bl(),"utf-8"),ue.existsSync(t)?{step:"user-config",outcome:"unchanged",message:`User-global config already present at ${t} (refreshed reference examples)`,level:"info"}:(ue.writeFileSync(t,`{}
345
+ `,"utf-8"),{step:"user-config",outcome:"written",message:`Wrote user-global config to ${t} (see the sibling .example.jsonc files for reference)`,level:"info"})},cP=async e=>{if(Tl.env.INFRA_KIT_NO_SEED)return[To("skipped","INFRA_KIT_NO_SEED is set")];if(e===null)return[To("skipped","not inside a git repository")];try{let t=await Y();if(!ue.existsSync(t.main))return[To("skipped",`no project config at ${t.main}`)];let r=await on(t);return r.createdConfig?[{step:"project-config",outcome:"written",message:sn(r),level:"info"}]:[To("unchanged","the user-project config was already present")]}catch(t){return d.debug({err:t,msg:"Skipped seeding the user-project config (init)."}),[To("warned",t instanceof Error?t.message:String(t))]}},To=(e,t)=>({step:"project-config",outcome:e,message:`Skipped seeding the user-project config \u2014 ${t}`,level:"silent"}),lP=e=>{let t=[];return e.some(r=>r.type===void 0)&&t.push("infra-kit audit --fix --root"),e.some(r=>r.type!==void 0)&&t.push("infra-kit audit --fix --all"),t},uP=(e,t)=>{let r=t.filter(s=>s.action==="failed"),n=t.filter(s=>s.action!=="unchanged"&&s.action!=="failed"),o=[];return n.length===0?o.push({step:"guidance",outcome:"unchanged",message:`Agent-instruction files current (infra-kit ${e})`,level:"info"}):o.push({step:"guidance",outcome:"skipped",message:`${n.length} agent-instruction files differ from infra-kit ${e} \u2014 setup does not rewrite them; run:`,level:"info"},...lP(n).map(s=>({step:"guidance",outcome:"manual",message:s,level:"info"}))),r.length>0&&o.push({step:"guidance",outcome:"warned",message:`${r.length} agent-instruction files could not be checked \u2014 run: infra-kit audit --root && infra-kit audit --all`,level:"warn"}),o},dP=async()=>{let{skipped:e,root:t,version:r,written:n}=await _g({dryRun:!0});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:uP(r,n)}},Ri=e=>`cd ${Ip(e)} && infra-kit setup --skip-tools`,Co=(e,t,r,n)=>({step:e,outcome:"manual",message:`${r} needs ${n.join(", ")} \u2014 left for a human to commit; run: ${Ri(t)}`,level:"info"}),pP=(e,t)=>{let r=ee.relative(e,t.path);return t.status==="withheld"?Co("plugin-pointer",e,r,t.added):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"}},sh=(e,t)=>{let r=Me;if(t.kind==="stale"||t.kind==="wrong-key"){let o=t.kind==="stale"?oe: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 ${tt} from ${ee.join(e,Me)} \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 "${oe}" key`:`no ${r}`})`,level:"info"}},mP=(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 ${G} plugin for that project. If that is not the repo you meant to set up, revert that file and uninstall the plugin.`,level:"warn"}],fP=()=>[_c,ft].map(e=>({step:"plugin-pointer",outcome:"manual",message:e,level:"info"})),gP=e=>{let r={step:"plugin-pointer",outcome:"warned",message:`Claude Code plugin not updated \u2014 ${e.stale?`CLI ${U.version} is behind ${e.latestVersion}, update it first with the command below`:`CLI ${U.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:Ps(e.updateCommand),level:"info"}]:[r]},hP=(e,t)=>e.status==="skipped-cli-stale"?gP(t):e.status==="updated"?[{step:"plugin-pointer",outcome:"unchanged",message:`Claude Code plugin ${G} 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: ${Wr}`,level:"warn"}]:e.status==="installed"?[{step:"plugin-pointer",outcome:"written",message:`installed Claude Code plugin ${G} (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"},...fP()]:[{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: ${ft}`,level:"warn"}],lh={stale:!1},yP=async()=>{let e=Vn(),t=e===null?await qa(Tl.env):e.latestVersion;return t===null||!Ya(t,U.version)?lh:{stale:!0,latestVersion:t,updateCommand:e?.updateCommand??Cp(t)}},vP=async e=>{if(e===null)return[];let r=`${await Re(e)}${le}`,n=Object.values(Cr).filter(o=>!ue.existsSync(ee.join(r,o)));for(let o of Object.values(Cr))ue.mkdirSync(ee.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"}]},wP=(e,t)=>t?[{step:"plugin-pointer",outcome:"skipped",message:`Claude Code plugin ${G} is installed; the update worker keeps it current`,level:"debug"}]:[Co("plugin-pointer",e,".claude/settings.json",[`the ${G} plugin installed`])],kP=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(pP(e,Mc(ee.join(e,".claude","settings.json"),{write:!Ge.withheld})));let r=Xt({projectPath:e}).kind==="installed";if(Ge.withheld){t(...wP(e,r),sh(e,Vr(e)));return}let n=r?await yP():lh;t(...hP(Ac({projectRoot:e,cliIsStale:()=>n.stale}),n)),t(sh(e,Vr(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: ${ft}`,level:"warn"})}},uh=(e,t)=>{let r=ee.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},bP=(e,t)=>{let r=t.entries.filter(i=>i.status==="drifted"),n=t.entries.filter(i=>i.status!=="drifted"),o=uh(e,{...t,entries:n});if(t.status!=="ok"||r.length===0)return o;let s=r.map(i=>`ik-mcp "${i.name}"`);return[...o,Co("mcp-proxies",e,ee.relative(e,t.path),s)]},RP=async e=>{if(e===null)return[];if(!ue.existsSync(ee.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 W()).mcp}catch(r){let n=r instanceof Error?r.message:String(r),o=n.split(`
346
+ `)[0]??n;return Ge.withheld?[Co("mcp-proxies",e,"infra-kit.json",[`a config fix or migration (${o})`])]:[{step:"mcp-proxies",outcome:"warned",message:` ik-mcp entries not synced \u2014 infra-kit.json could not be loaded (${o})`,level:"warn"}]}return!t||Object.keys(t).length===0?[]:Ge.withheld?bP(e,so({projectRoot:e,proxies:t,write:!1})):uh(e,so({projectRoot:e,proxies:t,write:!0}))},SP=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"),EP=e=>{let t=Dt(e,lr,Ft);if(t!==null)return t;for(let[a,c]of XE){let l=Dt(e,a,c);if(l!==null)return l}let r=e.indexOf(ZE);if(r===-1)return e;let n=e.slice(0,r).replace(/\n+$/,""),o=e.slice(r).split(`
347
+ `),s=0;for(;s<o.length&&SP(o[s]);)s++;let i=o.slice(s).join(`
348
348
  `);return n+(i?`
349
- ${i}`:"")},uh=()=>{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(`
350
- `)},dh=()=>`${lr}
351
- ${uh()}
349
+ ${i}`:"")},dh=()=>{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(`
350
+ `)},ph=()=>`${lr}
351
+ ${dh()}
352
352
  ${Ft}`,$l=()=>["# 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.","# A load applies only at or under a directory its env-load.root names (no file: anywhere).","# 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',' local _ik_roots="$_ik_dir/env-load.root" _ik_pwd=${PWD:A} _ik_root',' if [[ -r "$_ik_roots" ]]; then',' for _ik_root in "${(@f)$(<$_ik_roots)}"; do',' [[ -n "$_ik_root" && ( "$_ik_pwd" == "$_ik_root" || "$_ik_pwd" == "$_ik_root"/* ) ]] && break'," _ik_root="," done",' [[ -n "$_ik_root" ]] || return'," fi",' source "$_ik_load"',' elif [[ -r "$_ik_clear" ]]; then',' source "$_ik_clear"'," fi"," }","fi"].join(`
353
353
  `),Al=()=>`${lr}
354
354
  ${$l()}
355
- ${Ft}`;import SP from"node:fs/promises";var Co=async(e,t)=>{if(!t)return{hasOverrides:!1,overrideKeys:[],unreadable:!1};try{let r=await SP.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}}},$o=e=>e.unreadable?"(unreadable \u2014 invalid JSON)":e.overrideKeys.length===0?"(empty \u2014 no overrides)":`(${e.overrideKeys.length} override(s): ${e.overrideKeys.join(", ")})`;import PP from"node:fs";import xP from"node:os";import ph from"node:path";import TP from"node:process";import{$ as EP}from"zx";var hn=()=>EP({quiet:!0});var CP=()=>[ph.join(xP.homedir(),".local","bin"),"/opt/homebrew/bin","/usr/local/bin"],$P=async e=>{try{return(await hn()`command -v ${e}`).stdout.trim()||null}catch{return null}},Ao=()=>({runCommand:async e=>{let t=await hn()`${e}`;return{stdout:`${t.stdout}
356
- ${t.stderr}`}},resolveBinPath:async e=>{let t=await $P(e);return t!==null?t:CP().map(r=>ph.join(r,e)).find(r=>PP.existsSync(r))??null},realpath:ye,platform:TP.platform});var Lt=(...e)=>({steps:e,needsSudo:!1,fetchesNetworkScript:!1}),yn=e=>/\d{1,10}\.\d{1,10}\.\d{1,10}/.exec(e)?.[0]??null,vn=["darwin","linux"],xi=e=>t=>_a(t,e)?"homebrew":"unknown",Ti=(e,t)=>r=>r===null?null:t(e(r),r),Il=e=>Ti(xi(e.kegName),t=>t==="homebrew"?Lt(["brew","upgrade",e.brewFormula]):null),mh=e=>Es(e,"Homebrew")||Es(e,"homebrew")?"homebrew":"unknown",AP={id:"brew",binName:"brew",probeArgv:["brew","--version"],versionFrom:yn,platforms:vn,prerequisites:[],bootstrapInstall:{steps:[["/bin/bash","-c","$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"]],needsSudo:!0,fetchesNetworkScript:!0},identify:mh,updateFor:Ti(mh,e=>e==="homebrew"?Lt(["brew","update"]):null)},Ol={brewFormula:"awscli",brewInstallSpec:"awscli",kegName:"awscli"},hh="https://awscli.amazonaws.com/v2/install.sh",yh={steps:[["/bin/bash","-c",`curl -fsSL ${hh} | bash`]],needsSudo:!1,fetchesNetworkScript:!0},OP="/usr/local/aws-cli",IP=e=>Dn(OP,e,ye)?{steps:[["sudo","/bin/bash","-c",`curl -fsSL ${hh} | bash -s -- --system`]],needsSudo:!0,fetchesNetworkScript:!0}:yh,fh=e=>_a(e,Ol.kegName)?"homebrew":Es(e,"aws-cli")?"script":"unknown",DP={id:"aws",binName:"aws",...Ol,probeArgv:["aws","--version"],versionFrom:yn,platforms:vn,prerequisites:[],bootstrapInstall:yh,identify:fh,updateFor:Ti(fh,(e,t)=>e==="homebrew"?Lt(["brew","upgrade",Ol.brewFormula]):e==="script"?IP(t):null)},Si={brewFormula:"git",brewInstallSpec:"git",kegName:"git"},NP={id:"git",binName:"git",...Si,probeArgv:["git","--version"],versionFrom:yn,platforms:vn,prerequisites:["brew"],bootstrapInstall:Lt(["brew","install",Si.brewInstallSpec]),identify:xi(Si.kegName),updateFor:Il(Si)},Ei={brewFormula:"gh",brewInstallSpec:"gh",kegName:"gh"},_P={id:"gh",binName:"gh",...Ei,probeArgv:["gh","--version"],versionFrom:yn,platforms:vn,prerequisites:["brew"],bootstrapInstall:Lt(["brew","install",Ei.brewInstallSpec]),identify:xi(Ei.kegName),updateFor:Il(Ei)},Pi={brewFormula:"doppler",brewInstallSpec:"dopplerhq/cli/doppler",kegName:"doppler"},MP={id:"doppler",binName:"doppler",...Pi,probeArgv:["doppler","--version"],versionFrom:yn,platforms:vn,prerequisites:["brew"],bootstrapInstall:Lt(["brew","install","gnupg"],["brew","install",Pi.brewInstallSpec]),identify:xi(Pi.kegName),updateFor:Il(Pi)},Oo="portless",gh=e=>xp(e,Oo)===null?"unknown":"npm",jP={id:"portless",binName:Oo,npmPackage:Oo,probeArgv:["portless","--version"],versionFrom:yn,platforms:[...vn,"win32"],prerequisites:[],bootstrapInstall:Lt(["npm","install","-g",Oo]),identify:gh,updateFor:Ti(gh,e=>e==="npm"?Lt(["npm","install","-g",`${Oo}@latest`]):null)},Dl={brew:AP,git:NP,aws:DP,gh:_P,doppler:MP,portless:jP},ur=Object.keys(Dl),Le=e=>Dl[e],Nl=(e,t)=>e.platforms.includes(t),_l=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 Le(o).prerequisites)n(i,[...s,o]);t.push(o)}};for(let o of e)n(o,[]);return t};var vh=e=>({id:e,present:!1,onPath:!1,binRealPath:null,version:null,manager:"unknown"}),wh=async(e,t)=>{try{return await e(t)}catch{return null}},FP=async(e,t)=>{try{let r=await e.resolveBinPath(t);return r==null?null:e.realpath(r)}catch{return null}},kh=async(e,t)=>{if(!Nl(e,t.platform))return vh(e.id);let r=await wh(t.runCommand,e.probeArgv),n=await FP(t,e.binName);if(r==null&&n==null)return vh(e.id);let o=r??(n==null?null:await wh(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)}},Io=async(e,t)=>Promise.all(e.map(r=>kh(Le(r),t)));import{$ as GP}from"zx";import{z as bh}from"zod";var Rh=/^\d{4}-\d{2}-\d{2}$/,Do=e=>{if(!Rh.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},Sh=e=>`Release date "${e}" is not a calendar date in yyyy-mm-dd form.`,wn=class extends Error{constructor(t){super(Sh(t)),this.name="InvalidReleaseDateError"}},dr=e=>{let t=e.trim();if(!Do(t))throw new wn(t);return t},No=e=>{let t=e.trim();return t===""||Do(t)?!0:Sh(t)},Ml=bh.string().refine(Do,{message:"Expected a calendar date in yyyy-mm-dd form."}),jl=bh.string().refine(e=>e===""||Do(e),{message:'Expected a calendar date in yyyy-mm-dd form, or "" to clear.'});var Bt=e=>e.slice(1).split(".").map(Number),kn=e=>[...e].sort((t,r)=>{let[n,o,s]=Bt(t),[i,a,c]=Bt(r);return n!==i?(n??0)-(i??0):o!==a?(o??0)-(a??0):(s??0)-(c??0)});var Ph="next",LP=/^v?(\d+)\.(\d+)\.(\d+)$/,BP=e=>e.replace(/^.*release\//,""),Fl=e=>{let t=BP(e.trim()),r=LP.exec(t);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null},Eh=e=>`${e[0]}.${e[1]}.${e[2]}`,Ll=e=>{let t=[...e.remoteBranches??[],...e.jiraVersions??[]],r=[],n=new Set;for(let o of t){let s=Fl(o);if(!s)continue;let i=Eh(s);n.has(i)||(n.add(i),r.push(s))}return kn(r.map(o=>Eh(o))).map(o=>Bt(`v${o}`))},pr=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},Bl=(e,t)=>{if(e.length===0)throw new pr;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`},bn=(e,t)=>{try{return Bl(e,t)}catch(r){if(r instanceof pr)return null;throw r}},Ul=e=>e.trim().toLowerCase()===Ph,$i=e=>Ul(e)||Fl(e)!==null?{version:e}:{name:e},UP=e=>e==="regular"||e==="hotfix",xh=e=>"name"in e,VP=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:dr(n)}},Vl=e=>{let t=e.trim();if(t==="")throw new Error("Release spec is empty");let r=t.indexOf(":"),{token:n,releaseDate:o}=VP(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 u=l.toLowerCase();if(!UP(u))throw new Error(`Invalid release type "${l}". Expected "regular" or "hotfix".`);s=u}return Ci({...$i(n),type:s},{description:i,releaseDate:o})},Wl=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},Ci=(e,t)=>{let{description:r,releaseDate:n}=t;return{...e,...r!==void 0&&r!==""?{description:r}:{},...n===void 0?{}:{releaseDate:n}}},WP=e=>{let t=e.name.trim();return $s(t),Ci({id:{kind:"name",name:t,raw:t},type:e.type},e)},Gl=(e,t)=>{let r=[...t];return e.map(n=>{if(xh(n))return WP(n);let o=n.version.trim();if(o==="")throw new Error("Release entry has an empty version");if(Ul(o)){let a=Bl(r,n.type);return r.push(Bt(`v${a}`)),Ci({id:me(a),type:n.type},n)}let s=Fl(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),Ci({id:me(i),type:n.type},n)})},Jl=e=>e.some(t=>!xh(t)&&Ul(t.version));var JP=e=>e.split(`
357
- `).map(t=>{let r=t.indexOf(" ");return r===-1?null:q(t.slice(r+1))}).filter(t=>t!==null&&t.kind==="version").map(t=>t.raw),KP=async()=>{let e=await GP({quiet:!0})`git ls-remote --heads origin 'release/v*'`;return JP(e.stdout)},HP=async()=>{let e=await ht();return e?(await Zr(e)).map(r=>r.name):[]},_o=async()=>{let[e,t]=await Promise.allSettled([KP(),HP()]);return e.status==="rejected"&&d.warn({err:e.reason},"Failed to list remote release branches; continuing without them"),t.status==="rejected"&&d.warn({err:t.reason},"Failed to fetch Jira versions; continuing without them"),Ll({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:t.status==="fulfilled"?t.value:[]})};import qP from"node:fs";import YP from"node:path";var Kl=[".claude/settings.json",".claude/settings.local.json"],zP=["infra-kit","ik","pnpm exec infra-kit","pnpm exec ik","pnpm infra-kit"],XP=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),ZP=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},QP=(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(XP).join(".*")}$`,"s").test(t)||n===t||n.startsWith(`${t} `)},ex=e=>{let t=e.groupPath.join(" ");return t===e.cliName?[t]:[t,e.cliName]},tx=()=>mr.filter(e=>e.mutating),rx=e=>{let t=ZP(e);return t===null?[]:tx().filter(r=>zP.some(n=>ex(r).some(o=>QP(t,`${n} ${o}`)))).map(r=>r.groupPath.join(" "))},nx=(e,t)=>{let r;try{r=qP.readFileSync(YP.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}},Th=e=>{let t={present:[],unreadable:[],hits:[]};for(let r of Kl){let n=nx(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=rx(o);s.length>0&&t.hits.push({file:r,pattern:o,commands:s})}}}return t};var ox=e=>e.every(t=>t.status!=="fail"),sx=["brew","git","gh","doppler","aws"],ix=async e=>{let t=await Io(sx,e);return new Map(t.map(r=>[r.id,{manager:r.manager,version:r.version,present:r.present,onPath:r.onPath}]))},wt=async(e,t,r,n)=>{try{return await hn()`${t}`,{name:e,status:"pass",message:r}}catch{return{name:e,status:"fail",message:n}}},ax=async()=>{let e="orca installed",t=await Ct();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)"}},Lh=(e,t,r,n)=>{let o=de.join(Fh.homedir(),t),s="Run: infra-kit setup --skip-tools";if(!te.existsSync(o))return{name:e,status:"fail",message:`~/${t} not found. ${s}`};let i=te.readFileSync(o,"utf-8"),a=i.indexOf(lr),c=i.indexOf(Ft);return a===-1||c===-1||c<a?{name:e,status:"fail",message:`infra-kit ${r} block missing from ~/${t}. ${s}`}:i.slice(a,c+Ft.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`}},cx=()=>Lh("zshrc init block",".zshrc","shell",dh()),lx=()=>Lh("zshenv session block",".zshenv","session-env",Al()),ux=async()=>{let e="pnpm enableGlobalVirtualStore";try{let t=await P(),r=de.join(t,"pnpm-workspace.yaml");if(!te.existsSync(r))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${r}`};let n=te.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}`}}},dx=async()=>{try{return Pt(),{config:await W(),error:null}}catch(e){return{config:null,error:e}}},px=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)"}},mx=384,Hl=448,fx=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(", "),gx=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}}})),hx=async(e,t={})=>{let r="env tokens configured",n=t.readStore??Je,o=t.resolveToken??Am;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 gx(await Ls(),o);return{name:r,status:"pass",message:fx(s)}},yx=()=>it.env[Qt]||void 0,vx=async(e={})=>{let t="tokens.json present",r=e.readStore??Je,n=e.storePath??Tt;if((e.readEnvToken??yx)())return{name:t,status:"skip",message:`${Qt} is set; that channel takes precedence over the store`};let s;try{s=v(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 ${Qt} instead.`}}return{name:t,status:"pass",message:`${s} holds ${a.length} token(s): ${a.join(", ")}`}},Mo=(e,t)=>{let r=t(e);return r===null?null:r.mode&511},wx=async(e,t={})=>{let r="tokens.json perms",n=t.storePath??Tt,o=t.statPath??kx,s=t.chmodPath??te.chmodSync,i;try{i=await n()}catch{return{name:r,status:"skip",message:"the token store path could not be resolved"}}if(Mo(i,o)===null)return{name:r,status:"skip",message:`No store to protect at ${v(i)} (see tokens.json present)`};let a=de.dirname(i),c=de.dirname(a),l=de.dirname(c),p=[{target:l,expected:Hl,actual:Mo(l,o)},{target:c,expected:Hl,actual:Mo(c,o)},{target:a,expected:Hl,actual:Mo(a,o)},{target:i,expected:mx,actual:Mo(i,o)}].filter(f=>f.actual!==null&&f.actual!==f.expected);if(p.length===0)return{name:r,status:"pass",message:`${v(i)} is 0600 (0700 dirs)`};let m=p.map(f=>`${v(f.target)} is ${Ch(f.actual)}, expected ${Ch(f.expected)}`).join("; ");if(!e)return{name:r,status:"fail",message:`${m}. Fix: run \`infra-kit setup --skip-tools\` or \`infra-kit doctor --fix\`.`};for(let f of p)s(f.target,f.expected);return{name:r,status:"pass",message:`Tightened ${p.length} path(s): ${m}`}},Ch=e=>`0${e.toString(8).padStart(3,"0")}`,kx=e=>{try{return te.statSync(e)}catch{return null}},bx=async()=>{let e="user override path";try{let t=await Y(),r=te.existsSync(t.userProject),n=await Co(t.userProject,r),o=r?$o(n):"(not created \u2014 seed failed?)";return{name:e,status:"pass",message:`${v(t.userProject)} ${o} \u2014 project: ${t.projectName}`}}catch(t){return{name:e,status:"fail",message:t.message}}},Rx=async()=>{let e="legacy user-global config",t;try{t=await Y()}catch{return{name:e,status:"skip",message:"infra-kit config paths could not be resolved"}}let r=de.join(de.dirname(t.userGlobal),"config.json");return te.existsSync(r)?te.existsSync(t.userGlobal)?{name:e,status:"fail",message:`Stale legacy config.json found at ${v(r)} \u2014 ${v(t.userGlobal)} is active; remove the old file.`}:{name:e,status:"fail",message:`Legacy user-global config.json found at ${v(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"}},$h=/^\d+\.\d+\.\d+$/,Sx=(e,t)=>e===t||!$h.test(e)||!$h.test(t)?!1:kn([`v${e}`,`v${t}`])[0]===`v${e}`,Ex=async(e,t)=>{let r;try{r=await Pe(e)}catch{return[]}let n=[];for(let o of r){let s=nr(or(de.join(o,"CLAUDE.md")));s.state==="ok"&&s.version!==void 0&&Sx(s.version,t)&&n.push(s.version)}return n},Px=async(e,t)=>{let r=await Ex(e,t);if(r.length===0)return"";let n=kn(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`},xx=async()=>{let e=[{name:"CLAUDE.md block",status:"skip",message:"no infra-kit config in this repo"}],t;try{t=(await Y()).main}catch{return e}if(!te.existsSync(t))return e;let r=de.dirname(t),n=de.join(r,"CLAUDE.md"),o=te.existsSync(n)?te.readFileSync(n,"utf-8"):"",s=Xe(o,_e,Ze),i=s?"CLAUDE.md block present":"infra-kit block missing from CLAUDE.md. Run: infra-kit setup --skip-tools",a=await Px(r,U.version);return[{name:"CLAUDE.md block",status:s?"pass":"fail",message:`${i}${a}`}]},Tx=async()=>{try{let e=(await Y()).main;return te.existsSync(e)?de.dirname(e):null}catch{return null}},Cx=e=>{let t=ym();return t===null||!Bn(t,e)?"":` \u2014 plugin ${t} is fetched but not applied. Run: ${Wr}`},$x=e=>{let t=e.kind==="installed"?_s(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 ${G} version ${t}${Cx(t)}`}},Ah=3,Oh=(e,t)=>ye(e)===ye(t),Ax=e=>{if(e===void 0||e.gitRoot===null)return"";let t=v(e.gitRoot);if(e.projectDir!==null){if(Oh(e.projectDir,e.gitRoot))return"";let r=Dn(e.gitRoot,ye(e.projectDir),ye)?"below the repo root":"not this checkout";return` \u2014 this session was launched from ${v(e.projectDir)}, ${r}: the plugin and this repo's .claude/settings.json hooks load only from ${t} (measured); restart Claude Code there`}return Oh(e.cwd,e.gitRoot)?"":` \u2014 if Claude Code was launched from ${v(e.cwd)} rather than ${t}, it loaded neither the plugin nor this repo's hooks; launch it at ${t}`},Ox=(e,t)=>{let r="plugin installed",n=Ax(t);if(e.kind==="installed"){let{scope:c,projectPath:l}=e.installation,u=l===null?"":`, ${v(l)}`;return{name:r,status:"pass",message:`Plugin ${G} installed (${c??"unknown"} scope${u})${n}`}}if(e.kind==="absent")return{name:r,status:"fail",message:`Plugin ${G} is not installed. Run: ${ft}${n}`};let o=e.installations.map(c=>c.projectPath===null?"(unnamed project)":v(c.projectPath)),s=o.length-Ah,i=s>0?` and ${s} more`:"",a=`${o.slice(0,Ah).join(", ")}${i}`;return{name:r,status:"fail",message:`Plugin ${G} is installed for ${a} only, not this project. Run: ${ft}${n}`}},Ix=()=>wt("claude CLI",["claude","--version"],"Installed: claude","claude CLI not found on PATH \u2014 `infra-kit setup` cannot install the plugin; install Claude Code first");var Dx=(e,...t)=>{try{return JSON.parse(te.readFileSync(de.join(e,...t),"utf-8"))}catch{return null}},Nx=e=>{if(e.kind!=="installed")return{kind:"not-installed"};let t=_s(e.installation),{installPath:r}=e.installation;if(r===null)return{kind:"skills-only",version:t};let n=Dx(r,Me),o=n!==null&&typeof n=="object"?n[et]:void 0;return o==null||typeof o!="object"?{kind:"skills-only",version:t}:{kind:"stale-server",version:t,keys:Object.keys(o)}},Ih=e=>`Plugin ${G} ${e===null?"(version unreadable)":e}`,_x=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: ${ft}`};if(e.kind==="stale-server"){let r=e.keys.length===0?"":` (under "${e.keys.join('", "')}")`;return{name:t,status:"pass",message:`${Ih(e.version)} still carries an MCP server in its ${Me}${r} \u2014 a copy from before the plugin went skills-only. Update it: infra-kit setup (or ${Wr}), then restart Claude Code`}}return{name:t,status:"pass",message:`${Ih(e.version)} is skills-only \u2014 no ${Me}, as shipped; the /infra-kit:* skills drive the infra-kit CLI`}},Mx=(e,t)=>{let r=Xt(e===null?{}:{projectPath:e}),n=Ln();return[{name:"marketplace registered",status:n?"pass":"fail",message:n?`Marketplace ${oe} is known to Claude Code`:`Marketplace ${oe} is not registered. Run: claude plugin marketplace add ${xt}`},Ox(r,t),$x(r),_x(Nx(r)),{name:"CLI version",status:"pass",message:`infra-kit CLI ${U.version}`}]},jx=(e,t)=>{let r="background setup";if(e===null)return{name:r,status:"skip",message:"not run yet \u2014 it runs after the next background update check"};if(e.version!==t)return{name:r,status:"skip",message:`last ran for ${e.version}; runs for ${t} after the next background update check`};if(e.finishedMs===null)return{name:r,status:"skip",message:`a pass for ${t} is running, or was interrupted and will be retried`};let n=e.runs.filter(o=>o.status!=="ok");return n.length===0?{name:r,status:"pass",message:`ran for ${t} on the machine and ${e.runs.length-1} project(s)`}:{name:r,status:"warn",message:`${n.length} run(s) left work for you (${n.map(o=>`${o.root??"machine"}: ${o.status}`).join(", ")}) \u2014 see ${v(cn())}, or run: infra-kit setup`}},Fx=({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(", ")},Lx=e=>{let t="Agent mode",r=Cs(e),n=Fx(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})`}},Dh=4,Bx=e=>{let t=e.slice(0,Dh).join(", "),r=e.length-Dh;return r>0?`${t} +${r} more`:t},Ux=e=>{let t="Agent allowlist",{present:r,unreadable:n,hits:o}=Th(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"} (${Bx(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 ${Kl.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`}},Vx=(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`},Wx=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 Rg(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?v(i.worktreePath):"worktree missing";return`${i.branch} (${Vx(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`}},Bh=e=>Ma(["trust"],{bin:e}),Gx=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),Nh="ERR_TLS_CERT_ALTNAME_INVALID",Uh=()=>`portless serving TLS on :${Et}`,Jx=async(e,t,r)=>{let n=Uh();return await e(Et,!0)?{name:n,status:"pass",message:`portless is serving HTTPS on :${Et}`}:{name:n,status:"fail",message:`No portless daemon is serving HTTPS on :${Et}. Install it once (needs root): \`${St(t,r)}\`.`}},Kx=async(e,t,r,n,o)=>{let s="portless CA chain valid",i=["localhost",...t.slice(0,1).map(u=>u.name)],c=(await Promise.all(i.map(async u=>({servername:u,result:await e(Et,u)})))).filter(u=>!u.result.ok);if(c.length===0)return{name:s,status:"pass",message:`Served certificate chains to ${v(r)} (${i.join(", ")})`};let l=c.map(u=>u.result.ok?"":u.result.code);return l.includes(Nh)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${Nh} for servername(s) ${c.map(u=>u.servername).join(", ")} \u2014 doctor's probe is wrong, your trust store is not implicated. Please report this.`}:l.some(u=>Gx.has(u))?{name:s,status:"fail",message:`The daemon is serving a certificate that does not chain to ${v(r)}. Its CA was regenerated \u2014 run \`${Bh(n)}\`, or reinstall: \`${St(n,o)}\`.`}:{name:s,status:"fail",message:`TLS handshake failed (${l.join(", ")})`}},Hx=(e,t,r)=>{let n="portless CA trusted";return e?{name:n,status:"pass",message:`${v(t)} matches the recorded ca.trusted fingerprint`}:{name:n,status:"fail",message:`The portless CA is not trusted (or was regenerated). Run: \`${Bh(r)}\` (no sudo needed).`}},qx=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 \`${Ma(["alias","--remove","<name>"],{bin:r})}\`.`}},Ut="portless service target",Fo=e=>({name:Ut,status:"warn",message:e}),Vh=e=>e==="darwin"?Np:e==="linux"?_p:null,Yx=e=>e==="darwin"?`sudo launchctl kickstart -k system/${Dp}`:`sudo systemctl restart ${Mp}`,zx="/bin/ps",Xx=e=>{try{let t=jh(zx,["-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}},_h=e=>{try{return te.readFileSync(e,"utf-8")}catch{return null}},Zx=e=>{try{return te.statSync(e).mtime}catch{return null}},Qx=2e3,eT=e=>{try{let t=jh(e,["-p","process.version"],{encoding:"utf-8",timeout:Qx}),r=t.stdout?.trim()??"";return{version:r===""?null:r,status:t.status,signal:t.signal}}catch{return{version:null,status:null,signal:null}}},tT=(e,t)=>({platform:e.platform??it.platform,readServiceFile:e.readServiceFile??_h,readFile:e.readFile??_h,exists:e.exists??te.existsSync,realpath:e.realpath??ye,mtime:e.mtime??Zx,execPath:e.execPath??it.execPath,home:e.home??Fh.homedir(),cwd:e.cwd??it.cwd(),repoRoot:e.repoRoot??So,stateDir:(e.stateDir??Fp)(),processStartTime:e.processStartTime??Xx,version:e.version??it.version,arch:e.arch??it.arch,nodeVersionOf:e.nodeVersionOf??eT,isGlobal:e.isGlobal??Ts().node.isGlobal,nodeFs:e.nodeFs??te,stableNode:null,stableNodeSidecar:null,bin:t}),Lo="portless node",fr="~/.infra-kit/node",jo=e=>({row:{name:Lo,status:"fail",message:e},stableNode:null,sidecar:null}),Mh=(e,t)=>{try{return e(t,{throwIfNoEntry:!1})}catch{return}},rT=e=>e.signal!==null?`killed by ${e.signal}`:e.status===null?"did not start":e.status!==0?`exit ${e.status}`:`printed ${e.version??"nothing"}`,nT=(e,t)=>e.status===0&&e.signal===null&&e.version===t.version,oT=e=>{let t=Wp(e.home),r=Mh(e.nodeFs.lstatSync,t);if(r===void 0)return jo(`${fr} is missing and could not be written \u2014 run \`infra-kit setup\` and see the debug log`);if(!r.isFile())return jo(`${fr} is not a regular file; infra-kit will not replace it \u2014 move it away and run \`infra-kit setup\``);let n=Gp(e.home,e.nodeFs);if(n===null)return jo(`${fr} has no readable node.source.json and it could not be rewritten \u2014 run \`infra-kit setup\``);let o=Mh(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 jo(`${fr} is Node ${n.version} (${n.method} of ${v(n.source)}); infra-kit runs ${e.version} at ${v(e.execPath)}, a different file, and could not relink it \u2014 run \`infra-kit setup\``);if(!i){let c=e.nodeVersionOf(t);if(!nT(c,e))return jo(`${fr} does not run as Node ${e.version} (${rT(c)}). Re-run through the current Node: \`${St(e.bin,{...e,stableNode:null})}\`, then \`infra-kit setup\``)}return{row:{name:Lo,status:"pass",message:`${fr} is Node ${n.version} (${n.arch}, ${n.method} of ${v(n.source)})`},stableNode:t,sidecar:n}},sT=e=>{if(Vh(e.platform)===null)return{row:{name:Lo,status:"skip",message:"no portless OS service on this platform"},stableNode:null,sidecar:null};let t=oT(e);return e.isGlobal()?t:{...t,row:{name:Lo,status:"skip",message:`not a global install; the global infra-kit keeps ${fr} current`}}},Wh=(e,t)=>{let r=tT(e,t),n=sT(r);return{seams:{...r,stableNode:n.stableNode,stableNodeSidecar:n.sidecar},node:n.row}},iT=(e,t)=>{let r=t.readFile(de.join(e,"package.json"));try{let n=r===null?null:ge.object({version:ge.string()}).safeParse(JSON.parse(r));return n?.success===!0?n.data.version:"?"}catch{return"?"}},aT=e=>{let t=Number.parseInt(e.readFile(de.join(e.stateDir,"proxy.pid"))?.trim()??"",10);return!Number.isInteger(t)||t<=0?null:e.processStartTime(t)},cT=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?null:t},lT=(e,t,r)=>{let n=aT(r),o=a=>n!==null&&a!==null&&n.getTime()<a.getTime(),s=r.stableNodeSidecar,i=[...s!==null&&o(cT(s.versionChangedAt))?[`Node ${s.version}`]:[],...o(r.mtime(de.join(e,"package.json")))?[`portless ${t}`]:[]];return i.length===0?null:i.join(" and ")},uT=async(e,t)=>{let r=t.realpath(t.cwd);return r===t.realpath(t.home)?!1:Dn(await t.repoRoot()??r,e,t.realpath)},gr=e=>({state:"drifted",row:e}),dT=async(e,t,r)=>{let n=St(r.bin,r);if(!r.exists(e))return gr({name:Ut,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=de.join(ja(r.home),"dist","cli.js");if(t!==o)return gr(Fo(`The service points at \`${t}\`, a version-specific location. Re-run once to switch it to the stable link: \`${n}\``));if(xs(r.home,r.exists)===null)return gr({name:Ut,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(ja(r.home));if(await uT(s,r))return gr({name:Ut,status:"fail",message:`The service runs portless from a project checkout (${s}). Re-run \`service install\` from the global install: \`${n}\``});let i=pT(e,n,r);if(i!==null)return i;let a=iT(s,r),c=lT(s,a,r);return c!==null?{state:"converged",row:Fo(`The running daemon predates ${c} that \`dev\` will talk to. Restart it: \`${Yx(r.platform)}\` (or reboot).`)}:{state:"converged",row:{name:Ut,status:"pass",message:`service runs \`${e}\` (Node ${r.version}) + stable link \u2192 portless ${a}`}}},pT=(e,t,r)=>r.stableNode!==null?r.realpath(e)===r.realpath(r.stableNode)?null:gr(Fo(`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:gr(Fo(`The service runs \`${e}\`; infra-kit runs \`${r.execPath}\`. Works until the old Node is removed. Re-run when convenient: \`${t}\``)),Gh=async e=>{let t=Vh(e.platform);if(t===null)return{state:"absent",row:{name:Ut,status:"skip",message:"no portless OS service file on this platform"}};let r=e.readServiceFile(t);if(r===null)return{state:"absent",row:{name:Ut,status:"skip",message:`the OS service is not installed (no ${t})`}};let[n,o]=Jf(e.platform,r)??[];return n===void 0||o===void 0?gr(Fo(`could not parse ${t} \u2014 re-run \`${St(e.bin,e)}\` to rewrite it.`)):dT(n,o,e)},Jh=async(e,t)=>{let{seams:r}=Wh(e,t);return{state:(await Gh(r)).state,stableNode:r.stableNode}},mT=()=>[Lo,Ut,Uh(),"portless CA chain valid","portless CA trusted","portless routes"],fT=async(e={})=>{let t=e.resolveBin??Ip,r=e.isProxyServing??jp,n=e.handshake??Up,o=e.caTrusted??Bp,s=e.routes??_n,i=e.isListening??Nn,a=(e.caPath??Lp)(),c=t();if(c===null)return[{name:"portless installed",status:"fail",message:"portless is not resolvable from node_modules \u2014 run `pnpm install`."},...mT().map(b=>({name:b,status:"skip",message:"portless not resolvable"}))];let l={name:"portless installed",status:"pass",message:"portless is resolvable from node_modules"},{seams:u,node:p}=Wh(e,c),m=s(),f=await Jx(r,c,u),y=f.status==="fail"?{name:"portless CA chain valid",status:"skip",message:"no daemon to handshake with"}:await Kx(n,m,a,c,u);return[l,p,(await Gh(u)).row,f,y,Hx(o(),a,c),await qx(m,i,c)]},gT=async(e={})=>{let t="portless routes",r=e.routes??_n,n=e.isListening??Nn,o=e.devSessionRunning??Bf,s=r();if(s.length===0)return{name:t,status:"pass",message:"No portless routes registered"};let i=await Promise.all(s.map(async u=>({name:u.name,port:u.port,live:await n(u.port)}))),{prunable:a,withheld:c}=Lf(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??Vp().removeAlias;for(let u of a)await l(u);return{name:t,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},Ai=async(e={})=>{let t=await dx(),r=ix(e.probeDeps??Ao()),n=async(m,f)=>{let[y,b]=await Promise.all([f,r]),w=b.get(m);return w===void 0?y:{...y,detail:w}},o=await Promise.all([n("brew",wt("brew installed",Le("brew").probeArgv,"Homebrew is installed","Homebrew is not installed. Install from: https://brew.sh/")),n("git",wt("git installed",Le("git").probeArgv,"git is installed","git is not installed. Install with: brew install git")),n("gh",wt("gh installed",Le("gh").probeArgv,"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/")),wt("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),n("doppler",wt("doppler installed",Le("doppler").probeArgv,"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli")),n("aws",wt("aws installed",Le("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")),wt("package manager installed",["pnpm","--version"],"Installed: pnpm","pnpm is not installed. Install from: https://pnpm.io/installation"),wt("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"),ax(),Promise.resolve(cx()),Promise.resolve(lx()),ux(),Promise.resolve(px(t)),vx(),hx(t),wx(e.fix??!1),bx(),Rx()]),s=await fT(e.portlessDeps);if(e.fix){let m=await gT(),f=s.findIndex(y=>y.name===m.name);f>=0?s[f]=m:s.push(m)}let i=await Tx(),a=await So(),c={projectDir:it.env.CLAUDE_PROJECT_DIR||null,cwd:it.cwd(),gitRoot:a},l=[await Ix(),...Mx(i,c),Eo(),Lx({env:it.env,stdinIsTTY:it.stdin.isTTY===!0,flag:_.source==="flag"}),a===null?{name:"Agent allowlist",status:"skip",message:"no git root"}:Ux(a)],u=[...o,await Wx(a),...s,...await xx(),...l,jx(ln(),U.version)],p={checks:u.map(m=>({name:m.name,status:m.status,message:m.message,fixable:Xc.has(m.name),detail:m.detail})),allPassed:ox(u),cliVersion:U.version};return{content:k(JSON.stringify(p,null,2)),structuredContent:p}},ql=E({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:ge.array(ge.object({name:ge.string().describe("Name of the check"),status:ge.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:ge.string().describe("Details about the check result"),fixable:ge.boolean().describe("Whether `infra-kit doctor --fix` repairs this row"),detail:ge.object({manager:ge.string().describe("Which package manager owns this install, read from its resolved path"),version:ge.string().nullable().describe("The version the tool reported, or null"),present:ge.boolean().describe("The tool is installed somewhere findable \u2014 on PATH or not"),onPath:ge.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:ge.boolean().describe("Whether no check failed (warnings and skips do not count)"),cliVersion:ge.string().describe("Version of the infra-kit CLI that produced this report")},handler:()=>Ai()});import{E2E_MODE_ENV as VT}from"@slip-stream-kit/config/internal";import ru from"node:fs";import WT from"node:os";import Uo from"node:path";import Di from"node:process";import{z as R}from"zod";var at=(e,t,r)=>new C({status:"refused",reason:e,...t},2,r);import{describeProxyRoutes as hT,loadDev as yT,readAppAliasName as vT,readCloudOrigin as wT,readLocalContext as Hh}from"@slip-stream-kit/config/internal";import Kh from"node:fs";import hr from"node:path";import Oi from"node:process";import{z as Yl}from"zod";var kT=async e=>{let t=hr.join(e,"apps"),r=Kh.existsSync(t)?Kh.readdirSync(t).toSorted():[],n=[];for(let o of r){let s=hr.join(t,o,"tests"),a=(await It(s))?.e2e;a?.target!==void 0&&n.push({app:o,testsDir:s,e2e:{target:a.target}})}return n},bT=(e,t)=>{let[r,n]=hr.relative(e,t).split(hr.sep);return r==="apps"&&n?n:void 0},RT=(e,t,r,n)=>{let o=c=>e.find(l=>l.app===c),s=o(t)??(t===void 0?o(bT(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 g(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 C({status:"argument_required",argument:a,choices:Yl.toJSONSchema(Yl.object({app:Yl.enum(i)})),agentMode:_.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(", ")}`})},ST=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}})),ET=e=>co(e).apps.find(t=>t.env!=="")?.env??null,zl=async(e,t={})=>{let r=t.cwd??Oi.cwd(),n=t.projectRoot??await P(),o=(t.env??Oi.env)[xr]||null,s=t.healthProbe??za,i=RT(await kT(n),e,r,n),{target:a}=i.e2e,[c,l]=a.split("/"),u=hr.join(n,"apps",c,l),p=(await er(u)).name,m=(await It(u))?.deployedUrlEnv??null;if(!p)throw new g(void 0,{operation:`resolve e2e target ${a}`,remediation:`check \`e2e.target\` in ${hr.join(i.testsDir,"infra-kit.config.ts")}`,stderrExcerpt:`${u} has no package.json name`});let f=Vm(u),y=vT(p,u),b=`${y}.localhost`,w=`https://${b}`,x=0;if(l==="ui")x=(t.listRoutes??_n)().find(T=>T.name===b||T.name===y)?.port??0;else{let T=Hh(u).info.get(p);x=T?.port??0,w=T?.origin??w}let D=x>0&&await s({tag:a,port:x,kind:l})==="ok",N=D?ET(u):null;return{app:i.app,testsDir:i.testsDir,target:a,kind:l,targetDir:u,packageName:p,deployedUrlEnv:m,release:f,env:o,servedEnv:N,localUrl:w,served:D}},qh=e=>{let{app:t,testsDir:r,target:n,packageName:o,deployedUrlEnv:s,release:i,env:a,servedEnv:c,localUrl:l}=e;return{app:t,testsDir:r,target:n,packageName:o,deployedUrlEnv:s,release:i,env:a,servedEnv:c,localUrl:l}},Xl=async(e,t={})=>{let r=t.healthProbe??za,n=Hh(e.targetDir),o=e.kind==="ui"?await yT(e.targetDir):void 0,s=o?.proxy?hT({proxy:o.proxy,localContext:n,env:e.env??void 0,cloud:wT(e.deployedUrlEnv??void 0,t.env??Oi.env),getRelease:()=>e.release}):[],i=new Map([...n.info].map(([a,c])=>[a,c.port]));return{...qh(e),mode:"local",baseUrl:e.localUrl,routes:await ST(s,i,r)}},Zl=(e,t={})=>{let{env:r,deployedUrlEnv:n,target:o}=e;if(!n)throw at("no_deployed_url_env",{target:o},{operation:`resolve the deployed app ${e.app}'s cloud e2e run targets`,remediation:`declare \`deployedUrlEnv: '<APP>_URL'\` in ${hr.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??Oi.env)[n];if(!r||!s){let i=s?xr:n;throw at("env_not_loaded",{missing:i},{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 ${xr}, and ${i} is not set`})}return{...qh(e),mode:"cloud",baseUrl:s,routes:[]}};import PT from"node:fs";import xT from"node:path";import{stripVTControlCharacters as TT}from"node:util";import{z as A}from"zod";var Yh=2e3,zh="--reporter=line,json",Xh=e=>({PLAYWRIGHT_JSON_OUTPUT_FILE:e,PLAYWRIGHT_JSON_OUTPUT_NAME:e}),Zh=e=>e.some(t=>t==="--reporter"||t.startsWith("--reporter=")),Ql=A.object({message:A.string().optional()}),Qh=A.object({type:A.string()}),CT=A.object({status:A.string(),retry:A.number(),error:Ql.optional(),errors:A.array(Ql).optional(),annotations:A.array(Qh).optional(),attachments:A.array(A.object({name:A.string(),path:A.string().optional()})).optional()}),$T=A.object({projectName:A.string(),status:A.string(),expectedStatus:A.string().optional(),annotations:A.array(Qh).optional(),results:A.array(CT)}),AT=A.object({title:A.string(),file:A.string(),line:A.number().optional(),tests:A.array($T)}),ey=A.lazy(()=>A.object({title:A.string(),specs:A.array(AT).optional(),suites:A.array(ey).optional()})),OT=A.object({config:A.object({rootDir:A.string().optional()}).optional(),suites:A.array(ey),errors:A.array(Ql).optional(),stats:A.object({expected:A.number(),unexpected:A.number(),flaky:A.number(),skipped:A.number()})}),ty=e=>{let t=TT(e);return t.length>Yh?`${t.slice(0,Yh)}\u2026`:t},IT=e=>{let t=e.error?.message??e.errors?.[0]?.message;return t===void 0?null:ty(t)},DT=e=>e.status==="unexpected"||e.status==="flaky",NT=e=>{let t=new Map;for(let r of e)t.set(r.projectName,[...t.get(r.projectName)??[],r]);return t},_T=e=>new Set([...e.annotations??[],...e.results.flatMap(t=>t.annotations??[])].map(t=>t.type)),MT=(e,t)=>{let r=e.filter(DT),n=r.at(-1);if(!n)return null;let o=n.results.findLast(i=>i.status!=="passed"&&i.status!=="skipped"),s=r.length===e.length&&n.status==="unexpected";return{...t,status:s?"unexpected":"flaky",retry:o?.retry??0,runs:e.length,failedRuns:r.length,error:o?IT(o):"Expected to fail, but passed.",tracePath:o?.attachments?.find(i=>i.name==="trace")?.path??null}},jT=e=>{let t=OT.safeParse(e);if(!t.success)return null;let{config:r,suites:n,errors:o,stats:s}=t.data,i=[],a=new Map,c=0,l=(p,m)=>{let f=new Set(m.flatMap(w=>[..._T(w)])),y=m.some(w=>w.expectedStatus==="failed");if(!y&&!f.has("fixme")&&!f.has("skip"))return;let b=a.get(p)??{file:p,fail:0,fixme:0,skip:0};y&&(b.fail+=1),f.has("fixme")?b.fixme+=1:f.has("skip")&&(b.skip+=1),a.set(p,b)},u=(p,m)=>{for(let f of p.specs??[]){let y=r?.rootDir?xT.resolve(r.rootDir,f.file):f.file,b=[...m,f.title].join(" \u203A ");l(y,f.tests);for(let[w,x]of NT(f.tests)){let D=MT(x,{title:b,file:y,line:f.line??null,project:w});D&&(D.runs>1&&D.failedRuns<D.runs&&(c+=1),i.push(D))}}for(let f of p.suites??[])u(f,[...m,f.title])};for(let p of n)u(p,[]);return{summary:{expected:s.expected,unexpected:s.unexpected,flaky:s.flaky,skipped:s.skipped,repeatFlaky:c},failures:i,annotated:[...a.values()],errors:(o??[]).flatMap(p=>p.message===void 0?[]:[ty(p.message)])}},ry=e=>{try{return jT(JSON.parse(PT.readFileSync(e,"utf8")))}catch{return null}};import Bo from"node:fs";import oy from"node:path";import Ii from"node:process";var FT=e=>oy.join(e,"node_modules",".cache","infra-kit-e2e.lock"),LT=e=>{try{return Ii.kill(e,0),!0}catch(t){return t.code==="EPERM"}},ny=e=>{try{return Bo.writeFileSync(e,String(Ii.pid),{flag:"wx"}),!0}catch(t){if(t.code==="EEXIST")return!1;throw t}},eu=e=>{try{let t=Number.parseInt(Bo.readFileSync(e,"utf8"),10);return Number.isInteger(t)&&t>0?t:null}catch{return null}},sy=e=>{let t=FT(e);if(Bo.mkdirSync(oy.dirname(t),{recursive:!0}),!ny(t)){let r=eu(t);if(r!==null&&r!==Ii.pid&&LT(r))return{holder:r};if(Bo.rmSync(t,{force:!0}),!ny(t))return{holder:eu(t)??0}}return{release:()=>{eu(t)===Ii.pid&&Bo.rmSync(t,{force:!0})}}};import{spawn as BT}from"node:child_process";import UT from"node:os";import tu from"node:process";var iy=(e,t,r)=>new Promise((n,o)=>{let s=BT(e,t,r),i=tu.stdin.isTTY?["SIGTERM","SIGHUP"]:["SIGINT","SIGTERM","SIGHUP"],a=l=>{s.kill(l)},c=()=>{for(let l of i)tu.off(l,a)};for(let l of i)tu.on(l,a);s.once("error",l=>{c(),o(l)}),s.once("close",(l,u)=>{c(),n(l??(u?128+UT.constants.signals[u]:1))})});var GT=["playwright.config.ts","playwright.config.mts","playwright.config.js","playwright.config.mjs"],JT=e=>GT.some(t=>{try{return ru.readFileSync(Uo.join(e,t),"utf8").includes("infraKitE2e")}catch{return!1}}),nu=e=>`infra-kit dev ${e.target.split("/")[0]} --no-watch --reuse`,KT=(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(`
358
- `)},HT=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 at("dead_local_routes",{routes:r},{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(", ")}`})},qT=async(e,t)=>{if(e.env===null||!Bm(e.env))return;let r=await(t.protectedEnvAccess??Ye)();if(r.allowed)return;let n=`run ${e.app} e2e against "${e.env}"`;throw r.reason==="agent-blocked"?at("protected_env",{env:e.env,humanMayRun:!0},{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`}):at("protected_env",{env:e.env,humanMayRun:!1},{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`})},YT=e=>{if(!(e.servedEnv===null||e.servedEnv===e.env))throw at("served_env_mismatch",{servedEnv:e.servedEnv,env:e.env},{operation:`run ${e.app} e2e against the local dev server`,remediation:`load the same env (\`infra-kit env-load -c ${e.servedEnv}\`), or restart \`infra-kit dev\` under "${e.env??"none"}"`,stderrExcerpt:`the dev server serving ${e.target} runs with env "${e.servedEnv}", this shell with "${e.env??"none"}"`})},zT=async(e,t)=>{if(e.served){YT(e);let p=await Xl(e,t);return HT(p),p}if(!JT(e.testsDir))throw at("no_dev_server",{devCommand:nu(e)},{operation:`run ${e.app} e2e locally`,remediation:`start it (\`${nu(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,servedEnv:l,localUrl:u}=e;return{app:r,testsDir:n,target:o,packageName:s,deployedUrlEnv:i,release:a,env:c,servedEnv:l,localUrl:u,mode:"local",baseUrl:u,routes:[]}},XT=(e,t,r)=>iy("pnpm",["exec","playwright","test",...t],{cwd:e.testsDir,env:{...Di.env,...r,[VT]:e.mode},stdio:["inherit",zt.enabled||K()?2:"inherit","inherit"]}),ZT=(e,t)=>{let r=t.findIndex(s=>s==="--output"||s.startsWith("--output="));if(r!==-1){let s=t[r]==="--output"?t[r+1]??"":t[r].slice(9);return{args:t,outputDir:Uo.resolve(e.testsDir,s)}}let n=new Date().toISOString().replace(/[:.]/g,"-"),o=Uo.join(e.testsDir,"test-results",`ik-e2e-${n}-${Di.pid}`);return{args:[...t,`--output=${o}`],outputDir:o}},QT=e=>{if(e.mode==="cloud")return()=>{};let t=sy(e.testsDir);if("holder"in t)throw at("run_in_progress",{pid:t.holder},{operation:`run ${e.app} e2e locally`,remediation:`wait for it to finish (or stop process ${t.holder}), then re-run`,stderrExcerpt:`another local e2e run of ${e.app} (pid ${t.holder}) is using its dev server`});return t.release},Ni=async(e,t={})=>{let r=await zl(e.app,t),n=e.cloud?Zl(r,t):await zT(r,t);d.info(KT(n,r.served)),n.mode==="cloud"&&await qT(n,t);let o={...n,served:r.served,devCommand:n.mode==="local"&&!r.served?nu(r):null,playwrightArgs:e.playwrightArgs??[]};if(e.dryRun)return su({...o,ran:!1,exitCode:null,...ou});n.mode==="cloud"&&await L(e.yes,`Run ${n.app} e2e against ${n.baseUrl} ("${n.env}", shared)?`,{plan:o});let s=QT(n);try{return await eC(o,t.runPlaywright??XT)}finally{s()}},eC=async(e,t)=>{if(!K()||Zh(e.playwrightArgs)){let i=await t(e,e.playwrightArgs,{});return i!==0&&(Di.exitCode=i),su({...e,ran:!0,exitCode:i,...ou,report:K()?"caller-reporter":"off"})}let{args:r,outputDir:n}=ZT(e,e.playwrightArgs),o=ru.mkdtempSync(Uo.join(WT.tmpdir(),"ik-e2e-report-")),s=Uo.join(o,"report.json");try{let i=await t(e,[zh,...r],Xh(s));i!==0&&(Di.exitCode=i);let a=ry(s);return su({...e,ran:!0,exitCode:i,...a?{report:"collected",...a}:{...ou,report:"unavailable"},outputDir:n})}finally{ru.rmSync(o,{recursive:!0,force:!0})}},ou={report:"off",outputDir:null,summary:null,failures:[],annotated:[],errors:[]},su=e=>({content:k(JSON.stringify(e,null,2)),structuredContent:e}),tC={app:R.string(),testsDir:R.string(),target:R.string().describe("The package under test, `<app>/ui` or `<app>/api`."),packageName:R.string(),mode:R.enum(["local","cloud"]).describe("local (default): this worktree\u2019s dev server. cloud (--cloud): the deployed app at env."),baseUrl:R.string().describe("The URL the run was pointed at: the local alias, or the deployed URL."),deployedUrlEnv:R.string().nullable().describe("The target\u2019s variable holding its deployed URL; a cloud run reads it. Null when it declares none."),release:R.string().describe("This worktree\u2019s release slug \u2014 the first label of every local alias."),env:R.string().nullable().describe("INFRA_KIT_ENV of this process; the env a cloud run targets."),servedEnv:R.string().nullable().describe("Served local runs: the INFRA_KIT_ENV the running dev session recorded \u2014 where its cloud routes go. Null when nothing served the target or the session recorded none. A local run refuses when it differs from env."),localUrl:R.string().describe("This worktree\u2019s address for the target, whether or not anything serves it."),served:R.boolean().describe("Whether this worktree\u2019s dev server already served the target when the run began."),devCommand:R.string().nullable().describe("Local runs with nothing served: the dev command the Playwright config starts, and stops after."),routes:R.array(R.object({path:R.string(),packageName:R.string(),source:R.enum(["local","cloud"]),target:R.string().nullable(),live:R.boolean().nullable()})).describe("Served local UI runs only: the dev proxy\u2019s route-by-route local/cloud split, local backends probed."),playwrightArgs:R.array(R.string()),ran:R.boolean().describe("False for --dry-run."),exitCode:R.number().nullable().describe("Playwright\u2019s exit code; null when it did not run."),report:R.enum(["off","caller-reporter","unavailable","collected"]).describe("Per-test results: collected from Playwright\u2019s JSON reporter under --json/agent mode; caller-reporter when playwrightArgs carried its own --reporter; unavailable when the run wrote no readable report; off otherwise."),outputDir:R.string().nullable().describe("Where this run\u2019s traces and attachments live \u2014 its own directory, so a later run cannot delete them. Null unless report is collected or unavailable."),summary:R.object({expected:R.number(),unexpected:R.number(),flaky:R.number(),skipped:R.number(),repeatFlaky:R.number()}).nullable().describe("Playwright\u2019s counts by outcome, one per run (each --repeat-each repeat counts), plus repeatFlaky: tests that passed in some repeats and failed in others. Null unless report is collected."),failures:R.array(R.object({title:R.string().describe("Describe path and test title, joined with \u203A."),file:R.string(),line:R.number().nullable(),project:R.string(),status:R.enum(["unexpected","flaky"]).describe("flaky: failed, then passed on a retry or in another --repeat-each repeat."),retry:R.number().describe("The retry index of the failed attempt reported here."),runs:R.number().describe("How many times the test ran in this project \u2014 its --repeat-each repeats."),failedRuns:R.number().describe("How many of those runs failed."),error:R.string().nullable().describe("The failure message, ANSI stripped, truncated to 2000 characters."),tracePath:R.string().nullable().describe("The failed attempt\u2019s trace.zip; open with `playwright show-trace`.")})).describe("One entry per test and project that failed, needed a retry, or failed in some repeat; empty unless report is collected."),annotated:R.array(R.object({file:R.string(),fail:R.number().describe("test.fail \u2014 green only while the bug it registers exists."),fixme:R.number().describe("test.fixme \u2014 skipped as unfinished."),skip:R.number().describe("test.skip, declared or called at runtime, conditional ones included.")})).describe("Per spec file, the tests that passed or skipped while asserting little, as Playwright ran them; empty unless report is collected."),errors:R.array(R.string()).describe("Run-level errors with no test to blame (config, global setup, a spec that fails to import), ANSI stripped and truncated; empty unless report is collected.")},iu=E({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:R.string().optional().describe("App folder with an apps/<app>/tests e2e package; inferred from cwd when omitted."),dryRun:R.boolean().optional(),yes:R.boolean().optional(),cloud:R.boolean().optional().describe("Run against the deployed app at INFRA_KIT_ENV instead of this worktree."),playwrightArgs:R.array(R.string()).optional().describe("Passed to `playwright test` verbatim \u2014 a spec path, `--grep <title>`, `--project=chromium`.")},outputSchema:tC,handler:e=>Ni(e)});import _i from"node:fs";import au from"node:path";import{z as Vo}from"zod";var rC=e=>[...e.map(t=>`unset ${t}`),`unset ${xr}`,`unset ${ks}`,`unset ${bs}`,`unset ${Rp}`,`unset ${Rs}`],Mi=async()=>{let e=Tr(),t=au.join(e,Pr);if(!_i.existsSync(t))throw new Error("No loaded environment found. Run `env-load` first.");let r=Ss(t),n=rC(r),o=au.resolve(e,vs);_i.mkdirSync(e,{recursive:!0,mode:448}),Rt(o,`${n.join(`
355
+ ${Ft}`;import PP from"node:fs/promises";var $o=async(e,t)=>{if(!t)return{hasOverrides:!1,overrideKeys:[],unreadable:!1};try{let r=await PP.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}}},Ao=e=>e.unreadable?"(unreadable \u2014 invalid JSON)":e.overrideKeys.length===0?"(empty \u2014 no overrides)":`(${e.overrideKeys.length} override(s): ${e.overrideKeys.join(", ")})`;import TP from"node:fs";import CP from"node:os";import mh from"node:path";import $P from"node:process";import{$ as xP}from"zx";var hn=()=>xP({quiet:!0});var AP=()=>[mh.join(CP.homedir(),".local","bin"),"/opt/homebrew/bin","/usr/local/bin"],OP=async e=>{try{return(await hn()`command -v ${e}`).stdout.trim()||null}catch{return null}},Oo=()=>({runCommand:async e=>{let t=await hn()`${e}`;return{stdout:`${t.stdout}
356
+ ${t.stderr}`}},resolveBinPath:async e=>{let t=await OP(e);return t!==null?t:AP().map(r=>mh.join(r,e)).find(r=>TP.existsSync(r))??null},realpath:ve,platform:$P.platform});var Lt=(...e)=>({steps:e,needsSudo:!1,fetchesNetworkScript:!1}),yn=e=>/\d{1,10}\.\d{1,10}\.\d{1,10}/.exec(e)?.[0]??null,vn=["darwin","linux"],xi=e=>t=>_a(t,e)?"homebrew":"unknown",Ti=(e,t)=>r=>r===null?null:t(e(r),r),Il=e=>Ti(xi(e.kegName),t=>t==="homebrew"?Lt(["brew","upgrade",e.brewFormula]):null),fh=e=>Es(e,"Homebrew")||Es(e,"homebrew")?"homebrew":"unknown",IP={id:"brew",binName:"brew",probeArgv:["brew","--version"],versionFrom:yn,platforms:vn,prerequisites:[],bootstrapInstall:{steps:[["/bin/bash","-c","$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"]],needsSudo:!0,fetchesNetworkScript:!0},identify:fh,updateFor:Ti(fh,e=>e==="homebrew"?Lt(["brew","update"]):null)},Ol={brewFormula:"awscli",brewInstallSpec:"awscli",kegName:"awscli"},yh="https://awscli.amazonaws.com/v2/install.sh",vh={steps:[["/bin/bash","-c",`curl -fsSL ${yh} | bash`]],needsSudo:!1,fetchesNetworkScript:!0},DP="/usr/local/aws-cli",NP=e=>Nn(DP,e,ve)?{steps:[["sudo","/bin/bash","-c",`curl -fsSL ${yh} | bash -s -- --system`]],needsSudo:!0,fetchesNetworkScript:!0}:vh,gh=e=>_a(e,Ol.kegName)?"homebrew":Es(e,"aws-cli")?"script":"unknown",_P={id:"aws",binName:"aws",...Ol,probeArgv:["aws","--version"],versionFrom:yn,platforms:vn,prerequisites:[],bootstrapInstall:vh,identify:gh,updateFor:Ti(gh,(e,t)=>e==="homebrew"?Lt(["brew","upgrade",Ol.brewFormula]):e==="script"?NP(t):null)},Si={brewFormula:"git",brewInstallSpec:"git",kegName:"git"},MP={id:"git",binName:"git",...Si,probeArgv:["git","--version"],versionFrom:yn,platforms:vn,prerequisites:["brew"],bootstrapInstall:Lt(["brew","install",Si.brewInstallSpec]),identify:xi(Si.kegName),updateFor:Il(Si)},Ei={brewFormula:"gh",brewInstallSpec:"gh",kegName:"gh"},jP={id:"gh",binName:"gh",...Ei,probeArgv:["gh","--version"],versionFrom:yn,platforms:vn,prerequisites:["brew"],bootstrapInstall:Lt(["brew","install",Ei.brewInstallSpec]),identify:xi(Ei.kegName),updateFor:Il(Ei)},Pi={brewFormula:"doppler",brewInstallSpec:"dopplerhq/cli/doppler",kegName:"doppler"},FP={id:"doppler",binName:"doppler",...Pi,probeArgv:["doppler","--version"],versionFrom:yn,platforms:vn,prerequisites:["brew"],bootstrapInstall:Lt(["brew","install","gnupg"],["brew","install",Pi.brewInstallSpec]),identify:xi(Pi.kegName),updateFor:Il(Pi)},Io="portless",hh=e=>Tp(e,Io)===null?"unknown":"npm",LP={id:"portless",binName:Io,npmPackage:Io,probeArgv:["portless","--version"],versionFrom:yn,platforms:[...vn,"win32"],prerequisites:[],bootstrapInstall:Lt(["npm","install","-g",Io]),identify:hh,updateFor:Ti(hh,e=>e==="npm"?Lt(["npm","install","-g",`${Io}@latest`]):null)},Dl={brew:IP,git:MP,aws:_P,gh:jP,doppler:FP,portless:LP},ur=Object.keys(Dl),Le=e=>Dl[e],Nl=(e,t)=>e.platforms.includes(t),_l=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 Le(o).prerequisites)n(i,[...s,o]);t.push(o)}};for(let o of e)n(o,[]);return t};var wh=e=>({id:e,present:!1,onPath:!1,binRealPath:null,version:null,manager:"unknown"}),kh=async(e,t)=>{try{return await e(t)}catch{return null}},BP=async(e,t)=>{try{let r=await e.resolveBinPath(t);return r==null?null:e.realpath(r)}catch{return null}},bh=async(e,t)=>{if(!Nl(e,t.platform))return wh(e.id);let r=await kh(t.runCommand,e.probeArgv),n=await BP(t,e.binName);if(r==null&&n==null)return wh(e.id);let o=r??(n==null?null:await kh(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)}},Do=async(e,t)=>Promise.all(e.map(r=>bh(Le(r),t)));import{$ as KP}from"zx";import{z as Rh}from"zod";var Sh=/^\d{4}-\d{2}-\d{2}$/,No=e=>{if(!Sh.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},Eh=e=>`Release date "${e}" is not a calendar date in yyyy-mm-dd form.`,wn=class extends Error{constructor(t){super(Eh(t)),this.name="InvalidReleaseDateError"}},dr=e=>{let t=e.trim();if(!No(t))throw new wn(t);return t},_o=e=>{let t=e.trim();return t===""||No(t)?!0:Eh(t)},Ml=Rh.string().refine(No,{message:"Expected a calendar date in yyyy-mm-dd form."}),jl=Rh.string().refine(e=>e===""||No(e),{message:'Expected a calendar date in yyyy-mm-dd form, or "" to clear.'});var Bt=e=>e.slice(1).split(".").map(Number),kn=e=>[...e].sort((t,r)=>{let[n,o,s]=Bt(t),[i,a,c]=Bt(r);return n!==i?(n??0)-(i??0):o!==a?(o??0)-(a??0):(s??0)-(c??0)});var xh="next",UP=/^v?(\d+)\.(\d+)\.(\d+)$/,VP=e=>e.replace(/^.*release\//,""),Fl=e=>{let t=VP(e.trim()),r=UP.exec(t);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null},Ph=e=>`${e[0]}.${e[1]}.${e[2]}`,Ll=e=>{let t=[...e.remoteBranches??[],...e.jiraVersions??[]],r=[],n=new Set;for(let o of t){let s=Fl(o);if(!s)continue;let i=Ph(s);n.has(i)||(n.add(i),r.push(s))}return kn(r.map(o=>Ph(o))).map(o=>Bt(`v${o}`))},pr=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},Bl=(e,t)=>{if(e.length===0)throw new pr;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`},bn=(e,t)=>{try{return Bl(e,t)}catch(r){if(r instanceof pr)return null;throw r}},Ul=e=>e.trim().toLowerCase()===xh,$i=e=>Ul(e)||Fl(e)!==null?{version:e}:{name:e},WP=e=>e==="regular"||e==="hotfix",Th=e=>"name"in e,GP=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:dr(n)}},Vl=e=>{let t=e.trim();if(t==="")throw new Error("Release spec is empty");let r=t.indexOf(":"),{token:n,releaseDate:o}=GP(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 u=l.toLowerCase();if(!WP(u))throw new Error(`Invalid release type "${l}". Expected "regular" or "hotfix".`);s=u}return Ci({...$i(n),type:s},{description:i,releaseDate:o})},Wl=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},Ci=(e,t)=>{let{description:r,releaseDate:n}=t;return{...e,...r!==void 0&&r!==""?{description:r}:{},...n===void 0?{}:{releaseDate:n}}},JP=e=>{let t=e.name.trim();return $s(t),Ci({id:{kind:"name",name:t,raw:t},type:e.type},e)},Gl=(e,t)=>{let r=[...t];return e.map(n=>{if(Th(n))return JP(n);let o=n.version.trim();if(o==="")throw new Error("Release entry has an empty version");if(Ul(o)){let a=Bl(r,n.type);return r.push(Bt(`v${a}`)),Ci({id:me(a),type:n.type},n)}let s=Fl(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),Ci({id:me(i),type:n.type},n)})},Jl=e=>e.some(t=>!Th(t)&&Ul(t.version));var HP=e=>e.split(`
357
+ `).map(t=>{let r=t.indexOf(" ");return r===-1?null:q(t.slice(r+1))}).filter(t=>t!==null&&t.kind==="version").map(t=>t.raw),qP=async()=>{let e=await KP({quiet:!0})`git ls-remote --heads origin 'release/v*'`;return HP(e.stdout)},YP=async()=>{let e=await ht();return e?(await Zr(e)).map(r=>r.name):[]},Mo=async()=>{let[e,t]=await Promise.allSettled([qP(),YP()]);return e.status==="rejected"&&d.warn({err:e.reason},"Failed to list remote release branches; continuing without them"),t.status==="rejected"&&d.warn({err:t.reason},"Failed to fetch Jira versions; continuing without them"),Ll({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:t.status==="fulfilled"?t.value:[]})};import zP from"node:fs";import XP from"node:path";var Kl=[".claude/settings.json",".claude/settings.local.json"],ZP=["infra-kit","ik","pnpm exec infra-kit","pnpm exec ik","pnpm infra-kit"],QP=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),ex=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},tx=(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(QP).join(".*")}$`,"s").test(t)||n===t||n.startsWith(`${t} `)},rx=e=>{let t=e.groupPath.join(" ");return t===e.cliName?[t]:[t,e.cliName]},nx=()=>mr.filter(e=>e.mutating),ox=e=>{let t=ex(e);return t===null?[]:nx().filter(r=>ZP.some(n=>rx(r).some(o=>tx(t,`${n} ${o}`)))).map(r=>r.groupPath.join(" "))},sx=(e,t)=>{let r;try{r=zP.readFileSync(XP.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}},Ch=e=>{let t={present:[],unreadable:[],hits:[]};for(let r of Kl){let n=sx(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=ox(o);s.length>0&&t.hits.push({file:r,pattern:o,commands:s})}}}return t};var ix=e=>e.every(t=>t.status!=="fail"),ax=["brew","git","gh","doppler","aws"],cx=async e=>{let t=await Do(ax,e);return new Map(t.map(r=>[r.id,{manager:r.manager,version:r.version,present:r.present,onPath:r.onPath}]))},wt=async(e,t,r,n)=>{try{return await hn()`${t}`,{name:e,status:"pass",message:r}}catch{return{name:e,status:"fail",message:n}}},lx=async()=>{let e="orca installed",t=await Ct();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)"}},Bh=(e,t,r,n)=>{let o=de.join(Lh.homedir(),t),s="Run: infra-kit setup --skip-tools";if(!te.existsSync(o))return{name:e,status:"fail",message:`~/${t} not found. ${s}`};let i=te.readFileSync(o,"utf-8"),a=i.indexOf(lr),c=i.indexOf(Ft);return a===-1||c===-1||c<a?{name:e,status:"fail",message:`infra-kit ${r} block missing from ~/${t}. ${s}`}:i.slice(a,c+Ft.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`}},ux=()=>Bh("zshrc init block",".zshrc","shell",ph()),dx=()=>Bh("zshenv session block",".zshenv","session-env",Al()),px=async()=>{let e="pnpm enableGlobalVirtualStore";try{let t=await P(),r=de.join(t,"pnpm-workspace.yaml");if(!te.existsSync(r))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${r}`};let n=te.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}`}}},mx=async()=>{try{return Pt(),{config:await W(),error:null}}catch(e){return{config:null,error:e}}},fx=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)"}},gx=384,Hl=448,hx=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(", "),yx=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}}})),vx=async(e,t={})=>{let r="env tokens configured",n=t.readStore??Je,o=t.resolveToken??Om;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 yx(await Ls(),o);return{name:r,status:"pass",message:hx(s)}},wx=()=>at.env[Qt]||void 0,kx=async(e={})=>{let t="tokens.json present",r=e.readStore??Je,n=e.storePath??Tt;if((e.readEnvToken??wx)())return{name:t,status:"skip",message:`${Qt} is set; that channel takes precedence over the store`};let s;try{s=v(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 ${Qt} instead.`}}return{name:t,status:"pass",message:`${s} holds ${a.length} token(s): ${a.join(", ")}`}},jo=(e,t)=>{let r=t(e);return r===null?null:r.mode&511},bx=async(e,t={})=>{let r="tokens.json perms",n=t.storePath??Tt,o=t.statPath??Rx,s=t.chmodPath??te.chmodSync,i;try{i=await n()}catch{return{name:r,status:"skip",message:"the token store path could not be resolved"}}if(jo(i,o)===null)return{name:r,status:"skip",message:`No store to protect at ${v(i)} (see tokens.json present)`};let a=de.dirname(i),c=de.dirname(a),l=de.dirname(c),p=[{target:l,expected:Hl,actual:jo(l,o)},{target:c,expected:Hl,actual:jo(c,o)},{target:a,expected:Hl,actual:jo(a,o)},{target:i,expected:gx,actual:jo(i,o)}].filter(f=>f.actual!==null&&f.actual!==f.expected);if(p.length===0)return{name:r,status:"pass",message:`${v(i)} is 0600 (0700 dirs)`};let m=p.map(f=>`${v(f.target)} is ${$h(f.actual)}, expected ${$h(f.expected)}`).join("; ");if(!e)return{name:r,status:"fail",message:`${m}. Fix: run \`infra-kit setup --skip-tools\` or \`infra-kit doctor --fix\`.`};for(let f of p)s(f.target,f.expected);return{name:r,status:"pass",message:`Tightened ${p.length} path(s): ${m}`}},$h=e=>`0${e.toString(8).padStart(3,"0")}`,Rx=e=>{try{return te.statSync(e)}catch{return null}},Sx=async()=>{let e="user override path";try{let t=await Y(),r=te.existsSync(t.userProject),n=await $o(t.userProject,r),o=r?Ao(n):"(not created \u2014 seed failed?)";return{name:e,status:"pass",message:`${v(t.userProject)} ${o} \u2014 project: ${t.projectName}`}}catch(t){return{name:e,status:"fail",message:t.message}}},Ex=async()=>{let e="legacy user-global config",t;try{t=await Y()}catch{return{name:e,status:"skip",message:"infra-kit config paths could not be resolved"}}let r=de.join(de.dirname(t.userGlobal),"config.json");return te.existsSync(r)?te.existsSync(t.userGlobal)?{name:e,status:"fail",message:`Stale legacy config.json found at ${v(r)} \u2014 ${v(t.userGlobal)} is active; remove the old file.`}:{name:e,status:"fail",message:`Legacy user-global config.json found at ${v(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"}},Ah=/^\d+\.\d+\.\d+$/,Px=(e,t)=>e===t||!Ah.test(e)||!Ah.test(t)?!1:kn([`v${e}`,`v${t}`])[0]===`v${e}`,xx=async(e,t)=>{let r;try{r=await Pe(e)}catch{return[]}let n=[];for(let o of r){let s=nr(or(de.join(o,"CLAUDE.md")));s.state==="ok"&&s.version!==void 0&&Px(s.version,t)&&n.push(s.version)}return n},Tx=async(e,t)=>{let r=await xx(e,t);if(r.length===0)return"";let n=kn(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`},Cx=async()=>{let e=[{name:"CLAUDE.md block",status:"skip",message:"no infra-kit config in this repo"}],t;try{t=(await Y()).main}catch{return e}if(!te.existsSync(t))return e;let r=de.dirname(t),n=de.join(r,"CLAUDE.md"),o=te.existsSync(n)?te.readFileSync(n,"utf-8"):"",s=Ze(o,_e,Qe),i=s?"CLAUDE.md block present":"infra-kit block missing from CLAUDE.md. Run: infra-kit setup --skip-tools",a=await Tx(r,U.version);return[{name:"CLAUDE.md block",status:s?"pass":"fail",message:`${i}${a}`}]},$x=async()=>{try{let e=(await Y()).main;return te.existsSync(e)?de.dirname(e):null}catch{return null}},Ax=e=>{let t=vm();return t===null||!Un(t,e)?"":` \u2014 plugin ${t} is fetched but not applied. Run: ${Wr}`},Ox=e=>{let t=e.kind==="installed"?_s(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 ${G} version ${t}${Ax(t)}`}},Oh=3,Ih=(e,t)=>ve(e)===ve(t),Ix=e=>{if(e===void 0||e.gitRoot===null)return"";let t=v(e.gitRoot);if(e.projectDir!==null){if(Ih(e.projectDir,e.gitRoot))return"";let r=Nn(e.gitRoot,ve(e.projectDir),ve)?"below the repo root":"not this checkout";return` \u2014 this session was launched from ${v(e.projectDir)}, ${r}: the plugin and this repo's .claude/settings.json hooks load only from ${t} (measured); restart Claude Code there`}return Ih(e.cwd,e.gitRoot)?"":` \u2014 if Claude Code was launched from ${v(e.cwd)} rather than ${t}, it loaded neither the plugin nor this repo's hooks; launch it at ${t}`},Dx=(e,t)=>{let r="plugin installed",n=Ix(t);if(e.kind==="installed"){let{scope:c,projectPath:l}=e.installation,u=l===null?"":`, ${v(l)}`;return{name:r,status:"pass",message:`Plugin ${G} installed (${c??"unknown"} scope${u})${n}`}}if(e.kind==="absent")return{name:r,status:"fail",message:`Plugin ${G} is not installed. Run: ${ft}${n}`};let o=e.installations.map(c=>c.projectPath===null?"(unnamed project)":v(c.projectPath)),s=o.length-Oh,i=s>0?` and ${s} more`:"",a=`${o.slice(0,Oh).join(", ")}${i}`;return{name:r,status:"fail",message:`Plugin ${G} is installed for ${a} only, not this project. Run: ${ft}${n}`}},Nx=()=>wt("claude CLI",["claude","--version"],"Installed: claude","claude CLI not found on PATH \u2014 `infra-kit setup` cannot install the plugin; install Claude Code first");var _x=(e,...t)=>{try{return JSON.parse(te.readFileSync(de.join(e,...t),"utf-8"))}catch{return null}},Mx=e=>{if(e.kind!=="installed")return{kind:"not-installed"};let t=_s(e.installation),{installPath:r}=e.installation;if(r===null)return{kind:"skills-only",version:t};let n=_x(r,Me),o=n!==null&&typeof n=="object"?n[tt]:void 0;return o==null||typeof o!="object"?{kind:"skills-only",version:t}:{kind:"stale-server",version:t,keys:Object.keys(o)}},Dh=e=>`Plugin ${G} ${e===null?"(version unreadable)":e}`,jx=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: ${ft}`};if(e.kind==="stale-server"){let r=e.keys.length===0?"":` (under "${e.keys.join('", "')}")`;return{name:t,status:"pass",message:`${Dh(e.version)} still carries an MCP server in its ${Me}${r} \u2014 a copy from before the plugin went skills-only. Update it: infra-kit setup (or ${Wr}), then restart Claude Code`}}return{name:t,status:"pass",message:`${Dh(e.version)} is skills-only \u2014 no ${Me}, as shipped; the /infra-kit:* skills drive the infra-kit CLI`}},Fx=(e,t)=>{let r=Xt(e===null?{}:{projectPath:e}),n=Bn();return[{name:"marketplace registered",status:n?"pass":"fail",message:n?`Marketplace ${oe} is known to Claude Code`:`Marketplace ${oe} is not registered. Run: claude plugin marketplace add ${xt}`},Dx(r,t),Ox(r),jx(Mx(r)),{name:"CLI version",status:"pass",message:`infra-kit CLI ${U.version}`}]},Lx=(e,t)=>{let r="background setup";if(e===null)return{name:r,status:"skip",message:"not run yet \u2014 it runs after the next background update check"};if(e.version!==t)return{name:r,status:"skip",message:`last ran for ${e.version}; runs for ${t} after the next background update check`};if(e.finishedMs===null)return{name:r,status:"skip",message:`a pass for ${t} is running, or was interrupted and will be retried`};let n=e.runs.filter(o=>o.status!=="ok");return n.length===0?{name:r,status:"pass",message:`ran for ${t} on the machine and ${e.runs.length-1} project(s)`}:{name:r,status:"warn",message:`${n.length} run(s) left work for you (${n.map(o=>`${o.root??"machine"}: ${o.status}`).join(", ")}) \u2014 see ${v(cn())}, or run: infra-kit setup`}},Bx=({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(", ")},Ux=e=>{let t="Agent mode",r=Cs(e),n=Bx(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})`}},Nh=4,Vx=e=>{let t=e.slice(0,Nh).join(", "),r=e.length-Nh;return r>0?`${t} +${r} more`:t},Wx=e=>{let t="Agent allowlist",{present:r,unreadable:n,hits:o}=Ch(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"} (${Vx(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 ${Kl.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`}},Gx=(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`},Jx=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 Sg(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?v(i.worktreePath):"worktree missing";return`${i.branch} (${Gx(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`}},Uh=e=>Ma(["trust"],{bin:e}),Kx=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),_h="ERR_TLS_CERT_ALTNAME_INVALID",Vh=()=>`portless serving TLS on :${Et}`,Hx=async(e,t,r)=>{let n=Vh();return await e(Et,!0)?{name:n,status:"pass",message:`portless is serving HTTPS on :${Et}`}:{name:n,status:"fail",message:`No portless daemon is serving HTTPS on :${Et}. Install it once (needs root): \`${St(t,r)}\`.`}},qx=async(e,t,r,n,o)=>{let s="portless CA chain valid",i=["localhost",...t.slice(0,1).map(u=>u.name)],c=(await Promise.all(i.map(async u=>({servername:u,result:await e(Et,u)})))).filter(u=>!u.result.ok);if(c.length===0)return{name:s,status:"pass",message:`Served certificate chains to ${v(r)} (${i.join(", ")})`};let l=c.map(u=>u.result.ok?"":u.result.code);return l.includes(_h)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${_h} for servername(s) ${c.map(u=>u.servername).join(", ")} \u2014 doctor's probe is wrong, your trust store is not implicated. Please report this.`}:l.some(u=>Kx.has(u))?{name:s,status:"fail",message:`The daemon is serving a certificate that does not chain to ${v(r)}. Its CA was regenerated \u2014 run \`${Uh(n)}\`, or reinstall: \`${St(n,o)}\`.`}:{name:s,status:"fail",message:`TLS handshake failed (${l.join(", ")})`}},Yx=(e,t,r)=>{let n="portless CA trusted";return e?{name:n,status:"pass",message:`${v(t)} matches the recorded ca.trusted fingerprint`}:{name:n,status:"fail",message:`The portless CA is not trusted (or was regenerated). Run: \`${Uh(r)}\` (no sudo needed).`}},zx=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 \`${Ma(["alias","--remove","<name>"],{bin:r})}\`.`}},Ut="portless service target",Lo=e=>({name:Ut,status:"warn",message:e}),Wh=e=>e==="darwin"?_p:e==="linux"?Mp:null,Xx=e=>e==="darwin"?`sudo launchctl kickstart -k system/${Np}`:`sudo systemctl restart ${jp}`,Zx="/bin/ps",Qx=e=>{try{let t=Fh(Zx,["-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}},Mh=e=>{try{return te.readFileSync(e,"utf-8")}catch{return null}},eT=e=>{try{return te.statSync(e).mtime}catch{return null}},tT=2e3,rT=e=>{try{let t=Fh(e,["-p","process.version"],{encoding:"utf-8",timeout:tT}),r=t.stdout?.trim()??"";return{version:r===""?null:r,status:t.status,signal:t.signal}}catch{return{version:null,status:null,signal:null}}},nT=(e,t)=>({platform:e.platform??at.platform,readServiceFile:e.readServiceFile??Mh,readFile:e.readFile??Mh,exists:e.exists??te.existsSync,realpath:e.realpath??ve,mtime:e.mtime??eT,execPath:e.execPath??at.execPath,home:e.home??Lh.homedir(),cwd:e.cwd??at.cwd(),repoRoot:e.repoRoot??Eo,stateDir:(e.stateDir??Lp)(),processStartTime:e.processStartTime??Qx,version:e.version??at.version,arch:e.arch??at.arch,nodeVersionOf:e.nodeVersionOf??rT,isGlobal:e.isGlobal??Ts().node.isGlobal,nodeFs:e.nodeFs??te,stableNode:null,stableNodeSidecar:null,bin:t}),Bo="portless node",fr="~/.infra-kit/node",Fo=e=>({row:{name:Bo,status:"fail",message:e},stableNode:null,sidecar:null}),jh=(e,t)=>{try{return e(t,{throwIfNoEntry:!1})}catch{return}},oT=e=>e.signal!==null?`killed by ${e.signal}`:e.status===null?"did not start":e.status!==0?`exit ${e.status}`:`printed ${e.version??"nothing"}`,sT=(e,t)=>e.status===0&&e.signal===null&&e.version===t.version,iT=e=>{let t=Gp(e.home),r=jh(e.nodeFs.lstatSync,t);if(r===void 0)return Fo(`${fr} is missing and could not be written \u2014 run \`infra-kit setup\` and see the debug log`);if(!r.isFile())return Fo(`${fr} is not a regular file; infra-kit will not replace it \u2014 move it away and run \`infra-kit setup\``);let n=Jp(e.home,e.nodeFs);if(n===null)return Fo(`${fr} has no readable node.source.json and it could not be rewritten \u2014 run \`infra-kit setup\``);let o=jh(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 Fo(`${fr} is Node ${n.version} (${n.method} of ${v(n.source)}); infra-kit runs ${e.version} at ${v(e.execPath)}, a different file, and could not relink it \u2014 run \`infra-kit setup\``);if(!i){let c=e.nodeVersionOf(t);if(!sT(c,e))return Fo(`${fr} does not run as Node ${e.version} (${oT(c)}). Re-run through the current Node: \`${St(e.bin,{...e,stableNode:null})}\`, then \`infra-kit setup\``)}return{row:{name:Bo,status:"pass",message:`${fr} is Node ${n.version} (${n.arch}, ${n.method} of ${v(n.source)})`},stableNode:t,sidecar:n}},aT=e=>{if(Wh(e.platform)===null)return{row:{name:Bo,status:"skip",message:"no portless OS service on this platform"},stableNode:null,sidecar:null};let t=iT(e);return e.isGlobal()?t:{...t,row:{name:Bo,status:"skip",message:`not a global install; the global infra-kit keeps ${fr} current`}}},Gh=(e,t)=>{let r=nT(e,t),n=aT(r);return{seams:{...r,stableNode:n.stableNode,stableNodeSidecar:n.sidecar},node:n.row}},cT=(e,t)=>{let r=t.readFile(de.join(e,"package.json"));try{let n=r===null?null:ge.object({version:ge.string()}).safeParse(JSON.parse(r));return n?.success===!0?n.data.version:"?"}catch{return"?"}},lT=e=>{let t=Number.parseInt(e.readFile(de.join(e.stateDir,"proxy.pid"))?.trim()??"",10);return!Number.isInteger(t)||t<=0?null:e.processStartTime(t)},uT=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?null:t},dT=(e,t,r)=>{let n=lT(r),o=a=>n!==null&&a!==null&&n.getTime()<a.getTime(),s=r.stableNodeSidecar,i=[...s!==null&&o(uT(s.versionChangedAt))?[`Node ${s.version}`]:[],...o(r.mtime(de.join(e,"package.json")))?[`portless ${t}`]:[]];return i.length===0?null:i.join(" and ")},pT=async(e,t)=>{let r=t.realpath(t.cwd);return r===t.realpath(t.home)?!1:Nn(await t.repoRoot()??r,e,t.realpath)},gr=e=>({state:"drifted",row:e}),mT=async(e,t,r)=>{let n=St(r.bin,r);if(!r.exists(e))return gr({name:Ut,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=de.join(ja(r.home),"dist","cli.js");if(t!==o)return gr(Lo(`The service points at \`${t}\`, a version-specific location. Re-run once to switch it to the stable link: \`${n}\``));if(xs(r.home,r.exists)===null)return gr({name:Ut,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(ja(r.home));if(await pT(s,r))return gr({name:Ut,status:"fail",message:`The service runs portless from a project checkout (${s}). Re-run \`service install\` from the global install: \`${n}\``});let i=fT(e,n,r);if(i!==null)return i;let a=cT(s,r),c=dT(s,a,r);return c!==null?{state:"converged",row:Lo(`The running daemon predates ${c} that \`dev\` will talk to. Restart it: \`${Xx(r.platform)}\` (or reboot).`)}:{state:"converged",row:{name:Ut,status:"pass",message:`service runs \`${e}\` (Node ${r.version}) + stable link \u2192 portless ${a}`}}},fT=(e,t,r)=>r.stableNode!==null?r.realpath(e)===r.realpath(r.stableNode)?null:gr(Lo(`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:gr(Lo(`The service runs \`${e}\`; infra-kit runs \`${r.execPath}\`. Works until the old Node is removed. Re-run when convenient: \`${t}\``)),Jh=async e=>{let t=Wh(e.platform);if(t===null)return{state:"absent",row:{name:Ut,status:"skip",message:"no portless OS service file on this platform"}};let r=e.readServiceFile(t);if(r===null)return{state:"absent",row:{name:Ut,status:"skip",message:`the OS service is not installed (no ${t})`}};let[n,o]=Kf(e.platform,r)??[];return n===void 0||o===void 0?gr(Lo(`could not parse ${t} \u2014 re-run \`${St(e.bin,e)}\` to rewrite it.`)):mT(n,o,e)},Kh=async(e,t)=>{let{seams:r}=Gh(e,t);return{state:(await Jh(r)).state,stableNode:r.stableNode}},gT=()=>[Bo,Ut,Vh(),"portless CA chain valid","portless CA trusted","portless routes"],hT=async(e={})=>{let t=e.resolveBin??Dp,r=e.isProxyServing??Fp,n=e.handshake??Vp,o=e.caTrusted??Up,s=e.routes??Mn,i=e.isListening??_n,a=(e.caPath??Bp)(),c=t();if(c===null)return[{name:"portless installed",status:"fail",message:"portless is not resolvable from node_modules \u2014 run `pnpm install`."},...gT().map(b=>({name:b,status:"skip",message:"portless not resolvable"}))];let l={name:"portless installed",status:"pass",message:"portless is resolvable from node_modules"},{seams:u,node:p}=Gh(e,c),m=s(),f=await Hx(r,c,u),y=f.status==="fail"?{name:"portless CA chain valid",status:"skip",message:"no daemon to handshake with"}:await qx(n,m,a,c,u);return[l,p,(await Jh(u)).row,f,y,Yx(o(),a,c),await zx(m,i,c)]},yT=async(e={})=>{let t="portless routes",r=e.routes??Mn,n=e.isListening??_n,o=e.devSessionRunning??Uf,s=r();if(s.length===0)return{name:t,status:"pass",message:"No portless routes registered"};let i=await Promise.all(s.map(async u=>({name:u.name,port:u.port,live:await n(u.port)}))),{prunable:a,withheld:c}=Bf(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??Wp().removeAlias;for(let u of a)await l(u);return{name:t,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},Ai=async(e={})=>{let t=await mx(),r=cx(e.probeDeps??Oo()),n=async(m,f)=>{let[y,b]=await Promise.all([f,r]),w=b.get(m);return w===void 0?y:{...y,detail:w}},o=await Promise.all([n("brew",wt("brew installed",Le("brew").probeArgv,"Homebrew is installed","Homebrew is not installed. Install from: https://brew.sh/")),n("git",wt("git installed",Le("git").probeArgv,"git is installed","git is not installed. Install with: brew install git")),n("gh",wt("gh installed",Le("gh").probeArgv,"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/")),wt("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),n("doppler",wt("doppler installed",Le("doppler").probeArgv,"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli")),n("aws",wt("aws installed",Le("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")),wt("package manager installed",["pnpm","--version"],"Installed: pnpm","pnpm is not installed. Install from: https://pnpm.io/installation"),wt("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"),lx(),Promise.resolve(ux()),Promise.resolve(dx()),px(),Promise.resolve(fx(t)),kx(),vx(t),bx(e.fix??!1),Sx(),Ex()]),s=await hT(e.portlessDeps);if(e.fix){let m=await yT(),f=s.findIndex(y=>y.name===m.name);f>=0?s[f]=m:s.push(m)}let i=await $x(),a=await Eo(),c={projectDir:at.env.CLAUDE_PROJECT_DIR||null,cwd:at.cwd(),gitRoot:a},l=[await Nx(),...Fx(i,c),Po(),Ux({env:at.env,stdinIsTTY:at.stdin.isTTY===!0,flag:_.source==="flag"}),a===null?{name:"Agent allowlist",status:"skip",message:"no git root"}:Wx(a)],u=[...o,await Jx(a),...s,...await Cx(),...l,Lx(ln(),U.version)],p={checks:u.map(m=>({name:m.name,status:m.status,message:m.message,fixable:Xc.has(m.name),detail:m.detail})),allPassed:ix(u),cliVersion:U.version};return{content:k(JSON.stringify(p,null,2)),structuredContent:p}},ql=E({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:ge.array(ge.object({name:ge.string().describe("Name of the check"),status:ge.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:ge.string().describe("Details about the check result"),fixable:ge.boolean().describe("Whether `infra-kit doctor --fix` repairs this row"),detail:ge.object({manager:ge.string().describe("Which package manager owns this install, read from its resolved path"),version:ge.string().nullable().describe("The version the tool reported, or null"),present:ge.boolean().describe("The tool is installed somewhere findable \u2014 on PATH or not"),onPath:ge.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:ge.boolean().describe("Whether no check failed (warnings and skips do not count)"),cliVersion:ge.string().describe("Version of the infra-kit CLI that produced this report")},handler:()=>Ai()});import{E2E_MODE_ENV as GT}from"@slip-stream-kit/config/internal";import ru from"node:fs";import JT from"node:os";import Vo from"node:path";import Di from"node:process";import{z as R}from"zod";var ct=(e,t,r)=>new C({status:"refused",reason:e,...t},2,r);import{describeProxyRoutes as vT,loadDev as wT,readAppAliasName as kT,readCloudOrigin as bT,readLocalContext as qh}from"@slip-stream-kit/config/internal";import Hh from"node:fs";import hr from"node:path";import Oi from"node:process";import{z as Yl}from"zod";var RT=async e=>{let t=hr.join(e,"apps"),r=Hh.existsSync(t)?Hh.readdirSync(t).toSorted():[],n=[];for(let o of r){let s=hr.join(t,o,"tests"),a=(await It(s))?.e2e;a?.target!==void 0&&n.push({app:o,testsDir:s,e2e:{target:a.target}})}return n},ST=(e,t)=>{let[r,n]=hr.relative(e,t).split(hr.sep);return r==="apps"&&n?n:void 0},ET=(e,t,r,n)=>{let o=c=>e.find(l=>l.app===c),s=o(t)??(t===void 0?o(ST(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 g(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 C({status:"argument_required",argument:a,choices:Yl.toJSONSchema(Yl.object({app:Yl.enum(i)})),agentMode:_.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(", ")}`})},PT=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}})),xT=e=>lo(e).apps.find(t=>t.env!=="")?.env??null,zl=async(e,t={})=>{let r=t.cwd??Oi.cwd(),n=t.projectRoot??await P(),o=(t.env??Oi.env)[xr]||null,s=t.healthProbe??za,i=ET(await RT(n),e,r,n),{target:a}=i.e2e,[c,l]=a.split("/"),u=hr.join(n,"apps",c,l),p=(await er(u)).name,m=(await It(u))?.deployedUrlEnv??null;if(!p)throw new g(void 0,{operation:`resolve e2e target ${a}`,remediation:`check \`e2e.target\` in ${hr.join(i.testsDir,"infra-kit.config.ts")}`,stderrExcerpt:`${u} has no package.json name`});let f=Wm(u),y=kT(p,u),b=`${y}.localhost`,w=`https://${b}`,x=0;if(l==="ui")x=(t.listRoutes??Mn)().find(T=>T.name===b||T.name===y)?.port??0;else{let T=qh(u).info.get(p);x=T?.port??0,w=T?.origin??w}let D=x>0&&await s({tag:a,port:x,kind:l})==="ok",N=D?xT(u):null;return{app:i.app,testsDir:i.testsDir,target:a,kind:l,targetDir:u,packageName:p,deployedUrlEnv:m,release:f,env:o,servedEnv:N,localUrl:w,served:D}},Yh=e=>{let{app:t,testsDir:r,target:n,packageName:o,deployedUrlEnv:s,release:i,env:a,servedEnv:c,localUrl:l}=e;return{app:t,testsDir:r,target:n,packageName:o,deployedUrlEnv:s,release:i,env:a,servedEnv:c,localUrl:l}},Xl=async(e,t={})=>{let r=t.healthProbe??za,n=qh(e.targetDir),o=e.kind==="ui"?await wT(e.targetDir):void 0,s=o?.proxy?vT({proxy:o.proxy,localContext:n,env:e.env??void 0,cloud:bT(e.deployedUrlEnv??void 0,t.env??Oi.env),getRelease:()=>e.release}):[],i=new Map([...n.info].map(([a,c])=>[a,c.port]));return{...Yh(e),mode:"local",baseUrl:e.localUrl,routes:await PT(s,i,r)}},Zl=(e,t={})=>{let{env:r,deployedUrlEnv:n,target:o}=e;if(!n)throw ct("no_deployed_url_env",{target:o},{operation:`resolve the deployed app ${e.app}'s cloud e2e run targets`,remediation:`declare \`deployedUrlEnv: '<APP>_URL'\` in ${hr.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??Oi.env)[n];if(!r||!s){let i=s?xr:n;throw ct("env_not_loaded",{missing:i},{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 ${xr}, and ${i} is not set`})}return{...Yh(e),mode:"cloud",baseUrl:s,routes:[]}};import TT from"node:fs";import CT from"node:path";import{stripVTControlCharacters as $T}from"node:util";import{z as A}from"zod";var zh=2e3,Xh="--reporter=line,json",Zh=e=>({PLAYWRIGHT_JSON_OUTPUT_FILE:e,PLAYWRIGHT_JSON_OUTPUT_NAME:e}),Qh=e=>e.some(t=>t==="--reporter"||t.startsWith("--reporter=")),Ql=A.object({message:A.string().optional()}),ey=A.object({type:A.string()}),AT=A.object({status:A.string(),retry:A.number(),error:Ql.optional(),errors:A.array(Ql).optional(),annotations:A.array(ey).optional(),attachments:A.array(A.object({name:A.string(),path:A.string().optional()})).optional()}),OT=A.object({projectName:A.string(),status:A.string(),expectedStatus:A.string().optional(),annotations:A.array(ey).optional(),results:A.array(AT)}),IT=A.object({title:A.string(),file:A.string(),line:A.number().optional(),tests:A.array(OT)}),ty=A.lazy(()=>A.object({title:A.string(),specs:A.array(IT).optional(),suites:A.array(ty).optional()})),DT=A.object({config:A.object({rootDir:A.string().optional()}).optional(),suites:A.array(ty),errors:A.array(Ql).optional(),stats:A.object({expected:A.number(),unexpected:A.number(),flaky:A.number(),skipped:A.number()})}),ry=e=>{let t=$T(e);return t.length>zh?`${t.slice(0,zh)}\u2026`:t},NT=e=>{let t=e.error?.message??e.errors?.[0]?.message;return t===void 0?null:ry(t)},_T=e=>e.status==="unexpected"||e.status==="flaky",MT=e=>{let t=new Map;for(let r of e)t.set(r.projectName,[...t.get(r.projectName)??[],r]);return t},jT=e=>new Set([...e.annotations??[],...e.results.flatMap(t=>t.annotations??[])].map(t=>t.type)),FT=(e,t)=>{let r=e.filter(_T),n=r.at(-1);if(!n)return null;let o=n.results.findLast(i=>i.status!=="passed"&&i.status!=="skipped"),s=r.length===e.length&&n.status==="unexpected";return{...t,status:s?"unexpected":"flaky",retry:o?.retry??0,runs:e.length,failedRuns:r.length,error:o?NT(o):"Expected to fail, but passed.",tracePath:o?.attachments?.find(i=>i.name==="trace")?.path??null}},LT=e=>{let t=DT.safeParse(e);if(!t.success)return null;let{config:r,suites:n,errors:o,stats:s}=t.data,i=[],a=new Map,c=0,l=(p,m)=>{let f=new Set(m.flatMap(w=>[...jT(w)])),y=m.some(w=>w.expectedStatus==="failed");if(!y&&!f.has("fixme")&&!f.has("skip"))return;let b=a.get(p)??{file:p,fail:0,fixme:0,skip:0};y&&(b.fail+=1),f.has("fixme")?b.fixme+=1:f.has("skip")&&(b.skip+=1),a.set(p,b)},u=(p,m)=>{for(let f of p.specs??[]){let y=r?.rootDir?CT.resolve(r.rootDir,f.file):f.file,b=[...m,f.title].join(" \u203A ");l(y,f.tests);for(let[w,x]of MT(f.tests)){let D=FT(x,{title:b,file:y,line:f.line??null,project:w});D&&(D.runs>1&&D.failedRuns<D.runs&&(c+=1),i.push(D))}}for(let f of p.suites??[])u(f,[...m,f.title])};for(let p of n)u(p,[]);return{summary:{expected:s.expected,unexpected:s.unexpected,flaky:s.flaky,skipped:s.skipped,repeatFlaky:c},failures:i,annotated:[...a.values()],errors:(o??[]).flatMap(p=>p.message===void 0?[]:[ry(p.message)])}},ny=e=>{try{return LT(JSON.parse(TT.readFileSync(e,"utf8")))}catch{return null}};import Uo from"node:fs";import sy from"node:path";import Ii from"node:process";var BT=e=>sy.join(e,"node_modules",".cache","infra-kit-e2e.lock"),UT=e=>{try{return Ii.kill(e,0),!0}catch(t){return t.code==="EPERM"}},oy=e=>{try{return Uo.writeFileSync(e,String(Ii.pid),{flag:"wx"}),!0}catch(t){if(t.code==="EEXIST")return!1;throw t}},eu=e=>{try{let t=Number.parseInt(Uo.readFileSync(e,"utf8"),10);return Number.isInteger(t)&&t>0?t:null}catch{return null}},iy=e=>{let t=BT(e);if(Uo.mkdirSync(sy.dirname(t),{recursive:!0}),!oy(t)){let r=eu(t);if(r!==null&&r!==Ii.pid&&UT(r))return{holder:r};if(Uo.rmSync(t,{force:!0}),!oy(t))return{holder:eu(t)??0}}return{release:()=>{eu(t)===Ii.pid&&Uo.rmSync(t,{force:!0})}}};import{spawn as VT}from"node:child_process";import WT from"node:os";import tu from"node:process";var ay=(e,t,r)=>new Promise((n,o)=>{let s=VT(e,t,r),i=tu.stdin.isTTY?["SIGTERM","SIGHUP"]:["SIGINT","SIGTERM","SIGHUP"],a=l=>{s.kill(l)},c=()=>{for(let l of i)tu.off(l,a)};for(let l of i)tu.on(l,a);s.once("error",l=>{c(),o(l)}),s.once("close",(l,u)=>{c(),n(l??(u?128+WT.constants.signals[u]:1))})});var KT=["playwright.config.ts","playwright.config.mts","playwright.config.js","playwright.config.mjs"],HT=e=>KT.some(t=>{try{return ru.readFileSync(Vo.join(e,t),"utf8").includes("infraKitE2e")}catch{return!1}}),nu=e=>`infra-kit dev ${e.target.split("/")[0]} --no-watch --reuse`,qT=(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(`
358
+ `)},YT=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 ct("dead_local_routes",{routes:r},{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(", ")}`})},zT=async(e,t)=>{if(e.env===null||!Um(e.env))return;let r=await(t.protectedEnvAccess??ze)();if(r.allowed)return;let n=`run ${e.app} e2e against "${e.env}"`;throw r.reason==="agent-blocked"?ct("protected_env",{env:e.env,humanMayRun:!0},{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`}):ct("protected_env",{env:e.env,humanMayRun:!1},{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`})},XT=e=>{if(!(e.servedEnv===null||e.servedEnv===e.env))throw ct("served_env_mismatch",{servedEnv:e.servedEnv,env:e.env},{operation:`run ${e.app} e2e against the local dev server`,remediation:`load the same env (\`infra-kit env-load -c ${e.servedEnv}\`), or restart \`infra-kit dev\` under "${e.env??"none"}"`,stderrExcerpt:`the dev server serving ${e.target} runs with env "${e.servedEnv}", this shell with "${e.env??"none"}"`})},ZT=async(e,t)=>{if(e.served){XT(e);let p=await Xl(e,t);return YT(p),p}if(!HT(e.testsDir))throw ct("no_dev_server",{devCommand:nu(e)},{operation:`run ${e.app} e2e locally`,remediation:`start it (\`${nu(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,servedEnv:l,localUrl:u}=e;return{app:r,testsDir:n,target:o,packageName:s,deployedUrlEnv:i,release:a,env:c,servedEnv:l,localUrl:u,mode:"local",baseUrl:u,routes:[]}},QT=(e,t,r)=>ay("pnpm",["exec","playwright","test",...t],{cwd:e.testsDir,env:{...Di.env,...r,[GT]:e.mode},stdio:["inherit",zt.enabled||H()?2:"inherit","inherit"]}),eC=(e,t)=>{let r=t.findIndex(s=>s==="--output"||s.startsWith("--output="));if(r!==-1){let s=t[r]==="--output"?t[r+1]??"":t[r].slice(9);return{args:t,outputDir:Vo.resolve(e.testsDir,s)}}let n=new Date().toISOString().replace(/[:.]/g,"-"),o=Vo.join(e.testsDir,"test-results",`ik-e2e-${n}-${Di.pid}`);return{args:[...t,`--output=${o}`],outputDir:o}},tC=e=>{if(e.mode==="cloud")return()=>{};let t=iy(e.testsDir);if("holder"in t)throw ct("run_in_progress",{pid:t.holder},{operation:`run ${e.app} e2e locally`,remediation:`wait for it to finish (or stop process ${t.holder}), then re-run`,stderrExcerpt:`another local e2e run of ${e.app} (pid ${t.holder}) is using its dev server`});return t.release},Ni=async(e,t={})=>{let r=await zl(e.app,t),n=e.cloud?Zl(r,t):await ZT(r,t);d.info(qT(n,r.served)),n.mode==="cloud"&&await zT(n,t);let o={...n,served:r.served,devCommand:n.mode==="local"&&!r.served?nu(r):null,playwrightArgs:e.playwrightArgs??[]};if(e.dryRun)return su({...o,ran:!1,exitCode:null,...ou});n.mode==="cloud"&&await L(e.yes,`Run ${n.app} e2e against ${n.baseUrl} ("${n.env}", shared)?`,{plan:o});let s=tC(n);try{return await rC(o,t.runPlaywright??QT)}finally{s()}},rC=async(e,t)=>{if(!H()||Qh(e.playwrightArgs)){let i=await t(e,e.playwrightArgs,{});return i!==0&&(Di.exitCode=i),su({...e,ran:!0,exitCode:i,...ou,report:H()?"caller-reporter":"off"})}let{args:r,outputDir:n}=eC(e,e.playwrightArgs),o=ru.mkdtempSync(Vo.join(JT.tmpdir(),"ik-e2e-report-")),s=Vo.join(o,"report.json");try{let i=await t(e,[Xh,...r],Zh(s));i!==0&&(Di.exitCode=i);let a=ny(s);return su({...e,ran:!0,exitCode:i,...a?{report:"collected",...a}:{...ou,report:"unavailable"},outputDir:n})}finally{ru.rmSync(o,{recursive:!0,force:!0})}},ou={report:"off",outputDir:null,summary:null,failures:[],annotated:[],errors:[]},su=e=>({content:k(JSON.stringify(e,null,2)),structuredContent:e}),nC={app:R.string(),testsDir:R.string(),target:R.string().describe("The package under test, `<app>/ui` or `<app>/api`."),packageName:R.string(),mode:R.enum(["local","cloud"]).describe("local (default): this worktree\u2019s dev server. cloud (--cloud): the deployed app at env."),baseUrl:R.string().describe("The URL the run was pointed at: the local alias, or the deployed URL."),deployedUrlEnv:R.string().nullable().describe("The target\u2019s variable holding its deployed URL; a cloud run reads it. Null when it declares none."),release:R.string().describe("This worktree\u2019s release slug \u2014 the first label of every local alias."),env:R.string().nullable().describe("INFRA_KIT_ENV of this process; the env a cloud run targets."),servedEnv:R.string().nullable().describe("Served local runs: the INFRA_KIT_ENV the running dev session recorded \u2014 where its cloud routes go. Null when nothing served the target or the session recorded none. A local run refuses when it differs from env."),localUrl:R.string().describe("This worktree\u2019s address for the target, whether or not anything serves it."),served:R.boolean().describe("Whether this worktree\u2019s dev server already served the target when the run began."),devCommand:R.string().nullable().describe("Local runs with nothing served: the dev command the Playwright config starts, and stops after."),routes:R.array(R.object({path:R.string(),packageName:R.string(),source:R.enum(["local","cloud"]),target:R.string().nullable(),live:R.boolean().nullable()})).describe("Served local UI runs only: the dev proxy\u2019s route-by-route local/cloud split, local backends probed."),playwrightArgs:R.array(R.string()),ran:R.boolean().describe("False for --dry-run."),exitCode:R.number().nullable().describe("Playwright\u2019s exit code; null when it did not run."),report:R.enum(["off","caller-reporter","unavailable","collected"]).describe("Per-test results: collected from Playwright\u2019s JSON reporter under --json/agent mode; caller-reporter when playwrightArgs carried its own --reporter; unavailable when the run wrote no readable report; off otherwise."),outputDir:R.string().nullable().describe("Where this run\u2019s traces and attachments live \u2014 its own directory, so a later run cannot delete them. Null unless report is collected or unavailable."),summary:R.object({expected:R.number(),unexpected:R.number(),flaky:R.number(),skipped:R.number(),repeatFlaky:R.number()}).nullable().describe("Playwright\u2019s counts by outcome, one per run (each --repeat-each repeat counts), plus repeatFlaky: tests that passed in some repeats and failed in others. Null unless report is collected."),failures:R.array(R.object({title:R.string().describe("Describe path and test title, joined with \u203A."),file:R.string(),line:R.number().nullable(),project:R.string(),status:R.enum(["unexpected","flaky"]).describe("flaky: failed, then passed on a retry or in another --repeat-each repeat."),retry:R.number().describe("The retry index of the failed attempt reported here."),runs:R.number().describe("How many times the test ran in this project \u2014 its --repeat-each repeats."),failedRuns:R.number().describe("How many of those runs failed."),error:R.string().nullable().describe("The failure message, ANSI stripped, truncated to 2000 characters."),tracePath:R.string().nullable().describe("The failed attempt\u2019s trace.zip; open with `playwright show-trace`.")})).describe("One entry per test and project that failed, needed a retry, or failed in some repeat; empty unless report is collected."),annotated:R.array(R.object({file:R.string(),fail:R.number().describe("test.fail \u2014 green only while the bug it registers exists."),fixme:R.number().describe("test.fixme \u2014 skipped as unfinished."),skip:R.number().describe("test.skip, declared or called at runtime, conditional ones included.")})).describe("Per spec file, the tests that passed or skipped while asserting little, as Playwright ran them; empty unless report is collected."),errors:R.array(R.string()).describe("Run-level errors with no test to blame (config, global setup, a spec that fails to import), ANSI stripped and truncated; empty unless report is collected.")},iu=E({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:R.string().optional().describe("App folder with an apps/<app>/tests e2e package; inferred from cwd when omitted."),dryRun:R.boolean().optional(),yes:R.boolean().optional(),cloud:R.boolean().optional().describe("Run against the deployed app at INFRA_KIT_ENV instead of this worktree."),playwrightArgs:R.array(R.string()).optional().describe("Passed to `playwright test` verbatim \u2014 a spec path, `--grep <title>`, `--project=chromium`.")},outputSchema:nC,handler:e=>Ni(e)});import _i from"node:fs";import au from"node:path";import{z as Wo}from"zod";var oC=e=>[...e.map(t=>`unset ${t}`),`unset ${xr}`,`unset ${ks}`,`unset ${bs}`,`unset ${Sp}`,`unset ${Rs}`],Mi=async()=>{let e=Tr(),t=au.join(e,Pr);if(!_i.existsSync(t))throw new Error("No loaded environment found. Run `env-load` first.");let r=Ss(t),n=oC(r),o=au.resolve(e,vs);_i.mkdirSync(e,{recursive:!0,mode:448}),Rt(o,`${n.join(`
359
359
  `)}
360
- `,384),_i.rmSync(t,{force:!0}),_i.rmSync(au.join(e,ws),{force:!0});let s={filePath:o,variableCount:r.length,unsetStatements:n};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}},cu=E({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:Vo.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{filePath:Vo.string().describe("Path to the file that must be sourced to apply"),variableCount:Vo.number().describe("Number of variables cleared"),unsetStatements:Vo.array(Vo.string()).describe("Unset statements generated")},handler:()=>Mi()});import nC from"node:path";import Wo from"node:process";import{z as Rn}from"zod";var ji=async()=>{d.info("Environment session status:");let e=Tr(),t=Wo.env[In],r=nC.join(e,Pr),n=0,o=0,s=Wo.env[ks]??null,i=Wo.env[bs]??null,a=Wo.env[Rs]??null;if(s){let l=Ss(r);l.length>0&&(o=l.length,n=l.filter(p=>p in Wo.env).length);let u=a?.replace(/\.\d{3}Z$/,"")??null;if(d.info(` ${s}: ${n} of ${o} vars loaded (project: ${i}, loadedAt: ${u}, session: ${t})
360
+ `,384),_i.rmSync(t,{force:!0}),_i.rmSync(au.join(e,ws),{force:!0});let s={filePath:o,variableCount:r.length,unsetStatements:n};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}},cu=E({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:Wo.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{filePath:Wo.string().describe("Path to the file that must be sourced to apply"),variableCount:Wo.number().describe("Number of variables cleared"),unsetStatements:Wo.array(Wo.string()).describe("Unset statements generated")},handler:()=>Mi()});import sC from"node:path";import Go from"node:process";import{z as Rn}from"zod";var ji=async()=>{d.info("Environment session status:");let e=Tr(),t=Go.env[Dn],r=sC.join(e,Pr),n=0,o=0,s=Go.env[ks]??null,i=Go.env[bs]??null,a=Go.env[Rs]??null;if(s){let l=Ss(r);l.length>0&&(o=l.length,n=l.filter(p=>p in Go.env).length);let u=a?.replace(/\.\d{3}Z$/,"")??null;if(d.info(` ${s}: ${n} of ${o} vars loaded (project: ${i}, loadedAt: ${u}, session: ${t})
361
361
  `),o>0&&n<o){let p=o-n;d.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 d.info(` Session ${t}: no env loaded
362
- `);let c={sessionId:t,sessionLoadedCount:n,sessionTotalCount:o,sessionConfig:s,sessionProject:i,sessionLoadedAt:a};return{content:k(JSON.stringify(c,null,2)),structuredContent:c}},lu=E({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:ji});import oC from"node:process";import{z as Vt}from"zod";var ay="****",ke=e=>typeof e!="string"||e.length<8?ay:`${ay}${e.slice(-4)}`;var cy=(e,t,r)=>e.map(n=>{let o=r||t[n];return o?{env:n,source:r?`env:${Qt}`:"store",redactedToken:ke(o),present:!0}:{env:n,source:"-",redactedToken:"-",present:!1}}),sC=["ENV","SOURCE","TOKEN","PRESENT"],ly=(e,t)=>{let r=[...sC,...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())},Fi=async({check:e}={})=>{let t=await Ls(),r=await Je(),n=oC.env[Qt],o=cy(t,r?.envs??{},n);if(e){let a=await Zt();for(let c of o){if(!c.present)continue;let l=n||r.envs[c.env],u=await $m({childEnv:Wn(l),project:a,config:c.env});c.status=u.outcome}}for(let a of ly(o,!!e))d.info(a);let s=o.filter(a=>!a.present);s.length>0&&d.info(`
363
- 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}},uu=E({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:Vt.boolean().optional().describe("Probe Doppler for each token\u2019s validity and scope (one cheap call per environment).")},outputSchema:{tokens:Vt.array(Vt.object({env:Vt.string().describe("Environment / Doppler config name"),source:Vt.string().describe('"store", "env:INFRA_KIT_ENV_TOKEN", or "-" when absent'),redactedToken:Vt.string().describe("Redacted token \u2014 last 4 chars at most, never the raw value"),present:Vt.boolean().describe("Whether a token is configured for this environment"),status:Vt.string().optional().describe("Only with check=true: valid | revoked | mis-scoped | unreachable")})).describe("One row per declared environment")},handler:Fi});import{z as S}from"zod";import{$ as iC}from"zx";var aC=(e,t)=>({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0,dryRun:e,atomicPush:{attempted:!1,aborted:!1},results:[],skipped:t}),cC=e=>e.dualBase?"open PRs to both dev and main":e.titleMismatch?"title/base mismatch":e.type==="hotfix"?"hotfix (targets main)":null,lC=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(", ")},pu=e=>({content:k(JSON.stringify(e,null,2)),structuredContent:e}),du=new Set(["up-to-date","fast-forward","merged"]),uC=(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=we(me(a))}catch(l){throw new g(l,{operation:`resolve release selector "${a}"`,remediation:`pass one of: ${t.join(", ")}`})}if(!o.has(c)){let l=s.get(c);throw new g(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))},dC={"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"},dy=e=>{let t=dC[e.status];if(e.status==="conflict"){let r=e.conflictPaths?.length??0;return`${t}: ${r} file(s)`}return e.reason?`${t}: ${e.reason}`:t},pC=(e,t)=>{d.info(`
364
- \u{1F4CB} Merge plan:`);for(let r of e)d.info(` ${r.branch} \u2014 ${dy(r)}`);for(let r of t)d.info(` ${r.branch} \u2014 skipped: ${r.reason}`)},mC=(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`},fC=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=q(i.branch);return a?[[ne(a),dy(i)]]:[]}));return jt(ce({branches:r,descriptions:s}),{required:!0})},gC=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 b of y)d.info(`\u2139\uFE0F ${b} was merged by someone else while we planned \u2014 dropping it from the push`)},c=await ko(t,ig(i));a(c.nowUpToDate);let l=c.kept,u=new Map;if(s&&l.length>0){d.info(`
365
- \u{1F50E} Verifying ${l.length} merge(s) with: ${s}`);let y=await cg({worktreePath:r,refs:l,command:s});u=y.failed;for(let[w,x]of y.failed)d.info(`\u2717 ${w} failed verification \u2014 not pushing it. ${x.split(`
366
- `)[0]??""}`);let b=await ko(t,y.kept);a(b.nowUpToDate),l=b.kept}if(l.length===0)return{pushed:!1,pushAborted:!1,verifyFailed:u};d.info(`
362
+ `);let c={sessionId:t,sessionLoadedCount:n,sessionTotalCount:o,sessionConfig:s,sessionProject:i,sessionLoadedAt:a};return{content:k(JSON.stringify(c,null,2)),structuredContent:c}},lu=E({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:ji});import iC from"node:process";import{z as Vt}from"zod";var cy="****",be=e=>typeof e!="string"||e.length<8?cy:`${cy}${e.slice(-4)}`;var ly=(e,t,r)=>e.map(n=>{let o=r||t[n];return o?{env:n,source:r?`env:${Qt}`:"store",redactedToken:be(o),present:!0}:{env:n,source:"-",redactedToken:"-",present:!1}}),aC=["ENV","SOURCE","TOKEN","PRESENT"],uy=(e,t)=>{let r=[...aC,...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())},Fi=async({check:e}={})=>{let t=await Ls(),r=await Je(),n=iC.env[Qt],o=ly(t,r?.envs??{},n);if(e){let a=await Zt();for(let c of o){if(!c.present)continue;let l=n||r.envs[c.env],u=await Am({childEnv:Gn(l),project:a,config:c.env});c.status=u.outcome}}for(let a of uy(o,!!e))d.info(a);let s=o.filter(a=>!a.present);s.length>0&&d.info(`
363
+ 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}},uu=E({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:Vt.boolean().optional().describe("Probe Doppler for each token\u2019s validity and scope (one cheap call per environment).")},outputSchema:{tokens:Vt.array(Vt.object({env:Vt.string().describe("Environment / Doppler config name"),source:Vt.string().describe('"store", "env:INFRA_KIT_ENV_TOKEN", or "-" when absent'),redactedToken:Vt.string().describe("Redacted token \u2014 last 4 chars at most, never the raw value"),present:Vt.boolean().describe("Whether a token is configured for this environment"),status:Vt.string().optional().describe("Only with check=true: valid | revoked | mis-scoped | unreachable")})).describe("One row per declared environment")},handler:Fi});import{z as S}from"zod";import{$ as cC}from"zx";var lC=(e,t)=>({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0,dryRun:e,atomicPush:{attempted:!1,aborted:!1},results:[],skipped:t}),uC=e=>e.dualBase?"open PRs to both dev and main":e.titleMismatch?"title/base mismatch":e.type==="hotfix"?"hotfix (targets main)":null,dC=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(", ")},pu=e=>({content:k(JSON.stringify(e,null,2)),structuredContent:e}),du=new Set(["up-to-date","fast-forward","merged"]),pC=(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=ke(me(a))}catch(l){throw new g(l,{operation:`resolve release selector "${a}"`,remediation:`pass one of: ${t.join(", ")}`})}if(!o.has(c)){let l=s.get(c);throw new g(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))},mC={"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"},py=e=>{let t=mC[e.status];if(e.status==="conflict"){let r=e.conflictPaths?.length??0;return`${t}: ${r} file(s)`}return e.reason?`${t}: ${e.reason}`:t},fC=(e,t)=>{d.info(`
364
+ \u{1F4CB} Merge plan:`);for(let r of e)d.info(` ${r.branch} \u2014 ${py(r)}`);for(let r of t)d.info(` ${r.branch} \u2014 skipped: ${r.reason}`)},gC=(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`},hC=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=q(i.branch);return a?[[ne(a),py(i)]]:[]}));return jt(ce({branches:r,descriptions:s}),{required:!0})},yC=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 b of y)d.info(`\u2139\uFE0F ${b} was merged by someone else while we planned \u2014 dropping it from the push`)},c=await bo(t,ag(i));a(c.nowUpToDate);let l=c.kept,u=new Map;if(s&&l.length>0){d.info(`
365
+ \u{1F50E} Verifying ${l.length} merge(s) with: ${s}`);let y=await lg({worktreePath:r,refs:l,command:s});u=y.failed;for(let[w,x]of y.failed)d.info(`\u2717 ${w} failed verification \u2014 not pushing it. ${x.split(`
366
+ `)[0]??""}`);let b=await bo(t,y.kept);a(b.nowUpToDate),l=b.kept}if(l.length===0)return{pushed:!1,pushAborted:!1,verifyFailed:u};d.info(`
367
367
  \u2B06\uFE0F Pushing atomically: ${l.map(y=>y.branch).join(", ")}`);let p=await Is(t,l);if(p.pushed)return{pushed:!0,pushAborted:!1,verifyFailed:u};let f=(await Promise.all(l.map(async y=>({branch:y.branch,landed:await Or(t,y.branch)===y.sha})))).filter(y=>y.landed);return f.length>0&&d.warn(`\u26A0\uFE0F The push reported failure, but origin already carries ${f.map(y=>y.branch).join(", ")} \u2014 re-run to reconcile.`),{pushed:!1,pushAborted:!0,verifyFailed:u,abortedBy:p.stderr?.split(`
368
- `)[0],observedLanded:f.map(y=>y.branch)}},hC=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 g(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 g(void 0,{operation:"choose the merge-dev mode",stderrExcerpt:"--tree belongs to --continue",remediation:"run the rerun a --continue preview printed, unchanged"})},uy=e=>{let{results:t,atomicPush:r,declined:n}=e;for(let i of t){let a=i.reason?.split(`
369
- `)[0];d.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=>!du.has(i.status));return pu({successfulMerges:o.length-s.length,failedMerges:s.length,failedBranches:s.map(i=>i.branch),totalBranches:t.length,dryRun:!1,atomicPush:r,results:t,skipped:[]})},yC=async e=>{let{all:t,versions:r,verify:n,confirmedCommand:o}=e,s=await Re();if(e.abort)return uy(await Ig({cwd:s,versions:r,all:t,confirmedCommand:o}));let i=typeof n=="string"&&n.length>0?n:void 0;return uy(await Ag({cwd:s,versions:r,all:t,verify:i,trees:Og(e.tree),confirmedCommand:o}))},Li=async e=>{let{all:t,versions:r,dryRun:n=!1,verify:o,keepConflicts:s=!1,confirmedCommand:i}=e;hC(e);let a=o===!0?ag:o||void 0;if(await Qc({operation:"merge dev into release branches"}),e.continue||e.abort)return yC(e);let c=[],l=[];for(let J of await F()){let Yt=cC(J);Yt?l.push({branch:J.branch,reason:Yt}):c.push(J.branch)}if(c.length===0)return d.info(l.length===0?"\u2139\uFE0F No open release branches found":`\u2139\uFE0F No open regular release branches \u2014 ${l.length} skipped (${lC(l)})`),h.print(),pu(aC(n,l));let u=await Re();try{await iC({cwd:u,quiet:!0})`git fetch origin --prune`}catch(J){throw new g(J,{operation:"fetch origin before planning the merges",remediation:"check network access and that `origin` is reachable"})}let p=r===void 0?c:uC(r,c,l),m=await im({cwd:u},async J=>{let Yt=li(J.remove);try{return await vC({cwd:u,worktree:J,toPlan:p,candidates:c,skipped:l,all:t,versions:r,dryRun:n,verify:a,keepConflicts:s,confirmedCommand:i})}finally{Yt()}}),{entries:f,selected:y,pushed:b,pushAborted:w,abortedBy:x,declined:D,verifyFailed:N,handOffs:T}=m,he=await qe(u).catch(()=>[]);return bC({entries:f,selected:y,pushed:b,pushAborted:w,abortedBy:x,declined:D,verifyFailed:N,handOffs:T,dryRun:n,worktrees:he,skipped:l})},vC=async e=>{let{cwd:t,worktree:r,toPlan:n,candidates:o,skipped:s,all:i,versions:a,dryRun:c,verify:l,keepConflicts:u,confirmedCommand:p}=e,m=u?await De(t,"origin/dev"):null,f=await sg({cwd:t,worktreePath:r.path,branches:n}),y={entries:f,pushed:!1,pushAborted:!1,declined:!1};if(pC(f,s),c)return{...y,selected:n};let b=await fC({entries:f,toPlan:n,all:i,explicit:a!==void 0});b.length===o.length?h.addOption("--all",!0):h.addOption("--versions",b);let w=f.filter(T=>b.includes(T.branch)&&T.mergeSha).length;w>0&&d.info(`
370
- \u2139\uFE0F This will push ${w} branch(es), re-running CI on ${w} open PR(s). If the repo dismisses stale approvals on new commits, those PRs lose them.`);try{await L(p,`Are you sure you want to merge dev into these branches: ${b.join(", ")}?`,{throwOnDecline:!0,plan:wC(f,b,s)})}catch(T){if(!pt(T))throw T;return{...y,selected:b,declined:!0}}p||h.addOption("--yes",!0);let x=await gC({cwd:t,worktreePath:r.path,entries:f,selected:b,verify:l}),D=f.filter(T=>b.includes(T.branch)&&T.status==="conflict").map(T=>T.branch),N=u&&m&&D.length>0?await Tg({cwd:t,branches:D,devSha:m}):void 0;return{entries:f,selected:b,declined:!1,...x,handOffs:N}},wC=(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:fl(n.conflictPaths)}:{},...n.reason?{reason:n.reason}:{}})),skipped:r}),kC=(e,t)=>e.resolution?`# ${e.branch} \u2014 ${e.status}, left to resolve in ${e.resolution.worktreePath} (then --continue)
368
+ `)[0],observedLanded:f.map(y=>y.branch)}},vC=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 g(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 g(void 0,{operation:"choose the merge-dev mode",stderrExcerpt:"--tree belongs to --continue",remediation:"run the rerun a --continue preview printed, unchanged"})},dy=e=>{let{results:t,atomicPush:r,declined:n}=e;for(let i of t){let a=i.reason?.split(`
369
+ `)[0];d.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=>!du.has(i.status));return pu({successfulMerges:o.length-s.length,failedMerges:s.length,failedBranches:s.map(i=>i.branch),totalBranches:t.length,dryRun:!1,atomicPush:r,results:t,skipped:[]})},wC=async e=>{let{all:t,versions:r,verify:n,confirmedCommand:o}=e,s=await Re();if(e.abort)return dy(await Dg({cwd:s,versions:r,all:t,confirmedCommand:o}));let i=typeof n=="string"&&n.length>0?n:void 0;return dy(await Og({cwd:s,versions:r,all:t,verify:i,trees:Ig(e.tree),confirmedCommand:o}))},Li=async e=>{let{all:t,versions:r,dryRun:n=!1,verify:o,keepConflicts:s=!1,confirmedCommand:i}=e;vC(e);let a=o===!0?cg:o||void 0;if(await Qc({operation:"merge dev into release branches"}),e.continue||e.abort)return wC(e);let c=[],l=[];for(let K of await F()){let Yt=uC(K);Yt?l.push({branch:K.branch,reason:Yt}):c.push(K.branch)}if(c.length===0)return d.info(l.length===0?"\u2139\uFE0F No open release branches found":`\u2139\uFE0F No open regular release branches \u2014 ${l.length} skipped (${dC(l)})`),h.print(),pu(lC(n,l));let u=await Re();try{await cC({cwd:u,quiet:!0})`git fetch origin --prune`}catch(K){throw new g(K,{operation:"fetch origin before planning the merges",remediation:"check network access and that `origin` is reachable"})}let p=r===void 0?c:pC(r,c,l),m=await am({cwd:u},async K=>{let Yt=li(K.remove);try{return await kC({cwd:u,worktree:K,toPlan:p,candidates:c,skipped:l,all:t,versions:r,dryRun:n,verify:a,keepConflicts:s,confirmedCommand:i})}finally{Yt()}}),{entries:f,selected:y,pushed:b,pushAborted:w,abortedBy:x,declined:D,verifyFailed:N,handOffs:T}=m,ye=await Ye(u).catch(()=>[]);return SC({entries:f,selected:y,pushed:b,pushAborted:w,abortedBy:x,declined:D,verifyFailed:N,handOffs:T,dryRun:n,worktrees:ye,skipped:l})},kC=async e=>{let{cwd:t,worktree:r,toPlan:n,candidates:o,skipped:s,all:i,versions:a,dryRun:c,verify:l,keepConflicts:u,confirmedCommand:p}=e,m=u?await De(t,"origin/dev"):null,f=await ig({cwd:t,worktreePath:r.path,branches:n}),y={entries:f,pushed:!1,pushAborted:!1,declined:!1};if(fC(f,s),c)return{...y,selected:n};let b=await hC({entries:f,toPlan:n,all:i,explicit:a!==void 0});b.length===o.length?h.addOption("--all",!0):h.addOption("--versions",b);let w=f.filter(T=>b.includes(T.branch)&&T.mergeSha).length;w>0&&d.info(`
370
+ \u2139\uFE0F This will push ${w} branch(es), re-running CI on ${w} open PR(s). If the repo dismisses stale approvals on new commits, those PRs lose them.`);try{await L(p,`Are you sure you want to merge dev into these branches: ${b.join(", ")}?`,{throwOnDecline:!0,plan:bC(f,b,s)})}catch(T){if(!pt(T))throw T;return{...y,selected:b,declined:!0}}p||h.addOption("--yes",!0);let x=await yC({cwd:t,worktreePath:r.path,entries:f,selected:b,verify:l}),D=f.filter(T=>b.includes(T.branch)&&T.status==="conflict").map(T=>T.branch),N=u&&m&&D.length>0?await Cg({cwd:t,branches:D,devSha:m}):void 0;return{entries:f,selected:b,declined:!1,...x,handOffs:N}},bC=(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:fl(n.conflictPaths)}:{},...n.reason?{reason:n.reason}:{}})),skipped:r}),RC=(e,t)=>e.resolution?`# ${e.branch} \u2014 ${e.status}, left to resolve in ${e.resolution.worktreePath} (then --continue)
371
371
  `:`# ${e.branch} \u2014 ${e.status}
372
- ${mC(e.branch,t)}
373
- `,bC=e=>{let{entries:t,selected:r,pushed:n,pushAborted:o,abortedBy:s,declined:i,dryRun:a,worktrees:c,verifyFailed:l,handOffs:u,skipped:p}=e,m=new Set(n?t.filter(w=>r.includes(w.branch)&&w.mergeSha&&!l?.has(w.branch)).map(w=>w.branch):[]),f=t.filter(w=>r.includes(w.branch)).map(w=>{let x=!!w.mergeSha,D=l?.has(w.branch)??!1,N=l?.get(w.branch),T=o&&x?"push-aborted":w.status,he=D?"verify-failed":T,J=u?.get(w.branch);return{branch:w.branch,status:he,mergeSha:w.mergeSha,conflictPaths:w.conflictPaths,pushed:m.has(w.branch),reason:N??J?.reason??w.reason,...J?.resolution?{resolution:J.resolution}:{}}}),y=f.filter(w=>!du.has(w.status));for(let w of f){let x=t.find(D=>D.branch===w.branch);d.info({branch:w.branch,status:w.status,mergeSha:w.mergeSha,conflictCount:w.conflictPaths?.length??0,durationMs:x?.durationMs,pushed:w.pushed,msg:"merge-dev branch result"})}if(i||a)d.info(i?`
372
+ ${gC(e.branch,t)}
373
+ `,SC=e=>{let{entries:t,selected:r,pushed:n,pushAborted:o,abortedBy:s,declined:i,dryRun:a,worktrees:c,verifyFailed:l,handOffs:u,skipped:p}=e,m=new Set(n?t.filter(w=>r.includes(w.branch)&&w.mergeSha&&!l?.has(w.branch)).map(w=>w.branch):[]),f=t.filter(w=>r.includes(w.branch)).map(w=>{let x=!!w.mergeSha,D=l?.has(w.branch)??!1,N=l?.get(w.branch),T=o&&x?"push-aborted":w.status,ye=D?"verify-failed":T,K=u?.get(w.branch);return{branch:w.branch,status:ye,mergeSha:w.mergeSha,conflictPaths:w.conflictPaths,pushed:m.has(w.branch),reason:N??K?.reason??w.reason,...K?.resolution?{resolution:K.resolution}:{}}}),y=f.filter(w=>!du.has(w.status));for(let w of f){let x=t.find(D=>D.branch===w.branch);d.info({branch:w.branch,status:w.status,mergeSha:w.mergeSha,conflictCount:w.conflictPaths?.length??0,durationMs:x?.durationMs,pushed:w.pushed,msg:"merge-dev branch result"})}if(i||a)d.info(i?`
374
374
  Operation cancelled \u2014 nothing was pushed.
375
375
  `:`
376
376
  \u{1F50D} Dry run \u2014 nothing was pushed.
377
377
  `);else if(y.length>0){d.info(`
378
378
  \u26A0\uFE0F ${y.length} branch(es) did not merge.
379
- `);for(let w of y)d.info(kC(w,c))}else d.info(`\u2705 All merges completed successfully!
380
- `);h.print();let b=a||i;return pu({successfulMerges:b?0:f.filter(w=>du.has(w.status)).length,failedMerges:b?0:y.length,failedBranches:b?[]:y.map(w=>w.branch),totalBranches:f.length,dryRun:a,atomicPush:{attempted:!a&&!i,aborted:o,abortedBy:s},results:f.map(w=>b?{...w,pushed:!1}:w),skipped:p})},mu=E({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:S.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:S.union([S.string(),S.array(S.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:S.boolean().optional().describe("Compute and print the merge plan without pushing anything."),verify:S.union([S.boolean(),S.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:S.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:S.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:S.boolean().optional().describe("Discard the selected resolution worktrees and their state. Excludes `keepConflicts`, `continue` and `dryRun`."),tree:S.union([S.string(),S.array(S.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:S.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{successfulMerges:S.number().describe("Number of branches that reached their desired state"),failedMerges:S.number().describe("Number of branches that did not"),failedBranches:S.array(S.string()).describe("List of branches that did not merge"),totalBranches:S.number().describe("Total number of branches processed"),dryRun:S.boolean().describe("True when nothing was pushed because this was a plan-only run"),atomicPush:S.object({attempted:S.boolean(),aborted:S.boolean(),abortedBy:S.string().optional()}).describe("Outcome of the single all-or-nothing push"),results:S.array(S.object({branch:S.string(),status:S.string(),mergeSha:S.string().optional(),conflictPaths:S.array(S.string()).optional(),pushed:S.boolean(),reason:S.string().optional(),resolution:S.object({worktreePath:S.string(),baseSha:S.string(),devSha:S.string(),conflictPaths:S.array(S.string()),lockfileOnly:S.boolean(),rererePreResolved:S.array(S.string()),state:S.enum(["needs-agent","lockfile-only","exists"])}).optional().describe("The `keepConflicts` hand-off for a conflicted branch"),blocked:S.object({code:S.enum(["unmerged-paths","markers-remaining","out-of-scope-edit","verify-failed","verify-mutated-tree","parents-mismatch","git-too-old","tree-changed"]),paths:S.array(S.string()).optional(),detail:S.string()}).optional().describe("Why a `continue` run did not commit this resolution")})).describe("Per-branch terminal state"),skipped:S.array(S.object({branch:S.string(),reason:S.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:Li});import{z as qo}from"zod";import{$ as Be}from"zx";var py=(e,t)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-t).trim()},yr=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=py(t.stderr,500);o&&(r.stderr=o);let s=py(t.stdout,200);return s&&(r.stdout=s),r};var Go=e=>{let{removed:t,failed:r}=e;if(t.length>0){d.info("\u274C Removed worktrees:");for(let n of t)d.info(n);d.info("")}if(r.length>0){d.warn("\u26A0\uFE0F Not removed:");for(let{branch:n,reason:o}of r)d.warn(`${n} \u2014 ${o}`);d.warn("")}t.length===0&&r.length===0&&d.info("\u2139\uFE0F No worktrees to remove")};var Jo=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 ve()?new C({status:"partial_failure",...n},1,s):new g(void 0,s)};import Bi from"node:fs/promises";import{$ as gu}from"zx";var RC=new Set([".omc",".DS_Store"]),SC=new Set(["state","sessions"]),EC=2e3,hy="check 'git worktree list' for the path; uncommitted changes block removal",PC=e=>new Promise(t=>{setTimeout(t,e)}),fu=e=>typeof e=="object"&&e!==null?e.code:void 0,my=e=>{let t=e.length;for(;t>1&&e[t-1]==="/";)t-=1;return e.slice(0,t)},fy=async e=>{try{return my(await Bi.realpath(e))}catch{return my(e)}},xC=async e=>{let{projectRoot:t,worktreePath:r}=e;try{let n=await qe(t),o=await fy(r);for(let s of n)if(await fy(s.path)===o)return!0;return!1}catch{return!0}},TC=async e=>{let t;try{t=await Bi.readdir(e)}catch(n){return{kind:fu(n)==="ENOENT"?"gone":"not-sweepable",entries:[]}}if(!t.every(n=>RC.has(n)))return{kind:"not-sweepable",entries:t};if(!t.includes(".omc"))return{kind:"sweepable",entries:t};try{return{kind:(await Bi.readdir(`${e}/.omc`)).every(s=>SC.has(s))?"sweepable":"not-sweepable",entries:t}}catch(n){return{kind:fu(n)==="ENOENT"?"sweepable":"not-sweepable",entries:t}}},gy=async e=>{try{return await Bi.rm(e,{recursive:!0,force:!0}),"removed"}catch(t){return fu(t)==="ENOTEMPTY"?"busy":"failed"}},CC=async e=>{let{worktreePath:t,sleep:r}=e,n=await gy(t);return n!=="busy"?n==="removed":(await r(EC),await gy(t)==="removed")},Ko=(e,t,r)=>{let n=new g(t,{operation:`remove worktree for ${e}`,remediation:r});return d.error({error:t,branch:e,msg:n.message}),{branch:e,status:"failed",reason:n.message}},$C=async e=>{let{branch:t,worktreePath:r,projectRoot:n,error:o,sleep:s}=e;if(await xC({projectRoot:n,worktreePath:r}))return Ko(t,o,hy);let i=await TC(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 CC({worktreePath:r,sleep:s})?Ko(t,o,a):(d.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"})},AC=async e=>{try{return(await gu`git -C ${e} status --porcelain`).stdout.split(`
381
- `).filter(r=>r.trim().length>0)}catch{return[]}},OC=async e=>{let{branch:t,worktreeDir:r,projectRoot:n,orcaProbe:o,sleep:s}=e,i=`${r}/${t}`,a=await AC(i);if(a.length>0)return Ko(t,new Error(`uncommitted changes in ${i}: ${a.slice(0,5).join(", ")}`),hy);let c=await Dm(i,o);if(!c.closed&&"error"in c)return Ko(t,c.error,"close the Orca terminals of this worktree manually (orca terminal close --terminal <handle>) and re-run");try{return await gu`git worktree remove ${i}`,{branch:t,status:"removed"}}catch(l){return $C({branch:t,worktreePath:i,projectRoot:n,error:l,sleep:s})}},vr=async e=>{let{branches:t,worktreeDir:r,projectRoot:n,pruneFolder:o=!1,sleep:s=PC}=e,i=t.length>0?await Ct():"unreachable",a=await Promise.all(t.map(l=>OC({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 gu`git worktree prune`,c};var Ho=async(e,t)=>{if(!(await fe("release")).includes(e))return[];let n=await P(),o=`${n}${le}`,{removed:s,failed:i}=await vr({branches:[e],worktreeDir:o,projectRoot:n});if(!s.includes(e)){let a=i.find(c=>c.branch===e);throw new g(void 0,{...t,stderrExcerpt:a?.reason})}return s};var Sn=async(e,t,r)=>{try{return await r()}catch(n){throw d.debug({err:yr(n)},`Failed to ${e}`),new g(n,{operation:e,remediation:t})}},IC=async e=>{let t=Fa(e),r=await Be`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},yy=async()=>{let e=await Be`gh pr list --head dev --base main --state open --json number,state,title,baseRefName,headRefName --limit 5`;return JSON.parse(e.stdout)[0]??null},DC=async e=>{let t=yt(e),r=await rl(t);if(r.length>1){let s=r.map(i=>`#${i.number} \u2192 ${i.baseRefName}`).join(", ");throw new g(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 Yr(t);if(!n)throw d.error(`\u274C No PR found for branch ${t}.`),new g(void 0,{operation:`deliver release ${t}`,remediation:`confirm a PR exists ('gh pr list --head ${t} --state all')`});let o=fo(n.baseRefName);if(!o)throw new g(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}},NC=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 ae(),o=await Mt(ce({branches:t,descriptions:n,types:r})),s=e.find(i=>i.branch===o);if(!s)throw d.error(`\u274C Release branch ${o} not found in open PRs.`),new g(void 0,{operation:`deliver release ${o}`,remediation:`confirm an open PR exists for ${o} ('gh pr list')`});if(s.dualBase)throw new g(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}},_C=async e=>{let{selectedReleaseBranch:t,releaseType:r,prNumber:n}=e,o=rt(r),s=await nl(n);if(s.state==="MERGED"){d.info(`\u2713 Release PR ${t} already merged \u2014 skipping`);return}if(s.state==="CLOSED")throw new g(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 g(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 Sn(`merge release PR #${n} ${t} into ${o}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await Be`gh pr merge ${n} --squash --admin --delete-branch`})},MC=async e=>{let t=X(e),r=Fa(e),n=await yy();if(n){let s=n.number;return n.title!==r&&(d.info(`Adopting open dev \u2192 main PR #${s} ("${n.title}") and retitling for ${t}`),await Sn(`retitle dev \u2192 main PR #${s} to "${r}"`,`update manually: gh pr edit ${s} --title "${r}"`,async()=>{await Be`gh pr edit ${s} --title ${r}`})),s}await Sn(`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 Be`gh pr create --base main --head dev --title ${r} --body ""`});let o=await yy();if(!o)throw new g(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},jC=async e=>{let t=X(e);if(await IC(e)){d.info(`\u2713 RC PR for ${t} already merged into main \u2014 skipping`);return}let n=await MC(e);await Sn(`merge RC PR #${n} (dev \u2192 main) for ${t}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await Be`gh pr merge ${n} --squash --admin`})},FC=async()=>{Be.quiet=!1,await Sn("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await Be`gh workflow run deploy-all.yml --ref main -f environment=prod`}),Be.quiet=!0},LC=async()=>{await Sn("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 Be`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},BC=async e=>{try{await As(e)}catch(t){d.warn({err:yr(t)},`Failed to delete local branch ${e} (non-blocking)`)}try{await Os(e)}catch(t){d.warn({err:yr(t)},`Failed to delete remote branch ${e} (non-blocking)`)}},UC=async e=>{let t=await ht();if(!t){d.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let r=ne(e);await sl({versionName:r},t)}catch(r){let n=ho(r)&&r.kind==="auth"?" \u2014 reissue the Atlassian API token and update JIRA_TOKEN":"";d.error({err:yr(r)},`Failed to deliver Jira release (non-blocking)${n}`)}},Ui=async e=>{let{version:t,confirmedCommand:r}=e;await xe({operation:"deliver release"});let{selectedReleaseBranch:n,releaseType:o,prNumber:s}=t?await DC(t):await NC(),i=q(n);if(!i)throw new g(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=X(i);if(h.addOption("--version",a),d.info(`Delivering ${i.kind==="name"?"named release":"version"} ${n}`),ve())throw new C({status:"refused",agentMode:_.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 L(r,`Are you sure you want to deliver version ${n} to production?`),h.addOption("--yes",!0),Be.quiet=!0;let l=`${await P()}${le}`;await Ho(n,{operation:`remove worktree for ${n} before merge`,remediation:`run manually: git worktree remove ${l}/${n} (use --force if uncommitted changes)`}),await _C({selectedReleaseBranch:n,releaseType:o,prNumber:s}),o!=="hotfix"&&await jC(i),await FC(),await LC(),await BC(n),Be.quiet=!1,await UC(i),d.info(`Successfully delivered ${n} to production!`),h.print();let u={releaseBranch:n,version:a,type:o,success:!0};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}},hu=E({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:qo.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:qo.string().describe("The release branch that was delivered"),version:qo.string().describe("The version that was delivered"),type:qo.enum(["regular","hotfix"]).describe("Release type"),success:qo.boolean().describe("Whether the delivery was successful")},handler:Ui});import{z as kt}from"zod";import{$ as xu}from"zx";import{z as Xo}from"zod";import vy from"node:fs/promises";import yu from"node:path";var wy=".github/workflows",VC=/script_name:\s*(?<service>[a-z0-9-]+)/,WC=/uses:\s*\.\/\.github\/workflows\/_deploy-(?<service>[a-z0-9-]+)-jobs\.ya?ml/,GC=/inputs\.environment\s*==\s*'(?<env>[a-z0-9-]+)'/g,vu=async e=>{let t=yu.resolve(e,wy),r;try{r=await vy.readdir(t)}catch{return new Map}return ky(t,r.filter(n=>n.endsWith(".yml")||n.endsWith(".yaml")))},Yo=async(e,t)=>ky(yu.resolve(e,wy),[t]),ky=async(e,t)=>{let r=new Map;for(let n of t){let o;try{o=await vy.readFile(yu.resolve(e,n),"utf-8")}catch{continue}JC(o,r)}return r},JC=(e,t)=>{for(let r of e.split(/\n(?= {2}[\w-]+:)/i)){let n=VC.exec(r)?.groups?.service??WC.exec(r)?.groups?.service;if(n===void 0||r.trimStart().startsWith("#"))continue;let o=[...r.matchAll(GC)].map(s=>s.groups?.env??"");o.length!==0&&t.set(n,[...new Set([...t.get(n)??[],...o])])}},wu=(e,t)=>e===null?t??null:t===void 0?e:e.filter(r=>t.includes(r));import KC from"node:fs/promises";import HC from"node:path";import qC from"yaml";var YC=".github/workflows",zC="skip_terraform_deploy",zo=async(e,t)=>{let r=HC.resolve(e,YC,t),n;try{n=qC.parse(await KC.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!==zC).map(([i])=>i)};var by="dev",ku=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ry=(e,t)=>e[t]===void 0,Sy=(e,t)=>{let r=e[t];return typeof r=="string"&&r.length>0?r:void 0},bu=async e=>{try{return await e}catch{return[]}},XC=async()=>{let e=await F();return vt(e.map(t=>t.branch))},ZC=(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},wr=e=>{let{workflowFile:t,fields:r,toolName:n}=e,o=c=>(d.info({msg:`Tool execution form options empty (${t}): ${n}`,emptyList:c}),null),s=async c=>{let l=await bu(XC());if(l.length===0)return null;let u=Sy(c,"version");return Xo.enum([...new Set([...l,by])]).optional().describe(`Which release to deploy from. "${by}" deploys from the dev branch instead of a release branch. ${u===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 "${u}".`}`)},i=async c=>{let l=$t(await bu(At(t)),await Ye());if(l.length===0)return null;let u=l.filter(Vn),p=l.filter(f=>!Vn(f)),m=Sy(c,"env");return Xo.enum(l).optional().describe(`Target environment. Shared with the whole team: ${u.length>0?u.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 P(),l=await bu(zo(c,t));if(l.length===0)return null;let u=await Yo(c,t);return Xo.array(Xo.enum(l)).optional().describe(`Services to deploy. Environment gates declared by ${t} \u2014 ${ZC(l,u)} 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=>ku(c)?r.some(l=>Ry(c,l)):!1,buildRequestedSchema:async c=>{let l=ku(c)?c:{},u={};if(r.includes("version")){let p=await s(l);if(p===null)return o("releases");u.version=p}if(r.includes("env")){let p=await i(l);if(p===null)return o("envs");u.env=p}if(r.includes("services")&&Ry(l,"services")){let p=await a();if(p===null)return o("services");u.services=p}return Object.keys(u).length===0?o("fields"):Xo.object(u)},toArgs:(c,l)=>{let u={...ku(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;u[p]=m}}return u}}};import QC from"@inquirer/select";var En=async(e,t)=>{if(e.length===0)throw new g(void 0,{operation:t,remediation:"pass --env <name> explicitly",stderrExcerpt:"the workflow declares no `environment` choices to pick from"});return I(r=>QC({message:"\u{1F9EA} Select environment",choices:e.map(n=>({name:n,value:n}))},r),{whenHeadless:"refuse"})};import e$ from"@inquirer/confirm";var Zo=async e=>{let{confirmedCommand:t,branch:r,env:n}=e;if(t)return!0;let o=`Deploy ${r} \u2192 ${n} via GitHub Actions?`;K()&&Ms(o,{branch:r,env:n}),h.setInteractive();let s=await I(i=>e$({message:o,default:!1},i),{whenHeadless:"refuse"});return s&&h.addOption("--yes",!0),s};import t$ from"@inquirer/select";import r$ from"node:process";var Ru=()=>!K()&&r$.stdin.isTTY===!0,n$={ci:"Dispatch the GitHub workflow for a release ref",local:"Run devops/scripts/deploy-*.sh here, against your current checkout"},Su=async()=>I(e=>t$({message:"\u{1F680} Where should this deploy run?",choices:Wt.filter(t=>t!=="local").map(t=>({name:t,value:t,description:n$[t]}))},e),{whenHeadless:"refuse"});var Wt=["ci","local"],o$={ci:["--version","--skip-terraform"],local:["--dry-run","--print-env"]},Ey=e=>{if(!e){let r={operation:"resolve the deploy source",remediation:`pass --from with one of: ${Wt.join(", ")}`,stderrExcerpt:"--from is required \u2014 it decides whether this deploy runs in CI or on this machine"};throw K()?new C({status:"argument_required",argument:"from",agentMode:_.source},2,r):new g(void 0,r)}let t=Wt.find(r=>r===e);if(!t)throw new g(void 0,{operation:"resolve the deploy source",remediation:`use one of: ${Wt.join(", ")}`,stderrExcerpt:`unknown --from value "${e}"`});return t},Eu=(e,t)=>{let n=o$[e==="ci"?"local":"ci"].filter(o=>{let s=t[o];return s!==void 0&&s!==!1});if(n.length!==0)throw new g(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}`})},Pu=async e=>e||!Ru()?Ey(e):Su();var Qo=async e=>{if(e)return e==="dev"?"dev":yt(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 ae();return Mt([{value:"dev",label:"dev"},...ce({branches:r,descriptions:o,types:n})])};var Py="deploy-all.yml",xy=wr({workflowFile:Py,fields:["version","env"],toolName:"gh-release-deploy-all"}),Vi=async e=>{let{version:t,env:r,skipTerraform:n,confirmedCommand:o}=e;await ze({provider:xy,params:e,operation:"launch deploy-all workflow",argument:p=>p[0]??"version"});let s=await Qo(t),i=wo(s);h.addOption("--version",i);let a=await Ye(),c=$t(await At(Py),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),Fs({env:l,branch:s});let u=n??!1;if(u&&h.addOption("--skip-terraform",!0),!await Zo({confirmedCommand:o,branch:s,env:l})){d.info("Deployment cancelled");let p={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:u,success:!1};return{content:k(JSON.stringify(p,null,2)),structuredContent:p}}try{xu.quiet=!0,await xu`gh workflow run deploy-all.yml --ref ${s} -f environment=${l} ${u?["-f","skip_terraform_deploy=true"]:[]}`,xu.quiet=!1,d.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:u,success:!0};return{content:k(JSON.stringify(m,null,2)),structuredContent:m}}catch(p){throw d.error({error:p},"\u274C Error launching workflow"),new g(p,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},Tu=E({name:"gh-release-deploy-all",formProvider:xy,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:kt.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:kt.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:kt.boolean().optional().describe("Skip the terraform deployment stage."),confirm:kt.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:kt.string().describe("The release branch that was deployed"),version:kt.string().describe("The version that was deployed"),environment:kt.string().describe("The environment deployed to"),skipTerraformDeploy:kt.boolean().describe("Whether terraform deployment was skipped"),success:kt.boolean().describe("Whether the deployment was successful")},handler:Vi});import s$ from"@inquirer/checkbox";import{z as Ce}from"zod";import{$ as Cu}from"zx";var kr="deploy-selected-services.yml",Ty=wr({workflowFile:kr,fields:["version","env","services"],toolName:"gh-release-deploy-selected"}),Wi=async e=>{let{version:t,env:r,services:n,skipTerraform:o,confirmedCommand:s}=e;await ze({provider:Ty,params:e,operation:"launch deploy-selected workflow",argument:N=>N[0]??"version"});let i=await Qo(t),a=wo(i);h.addOption("--version",a);let c=await Ye(),l=$t(await At(kr),c),u="";r?u=r:(h.setInteractive(),u=await En(l,"launch deploy-selected workflow")),h.addOption("--env",u),Dr(u,"launch deploy-selected workflow",c),Fs({env:u,branch:i});let p=await P(),m=await zo(p,kr);if(m.length===0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${kr}`,stderrExcerpt:`no services found in .github/workflows/${kr}`});let f=[];if(n&&n.length>0?f=n:(h.setInteractive(),f=await I(N=>s$({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:m.map(T=>({name:T,value:T}))},N),{whenHeadless:"refuse"})),h.addOption("--services",f),f.length===0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${m.join(", ")}`,stderrExcerpt:"no services selected"});let y=f.filter(N=>!m.includes(N));if(y.length>0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${m.join(", ")}`,stderrExcerpt:`invalid services: ${y.join(", ")}`});let b=await Yo(p,kr),w=f.filter(N=>{let T=b.get(N);return T!==void 0&&!T.includes(u)});if(w.length>0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:w.map(N=>`${N} deploys only to: ${(b.get(N)??[]).join(", ")}`).join("; "),stderrExcerpt:`${kr} gates these services out of ${u}: ${w.join(", ")}`});let x=o??!1;x&&h.addOption("--skip-terraform",!0);let D=N=>{let T={releaseBranch:i,version:a,environment:u,services:f,skipTerraformDeploy:x,success:N};return{content:k(JSON.stringify(T,null,2)),structuredContent:T}};if(!await Zo({confirmedCommand:s,branch:i,env:u}))return d.info("Deployment cancelled"),D(!1);try{Cu.quiet=!0;let N=f.flatMap(he=>["-f",`${he}=true`]);return await Cu`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${u} ${N} ${x?["-f","skip_terraform_deploy=true"]:[]}`,Cu.quiet=!1,d.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${u}, services: ${f.join(", ")}`),h.print(),D(!0)}catch(N){throw d.error({error:N},"\u274C Error launching workflow"),new g(N,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},$u=E({name:"gh-release-deploy-selected",requiresHumanConfirm:!0,formProvider:Ty,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:Ce.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:Ce.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:Ce.array(Ce.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:Ce.boolean().optional().describe("Skip the terraform deployment stage."),confirm:Ce.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:Ce.string().describe("The release branch that was deployed"),version:Ce.string().describe("The version that was deployed"),environment:Ce.string().describe("The environment deployed to"),services:Ce.array(Ce.string()).describe("The services that were deployed"),skipTerraformDeploy:Ce.boolean().describe("Whether terraform deployment was skipped"),success:Ce.boolean().describe("Whether the deployment was successful")},handler:Wi});import{z as Gt}from"zod";var Gi=async()=>{let t=(await F()).flatMap(i=>{let a=q(i.branch);return a?[{version:X(a),jiraKey:ne(a),type:i.type,titleMismatch:i.titleMismatch}]:[]}),r=await ii(),n=Math.max(...t.map(i=>i.version.length)),o=t.map(i=>{let a=vo(i.version,i.type,n),c=r.get(i.jiraKey),l=c?.description?` ${c.description}`:"",u=c?.releaseDate?` \xB7 ships ${c.releaseDate}`:"",p=i.titleMismatch?" \u26A0 title/base mismatch":"";return`${a}${l}${u}${p}`});d.info(`All release branches:
379
+ `);for(let w of y)d.info(RC(w,c))}else d.info(`\u2705 All merges completed successfully!
380
+ `);h.print();let b=a||i;return pu({successfulMerges:b?0:f.filter(w=>du.has(w.status)).length,failedMerges:b?0:y.length,failedBranches:b?[]:y.map(w=>w.branch),totalBranches:f.length,dryRun:a,atomicPush:{attempted:!a&&!i,aborted:o,abortedBy:s},results:f.map(w=>b?{...w,pushed:!1}:w),skipped:p})},mu=E({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:S.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:S.union([S.string(),S.array(S.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:S.boolean().optional().describe("Compute and print the merge plan without pushing anything."),verify:S.union([S.boolean(),S.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:S.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:S.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:S.boolean().optional().describe("Discard the selected resolution worktrees and their state. Excludes `keepConflicts`, `continue` and `dryRun`."),tree:S.union([S.string(),S.array(S.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:S.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{successfulMerges:S.number().describe("Number of branches that reached their desired state"),failedMerges:S.number().describe("Number of branches that did not"),failedBranches:S.array(S.string()).describe("List of branches that did not merge"),totalBranches:S.number().describe("Total number of branches processed"),dryRun:S.boolean().describe("True when nothing was pushed because this was a plan-only run"),atomicPush:S.object({attempted:S.boolean(),aborted:S.boolean(),abortedBy:S.string().optional()}).describe("Outcome of the single all-or-nothing push"),results:S.array(S.object({branch:S.string(),status:S.string(),mergeSha:S.string().optional(),conflictPaths:S.array(S.string()).optional(),pushed:S.boolean(),reason:S.string().optional(),resolution:S.object({worktreePath:S.string(),baseSha:S.string(),devSha:S.string(),conflictPaths:S.array(S.string()),lockfileOnly:S.boolean(),rererePreResolved:S.array(S.string()),state:S.enum(["needs-agent","lockfile-only","exists"])}).optional().describe("The `keepConflicts` hand-off for a conflicted branch"),blocked:S.object({code:S.enum(["unmerged-paths","markers-remaining","out-of-scope-edit","verify-failed","verify-mutated-tree","parents-mismatch","git-too-old","tree-changed"]),paths:S.array(S.string()).optional(),detail:S.string()}).optional().describe("Why a `continue` run did not commit this resolution")})).describe("Per-branch terminal state"),skipped:S.array(S.object({branch:S.string(),reason:S.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:Li});import{z as Yo}from"zod";import{$ as Be}from"zx";var my=(e,t)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-t).trim()},yr=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=my(t.stderr,500);o&&(r.stderr=o);let s=my(t.stdout,200);return s&&(r.stdout=s),r};var Jo=e=>{let{removed:t,failed:r}=e;if(t.length>0){d.info("\u274C Removed worktrees:");for(let n of t)d.info(n);d.info("")}if(r.length>0){d.warn("\u26A0\uFE0F Not removed:");for(let{branch:n,reason:o}of r)d.warn(`${n} \u2014 ${o}`);d.warn("")}t.length===0&&r.length===0&&d.info("\u2139\uFE0F No worktrees to remove")};var Ko=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 we()?new C({status:"partial_failure",...n},1,s):new g(void 0,s)};import Bi from"node:fs/promises";import{$ as gu}from"zx";var EC=new Set([".omc",".DS_Store"]),PC=new Set(["state","sessions"]),xC=2e3,yy="check 'git worktree list' for the path; uncommitted changes block removal",TC=e=>new Promise(t=>{setTimeout(t,e)}),fu=e=>typeof e=="object"&&e!==null?e.code:void 0,fy=e=>{let t=e.length;for(;t>1&&e[t-1]==="/";)t-=1;return e.slice(0,t)},gy=async e=>{try{return fy(await Bi.realpath(e))}catch{return fy(e)}},CC=async e=>{let{projectRoot:t,worktreePath:r}=e;try{let n=await Ye(t),o=await gy(r);for(let s of n)if(await gy(s.path)===o)return!0;return!1}catch{return!0}},$C=async e=>{let t;try{t=await Bi.readdir(e)}catch(n){return{kind:fu(n)==="ENOENT"?"gone":"not-sweepable",entries:[]}}if(!t.every(n=>EC.has(n)))return{kind:"not-sweepable",entries:t};if(!t.includes(".omc"))return{kind:"sweepable",entries:t};try{return{kind:(await Bi.readdir(`${e}/.omc`)).every(s=>PC.has(s))?"sweepable":"not-sweepable",entries:t}}catch(n){return{kind:fu(n)==="ENOENT"?"sweepable":"not-sweepable",entries:t}}},hy=async e=>{try{return await Bi.rm(e,{recursive:!0,force:!0}),"removed"}catch(t){return fu(t)==="ENOTEMPTY"?"busy":"failed"}},AC=async e=>{let{worktreePath:t,sleep:r}=e,n=await hy(t);return n!=="busy"?n==="removed":(await r(xC),await hy(t)==="removed")},Ho=(e,t,r)=>{let n=new g(t,{operation:`remove worktree for ${e}`,remediation:r});return d.error({error:t,branch:e,msg:n.message}),{branch:e,status:"failed",reason:n.message}},OC=async e=>{let{branch:t,worktreePath:r,projectRoot:n,error:o,sleep:s}=e;if(await CC({projectRoot:n,worktreePath:r}))return Ho(t,o,yy);let i=await $C(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 AC({worktreePath:r,sleep:s})?Ho(t,o,a):(d.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"})},IC=async e=>{try{return(await gu`git -C ${e} status --porcelain`).stdout.split(`
381
+ `).filter(r=>r.trim().length>0)}catch{return[]}},DC=async e=>{let{branch:t,worktreeDir:r,projectRoot:n,orcaProbe:o,sleep:s}=e,i=`${r}/${t}`,a=await IC(i);if(a.length>0)return Ho(t,new Error(`uncommitted changes in ${i}: ${a.slice(0,5).join(", ")}`),yy);let c=await Nm(i,o);if(!c.closed&&"error"in c)return Ho(t,c.error,"close the Orca terminals of this worktree manually (orca terminal close --terminal <handle>) and re-run");try{return await gu`git worktree remove ${i}`,{branch:t,status:"removed"}}catch(l){return OC({branch:t,worktreePath:i,projectRoot:n,error:l,sleep:s})}},vr=async e=>{let{branches:t,worktreeDir:r,projectRoot:n,pruneFolder:o=!1,sleep:s=TC}=e,i=t.length>0?await Ct():"unreachable",a=await Promise.all(t.map(l=>DC({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 gu`git worktree prune`,c};var qo=async(e,t)=>{if(!(await fe("release")).includes(e))return[];let n=await P(),o=`${n}${le}`,{removed:s,failed:i}=await vr({branches:[e],worktreeDir:o,projectRoot:n});if(!s.includes(e)){let a=i.find(c=>c.branch===e);throw new g(void 0,{...t,stderrExcerpt:a?.reason})}return s};var Sn=async(e,t,r)=>{try{return await r()}catch(n){throw d.debug({err:yr(n)},`Failed to ${e}`),new g(n,{operation:e,remediation:t})}},NC=async e=>{let t=Fa(e),r=await Be`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},vy=async()=>{let e=await Be`gh pr list --head dev --base main --state open --json number,state,title,baseRefName,headRefName --limit 5`;return JSON.parse(e.stdout)[0]??null},_C=async e=>{let t=yt(e),r=await rl(t);if(r.length>1){let s=r.map(i=>`#${i.number} \u2192 ${i.baseRefName}`).join(", ");throw new g(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 Yr(t);if(!n)throw d.error(`\u274C No PR found for branch ${t}.`),new g(void 0,{operation:`deliver release ${t}`,remediation:`confirm a PR exists ('gh pr list --head ${t} --state all')`});let o=go(n.baseRefName);if(!o)throw new g(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}},MC=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 ae(),o=await Mt(ce({branches:t,descriptions:n,types:r})),s=e.find(i=>i.branch===o);if(!s)throw d.error(`\u274C Release branch ${o} not found in open PRs.`),new g(void 0,{operation:`deliver release ${o}`,remediation:`confirm an open PR exists for ${o} ('gh pr list')`});if(s.dualBase)throw new g(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}},jC=async e=>{let{selectedReleaseBranch:t,releaseType:r,prNumber:n}=e,o=nt(r),s=await nl(n);if(s.state==="MERGED"){d.info(`\u2713 Release PR ${t} already merged \u2014 skipping`);return}if(s.state==="CLOSED")throw new g(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 g(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 Sn(`merge release PR #${n} ${t} into ${o}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await Be`gh pr merge ${n} --squash --admin --delete-branch`})},FC=async e=>{let t=X(e),r=Fa(e),n=await vy();if(n){let s=n.number;return n.title!==r&&(d.info(`Adopting open dev \u2192 main PR #${s} ("${n.title}") and retitling for ${t}`),await Sn(`retitle dev \u2192 main PR #${s} to "${r}"`,`update manually: gh pr edit ${s} --title "${r}"`,async()=>{await Be`gh pr edit ${s} --title ${r}`})),s}await Sn(`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 Be`gh pr create --base main --head dev --title ${r} --body ""`});let o=await vy();if(!o)throw new g(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},LC=async e=>{let t=X(e);if(await NC(e)){d.info(`\u2713 RC PR for ${t} already merged into main \u2014 skipping`);return}let n=await FC(e);await Sn(`merge RC PR #${n} (dev \u2192 main) for ${t}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await Be`gh pr merge ${n} --squash --admin`})},BC=async()=>{Be.quiet=!1,await Sn("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await Be`gh workflow run deploy-all.yml --ref main -f environment=prod`}),Be.quiet=!0},UC=async()=>{await Sn("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 Be`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},VC=async e=>{try{await As(e)}catch(t){d.warn({err:yr(t)},`Failed to delete local branch ${e} (non-blocking)`)}try{await Os(e)}catch(t){d.warn({err:yr(t)},`Failed to delete remote branch ${e} (non-blocking)`)}},WC=async e=>{let t=await ht();if(!t){d.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let r=ne(e);await sl({versionName:r},t)}catch(r){let n=yo(r)&&r.kind==="auth"?" \u2014 reissue the Atlassian API token and update JIRA_TOKEN":"";d.error({err:yr(r)},`Failed to deliver Jira release (non-blocking)${n}`)}},Ui=async e=>{let{version:t,confirmedCommand:r}=e;await xe({operation:"deliver release"});let{selectedReleaseBranch:n,releaseType:o,prNumber:s}=t?await _C(t):await MC(),i=q(n);if(!i)throw new g(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=X(i);if(h.addOption("--version",a),d.info(`Delivering ${i.kind==="name"?"named release":"version"} ${n}`),we())throw new C({status:"refused",agentMode:_.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 L(r,`Are you sure you want to deliver version ${n} to production?`),h.addOption("--yes",!0),Be.quiet=!0;let l=`${await P()}${le}`;await qo(n,{operation:`remove worktree for ${n} before merge`,remediation:`run manually: git worktree remove ${l}/${n} (use --force if uncommitted changes)`}),await jC({selectedReleaseBranch:n,releaseType:o,prNumber:s}),o!=="hotfix"&&await LC(i),await BC(),await UC(),await VC(n),Be.quiet=!1,await WC(i),d.info(`Successfully delivered ${n} to production!`),h.print();let u={releaseBranch:n,version:a,type:o,success:!0};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}},hu=E({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:Yo.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:Yo.string().describe("The release branch that was delivered"),version:Yo.string().describe("The version that was delivered"),type:Yo.enum(["regular","hotfix"]).describe("Release type"),success:Yo.boolean().describe("Whether the delivery was successful")},handler:Ui});import{z as kt}from"zod";import{$ as xu}from"zx";import{z as Zo}from"zod";import wy from"node:fs/promises";import yu from"node:path";var ky=".github/workflows",GC=/script_name:\s*(?<service>[a-z0-9-]+)/,JC=/uses:\s*\.\/\.github\/workflows\/_deploy-(?<service>[a-z0-9-]+)-jobs\.ya?ml/,KC=/inputs\.environment\s*==\s*'(?<env>[a-z0-9-]+)'/g,vu=async e=>{let t=yu.resolve(e,ky),r;try{r=await wy.readdir(t)}catch{return new Map}return by(t,r.filter(n=>n.endsWith(".yml")||n.endsWith(".yaml")))},zo=async(e,t)=>by(yu.resolve(e,ky),[t]),by=async(e,t)=>{let r=new Map;for(let n of t){let o;try{o=await wy.readFile(yu.resolve(e,n),"utf-8")}catch{continue}HC(o,r)}return r},HC=(e,t)=>{for(let r of e.split(/\n(?= {2}[\w-]+:)/i)){let n=GC.exec(r)?.groups?.service??JC.exec(r)?.groups?.service;if(n===void 0||r.trimStart().startsWith("#"))continue;let o=[...r.matchAll(KC)].map(s=>s.groups?.env??"");o.length!==0&&t.set(n,[...new Set([...t.get(n)??[],...o])])}},wu=(e,t)=>e===null?t??null:t===void 0?e:e.filter(r=>t.includes(r));import qC from"node:fs/promises";import YC from"node:path";import zC from"yaml";var XC=".github/workflows",ZC="skip_terraform_deploy",Xo=async(e,t)=>{let r=YC.resolve(e,XC,t),n;try{n=zC.parse(await qC.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!==ZC).map(([i])=>i)};var Ry="dev",ku=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Sy=(e,t)=>e[t]===void 0,Ey=(e,t)=>{let r=e[t];return typeof r=="string"&&r.length>0?r:void 0},bu=async e=>{try{return await e}catch{return[]}},QC=async()=>{let e=await F();return vt(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},wr=e=>{let{workflowFile:t,fields:r,toolName:n}=e,o=c=>(d.info({msg:`Tool execution form options empty (${t}): ${n}`,emptyList:c}),null),s=async c=>{let l=await bu(QC());if(l.length===0)return null;let u=Ey(c,"version");return Zo.enum([...new Set([...l,Ry])]).optional().describe(`Which release to deploy from. "${Ry}" deploys from the dev branch instead of a release branch. ${u===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 "${u}".`}`)},i=async c=>{let l=$t(await bu(At(t)),await ze());if(l.length===0)return null;let u=l.filter(Wn),p=l.filter(f=>!Wn(f)),m=Ey(c,"env");return Zo.enum(l).optional().describe(`Target environment. Shared with the whole team: ${u.length>0?u.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 P(),l=await bu(Xo(c,t));if(l.length===0)return null;let u=await zo(c,t);return Zo.array(Zo.enum(l)).optional().describe(`Services to deploy. Environment gates declared by ${t} \u2014 ${e$(l,u)} 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=>ku(c)?r.some(l=>Sy(c,l)):!1,buildRequestedSchema:async c=>{let l=ku(c)?c:{},u={};if(r.includes("version")){let p=await s(l);if(p===null)return o("releases");u.version=p}if(r.includes("env")){let p=await i(l);if(p===null)return o("envs");u.env=p}if(r.includes("services")&&Sy(l,"services")){let p=await a();if(p===null)return o("services");u.services=p}return Object.keys(u).length===0?o("fields"):Zo.object(u)},toArgs:(c,l)=>{let u={...ku(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;u[p]=m}}return u}}};import t$ from"@inquirer/select";var En=async(e,t)=>{if(e.length===0)throw new g(void 0,{operation:t,remediation:"pass --env <name> explicitly",stderrExcerpt:"the workflow declares no `environment` choices to pick from"});return I(r=>t$({message:"\u{1F9EA} Select environment",choices:e.map(n=>({name:n,value:n}))},r),{whenHeadless:"refuse"})};import r$ from"@inquirer/confirm";var Qo=async e=>{let{confirmedCommand:t,branch:r,env:n}=e;if(t)return!0;let o=`Deploy ${r} \u2192 ${n} via GitHub Actions?`;H()&&Ms(o,{branch:r,env:n}),h.setInteractive();let s=await I(i=>r$({message:o,default:!1},i),{whenHeadless:"refuse"});return s&&h.addOption("--yes",!0),s};import n$ from"@inquirer/select";import o$ from"node:process";var Ru=()=>!H()&&o$.stdin.isTTY===!0,s$={ci:"Dispatch the GitHub workflow for a release ref",local:"Run devops/scripts/deploy-*.sh here, against your current checkout"},Su=async()=>I(e=>n$({message:"\u{1F680} Where should this deploy run?",choices:Wt.filter(t=>t!=="local").map(t=>({name:t,value:t,description:s$[t]}))},e),{whenHeadless:"refuse"});var Wt=["ci","local"],i$={ci:["--version","--skip-terraform"],local:["--dry-run","--print-env"]},Py=e=>{if(!e){let r={operation:"resolve the deploy source",remediation:`pass --from with one of: ${Wt.join(", ")}`,stderrExcerpt:"--from is required \u2014 it decides whether this deploy runs in CI or on this machine"};throw H()?new C({status:"argument_required",argument:"from",agentMode:_.source},2,r):new g(void 0,r)}let t=Wt.find(r=>r===e);if(!t)throw new g(void 0,{operation:"resolve the deploy source",remediation:`use one of: ${Wt.join(", ")}`,stderrExcerpt:`unknown --from value "${e}"`});return t},Eu=(e,t)=>{let n=i$[e==="ci"?"local":"ci"].filter(o=>{let s=t[o];return s!==void 0&&s!==!1});if(n.length!==0)throw new g(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}`})},Pu=async e=>e||!Ru()?Py(e):Su();var es=async e=>{if(e)return e==="dev"?"dev":yt(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 ae();return Mt([{value:"dev",label:"dev"},...ce({branches:r,descriptions:o,types:n})])};var xy="deploy-all.yml",Ty=wr({workflowFile:xy,fields:["version","env"],toolName:"gh-release-deploy-all"}),Vi=async e=>{let{version:t,env:r,skipTerraform:n,confirmedCommand:o}=e;await Xe({provider:Ty,params:e,operation:"launch deploy-all workflow",argument:p=>p[0]??"version"});let s=await es(t),i=ko(s);h.addOption("--version",i);let a=await ze(),c=$t(await At(xy),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),Fs({env:l,branch:s});let u=n??!1;if(u&&h.addOption("--skip-terraform",!0),!await Qo({confirmedCommand:o,branch:s,env:l})){d.info("Deployment cancelled");let p={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:u,success:!1};return{content:k(JSON.stringify(p,null,2)),structuredContent:p}}try{xu.quiet=!0,await xu`gh workflow run deploy-all.yml --ref ${s} -f environment=${l} ${u?["-f","skip_terraform_deploy=true"]:[]}`,xu.quiet=!1,d.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:u,success:!0};return{content:k(JSON.stringify(m,null,2)),structuredContent:m}}catch(p){throw d.error({error:p},"\u274C Error launching workflow"),new g(p,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},Tu=E({name:"gh-release-deploy-all",formProvider:Ty,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:kt.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:kt.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:kt.boolean().optional().describe("Skip the terraform deployment stage."),confirm:kt.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:kt.string().describe("The release branch that was deployed"),version:kt.string().describe("The version that was deployed"),environment:kt.string().describe("The environment deployed to"),skipTerraformDeploy:kt.boolean().describe("Whether terraform deployment was skipped"),success:kt.boolean().describe("Whether the deployment was successful")},handler:Vi});import a$ from"@inquirer/checkbox";import{z as Ce}from"zod";import{$ as Cu}from"zx";var kr="deploy-selected-services.yml",Cy=wr({workflowFile:kr,fields:["version","env","services"],toolName:"gh-release-deploy-selected"}),Wi=async e=>{let{version:t,env:r,services:n,skipTerraform:o,confirmedCommand:s}=e;await Xe({provider:Cy,params:e,operation:"launch deploy-selected workflow",argument:N=>N[0]??"version"});let i=await es(t),a=ko(i);h.addOption("--version",a);let c=await ze(),l=$t(await At(kr),c),u="";r?u=r:(h.setInteractive(),u=await En(l,"launch deploy-selected workflow")),h.addOption("--env",u),Dr(u,"launch deploy-selected workflow",c),Fs({env:u,branch:i});let p=await P(),m=await Xo(p,kr);if(m.length===0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${kr}`,stderrExcerpt:`no services found in .github/workflows/${kr}`});let f=[];if(n&&n.length>0?f=n:(h.setInteractive(),f=await I(N=>a$({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:m.map(T=>({name:T,value:T}))},N),{whenHeadless:"refuse"})),h.addOption("--services",f),f.length===0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${m.join(", ")}`,stderrExcerpt:"no services selected"});let y=f.filter(N=>!m.includes(N));if(y.length>0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${m.join(", ")}`,stderrExcerpt:`invalid services: ${y.join(", ")}`});let b=await zo(p,kr),w=f.filter(N=>{let T=b.get(N);return T!==void 0&&!T.includes(u)});if(w.length>0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:w.map(N=>`${N} deploys only to: ${(b.get(N)??[]).join(", ")}`).join("; "),stderrExcerpt:`${kr} gates these services out of ${u}: ${w.join(", ")}`});let x=o??!1;x&&h.addOption("--skip-terraform",!0);let D=N=>{let T={releaseBranch:i,version:a,environment:u,services:f,skipTerraformDeploy:x,success:N};return{content:k(JSON.stringify(T,null,2)),structuredContent:T}};if(!await Qo({confirmedCommand:s,branch:i,env:u}))return d.info("Deployment cancelled"),D(!1);try{Cu.quiet=!0;let N=f.flatMap(ye=>["-f",`${ye}=true`]);return await Cu`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${u} ${N} ${x?["-f","skip_terraform_deploy=true"]:[]}`,Cu.quiet=!1,d.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${u}, services: ${f.join(", ")}`),h.print(),D(!0)}catch(N){throw d.error({error:N},"\u274C Error launching workflow"),new g(N,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},$u=E({name:"gh-release-deploy-selected",requiresHumanConfirm:!0,formProvider:Cy,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:Ce.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:Ce.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:Ce.array(Ce.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:Ce.boolean().optional().describe("Skip the terraform deployment stage."),confirm:Ce.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:Ce.string().describe("The release branch that was deployed"),version:Ce.string().describe("The version that was deployed"),environment:Ce.string().describe("The environment deployed to"),services:Ce.array(Ce.string()).describe("The services that were deployed"),skipTerraformDeploy:Ce.boolean().describe("Whether terraform deployment was skipped"),success:Ce.boolean().describe("Whether the deployment was successful")},handler:Wi});import{z as Gt}from"zod";var Gi=async()=>{let t=(await F()).flatMap(i=>{let a=q(i.branch);return a?[{version:X(a),jiraKey:ne(a),type:i.type,titleMismatch:i.titleMismatch}]:[]}),r=await ii(),n=Math.max(...t.map(i=>i.version.length)),o=t.map(i=>{let a=wo(i.version,i.type,n),c=r.get(i.jiraKey),l=c?.description?` ${c.description}`:"",u=c?.releaseDate?` \xB7 ships ${c.releaseDate}`:"",p=i.titleMismatch?" \u26A0 title/base mismatch":"";return`${a}${l}${u}${p}`});d.info(`All release branches:
382
382
  `),d.info(`
383
383
  ${o.join(`
384
384
  `)}
385
- `);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}},Au=E({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:Gt.array(Gt.object({version:Gt.string().describe("Release version"),type:Gt.enum(["regular","hotfix"]).describe("Release type"),description:Gt.string().nullable().describe("Jira version description"),releaseDate:Gt.string().nullable().describe("Planned release date of the Jira version (yyyy-mm-dd)"),titleMismatch:Gt.boolean().describe("The PR title names a different release type than its base branch")})).describe("List of all release branches"),count:Gt.number().describe("Number of release branches")},handler:Gi});import i$ from"node:process";var Ou=e=>({...e}),Iu=e=>{let{env:t,branch:r,sha:n,isClean:o,ambient:s=i$.env}=e,i={VITE_DOMAIN_ENV:t,VITE_BRANCH_NAME:r,VITE_COMMIT_HASH:o?n:`${n}-dirty`},a={},c=[];for(let[l,u]of Object.entries(s)){if(l.startsWith("VITE_")){c.push(l);continue}a[l]=u}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}},Ji=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(`
386
- `)};import k$ from"@inquirer/checkbox";import b$ from"@inquirer/confirm";import R$ from"@inquirer/select";import{spawn as S$}from"node:child_process";import E$ from"node:process";import{z}from"zod";import{$ as ts}from"zx";import{$ as es}from"zx";var a$=async e=>{let t=es.quiet;es.quiet=!0;try{let r=`/${e}/environment`,n=await es`aws sts get-caller-identity --query Account --output text`,o=await es`aws ssm get-parameter --name ${r} --query Parameter.Value --output text`;return{accountId:n.stdout.trim(),stage:o.stdout.trim()}}catch(r){throw new g(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{es.quiet=t}},Cy=(e,t)=>{if(t.stage!==e)throw new g(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`})},$y=e=>{let{env:t,isShared:r,isClean:n}=e;if(!(!r||n))throw new g(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"})},Ay=(e,t)=>{if(t.includes(e))throw new g(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`})},Du=async e=>{let{env:t,project:r,isShared:n,isClean:o,runningEnvs:s,protectedEnvAccess:i}=e;Dr(t,`deploy to "${t}"`,i),Ay(t,s),$y({env:t,isShared:n,isClean:o});let a=await a$(r);return Cy(t,a),{identity:a}};import Oy from"node:fs/promises";import Ki from"node:path";var c$="devops/scripts",l$=/^deploy-(?<service>[a-z0-9-]+)\.sh$/,u$=/skip_unless_env_enabled\s+"[^"]*"\s+"[^"]*"\s+"(?<envs>[^"]*)"/,d$=/aws\s+ssm\s+get-parameter\s+--name[=\s]+(?<arg>[^\s)]+)/,p$=/aws\s+ssm\s+get-parameter\s+--name[=\s]+["']?\/(?<prefix>[\w.-]+)\/environment["']?(?![\w./-])/,Nu=async e=>{let t=Ki.resolve(e,c$),r;try{r=await Oy.readdir(t)}catch{return[]}let n=await vu(e);return(await Promise.all(r.map(s=>({entry:s,match:l$.exec(s)})).filter(s=>s.match!==null).map(async({entry:s,match:i})=>{let a=Ki.resolve(t,s),c=i?.groups?.service??"",l=f$(await m$(a));return{name:c,scriptPath:a,allowedEnvs:wu(g$(l),n.get(c)),ssmPrefix:y$(l)}}))).sort((s,i)=>s.name.localeCompare(i.name))},m$=async e=>{try{return await Oy.readFile(e,"utf-8")}catch{return""}},f$=e=>e.split(`
387
- `).map((t,r)=>({line:r+1,text:t})).filter(({text:t})=>!t.trimStart().startsWith("#")),g$=e=>{let t=e.reduce((n,{text:o})=>n??u$.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},h$=e=>{let t=e.replaceAll(/["']/g,"");return t.includes("$")&&(t.includes("/environment")||t.startsWith("$"))},y$=e=>{for(let{line:t,text:r}of e){let n=p$.exec(r)?.groups?.prefix;if(n!==void 0)return n;let o=d$.exec(r)?.groups?.arg;if(o!==void 0&&h$(o))return{unparseable:{line:t,text:r.trim()}}}return null},v$=e=>{let t=new Map;for(let r of e)typeof r.ssmPrefix=="string"&&t.set(r.ssmPrefix,[...t.get(r.ssmPrefix)??[],Ki.basename(r.scriptPath)]);return t},w$=e=>{let t=e.flatMap(r=>{if(r.ssmPrefix===null||typeof r.ssmPrefix=="string")return[];let{line:n,text:o}=r.ssmPrefix.unparseable;return[`${Ki.basename(r.scriptPath)}:${n}: ${o}`]});if(t.length!==0)throw new g(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("; ")})},Iy=e=>{w$(e);let t=v$(e),[r,...n]=t.keys();if(r===void 0)throw new g(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 g(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},Hi=(e,t)=>e.allowedEnvs===null||e.allowedEnvs.includes(t),_u=(e,t)=>e.filter(r=>Hi(r,t));var ju="deploy-all.yml",Ny="/bin/sh",P$=async()=>{let e=ts.quiet;ts.quiet=!0;try{let t=await ts`gh run list --workflow=${ju} --status=in_progress --json displayTitle`;return JSON.parse(t.stdout).flatMap(n=>/\[(?<env>[a-z0-9-]+)\]/.exec(n.displayTitle??"")?.groups?.env??[])}catch{return[]}finally{ts.quiet=e}},x$=async(e,t)=>{let r=e.map(o=>({name:o.name,value:o.name})),n=await I(o=>k$({message:`Deploy which services to ${t}?`,choices:r,pageSize:20},o),{whenHeadless:{refuse:"service"}});if(n.length===0)throw new g(void 0,{operation:"select services",remediation:"pick at least one service, or use `local deploy-all`",stderrExcerpt:"no services selected"});return n},T$=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 K()&&Ms(i,{env:t,services:n,accountId:o,shared:r}),r?I(a=>R$({message:i,choices:[{name:"No, cancel",value:!1},{name:`Yes, deploy to ${t}`,value:!0}]},a),{whenHeadless:"refuse"}):I(a=>b$({message:i,default:!1},a),{whenHeadless:"refuse"})},C$=(e,t,r)=>new Promise((n,o)=>{let s=S$(Ny,[e.scriptPath],{cwd:r,env:t,stdio:"inherit"});s.on("error",o),s.on("close",i=>{n(i??1)})}),$$=async e=>{let{chosen:t,childEnv:r,cwd:n,env:o}=e,s=[],i=[];for(let a of t){d.info(`\u2192 ${a.name} \u2192 ${o}`);let c=await C$(a,r,n);if(c!==0){i.push(a.name),d.error(`\u2717 ${a.name} failed (exit ${c})`);break}s.push(a.name),d.info(`\u2713 ${a.name}`)}return{deployed:s,failed:i}},A$=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 g(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&&!Hi(c,n)});if(i.length>0)throw new g(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))},Mu=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:Ou(o.contract),strippedVars:o.stripped,dryRun:a,success:c};return{content:k(JSON.stringify(l,null,2)),structuredContent:l}},O$=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(),x$(r,o))},_y=async(e,t)=>{let{env:r,service:n,confirmedCommand:o,dryRun:s,printEnv:i}=e,a=await P(),c=await Nu(a);if(c.length===0)throw new g(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=Iy(c);await ze({provider:Fu[t],params:e,operation:"deploy locally",argument:"env"});let u=await Ye(),p=$t(await At(ju),u),m=r??"";m||(h.setInteractive(),m=await En(p,"deploy locally")),h.addOption("--env",m);let f=_u(c,m);if(f.length===0)throw new g(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 O$({selection:t,eligible:f,service:n,env:m}),b=A$({names:y,services:c,env:m});if(t==="selected")for(let Na of y)h.addOption("--service",Na);let w=Vn(m),x=await Ar(),D=(await ts`git rev-parse HEAD`.quiet()).stdout.trim(),N=await em(),T=Iu({env:m,branch:x,sha:D,isClean:N});i&&d.info(`Deploy contract for ${m}:
388
- ${Ji(T)}`);let J=(await Du({env:m,project:l,isShared:w,isClean:N,runningEnvs:await P$(),protectedEnvAccess:u})).identity.accountId;if(s)return d.info([`Would deploy to "${m}" (AWS account ${J}) from this machine`,`Preflight parameter: /${l}/environment`,Ji(T),"Commands:",...b.map(Na=>` ${Ny} ${Na.scriptPath}`),"","Dry run: preflight and contract only \u2014 says nothing about whether the deploy would succeed."].join(`
389
- `)),Mu({env:m,accountId:J,names:y,built:T,deployed:[],failed:[],dryRun:!0,success:!0});if(!o&&!await T$({env:m,isShared:w,names:y,accountId:J}))return d.info("Deployment cancelled"),Mu({env:m,accountId:J,names:y,built:T,deployed:[],failed:[],dryRun:!1,success:!1});T.stripped.length>0&&d.info(`Stripped ambient VITE_* from the build env: ${T.stripped.join(", ")}`);let{deployed:Yt,failed:ys}=await $$({chosen:b,childEnv:T.childEnv,cwd:a,env:m});return ys.length>0&&(d.error(`Partial deploy to "${m}": succeeded [${Yt.join(", ")||"none"}], failed [${ys.join(", ")}]. There is no rollback \u2014 redeploy the previous commit to restore it.`),E$.exitCode=1),h.print(),Mu({env:m,accountId:J,names:y,built:T,deployed:Yt,failed:ys,dryRun:!1,success:ys.length===0})},My=async e=>_y(e,"all"),jy=async e=>_y(e,"selected"),Fy='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.',Ly={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.")},By={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")},Dy=e=>wr({workflowFile:ju,fields:["env"],toolName:e}),Fu={all:Dy("local-deploy-all"),selected:Dy("local-deploy-selected")},Lu=E({name:"local-deploy-all",description:`Deploy EVERY service enabled for an environment, from this machine. ${Fy}`,requiresHumanConfirm:!0,formProvider:Fu.all,inputSchema:Ly,outputSchema:By,handler:My}),Bu=E({name:"local-deploy-selected",description:`Deploy a NAMED SUBSET of services from this machine. ${Fy}`,requiresHumanConfirm:!0,formProvider:Fu.selected,inputSchema:{...Ly,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:By,handler:jy});import N$ from"@inquirer/confirm";import qi from"@inquirer/input";import Gy from"@inquirer/select";import Vu from"node:process";import{z as V}from"zod";import{z as rs}from"zod";var Pn=async(e,t)=>new Promise(r=>{let n=setTimeout(()=>{r(null)},t);e.then(o=>{clearTimeout(n),r(o)},()=>{clearTimeout(n),r(null)})});var Wy=2500,Uy=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Vy=e=>typeof e=="string"&&e.trim()!==""?e.trim():void 0,I$=async()=>{let e=await _o();return{regular:bn(e,"regular"),hotfix:bn(e,"hotfix")}},D$=(e,t)=>e===null?(d.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?(d.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).`,Uu=(e={})=>{let t=e.hintBudgetMs??Wy;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=>Uy(r)&&(r.releases===void 0||Array.isArray(r.releases)&&r.releases.length===0),buildRequestedSchema:async()=>{let r=await Pn(I$(),t);return rs.object({type:rs.enum(["regular","hotfix"]).describe('Release type. "regular" branches off dev and bumps the minor; "hotfix" branches off main and bumps the patch.'),release:rs.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. ${D$(r,t)}`),description:rs.string().optional().describe("Optional. Becomes the Jira fix version description and feeds the PR body. Blank means none."),releaseDate:rs.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=Vy(r.description),a=Vy(r.releaseDate),c=$i(o);return{...Uy(n)?n:{},releases:[{...c,type:s,...i===void 0?{}:{description:i},...a===void 0?{}:{releaseDate:a}}]}}}};var _$='"1.2.5" or "next"',Wu=(e,t)=>{try{return Gl(e,t)}catch(r){throw r instanceof pr?new g(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 zp?new g(r,{operation:"validate release name",remediation:'use a kebab-case name like "checkout-redesign" (lowercase, digits, single hyphens, not a reserved word)'}):r}},M$=async(e,t)=>{let r=bn(e,t),n=r?` [${r}]`:"",o=(await I(i=>qi({message:` Version (e.g. ${_$})${n}: `},i),{whenHeadless:"refuse"})).trim(),s=o===""?r??"":o;return s===""&&(d.error("No version provided. Exiting..."),Vu.exit(1)),s},j$=async()=>{let e=(await I(t=>qi({message:' Name (kebab-case, e.g. "checkout-redesign"): '},t),{whenHeadless:"refuse"})).trim();e===""&&(d.error("No name provided. Exiting..."),Vu.exit(1));try{$s(e)}catch(t){let r=t instanceof Error?t.message:String(t);d.error(`${r} Exiting...`),Vu.exit(1)}return e},F$=async()=>(await I(e=>qi({message:" Release date (yyyy-mm-dd, optional, press Enter to skip): ",validate:No},e),{whenHeadless:"refuse"})).trim(),L$=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=>Gy({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=>Gy({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 j$();l=Wu([{name:m,type:c}],[])[0]}else{let m=await M$(await n(),c);l=Wu([{version:m,type:c}],r)[0],l.id.kind==="version"&&r.push(Bt(`v${l.id.raw}`))}let u=(await I(m=>qi({message:" Description (optional, press Enter to skip): "},m),{whenHeadless:"refuse"})).trim(),p=await F$();o.push({...l,...u!==""?{description:u}:{},...p!==""?{releaseDate:p}:{}}),s=await I(m=>N$({message:"Add another release?",default:!1},m),{whenHeadless:"refuse"})}return o},B$=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 ")},Jy=e=>{for(let t of e)h.addOption("--release",Wl(t))},U$=async(e,t)=>{if(e&&e.length>0){let n=Jl(e)?await t():[],o=Wu(e,n);return Jy(o),o}if(ve())throw new C({status:"argument_required",argument:"release",agentMode:_.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 L$(t);return Jy(r),r},V$=e=>{if(new Set(e.map(r=>r.type)).size>1)throw new g(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"})},W$=async(e,t)=>{let r=e.map(B$).join(`
385
+ `);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}},Au=E({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:Gt.array(Gt.object({version:Gt.string().describe("Release version"),type:Gt.enum(["regular","hotfix"]).describe("Release type"),description:Gt.string().nullable().describe("Jira version description"),releaseDate:Gt.string().nullable().describe("Planned release date of the Jira version (yyyy-mm-dd)"),titleMismatch:Gt.boolean().describe("The PR title names a different release type than its base branch")})).describe("List of all release branches"),count:Gt.number().describe("Number of release branches")},handler:Gi});import c$ from"node:process";var Ou=e=>({...e}),Iu=e=>{let{env:t,branch:r,sha:n,isClean:o,ambient:s=c$.env}=e,i={VITE_DOMAIN_ENV:t,VITE_BRANCH_NAME:r,VITE_COMMIT_HASH:o?n:`${n}-dirty`},a={},c=[];for(let[l,u]of Object.entries(s)){if(l.startsWith("VITE_")){c.push(l);continue}a[l]=u}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}},Ji=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(`
386
+ `)};import R$ from"@inquirer/checkbox";import S$ from"@inquirer/confirm";import E$ from"@inquirer/select";import{spawn as P$}from"node:child_process";import x$ from"node:process";import{z}from"zod";import{$ as rs}from"zx";import{$ as ts}from"zx";var l$=async e=>{let t=ts.quiet;ts.quiet=!0;try{let r=`/${e}/environment`,n=await ts`aws sts get-caller-identity --query Account --output text`,o=await ts`aws ssm get-parameter --name ${r} --query Parameter.Value --output text`;return{accountId:n.stdout.trim(),stage:o.stdout.trim()}}catch(r){throw new g(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{ts.quiet=t}},$y=(e,t)=>{if(t.stage!==e)throw new g(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`})},Ay=e=>{let{env:t,isShared:r,isClean:n}=e;if(!(!r||n))throw new g(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"})},Oy=(e,t)=>{if(t.includes(e))throw new g(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`})},Du=async e=>{let{env:t,project:r,isShared:n,isClean:o,runningEnvs:s,protectedEnvAccess:i}=e;Dr(t,`deploy to "${t}"`,i),Oy(t,s),Ay({env:t,isShared:n,isClean:o});let a=await l$(r);return $y(t,a),{identity:a}};import Iy from"node:fs/promises";import Ki from"node:path";var u$="devops/scripts",d$=/^deploy-(?<service>[a-z0-9-]+)\.sh$/,p$=/skip_unless_env_enabled\s+"[^"]*"\s+"[^"]*"\s+"(?<envs>[^"]*)"/,m$=/aws\s+ssm\s+get-parameter\s+--name[=\s]+(?<arg>[^\s)]+)/,f$=/aws\s+ssm\s+get-parameter\s+--name[=\s]+["']?\/(?<prefix>[\w.-]+)\/environment["']?(?![\w./-])/,Nu=async e=>{let t=Ki.resolve(e,u$),r;try{r=await Iy.readdir(t)}catch{return[]}let n=await vu(e);return(await Promise.all(r.map(s=>({entry:s,match:d$.exec(s)})).filter(s=>s.match!==null).map(async({entry:s,match:i})=>{let a=Ki.resolve(t,s),c=i?.groups?.service??"",l=h$(await g$(a));return{name:c,scriptPath:a,allowedEnvs:wu(y$(l),n.get(c)),ssmPrefix:w$(l)}}))).sort((s,i)=>s.name.localeCompare(i.name))},g$=async e=>{try{return await Iy.readFile(e,"utf-8")}catch{return""}},h$=e=>e.split(`
387
+ `).map((t,r)=>({line:r+1,text:t})).filter(({text:t})=>!t.trimStart().startsWith("#")),y$=e=>{let t=e.reduce((n,{text:o})=>n??p$.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},v$=e=>{let t=e.replaceAll(/["']/g,"");return t.includes("$")&&(t.includes("/environment")||t.startsWith("$"))},w$=e=>{for(let{line:t,text:r}of e){let n=f$.exec(r)?.groups?.prefix;if(n!==void 0)return n;let o=m$.exec(r)?.groups?.arg;if(o!==void 0&&v$(o))return{unparseable:{line:t,text:r.trim()}}}return null},k$=e=>{let t=new Map;for(let r of e)typeof r.ssmPrefix=="string"&&t.set(r.ssmPrefix,[...t.get(r.ssmPrefix)??[],Ki.basename(r.scriptPath)]);return t},b$=e=>{let t=e.flatMap(r=>{if(r.ssmPrefix===null||typeof r.ssmPrefix=="string")return[];let{line:n,text:o}=r.ssmPrefix.unparseable;return[`${Ki.basename(r.scriptPath)}:${n}: ${o}`]});if(t.length!==0)throw new g(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("; ")})},Dy=e=>{b$(e);let t=k$(e),[r,...n]=t.keys();if(r===void 0)throw new g(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 g(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},Hi=(e,t)=>e.allowedEnvs===null||e.allowedEnvs.includes(t),_u=(e,t)=>e.filter(r=>Hi(r,t));var ju="deploy-all.yml",_y="/bin/sh",T$=async()=>{let e=rs.quiet;rs.quiet=!0;try{let t=await rs`gh run list --workflow=${ju} --status=in_progress --json displayTitle`;return JSON.parse(t.stdout).flatMap(n=>/\[(?<env>[a-z0-9-]+)\]/.exec(n.displayTitle??"")?.groups?.env??[])}catch{return[]}finally{rs.quiet=e}},C$=async(e,t)=>{let r=e.map(o=>({name:o.name,value:o.name})),n=await I(o=>R$({message:`Deploy which services to ${t}?`,choices:r,pageSize:20},o),{whenHeadless:{refuse:"service"}});if(n.length===0)throw new g(void 0,{operation:"select services",remediation:"pick at least one service, or use `local deploy-all`",stderrExcerpt:"no services selected"});return n},$$=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 H()&&Ms(i,{env:t,services:n,accountId:o,shared:r}),r?I(a=>E$({message:i,choices:[{name:"No, cancel",value:!1},{name:`Yes, deploy to ${t}`,value:!0}]},a),{whenHeadless:"refuse"}):I(a=>S$({message:i,default:!1},a),{whenHeadless:"refuse"})},A$=(e,t,r)=>new Promise((n,o)=>{let s=P$(_y,[e.scriptPath],{cwd:r,env:t,stdio:"inherit"});s.on("error",o),s.on("close",i=>{n(i??1)})}),O$=async e=>{let{chosen:t,childEnv:r,cwd:n,env:o}=e,s=[],i=[];for(let a of t){d.info(`\u2192 ${a.name} \u2192 ${o}`);let c=await A$(a,r,n);if(c!==0){i.push(a.name),d.error(`\u2717 ${a.name} failed (exit ${c})`);break}s.push(a.name),d.info(`\u2713 ${a.name}`)}return{deployed:s,failed:i}},I$=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 g(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&&!Hi(c,n)});if(i.length>0)throw new g(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))},Mu=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:Ou(o.contract),strippedVars:o.stripped,dryRun:a,success:c};return{content:k(JSON.stringify(l,null,2)),structuredContent:l}},D$=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(),C$(r,o))},My=async(e,t)=>{let{env:r,service:n,confirmedCommand:o,dryRun:s,printEnv:i}=e,a=await P(),c=await Nu(a);if(c.length===0)throw new g(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=Dy(c);await Xe({provider:Fu[t],params:e,operation:"deploy locally",argument:"env"});let u=await ze(),p=$t(await At(ju),u),m=r??"";m||(h.setInteractive(),m=await En(p,"deploy locally")),h.addOption("--env",m);let f=_u(c,m);if(f.length===0)throw new g(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 D$({selection:t,eligible:f,service:n,env:m}),b=I$({names:y,services:c,env:m});if(t==="selected")for(let Na of y)h.addOption("--service",Na);let w=Wn(m),x=await Ar(),D=(await rs`git rev-parse HEAD`.quiet()).stdout.trim(),N=await tm(),T=Iu({env:m,branch:x,sha:D,isClean:N});i&&d.info(`Deploy contract for ${m}:
388
+ ${Ji(T)}`);let K=(await Du({env:m,project:l,isShared:w,isClean:N,runningEnvs:await T$(),protectedEnvAccess:u})).identity.accountId;if(s)return d.info([`Would deploy to "${m}" (AWS account ${K}) from this machine`,`Preflight parameter: /${l}/environment`,Ji(T),"Commands:",...b.map(Na=>` ${_y} ${Na.scriptPath}`),"","Dry run: preflight and contract only \u2014 says nothing about whether the deploy would succeed."].join(`
389
+ `)),Mu({env:m,accountId:K,names:y,built:T,deployed:[],failed:[],dryRun:!0,success:!0});if(!o&&!await $$({env:m,isShared:w,names:y,accountId:K}))return d.info("Deployment cancelled"),Mu({env:m,accountId:K,names:y,built:T,deployed:[],failed:[],dryRun:!1,success:!1});T.stripped.length>0&&d.info(`Stripped ambient VITE_* from the build env: ${T.stripped.join(", ")}`);let{deployed:Yt,failed:ys}=await O$({chosen:b,childEnv:T.childEnv,cwd:a,env:m});return ys.length>0&&(d.error(`Partial deploy to "${m}": succeeded [${Yt.join(", ")||"none"}], failed [${ys.join(", ")}]. There is no rollback \u2014 redeploy the previous commit to restore it.`),x$.exitCode=1),h.print(),Mu({env:m,accountId:K,names:y,built:T,deployed:Yt,failed:ys,dryRun:!1,success:ys.length===0})},jy=async e=>My(e,"all"),Fy=async e=>My(e,"selected"),Ly='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.',By={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.")},Uy={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")},Ny=e=>wr({workflowFile:ju,fields:["env"],toolName:e}),Fu={all:Ny("local-deploy-all"),selected:Ny("local-deploy-selected")},Lu=E({name:"local-deploy-all",description:`Deploy EVERY service enabled for an environment, from this machine. ${Ly}`,requiresHumanConfirm:!0,formProvider:Fu.all,inputSchema:By,outputSchema:Uy,handler:jy}),Bu=E({name:"local-deploy-selected",description:`Deploy a NAMED SUBSET of services from this machine. ${Ly}`,requiresHumanConfirm:!0,formProvider:Fu.selected,inputSchema:{...By,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:Uy,handler:Fy});import M$ from"@inquirer/confirm";import qi from"@inquirer/input";import Jy from"@inquirer/select";import Vu from"node:process";import{z as V}from"zod";import{z as ns}from"zod";var Pn=async(e,t)=>new Promise(r=>{let n=setTimeout(()=>{r(null)},t);e.then(o=>{clearTimeout(n),r(o)},()=>{clearTimeout(n),r(null)})});var Gy=2500,Vy=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Wy=e=>typeof e=="string"&&e.trim()!==""?e.trim():void 0,N$=async()=>{let e=await Mo();return{regular:bn(e,"regular"),hotfix:bn(e,"hotfix")}},_$=(e,t)=>e===null?(d.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?(d.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).`,Uu=(e={})=>{let t=e.hintBudgetMs??Gy;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=>Vy(r)&&(r.releases===void 0||Array.isArray(r.releases)&&r.releases.length===0),buildRequestedSchema:async()=>{let r=await Pn(N$(),t);return ns.object({type:ns.enum(["regular","hotfix"]).describe('Release type. "regular" branches off dev and bumps the minor; "hotfix" branches off main and bumps the patch.'),release:ns.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. ${_$(r,t)}`),description:ns.string().optional().describe("Optional. Becomes the Jira fix version description and feeds the PR body. Blank means none."),releaseDate:ns.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=Wy(r.description),a=Wy(r.releaseDate),c=$i(o);return{...Vy(n)?n:{},releases:[{...c,type:s,...i===void 0?{}:{description:i},...a===void 0?{}:{releaseDate:a}}]}}}};var j$='"1.2.5" or "next"',Wu=(e,t)=>{try{return Gl(e,t)}catch(r){throw r instanceof pr?new g(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 Xp?new g(r,{operation:"validate release name",remediation:'use a kebab-case name like "checkout-redesign" (lowercase, digits, single hyphens, not a reserved word)'}):r}},F$=async(e,t)=>{let r=bn(e,t),n=r?` [${r}]`:"",o=(await I(i=>qi({message:` Version (e.g. ${j$})${n}: `},i),{whenHeadless:"refuse"})).trim(),s=o===""?r??"":o;return s===""&&(d.error("No version provided. Exiting..."),Vu.exit(1)),s},L$=async()=>{let e=(await I(t=>qi({message:' Name (kebab-case, e.g. "checkout-redesign"): '},t),{whenHeadless:"refuse"})).trim();e===""&&(d.error("No name provided. Exiting..."),Vu.exit(1));try{$s(e)}catch(t){let r=t instanceof Error?t.message:String(t);d.error(`${r} Exiting...`),Vu.exit(1)}return e},B$=async()=>(await I(e=>qi({message:" Release date (yyyy-mm-dd, optional, press Enter to skip): ",validate:_o},e),{whenHeadless:"refuse"})).trim(),U$=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=>Jy({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=>Jy({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 L$();l=Wu([{name:m,type:c}],[])[0]}else{let m=await F$(await n(),c);l=Wu([{version:m,type:c}],r)[0],l.id.kind==="version"&&r.push(Bt(`v${l.id.raw}`))}let u=(await I(m=>qi({message:" Description (optional, press Enter to skip): "},m),{whenHeadless:"refuse"})).trim(),p=await B$();o.push({...l,...u!==""?{description:u}:{},...p!==""?{releaseDate:p}:{}}),s=await I(m=>M$({message:"Add another release?",default:!1},m),{whenHeadless:"refuse"})}return o},V$=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 ")},Ky=e=>{for(let t of e)h.addOption("--release",Wl(t))},W$=async(e,t)=>{if(e&&e.length>0){let n=Jl(e)?await t():[],o=Wu(e,n);return Ky(o),o}if(we())throw new C({status:"argument_required",argument:"release",agentMode:_.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 U$(t);return Ky(r),r},G$=e=>{if(new Set(e.map(r=>r.type)).size>1)throw new g(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"})},J$=async(e,t)=>{let r=e.map(V$).join(`
390
390
  - `);await L(t,`Create the following ${e.length} release(s)?
391
391
  - ${r}
392
- `),h.addOption("--yes",!0)},G$=async e=>{let{entry:t,jiraConfig:r}=e,n=X(t.id),o=t.id.kind==="version"?`v${t.id.raw}`:t.id.name;try{await Hr({operation:`create release ${o}`});let s=await al(t.type),i=await cl({id:t.id,jiraConfig:r,description:t.description,...t.releaseDate===void 0?{}:{releaseDate:t.releaseDate},type:t.type,baseSha:s});return d.info(`\u2705 Successfully created release: ${o} (${t.type})`),d.info(`\u{1F517} GitHub PR: ${i.prUrl}`),d.info(`\u{1F517} Jira Version: ${i.jiraVersionUrl}
393
- `),{result:i}}catch(s){let i=ho(s)?s:void 0,a=new g(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 d.error(`\u274C ${a.message}
394
- `),{failure:{version:n,error:a.message}}}},J$=(e,t,r)=>{t===e?d.info(`\u2705 All ${e} release branch(es) were created successfully.`):t>0?(d.warn(`\u26A0\uFE0F ${t} of ${e} release branches were created successfully.`),d.warn(`\u274C ${r} release(s) failed.`)):d.error(`\u274C All ${e} release branch(es) failed to create.`)},Ky=Uu(),Yi=async e=>{let{releases:t,confirmedCommand:r}=e;await xe({operation:"create release"}),await ze({provider:Ky,params:e,operation:"create release",argument:"release"});let n=await en(),o=null,i=await U$(t,async()=>(o===null&&(o=await _o()),o));if(i.length===0)throw new g(void 0,{operation:"create release",remediation:'pass at least one entry in "releases" (e.g. [{ version: "1.2.5", type: "regular" }])',stderrExcerpt:"no releases provided"});V$(i),await uo({operation:"create release",base:rt(i[0].type)}),await W$(i,!!r);let a=[],c=[];for(let u of i){let{result:p,failure:m}=await G$({entry:u,jiraConfig:n});p&&a.push(p),m&&c.push(m)}J$(i.length,a.length,c.length),h.print();let l={createdBranches:a.map(u=>u.branchName),successCount:a.length,failureCount:c.length,releases:a,failedReleases:c};return{content:k(JSON.stringify(l,null,2)),structuredContent:l}},Gu=E({name:"release-create",requiresHumanConfirm:!0,formProvider:Ky,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:Ml.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:Yi});import Hy from"@inquirer/input";import{z as Ue}from"zod";var qy=["description","releaseDate"],K$=async()=>{let e=await F(),t=e.map(s=>s.branch),r=new Map(e.map(s=>[s.branch,s.type])),n=await ae(),o=await Mt(ce({branches:t,descriptions:n,types:r}));return{branch:o,type:r.get(o)||"regular"}},H$=async e=>{let r=(await F()).find(n=>n.branch===e);if(!r)throw new g(void 0,{operation:`edit release ${e}`,remediation:`confirm an open PR exists for ${e} ('gh pr list')`});return r.type},q$=async e=>{let t=e===""?"(no current description)":`current: "${e}"`,n=(await I(o=>Hy({message:` New description ${t} (press Enter to keep current): `},o),{whenHeadless:{refuse:"description"}})).trim();return n===""?e:n},Y$=async e=>{let t=e===null?"(no current date)":`current: ${e}`,n=(await I(o=>Hy({message:` Release date yyyy-mm-dd ${t} (press Enter to keep current): `,validate:No},o),{whenHeadless:{refuse:"releaseDate"}})).trim();return n===""?e:dr(n)},z$=e=>{if(e!==void 0)return e===""?null:e},X$=async e=>(h.setInteractive(),{description:await q$(e.description),releaseDate:await Y$(e.releaseDate)}),Ju=e=>e??"(none)",Z$=(e,t,r)=>e==="description"?` description: "${t.description}" \u2192 "${r.description}"`:` release date: ${Ju(t.releaseDate)} \u2192 ${Ju(r.releaseDate)}`,zi=async e=>{let{version:t,description:r,releaseDate:n,confirmedCommand:o}=e,s=z$(n),i=await en(),a;t?(a=yt(t),await H$(a)):(h.setInteractive(),a=(await K$()).branch);let c=q(a);if(!c)throw new g(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=X(c);h.addOption("--version",l);let u=ne(c),p=await gt(u,i);if(!p)throw new g(void 0,{operation:`edit release ${u}`,remediation:`create the Jira fix version "${u}" first or pick a different release`});let m={description:p.description??"",releaseDate:p.releaseDate||null},f=r!==void 0||s!==void 0;if(!f&&K())throw new C({status:"argument_required",argument:"description",agentMode:_.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=f?{description:r??m.description,releaseDate:s===void 0?m.releaseDate:s}:await X$(m),b=qy.filter(he=>y[he]!==m[he]),w=b.includes("description"),x=b.includes("releaseDate"),D=ar(i,p),N=he=>{let J={version:l,branch:a,jiraVersionUrl:D,previousDescription:m.description,newDescription:y.description,previousReleaseDate:m.releaseDate,newReleaseDate:y.releaseDate,changedFields:b,changed:he};return{content:k(JSON.stringify(J,null,2)),structuredContent:J}};if(b.length===0)return d.info(`No change \u2014 ${u} already has description "${m.description}" and release date ${Ju(m.releaseDate)}`),h.print(),N(!1);w&&h.addOption("--description",y.description),x&&h.addOption("--release-date",y.releaseDate??"");let T=b.map(he=>Z$(he,m,y));return await L(o,`Update ${u}?
392
+ `),h.addOption("--yes",!0)},K$=async e=>{let{entry:t,jiraConfig:r}=e,n=X(t.id),o=t.id.kind==="version"?`v${t.id.raw}`:t.id.name;try{await Hr({operation:`create release ${o}`});let s=await al(t.type),i=await cl({id:t.id,jiraConfig:r,description:t.description,...t.releaseDate===void 0?{}:{releaseDate:t.releaseDate},type:t.type,baseSha:s});return d.info(`\u2705 Successfully created release: ${o} (${t.type})`),d.info(`\u{1F517} GitHub PR: ${i.prUrl}`),d.info(`\u{1F517} Jira Version: ${i.jiraVersionUrl}
393
+ `),{result:i}}catch(s){let i=yo(s)?s:void 0,a=new g(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 d.error(`\u274C ${a.message}
394
+ `),{failure:{version:n,error:a.message}}}},H$=(e,t,r)=>{t===e?d.info(`\u2705 All ${e} release branch(es) were created successfully.`):t>0?(d.warn(`\u26A0\uFE0F ${t} of ${e} release branches were created successfully.`),d.warn(`\u274C ${r} release(s) failed.`)):d.error(`\u274C All ${e} release branch(es) failed to create.`)},Hy=Uu(),Yi=async e=>{let{releases:t,confirmedCommand:r}=e;await xe({operation:"create release"}),await Xe({provider:Hy,params:e,operation:"create release",argument:"release"});let n=await en(),o=null,i=await W$(t,async()=>(o===null&&(o=await Mo()),o));if(i.length===0)throw new g(void 0,{operation:"create release",remediation:'pass at least one entry in "releases" (e.g. [{ version: "1.2.5", type: "regular" }])',stderrExcerpt:"no releases provided"});G$(i),await po({operation:"create release",base:nt(i[0].type)}),await J$(i,!!r);let a=[],c=[];for(let u of i){let{result:p,failure:m}=await K$({entry:u,jiraConfig:n});p&&a.push(p),m&&c.push(m)}H$(i.length,a.length,c.length),h.print();let l={createdBranches:a.map(u=>u.branchName),successCount:a.length,failureCount:c.length,releases:a,failedReleases:c};return{content:k(JSON.stringify(l,null,2)),structuredContent:l}},Gu=E({name:"release-create",requiresHumanConfirm:!0,formProvider:Hy,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:Ml.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:Yi});import qy from"@inquirer/input";import{z as Ue}from"zod";var Yy=["description","releaseDate"],q$=async()=>{let e=await F(),t=e.map(s=>s.branch),r=new Map(e.map(s=>[s.branch,s.type])),n=await ae(),o=await Mt(ce({branches:t,descriptions:n,types:r}));return{branch:o,type:r.get(o)||"regular"}},Y$=async e=>{let r=(await F()).find(n=>n.branch===e);if(!r)throw new g(void 0,{operation:`edit release ${e}`,remediation:`confirm an open PR exists for ${e} ('gh pr list')`});return r.type},z$=async e=>{let t=e===""?"(no current description)":`current: "${e}"`,n=(await I(o=>qy({message:` New description ${t} (press Enter to keep current): `},o),{whenHeadless:{refuse:"description"}})).trim();return n===""?e:n},X$=async e=>{let t=e===null?"(no current date)":`current: ${e}`,n=(await I(o=>qy({message:` Release date yyyy-mm-dd ${t} (press Enter to keep current): `,validate:_o},o),{whenHeadless:{refuse:"releaseDate"}})).trim();return n===""?e:dr(n)},Z$=e=>{if(e!==void 0)return e===""?null:e},Q$=async e=>(h.setInteractive(),{description:await z$(e.description),releaseDate:await X$(e.releaseDate)}),Ju=e=>e??"(none)",eA=(e,t,r)=>e==="description"?` description: "${t.description}" \u2192 "${r.description}"`:` release date: ${Ju(t.releaseDate)} \u2192 ${Ju(r.releaseDate)}`,zi=async e=>{let{version:t,description:r,releaseDate:n,confirmedCommand:o}=e,s=Z$(n),i=await en(),a;t?(a=yt(t),await Y$(a)):(h.setInteractive(),a=(await q$()).branch);let c=q(a);if(!c)throw new g(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=X(c);h.addOption("--version",l);let u=ne(c),p=await gt(u,i);if(!p)throw new g(void 0,{operation:`edit release ${u}`,remediation:`create the Jira fix version "${u}" first or pick a different release`});let m={description:p.description??"",releaseDate:p.releaseDate||null},f=r!==void 0||s!==void 0;if(!f&&H())throw new C({status:"argument_required",argument:"description",agentMode:_.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=f?{description:r??m.description,releaseDate:s===void 0?m.releaseDate:s}:await Q$(m),b=Yy.filter(ye=>y[ye]!==m[ye]),w=b.includes("description"),x=b.includes("releaseDate"),D=ar(i,p),N=ye=>{let K={version:l,branch:a,jiraVersionUrl:D,previousDescription:m.description,newDescription:y.description,previousReleaseDate:m.releaseDate,newReleaseDate:y.releaseDate,changedFields:b,changed:ye};return{content:k(JSON.stringify(K,null,2)),structuredContent:K}};if(b.length===0)return d.info(`No change \u2014 ${u} already has description "${m.description}" and release date ${Ju(m.releaseDate)}`),h.print(),N(!1);w&&h.addOption("--description",y.description),x&&h.addOption("--release-date",y.releaseDate??"");let T=b.map(ye=>eA(ye,m,y));return await L(o,`Update ${u}?
395
395
  ${T.join(`
396
396
  `)}
397
- `),h.addOption("--yes",!0),await Qr({versionId:p.id,...w?{description:y.description}:{},...x?{releaseDate:y.releaseDate}:{}},i),w&&await ni({branch:a,body:go(D,y.description)}),d.info(`\u2705 Updated ${b.join(" and ")} for ${u}`),d.info(`\u{1F517} Jira Version: ${D}`),d.info(`\u{1F517} PR branch: ${a}
398
- `),h.print(),N(!0)},Ku=E({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:Ue.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:Ue.string().optional().describe("New description. Empty string clears the description."),releaseDate:jl.optional().describe("New planned release date (yyyy-mm-dd). Empty string clears the date.")},outputSchema:{version:Ue.string().describe("Release version"),branch:Ue.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:Ue.string().describe("Jira fix version URL"),previousDescription:Ue.string().describe("The description before the update"),newDescription:Ue.string().describe("The description after the update"),previousReleaseDate:Ue.string().nullable().describe("The planned release date before the update, or null"),newReleaseDate:Ue.string().nullable().describe("The planned release date after the update, or null"),changedFields:Ue.array(Ue.enum(qy)).describe("The fields whose value actually changed"),changed:Ue.boolean().describe("Whether anything actually changed")},handler:zi});import{z as re}from"zod";import{$ as qu}from"zx";import{z as Yy}from"zod";var Zy=2500,Xi="release-remove",zy=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Q$=e=>e.version===void 0||e.version==="",eA=async()=>{try{return{outcome:"listed",prs:await F()}}catch(e){return e instanceof g&&e.operation===mo?{outcome:"empty"}:{outcome:"failed"}}},Xy=(e,t)=>(e===null?d.info({msg:`Tool execution form enumeration timed out (gh pr list, ${t/1e3} s): ${Xi}`}):e.outcome==="failed"?d.info({msg:`Tool execution form enumeration failed (gh pr list): ${Xi}`}):d.info({msg:`Tool execution form options empty (open release PRs): ${Xi}`}),null),tA=(e,t)=>{let r=new Map(e.map(n=>[n.branch,n.type]));return ai(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}`}})},rA=(e,t,r)=>{let n=e.map(o=>o.prose).join("; ");return t!==null?`Open release PRs right now: ${n}. `:(d.info({msg:`Tool execution form descriptions unavailable (timeout): ${Xi}`}),`Open release PRs right now: ${n}. Jira descriptions could not be fetched within ${r/1e3} s. `)},Hu=(e={})=>{let t=e.fetchBudgetMs??Zy;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=>zy(r)&&Q$(r),buildRequestedSchema:async()=>{let[r,n]=await Promise.all([Pn(eA(),t),Pn(ae(),t)]);if(r===null||r.outcome!=="listed")return Xy(r,t);let o=tA(r.prs,n);return o.length===0?Xy({outcome:"empty"},t):Yy.object({version:Yy.enum(o.map(s=>s.label)).describe(`The ONE release to tear down. ${rA(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:{...zy(n)?n:{},version:r.version}}};var Qy=["worktree","pr","local-branch","remote-branch","jira"],rv={worktree:"remove the worktree",pr:"close the PR","local-branch":"delete the local branch","remote-branch":"delete the remote branch",jira:"remove the Jira fix version"},br="remove a release",Ke=e=>{throw d.warn({operation:e.operation},`\u26D4 ${e.stderrExcerpt??e.operation}`),new g(void 0,e)},ev=(e,t)=>{throw d.warn({operation:t.operation},`\u26D4 ${t.stderrExcerpt??t.operation}`),new C({...e,agentMode:_.source},2,t)},nA=e=>{ve()&&(e.version||ev({status:"argument_required",argument:"version"},{operation:br,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&&ev({status:"refused"},{operation:br,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"}))},nv=e=>{e.pr?.state==="MERGED"&&Ke({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`})},oA=(e,t)=>{if(t.skipJira||(e.jiraConfig||Ke({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)&&Ke({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||Ke({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)`}))},sA=e=>{if(e.worktreePresent||e.pr!==null||e.localTipSha!==null||e.remoteTipSha!==null||e.jira)return;Ke({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"})},iA=e=>{!e.worktreeDirty||e.worktreeDirty.length===0||Ke({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(", ")}`})},aA=async e=>(await qu`git -C ${e} status --porcelain`).stdout.split(`
399
- `).map(r=>r.trimEnd()).filter(r=>r.length>0),cA=async e=>{try{let{terminals:t}=await Im(e);return t.filter(r=>r.connected).length}catch(t){return d.debug({error:t,worktreePath:e},"release remove: orca terminal probe failed"),0}},lA=async e=>{let t=await js([e]);if(t!==null)throw d.warn({operation:br},`\u26D4 this command runs inside an Orca terminal of ${t}`),new C({status:"refused",reason:"orca_caller_inside_target",agentMode:_.source},2,{operation:br,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`})},uA=async(e,t)=>{let r={jiraConfig:null,jira:null,moveIssuesTo:null};if(t.skipJira)return r;let n=await ht();if(!n)return r;let o=await gt(ne(e),n),s=t.moveIssuesTo?await dA(t.moveIssuesTo,n):null;if(!o)return{jiraConfig:n,jira:null,moveIssuesTo:s};let i=await si(o.id,n);return{jiraConfig:n,moveIssuesTo:s,jira:{version:o,fixCount:i.issuesFixedCount,affectsCount:i.issuesAffectedCount,url:ar(n,o)}}},dA=async(e,t)=>{let r=await gt(e,t);return r||Ke({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}"`})},pA=async(e,t)=>{let r=q(e);r||Ke({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 P(),s=`${`${n}${le}`}/${e}`,[i,a,c,l]=await Promise.all([fe("release"),Yr(e),De(n,`refs/heads/${e}`),Or(n,e)]),u=i.includes(e);return u&&await lA(s),{...await uA(r,t),branch:e,id:r,label:X(r),baseBranch:a?.baseRefName??rt("regular"),worktreePath:s,worktreePresent:u,orcaTerminalCount:u?await cA(s):0,worktreeDirty:u?await aA(s):null,localTipSha:c,remoteTipSha:l,pr:a}},tv=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}),mA=(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}`},fA=(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: ${mA(e,t)}`];return e.orcaTerminalCount>0&&n.push(` \u2022 ${e.orcaTerminalCount} Orca terminal(s) in ${e.worktreePath} will be closed`),n.join(`
400
- `)},Zi=class extends Error{constructor(r,n){super(`step ${r} failed`,{cause:n});this.step=r;this.reason=n;this.name="StepFailure"}step;reason},gA=e=>typeof e=="string"?e:e.outcome;async function ns(e,t,r){try{let n=await r(),o=gA(n);return t.push({step:e}),d.info({step:e,outcome:o},`\u2705 ${rv[e]} \u2014 ${o}`),n}catch(n){throw new Zi(e,n)}}var hA=(e,t)=>t.step==="local-branch"&&e.localTipSha?`local-branch (was ${e.localTipSha.slice(0,7)})`:t.step,yA=e=>{let{plan:t,step:r,done:n,cause:o}=e,s=n.map(p=>hA(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}`,u=o instanceof g?o.remediation:void 0;return new g(o,{operation:`remove release ${t.label} \u2014 step ${Qy.indexOf(r)+1} of ${Qy.length} (${rv[r]})`,remediation:u?`${u} \u2014 ${l}`:l})},vA=async e=>(await Ho(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`})).includes(e.branch)?"removed":"absent",wA=async e=>{let t=await Yr(e.branch);if(nv({...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 qu`gh pr close ${String(t.number)} --comment ${r}`,{outcome:"closed",number:t.number}},kA=async e=>(await Ar()===e.branch&&await qu`git switch ${e.baseBranch}`,await As(e.branch),await rm(e.branch)?Ke({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"),bA=async e=>(await Os(e.branch),e.remoteTipSha?"deleted":"absent"),RA=async(e,t,r)=>{let n=await si(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}\``;Ke({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}`})},SA=async(e,t)=>t.skipJira?"skipped":!e.jira||!e.jiraConfig?"absent":(await RA(e,e.jira,e.jiraConfig),d.info({jiraVersionId:e.jira.version.id,jiraVersionName:e.jira.version.name},"\u{1F5D1}\uFE0F removing Jira fix version"),await il({versionId:e.jira.version.id,moveFixIssuesTo:e.moveIssuesTo?.id,moveAffectedIssuesTo:e.moveIssuesTo?.id},e.jiraConfig),"removed"),EA=(e,t)=>({branch:e.branch,version:e.label,baseBranch:e.baseBranch,worktree:t.worktree,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}),PA=async(e,t,r)=>{let n=await ns("worktree",r,()=>vA(e)),o=await ns("pr",r,()=>wA(e));d.info({branch:e.branch,localTipSha:e.localTipSha,remoteTipSha:e.remoteTipSha},"\u{1F516} branch tips before deletion");let s=await ns("local-branch",r,()=>kA(e)),i=await ns("remote-branch",r,()=>bA(e)),a=await ns("jira",r,()=>SA(e,t));return{worktree:n,pr:o,localBranch:s,remoteBranch:i,jira:a}},xA=async(e,t)=>{let r=[];try{return EA(e,await PA(e,t,r))}catch(n){throw n instanceof Zi?yA({plan:e,step:n.step,done:r,cause:n.reason}):n}},TA=async e=>{if(e)return yt(e);h.setInteractive();let[t,r]=await Promise.all([ae(),F()]),n=r.map(s=>s.branch);n.length===0&&Ke({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 Mt(ce({branches:n,descriptions:t,types:o}))}catch(s){throw Se(s)?s:new g(s,{operation:"select a release to remove",remediation:"pass `--version <ref>` (e.g. `--version 1.2.5`); the picker needs an interactive terminal"})}},ov=Hu(),Qi=async e=>{let{confirmedCommand:t,version:r,moveIssuesTo:n,skipJira:o}=e;await xe({operation:br}),await W(),await ze({provider:ov,params:e,operation:br,argument:"version"}),nA(e);try{let s=await pA(await TA(r),e);d.debug({plan:tv(s)},"release remove: resolved plan"),nv(s),oA(s,e),sA(s),await uo({operation:`remove release ${s.label}`,base:s.baseBranch}),iA(s),h.addOption("--version",s.label),n&&h.addOption("--move-issues-to",n),o&&h.addOption("--skip-jira",!0),await L(t,fA(s,!!o),{throwOnDecline:!0,plan:{...tv(s),skipJira:!!o}}),t||h.addOption("--yes",!0);let i=await xA(s,e);return h.print(),{content:k(JSON.stringify(i,null,2)),structuredContent:i}}catch(s){throw Se(s)||pt(s)||s instanceof g?s:(d.error({err:yr(s)},"\u274C Error removing release"),new g(s,{operation:br,remediation:"check `gh auth status`, `git worktree list` and the Jira credentials, then re-run"}))}},Yu=E({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), 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:ov,inputSchema:{version:re.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:re.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:re.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{branch:re.string().describe("The release branch that was targeted"),version:re.string().describe('The release label (e.g. "1.2.5")'),baseBranch:re.string().describe("The branch HEAD was moved to before the local delete"),worktree:re.enum(["removed","absent"]).describe("Whether a git worktree was removed or none existed"),pr:re.enum(["closed","already-closed","absent"]).describe("What happened to the release pull request"),prNumber:re.number().nullable().describe("The pull request number, or null when none exists"),localBranch:re.enum(["deleted","absent"]).describe("Whether a local branch was deleted or none existed"),localTipSha:re.string().nullable().describe("The local tip before deletion \u2014 the handle that restores the branch"),remoteBranch:re.enum(["deleted","absent"]).describe("Whether the origin branch was deleted or none existed"),remoteTipSha:re.string().nullable().describe("The origin tip before deletion"),jira:re.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:re.object({id:re.string(),name:re.string(),url:re.string()}).nullable().describe("The fix version this release owned, captured before removal \u2014 the id is the only handle that survives it")},handler:Qi});import{spawn as OA}from"node:child_process";import IA from"node:fs";import{homedir as DA}from"node:os";import ta from"node:process";import ea from"node:fs";import xn from"node:path";var CA=e=>{try{return ea.statSync(e).isFile()?ea.readFileSync(e,"utf8"):null}catch{return null}},$A=e=>{try{return ea.realpathSync(e)}catch{return e}},AA=(e,t)=>{let o=t(xn.join(e,".git"))?.split(`
401
- `).map(c=>c.trim()).find(c=>c.startsWith("gitdir:"))?.slice(7).trim();if(!o)return e;let s=xn.resolve(e,o),i=`${xn.sep}.git${xn.sep}worktrees${xn.sep}`,a=s.lastIndexOf(i);return a===-1?e:s.slice(0,a)},sv=(e={})=>{let t=e.listInstallations??Ga,r=e.exists??ea.existsSync,n=e.readGitFile??CA,o=e.realpath??$A,s=new Map;for(let i of t()){if(i.projectPath===null)continue;let a=AA(i.projectPath,n);if(!r(xn.join(a,"infra-kit.json")))continue;let c=o(a);s.has(c)||s.set(c,a)}return[...s.values()].sort()};var NA=180*1e3,_A=900*1e3,MA=4*1024*1024,jA=2e3,FA=e=>new Promise(t=>{let r={stdout:"",stderr:""},n=!1,o=!1,s,i=(u,p)=>{n||(n=!0,clearTimeout(s),t({status:u,stdout:r.stdout,stderr:r.stderr,error:p}))},a=OA(e.command,[...e.args],{cwd:e.cwd,env:e.env,stdio:["ignore","pipe","pipe"],detached:!0,windowsHide:!0});s=setTimeout(()=>{o=!0;try{a.pid!==void 0&&ta.kill(-a.pid,"SIGKILL")}catch{}i(null,`timed out after ${Math.round(e.timeoutMs/1e3)}s`)},e.timeoutMs);let c=u=>p=>{r[u].length<MA&&(r[u]+=p.toString("utf8"))};a.stdout.on("data",c("stdout")),a.stderr.on("data",c("stderr")),a.on("error",u=>{i(null,u.message)});let l=(u,p)=>{i(u,o||p===null?null:`killed by ${p}`)};a.on("close",l),a.on("exit",(u,p)=>{setTimeout(()=>{l(u,p)},jA).unref()})}),LA=({cwd:e,timeoutMs:t})=>FA({command:ta.execPath,args:[ta.argv[1]??"","setup","--unattended","--json"],cwd:e,env:xm(ta.env),timeoutMs:t}),BA=e=>{IA.writeFileSync(cn(),e,{mode:384})},UA=e=>{try{let t=JSON.parse(e);return!Array.isArray(t?.init)||!Array.isArray(t.tools)||typeof t.portlessService!="object"?null:t}catch{return null}},VA=new RegExp("\x1B\\[[0-9;]*m","g"),WA=e=>{if(e.error!==null)return e.error;try{let n=JSON.parse(e.stdout),o=n?.message??n?.error;if(typeof o=="string"&&o!=="")return o}catch{}let t=e.stderr.replace(VA,"").split(`
402
- `).map(n=>n.trim()).filter(Boolean).at(-1),r=`no setup report (exit ${String(e.status)})`;return t?`${r}: ${t.slice(0,300)}`:r},GA=(e,t)=>{let r=[],n=[];for(let a of e.init)a.outcome==="failed"?r.push(a.message):(a.outcome==="manual"||a.outcome==="warned")&&n.push(a.message);for(let a of e.tools)a.action==="failed"?r.push(`${a.id}: ${a.detail}`):a.before.present||n.push(`${a.id} is not installed \u2014 run: infra-kit setup --tools ${a.id}`);let{link:o,node:s,command:i}=e.portlessService;return(o==="failed"||s==="failed")&&r.push(`portless: link ${o}, node ${s}`),i!==null&&n.push(i),r.length===0&&t!==0&&r.push(`setup exited ${String(t)}`),r.length>0?{status:"failed",notes:[...r,...n]}:{status:n.length>0?"attention":"ok",notes:n}},iv=async(e,t,r,n)=>{let o=n-r.clock(),s=e===null?"infra-kit setup":Ri(e);if(o<=0)return{root:e,status:"failed",notes:[`out of time budget \u2014 run: ${s}`]};try{let i=await r.runSetupChild({cwd:t,timeoutMs:Math.min(NA,o)}),a=i.error===null?UA(i.stdout):null;return a===null?{root:e,status:"failed",notes:[`${WA(i)} \u2014 run: ${s}`]}:{root:e,...GA(a,i.status)}}catch(i){return{root:e,status:"failed",notes:[`${i instanceof Error?i.message:String(i)} \u2014 run: ${s}`]}}},JA=e=>{let t=e.find(n=>n.root===null),r=new Set(t?.notes??[]);return e.map(n=>{if(n.root===null||n.status==="failed")return n;let o=n.notes.filter(s=>!r.has(s));return{...n,notes:o,status:n.status==="attention"&&o.length===0?"ok":n.status}})},KA=e=>{let t=[`infra-kit ${e.version} unattended setup \u2014 ${new Date(e.finishedMs??e.startedMs).toISOString()} (attempt ${e.attempts})`];for(let r of e.runs){t.push("",`${r.status.padEnd(9)} ${r.root??"machine"}`);for(let n of r.notes)t.push(` ${n}`)}return`${t.join(`
397
+ `),h.addOption("--yes",!0),await Qr({versionId:p.id,...w?{description:y.description}:{},...x?{releaseDate:y.releaseDate}:{}},i),w&&await ni({branch:a,body:ho(D,y.description)}),d.info(`\u2705 Updated ${b.join(" and ")} for ${u}`),d.info(`\u{1F517} Jira Version: ${D}`),d.info(`\u{1F517} PR branch: ${a}
398
+ `),h.print(),N(!0)},Ku=E({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:Ue.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:Ue.string().optional().describe("New description. Empty string clears the description."),releaseDate:jl.optional().describe("New planned release date (yyyy-mm-dd). Empty string clears the date.")},outputSchema:{version:Ue.string().describe("Release version"),branch:Ue.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:Ue.string().describe("Jira fix version URL"),previousDescription:Ue.string().describe("The description before the update"),newDescription:Ue.string().describe("The description after the update"),previousReleaseDate:Ue.string().nullable().describe("The planned release date before the update, or null"),newReleaseDate:Ue.string().nullable().describe("The planned release date after the update, or null"),changedFields:Ue.array(Ue.enum(Yy)).describe("The fields whose value actually changed"),changed:Ue.boolean().describe("Whether anything actually changed")},handler:zi});import{z as re}from"zod";import{$ as qu}from"zx";import{z as zy}from"zod";var Qy=2500,Xi="release-remove",Xy=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),tA=e=>e.version===void 0||e.version==="",rA=async()=>{try{return{outcome:"listed",prs:await F()}}catch(e){return e instanceof g&&e.operation===fo?{outcome:"empty"}:{outcome:"failed"}}},Zy=(e,t)=>(e===null?d.info({msg:`Tool execution form enumeration timed out (gh pr list, ${t/1e3} s): ${Xi}`}):e.outcome==="failed"?d.info({msg:`Tool execution form enumeration failed (gh pr list): ${Xi}`}):d.info({msg:`Tool execution form options empty (open release PRs): ${Xi}`}),null),nA=(e,t)=>{let r=new Map(e.map(n=>[n.branch,n.type]));return ai(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}`}})},oA=(e,t,r)=>{let n=e.map(o=>o.prose).join("; ");return t!==null?`Open release PRs right now: ${n}. `:(d.info({msg:`Tool execution form descriptions unavailable (timeout): ${Xi}`}),`Open release PRs right now: ${n}. Jira descriptions could not be fetched within ${r/1e3} s. `)},Hu=(e={})=>{let t=e.fetchBudgetMs??Qy;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=>Xy(r)&&tA(r),buildRequestedSchema:async()=>{let[r,n]=await Promise.all([Pn(rA(),t),Pn(ae(),t)]);if(r===null||r.outcome!=="listed")return Zy(r,t);let o=nA(r.prs,n);return o.length===0?Zy({outcome:"empty"},t):zy.object({version:zy.enum(o.map(s=>s.label)).describe(`The ONE release to tear down. ${oA(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:{...Xy(n)?n:{},version:r.version}}};var ev=["worktree","pr","local-branch","remote-branch","jira"],nv={worktree:"remove the worktree",pr:"close the PR","local-branch":"delete the local branch","remote-branch":"delete the remote branch",jira:"remove the Jira fix version"},br="remove a release",Ke=e=>{throw d.warn({operation:e.operation},`\u26D4 ${e.stderrExcerpt??e.operation}`),new g(void 0,e)},tv=(e,t)=>{throw d.warn({operation:t.operation},`\u26D4 ${t.stderrExcerpt??t.operation}`),new C({...e,agentMode:_.source},2,t)},sA=e=>{we()&&(e.version||tv({status:"argument_required",argument:"version"},{operation:br,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&&tv({status:"refused"},{operation:br,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"}))},ov=e=>{e.pr?.state==="MERGED"&&Ke({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`})},iA=(e,t)=>{if(t.skipJira||(e.jiraConfig||Ke({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)&&Ke({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||Ke({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)`}))},aA=e=>{if(e.worktreePresent||e.pr!==null||e.localTipSha!==null||e.remoteTipSha!==null||e.jira)return;Ke({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"})},cA=e=>{!e.worktreeDirty||e.worktreeDirty.length===0||Ke({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(", ")}`})},lA=async e=>(await qu`git -C ${e} status --porcelain`).stdout.split(`
399
+ `).map(r=>r.trimEnd()).filter(r=>r.length>0),uA=async e=>{try{let{terminals:t}=await Dm(e);return t.filter(r=>r.connected).length}catch(t){return d.debug({error:t,worktreePath:e},"release remove: orca terminal probe failed"),0}},dA=async e=>{let t=await js([e]);if(t!==null)throw d.warn({operation:br},`\u26D4 this command runs inside an Orca terminal of ${t}`),new C({status:"refused",reason:"orca_caller_inside_target",agentMode:_.source},2,{operation:br,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`})},pA=async(e,t)=>{let r={jiraConfig:null,jira:null,moveIssuesTo:null};if(t.skipJira)return r;let n=await ht();if(!n)return r;let o=await gt(ne(e),n),s=t.moveIssuesTo?await mA(t.moveIssuesTo,n):null;if(!o)return{jiraConfig:n,jira:null,moveIssuesTo:s};let i=await si(o.id,n);return{jiraConfig:n,moveIssuesTo:s,jira:{version:o,fixCount:i.issuesFixedCount,affectsCount:i.issuesAffectedCount,url:ar(n,o)}}},mA=async(e,t)=>{let r=await gt(e,t);return r||Ke({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}"`})},fA=async(e,t)=>{let r=q(e);r||Ke({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 P(),s=`${`${n}${le}`}/${e}`,[i,a,c,l]=await Promise.all([fe("release"),Yr(e),De(n,`refs/heads/${e}`),Or(n,e)]),u=i.includes(e);return u&&await dA(s),{...await pA(r,t),branch:e,id:r,label:X(r),baseBranch:a?.baseRefName??nt("regular"),worktreePath:s,worktreePresent:u,orcaTerminalCount:u?await uA(s):0,worktreeDirty:u?await lA(s):null,localTipSha:c,remoteTipSha:l,pr:a}},rv=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}),gA=(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}`},hA=(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: ${gA(e,t)}`];return e.orcaTerminalCount>0&&n.push(` \u2022 ${e.orcaTerminalCount} Orca terminal(s) in ${e.worktreePath} will be closed`),n.join(`
400
+ `)},Zi=class extends Error{constructor(r,n){super(`step ${r} failed`,{cause:n});this.step=r;this.reason=n;this.name="StepFailure"}step;reason},yA=e=>typeof e=="string"?e:e.outcome;async function os(e,t,r){try{let n=await r(),o=yA(n);return t.push({step:e}),d.info({step:e,outcome:o},`\u2705 ${nv[e]} \u2014 ${o}`),n}catch(n){throw new Zi(e,n)}}var vA=(e,t)=>t.step==="local-branch"&&e.localTipSha?`local-branch (was ${e.localTipSha.slice(0,7)})`:t.step,wA=e=>{let{plan:t,step:r,done:n,cause:o}=e,s=n.map(p=>vA(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}`,u=o instanceof g?o.remediation:void 0;return new g(o,{operation:`remove release ${t.label} \u2014 step ${ev.indexOf(r)+1} of ${ev.length} (${nv[r]})`,remediation:u?`${u} \u2014 ${l}`:l})},kA=async e=>(await qo(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`})).includes(e.branch)?"removed":"absent",bA=async e=>{let t=await Yr(e.branch);if(ov({...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 qu`gh pr close ${String(t.number)} --comment ${r}`,{outcome:"closed",number:t.number}},RA=async e=>(await Ar()===e.branch&&await qu`git switch ${e.baseBranch}`,await As(e.branch),await nm(e.branch)?Ke({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"),SA=async e=>(await Os(e.branch),e.remoteTipSha?"deleted":"absent"),EA=async(e,t,r)=>{let n=await si(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}\``;Ke({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}`})},PA=async(e,t)=>t.skipJira?"skipped":!e.jira||!e.jiraConfig?"absent":(await EA(e,e.jira,e.jiraConfig),d.info({jiraVersionId:e.jira.version.id,jiraVersionName:e.jira.version.name},"\u{1F5D1}\uFE0F removing Jira fix version"),await il({versionId:e.jira.version.id,moveFixIssuesTo:e.moveIssuesTo?.id,moveAffectedIssuesTo:e.moveIssuesTo?.id},e.jiraConfig),"removed"),xA=(e,t)=>({branch:e.branch,version:e.label,baseBranch:e.baseBranch,worktree:t.worktree,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}),TA=async(e,t,r)=>{let n=await os("worktree",r,()=>kA(e)),o=await os("pr",r,()=>bA(e));d.info({branch:e.branch,localTipSha:e.localTipSha,remoteTipSha:e.remoteTipSha},"\u{1F516} branch tips before deletion");let s=await os("local-branch",r,()=>RA(e)),i=await os("remote-branch",r,()=>SA(e)),a=await os("jira",r,()=>PA(e,t));return{worktree:n,pr:o,localBranch:s,remoteBranch:i,jira:a}},CA=async(e,t)=>{let r=[];try{return xA(e,await TA(e,t,r))}catch(n){throw n instanceof Zi?wA({plan:e,step:n.step,done:r,cause:n.reason}):n}},$A=async e=>{if(e)return yt(e);h.setInteractive();let[t,r]=await Promise.all([ae(),F()]),n=r.map(s=>s.branch);n.length===0&&Ke({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 Mt(ce({branches:n,descriptions:t,types:o}))}catch(s){throw Se(s)?s:new g(s,{operation:"select a release to remove",remediation:"pass `--version <ref>` (e.g. `--version 1.2.5`); the picker needs an interactive terminal"})}},sv=Hu(),Qi=async e=>{let{confirmedCommand:t,version:r,moveIssuesTo:n,skipJira:o}=e;await xe({operation:br}),await W(),await Xe({provider:sv,params:e,operation:br,argument:"version"}),sA(e);try{let s=await fA(await $A(r),e);d.debug({plan:rv(s)},"release remove: resolved plan"),ov(s),iA(s,e),aA(s),await po({operation:`remove release ${s.label}`,base:s.baseBranch}),cA(s),h.addOption("--version",s.label),n&&h.addOption("--move-issues-to",n),o&&h.addOption("--skip-jira",!0),await L(t,hA(s,!!o),{throwOnDecline:!0,plan:{...rv(s),skipJira:!!o}}),t||h.addOption("--yes",!0);let i=await CA(s,e);return h.print(),{content:k(JSON.stringify(i,null,2)),structuredContent:i}}catch(s){throw Se(s)||pt(s)||s instanceof g?s:(d.error({err:yr(s)},"\u274C Error removing release"),new g(s,{operation:br,remediation:"check `gh auth status`, `git worktree list` and the Jira credentials, then re-run"}))}},Yu=E({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), 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:sv,inputSchema:{version:re.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:re.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:re.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{branch:re.string().describe("The release branch that was targeted"),version:re.string().describe('The release label (e.g. "1.2.5")'),baseBranch:re.string().describe("The branch HEAD was moved to before the local delete"),worktree:re.enum(["removed","absent"]).describe("Whether a git worktree was removed or none existed"),pr:re.enum(["closed","already-closed","absent"]).describe("What happened to the release pull request"),prNumber:re.number().nullable().describe("The pull request number, or null when none exists"),localBranch:re.enum(["deleted","absent"]).describe("Whether a local branch was deleted or none existed"),localTipSha:re.string().nullable().describe("The local tip before deletion \u2014 the handle that restores the branch"),remoteBranch:re.enum(["deleted","absent"]).describe("Whether the origin branch was deleted or none existed"),remoteTipSha:re.string().nullable().describe("The origin tip before deletion"),jira:re.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:re.object({id:re.string(),name:re.string(),url:re.string()}).nullable().describe("The fix version this release owned, captured before removal \u2014 the id is the only handle that survives it")},handler:Qi});import{spawn as DA}from"node:child_process";import NA from"node:fs";import{homedir as _A}from"node:os";import ta from"node:process";import ea from"node:fs";import xn from"node:path";var AA=e=>{try{return ea.statSync(e).isFile()?ea.readFileSync(e,"utf8"):null}catch{return null}},OA=e=>{try{return ea.realpathSync(e)}catch{return e}},IA=(e,t)=>{let o=t(xn.join(e,".git"))?.split(`
401
+ `).map(c=>c.trim()).find(c=>c.startsWith("gitdir:"))?.slice(7).trim();if(!o)return e;let s=xn.resolve(e,o),i=`${xn.sep}.git${xn.sep}worktrees${xn.sep}`,a=s.lastIndexOf(i);return a===-1?e:s.slice(0,a)},iv=(e={})=>{let t=e.listInstallations??Ga,r=e.exists??ea.existsSync,n=e.readGitFile??AA,o=e.realpath??OA,s=new Map;for(let i of t()){if(i.projectPath===null)continue;let a=IA(i.projectPath,n);if(!r(xn.join(a,"infra-kit.json")))continue;let c=o(a);s.has(c)||s.set(c,a)}return[...s.values()].sort()};var MA=180*1e3,jA=900*1e3,FA=4*1024*1024,LA=2e3,BA=e=>new Promise(t=>{let r={stdout:"",stderr:""},n=!1,o=!1,s,i=(u,p)=>{n||(n=!0,clearTimeout(s),t({status:u,stdout:r.stdout,stderr:r.stderr,error:p}))},a=DA(e.command,[...e.args],{cwd:e.cwd,env:e.env,stdio:["ignore","pipe","pipe"],detached:!0,windowsHide:!0});s=setTimeout(()=>{o=!0;try{a.pid!==void 0&&ta.kill(-a.pid,"SIGKILL")}catch{}i(null,`timed out after ${Math.round(e.timeoutMs/1e3)}s`)},e.timeoutMs);let c=u=>p=>{r[u].length<FA&&(r[u]+=p.toString("utf8"))};a.stdout.on("data",c("stdout")),a.stderr.on("data",c("stderr")),a.on("error",u=>{i(null,u.message)});let l=(u,p)=>{i(u,o||p===null?null:`killed by ${p}`)};a.on("close",l),a.on("exit",(u,p)=>{setTimeout(()=>{l(u,p)},LA).unref()})}),UA=({cwd:e,timeoutMs:t})=>BA({command:ta.execPath,args:[ta.argv[1]??"","setup","--unattended","--json"],cwd:e,env:Tm(ta.env),timeoutMs:t}),VA=e=>{NA.writeFileSync(cn(),e,{mode:384})},WA=e=>{try{let t=JSON.parse(e);return!Array.isArray(t?.init)||!Array.isArray(t.tools)||typeof t.portlessService!="object"?null:t}catch{return null}},GA=new RegExp("\x1B\\[[0-9;]*m","g"),JA=e=>{if(e.error!==null)return e.error;try{let n=JSON.parse(e.stdout),o=n?.message??n?.error;if(typeof o=="string"&&o!=="")return o}catch{}let t=e.stderr.replace(GA,"").split(`
402
+ `).map(n=>n.trim()).filter(Boolean).at(-1),r=`no setup report (exit ${String(e.status)})`;return t?`${r}: ${t.slice(0,300)}`:r},KA=(e,t)=>{let r=[],n=[];for(let a of e.init)a.outcome==="failed"?r.push(a.message):(a.outcome==="manual"||a.outcome==="warned")&&n.push(a.message);for(let a of e.tools)a.action==="failed"?r.push(`${a.id}: ${a.detail}`):a.before.present||n.push(`${a.id} is not installed \u2014 run: infra-kit setup --tools ${a.id}`);let{link:o,node:s,command:i}=e.portlessService;return(o==="failed"||s==="failed")&&r.push(`portless: link ${o}, node ${s}`),i!==null&&n.push(i),r.length===0&&t!==0&&r.push(`setup exited ${String(t)}`),r.length>0?{status:"failed",notes:[...r,...n]}:{status:n.length>0?"attention":"ok",notes:n}},av=async(e,t,r,n)=>{let o=n-r.clock(),s=e===null?"infra-kit setup":Ri(e);if(o<=0)return{root:e,status:"failed",notes:[`out of time budget \u2014 run: ${s}`]};try{let i=await r.runSetupChild({cwd:t,timeoutMs:Math.min(MA,o)}),a=i.error===null?WA(i.stdout):null;return a===null?{root:e,status:"failed",notes:[`${JA(i)} \u2014 run: ${s}`]}:{root:e,...KA(a,i.status)}}catch(i){return{root:e,status:"failed",notes:[`${i instanceof Error?i.message:String(i)} \u2014 run: ${s}`]}}},HA=e=>{let t=e.find(n=>n.root===null),r=new Set(t?.notes??[]);return e.map(n=>{if(n.root===null||n.status==="failed")return n;let o=n.notes.filter(s=>!r.has(s));return{...n,notes:o,status:n.status==="attention"&&o.length===0?"ok":n.status}})},qA=e=>{let t=[`infra-kit ${e.version} unattended setup \u2014 ${new Date(e.finishedMs??e.startedMs).toISOString()} (attempt ${e.attempts})`];for(let r of e.runs){t.push("",`${r.status.padEnd(9)} ${r.root??"machine"}`);for(let n of r.notes)t.push(` ${n}`)}return`${t.join(`
403
403
  `)}
404
- `},HA=e=>({version:e.version??U.version,home:e.home??DA(),clock:e.clock??Date.now,acquireLock:e.acquireLock??(()=>Ha({lockPath:Wg()})),readRecord:e.readRecord??ln,writeRecord:e.writeRecord??Gg,discoverProjects:e.discoverProjects??(()=>sv()),runSetupChild:e.runSetupChild??LA,writeLog:e.writeLog??BA}),qA=e=>{try{return{projects:e.discoverProjects(),error:null}}catch(t){return{projects:[],error:t instanceof Error?t.message:String(t)}}},YA=async e=>{let t=e.readRecord(),r=e.clock();if(!Hg(t,e.version,r))return"not-due";let n=t?.version===e.version?t.attempts+1:1;e.writeRecord({version:e.version,attempts:n,startedMs:r,finishedMs:null,runs:[]});let o=r+_A,s=await iv(null,e.home,e,o),i=qA(e),a=[i.error===null?s:{root:null,status:"failed",notes:[...s.notes,`could not list projects: ${i.error}`]}];for(let l of i.projects)a.push(await iv(l,l,e,o));let c={version:e.version,attempts:n,startedMs:r,finishedMs:e.clock(),runs:JA(a)};e.writeRecord(c);try{e.writeLog(KA(c))}catch{}return"ran"},av=async(e={})=>{try{let t=HA(e),r=t.acquireLock();if(r===null)return"already-running";try{return await YA(t)}finally{r()}}catch{return"not-due"}},zu=async(e={})=>{let t=await av(e);return{content:k(JSON.stringify({outcome:t})),structuredContent:{outcome:t}}};import{spawnSync as QA}from"node:child_process";import{homedir as eO}from"node:os";import tO from"node:process";var zA=e=>{let t=new Set(e.steps.map(r=>r[0]));return t.has("brew")?"homebrew":t.has("npm")?"npm":null},XA=e=>{let t=[];return e.needsSudo&&t.push("needs-sudo"),e.fetchesNetworkScript&&t.push("fetches-network-script"),t},ZA=(e,t)=>{let r=zA(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},os=(e,t)=>{let r=[...XA(e),...ZA(e,t)];return r.length===0?{executable:!0}:{executable:!1,reasons:r}},ss=e=>e.steps.map(Ie);var rO=["NONINTERACTIVE","CI","INTERACTIVE","HAVE_SUDO_ACCESS","SUDO_ASKPASS"],nO=e=>{let t={...Ap(e)};for(let r of rO)delete t[r];return t},Xu=(e,t,r={})=>{let n=r.spawnSync??QA,o=r.env??tO.env,s=(r.agentMode??ve)(),i=ss(e),a=os(e,t);return a.executable?s?{ran:!1,commands:i,refusedBecause:["agent-mode"]}:iO({recipe:e,spawn:n,env:o,commands:i,notify:r.notify??oO}):{ran:!1,commands:i,refusedBecause:a.reasons}},oO=e=>{d.info(e)},lv=64,sO=lv*1024*1024,iO=({recipe:e,spawn:t,env:r,commands:n,notify:o})=>{let s=nO(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:sO,cwd:eO(),env:s}),l=pO(c);if(l!==null)return{ran:!0,ok:!1,commands:n,failedStep:n[i],detail:l}}return{ran:!0,ok:!0,commands:n}},aO=5,cO=/^(?:error|fatal|warning: failed|[a-z-]{0,20} ERR!)[:\s]/i,cv=e=>e==null?[]:String(e).split(`
405
- `).map(t=>t.trim()).filter(t=>t.length>0),lO=e=>{let t=cv(e.stderr),r=cv(e.stdout),n=[...t,...r].filter(s=>cO.test(s)),o=t.length>0?t:r;return(n.length>0?n:o).slice(-aO).join(" / ")},uO="ENOBUFS",dO=e=>e.error?.code===uO,pO=e=>{if(dO(e))return`terminated after exceeding the ${lv} 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=lO(e),r=t===""?"":`: ${t}`;return`exited ${e.status??"unknown"}${r}`};var mO=e=>{let t=[];return e.some(n=>n.id==="brew"&&n.present)&&t.push("homebrew"),t.push("npm"),t},fO=e=>{let t=Le(e.id);return e.present?t.updateFor(e.binRealPath):t.bootstrapInstall},gO=(e,t)=>{let r=fO(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=os(r,n);return{state:e,action:e.present?"update":"install",recipe:r,executable:o.executable,refusedBecause:o.executable?[]:o.reasons,commands:ss(r),context:n}},ra=async(e=ur,t=Ao())=>{let r=await Io(ur,t),n={owner:null,present:mO(r)},o=_l(e),s=new Map(r.map(a=>[a.id,a]));return{plans:o.filter(a=>e.includes(a)).map(a=>gO(s.get(a),n)),context:n}};var Zu=(e,t)=>({...is(e),action:"skipped",commands:e.commands,detail:t}),is=e=>({id:e.state.id,before:{present:e.state.present,onPath:e.state.onPath,version:e.state.version,manager:e.state.manager}}),uv=(e,t)=>e.action==="none"?Zu(e,`nothing to do: ${e.state.manager} installs are not managed from here`):t==="update"&&e.action==="install"?Zu(e,"not installed, and --update only updates \u2014 drop the flag to install it"):e.executable?null:{...is(e),action:"refused",commands:e.commands,detail:`refused (${e.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},hO=(e,t)=>t.ran?t.ok?{...is(e),action:e.action==="install"?"installed":"updated",commands:t.commands,detail:e.action==="install"?"installed":"updated"}:{...is(e),action:"failed",commands:t.commands,detail:`${t.failedStep??"a step"} ${t.detail??"failed"}`}:{...is(e),action:"refused",commands:t.commands,detail:`refused (${t.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},Qu=async e=>{let t=e.run??Xu,{plans:r}=await ra(e.ids,e.probeDeps),n=[];for(let o of r){let s=uv(o,e.mode);if(s!==null){n.push(s);continue}n.push(hO(o,t(o.recipe,o.context)))}return n},ed=async(e,t)=>{let{plans:r}=await ra(e,t);return r.map(n=>uv(n,"converge")??Zu(n,`would ${n.action} \u2014 nothing was run (--skip-tools)`))};import IO from"node:process";import{z as O}from"zod";var td={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,"token-perms":10,chrome:11,shell:12},yO=Object.keys(td).sort((e,t)=>td[e]-td[t]),dv={skipped:0,ok:1,changed:2,manual:3,warn:4,fail:5},pv=new Set(["manual","warn","fail"]),rd=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 Ne(e)}},vO=e=>e.reduce((t,r)=>dv[r]>dv[t]?r:t,"skipped"),fv=e=>e.message.trim(),wO=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 "),mv=e=>e.message===gn,kO=(e,t)=>{let[r]=e;return e.length===1&&r!==void 0?fv(r):e.length>1?wO(e):t?"activate with the last line below":"see below"},bO=(e,t)=>{if(t.length===0)return{name:e,status:"skipped",message:"did not run"};let r=t.map(i=>rd(i.outcome)),n=t.filter(i=>pv.has(rd(i.outcome))).map(fv),o=t.filter(i=>!pv.has(rd(i.outcome))&&!mv(i)),s={name:e,status:vO(r),message:kO(o,t.some(mv))};return n.length>0?{...s,notes:n}:s},RO=e=>({label:"Local setup",rows:yO.map(t=>bO(t,e.filter(r=>r.step===t)))}),SO=(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 Ne(e.action)}},EO=(e,t)=>{let r=SO(e,t),n={name:e.id,status:r,message:e.detail};return r==="manual"&&e.commands.length>0?{...n,notes:[...e.commands]}:n},PO=(e,t)=>({label:t.skipTools?"Tools (probe: nothing installed)":"Tools",rows:e.map(r=>EO(r,t))}),xO=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 Ne(e)}},TO=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 Ne(e)}},CO=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 Ne(e)}},$O=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 Ne(e.outcome)}},AO=(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 Ne(e)}},OO=e=>({label:"Portless service",rows:[{name:"link",status:xO(e.link),message:CO(e.link)},{name:"node",status:TO(e.node.outcome),message:$O(e.node)},AO(e.service,e.command)]}),gv=(e,t)=>[RO(e.init),PO(e.tools,t),OO(e.portless)],hv=e=>e.some(t=>t.rows.some(r=>r.status==="fail"));var DO=()=>{let{link:e,node:t}=Ts();return{link:e,node:t,target:{home:e.home,isGlobal:e.isGlobal,processStartTime:()=>null}}},NO=async e=>{let t=Kp(e.link).outcome,r=Jp(e.node),n=xs(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 Jh(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}},vv="--unattended cannot be combined with --tools or --update: an unattended run installs and updates nothing (it implies --skip-tools).",wv="--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.",_O=e=>{let t=Array.isArray(e.update)?e.update:void 0,r=e.update===!0||t!==void 0,n=e.unattended===!0,o=e.skipTools===!0||n;if(n&&(e.tools!==void 0||r))throw new Error(vv);if(o&&(e.tools!==void 0||r))throw new Error(wv);return{ids:e.tools??t??ur,mode:r?"update":"converge",skipTools:o}},yv=(e,t)=>e instanceof fn?e.step:t.at(-1)?.step??"zshrc",MO=async()=>{let e=[];try{await Cl(t=>{e.push(t)})}catch(t){e.push({step:yv(t,e),outcome:"failed",message:`The ${yv(t,e)} step failed: ${t instanceof Error?t.message:String(t)}`,level:"warn"})}return e},jO=(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}`}))},FO=async(e,t)=>{try{return e.skipTools?await ed(e.ids,t.probeDeps):await Qu({ids:e.ids,mode:e.mode,probeDeps:t.probeDeps,run:t.run})}catch(r){return jO(e.ids,r)}},LO=e=>({step:e.step,outcome:e.outcome,message:e.message}),na=async(e={})=>{let t=_O(e);Ge.withheld=e.unattended===!0;let r=await MO(),n=await FO(t,e),o=await NO(e.portlessDeps??DO()),s=gv({init:r,tools:n,portless:o},{skipTools:t.skipTools});tt({title:"infra-kit setup",sections:s},{ascii:e.ascii}),d.info(gn),hv(s)&&(IO.exitCode=1);let i={init:r.map(LO),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}},BO=O.object({step:O.enum(["zshrc","zshenv","migrations","user-config","guidance","worktrees","plugin-pointer","mcp-server","mcp-proxies","project-config","token-perms","chrome","shell"]).describe("Which init step this reports on"),outcome:O.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:O.string().describe("The same line a human running this would have read")}),UO=O.object({id:O.string().describe("Dependency id"),action:O.enum(["installed","updated","skipped","refused","failed"]).describe("What happened"),before:O.object({present:O.boolean(),onPath:O.boolean(),version:O.string().nullable(),manager:O.string()}).describe("The tool\u2019s state before this run"),commands:O.array(O.string()).describe("The exact commands, one per step \u2014 printed even when refused"),detail:O.string().describe("Why, in one line")}),VO=O.object({link:O.enum(["created","repointed","unchanged","skipped-local","skipped-unresolved","failed"]).describe("What the ~/.infra-kit/portless link step did"),node:O.enum(["created","refreshed","unchanged","skipped-local","skipped-platform","failed"]).describe("What the ~/.infra-kit/node step did"),service:O.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:O.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")}),WO={init:O.array(BO).describe("One entry per init step, in the order they ran"),tools:O.array(UO).describe("One result per requested dependency"),portlessService:VO.describe("The portless link, node, and system-service step \u2014 run on every setup, never gated on the tool options"),converged:O.boolean().describe("Whether the dependency step could act at all (false under skipTools)"),changed:O.boolean().describe("Whether anything was installed or updated"),report:O.array(O.object({label:O.string().describe("Section heading"),rows:O.array(O.object({name:O.string().describe("Init step, tool id, or portless part"),status:O.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:O.string().describe("The row message, as printed"),notes:O.array(O.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:O.boolean().describe("Whether no tool failed (a refusal is not a failure)")},GO={tools:O.array(O.enum(ur)).optional().describe("Which tools to act on. Omit for all six."),mode:O.enum(["converge","update"]).optional().describe("converge (default): install what is missing and update the rest. update: never install."),skipTools:O.boolean().optional().describe("Read-only: run the init half, then REPORT what each tool needs without installing anything.")},nd=E({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, check the agent-instruction files (never rewritten here: drift is reported with the `audit --fix` command that refreshes them), 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:GO,outputSchema:WO,requiresHumanConfirm:!0,handler:e=>na({tools:e.tools,update:e.mode==="update",skipTools:e.skipTools})});import{existsSync as bv}from"node:fs";import Rv from"node:path";import tI from"node:process";import{z as bt}from"zod";import{createHash as JO}from"node:crypto";import{readFileSync as KO}from"node:fs";var Rr=e=>JO("sha256").update(KO(e)).digest("hex");import{readFileSync as ZO,writeFileSync as QO}from"node:fs";import aa from"node:path";import{z as ct}from"zod";var Q="vendor",HO=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack"]),qO=new Set([".sync-manifest.json",".eslintcache","log.txt","routeTree.gen.ts"]),YO=[".tsbuildinfo"],od=e=>HO.has(e),sd=e=>qO.has(e)?!0:YO.some(t=>e.endsWith(t)),oa=e=>{let t=e.split("/"),r=t.pop()??"";return t.some(o=>od(o))||sd(r)};import{readdirSync as zO}from"node:fs";import id from"node:path";var XO=e=>e.split(id.sep).join("/"),sa=e=>{let t=[],r=n=>{for(let o of zO(n,{withFileTypes:!0})){let s=id.join(n,o.name);if(o.isDirectory()){if(od(o.name))continue;r(s);continue}sd(o.name)||t.push(XO(id.relative(e,s)))}};return r(e),t.sort()};var Ve=".sync-manifest.json",ia=1,eI=ct.object({schemaVersion:ct.number().optional(),source:ct.string(),commit:ct.string(),syncedAt:ct.string(),fileCount:ct.number(),files:ct.record(ct.string(),ct.string())}),ad=e=>(e.schemaVersion??ia)>ia,kv=(e,t)=>{let r={},n=t?[...new Set(t)].sort():sa(e);for(let o of n)try{r[o]=Rr(aa.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},as=e=>{let t=aa.join(e,Ve),r;try{r=ZO(t,"utf8")}catch{throw new Error(`Missing ${Ve} at ${t}`)}let n=eI.safeParse(JSON.parse(r));if(!n.success)throw new Error(`Invalid ${Ve} at ${t}: ${ct.prettifyError(n.error)}`);return n.data},cd=(e,t,r)=>{let n=kv(e,r),o={schemaVersion:ia,source:t.source,commit:t.commit,syncedAt:new Date().toISOString(),fileCount:Object.keys(n).length,files:n};return QO(aa.join(e,Ve),`${JSON.stringify(o,null,2)}
404
+ `},YA=e=>({version:e.version??U.version,home:e.home??_A(),clock:e.clock??Date.now,acquireLock:e.acquireLock??(()=>Ha({lockPath:Gg()})),readRecord:e.readRecord??ln,writeRecord:e.writeRecord??Jg,discoverProjects:e.discoverProjects??(()=>iv()),runSetupChild:e.runSetupChild??UA,writeLog:e.writeLog??VA}),zA=e=>{try{return{projects:e.discoverProjects(),error:null}}catch(t){return{projects:[],error:t instanceof Error?t.message:String(t)}}},XA=async e=>{let t=e.readRecord(),r=e.clock();if(!qg(t,e.version,r))return"not-due";let n=t?.version===e.version?t.attempts+1:1;e.writeRecord({version:e.version,attempts:n,startedMs:r,finishedMs:null,runs:[]});let o=r+jA,s=await av(null,e.home,e,o),i=zA(e),a=[i.error===null?s:{root:null,status:"failed",notes:[...s.notes,`could not list projects: ${i.error}`]}];for(let l of i.projects)a.push(await av(l,l,e,o));let c={version:e.version,attempts:n,startedMs:r,finishedMs:e.clock(),runs:HA(a)};e.writeRecord(c);try{e.writeLog(qA(c))}catch{}return"ran"},cv=async(e={})=>{try{let t=YA(e),r=t.acquireLock();if(r===null)return"already-running";try{return await XA(t)}finally{r()}}catch{return"not-due"}},zu=async(e={})=>{let t=await cv(e);return{content:k(JSON.stringify({outcome:t})),structuredContent:{outcome:t}}};import{spawnSync as tO}from"node:child_process";import{homedir as rO}from"node:os";import nO from"node:process";var ZA=e=>{let t=new Set(e.steps.map(r=>r[0]));return t.has("brew")?"homebrew":t.has("npm")?"npm":null},QA=e=>{let t=[];return e.needsSudo&&t.push("needs-sudo"),e.fetchesNetworkScript&&t.push("fetches-network-script"),t},eO=(e,t)=>{let r=ZA(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},ss=(e,t)=>{let r=[...QA(e),...eO(e,t)];return r.length===0?{executable:!0}:{executable:!1,reasons:r}},is=e=>e.steps.map(Ie);var oO=["NONINTERACTIVE","CI","INTERACTIVE","HAVE_SUDO_ACCESS","SUDO_ASKPASS"],sO=e=>{let t={...Op(e)};for(let r of oO)delete t[r];return t},Xu=(e,t,r={})=>{let n=r.spawnSync??tO,o=r.env??nO.env,s=(r.agentMode??we)(),i=is(e),a=ss(e,t);return a.executable?s?{ran:!1,commands:i,refusedBecause:["agent-mode"]}:cO({recipe:e,spawn:n,env:o,commands:i,notify:r.notify??iO}):{ran:!1,commands:i,refusedBecause:a.reasons}},iO=e=>{d.info(e)},uv=64,aO=uv*1024*1024,cO=({recipe:e,spawn:t,env:r,commands:n,notify:o})=>{let s=sO(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:aO,cwd:rO(),env:s}),l=fO(c);if(l!==null)return{ran:!0,ok:!1,commands:n,failedStep:n[i],detail:l}}return{ran:!0,ok:!0,commands:n}},lO=5,uO=/^(?:error|fatal|warning: failed|[a-z-]{0,20} ERR!)[:\s]/i,lv=e=>e==null?[]:String(e).split(`
405
+ `).map(t=>t.trim()).filter(t=>t.length>0),dO=e=>{let t=lv(e.stderr),r=lv(e.stdout),n=[...t,...r].filter(s=>uO.test(s)),o=t.length>0?t:r;return(n.length>0?n:o).slice(-lO).join(" / ")},pO="ENOBUFS",mO=e=>e.error?.code===pO,fO=e=>{if(mO(e))return`terminated after exceeding the ${uv} 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=dO(e),r=t===""?"":`: ${t}`;return`exited ${e.status??"unknown"}${r}`};var gO=e=>{let t=[];return e.some(n=>n.id==="brew"&&n.present)&&t.push("homebrew"),t.push("npm"),t},hO=e=>{let t=Le(e.id);return e.present?t.updateFor(e.binRealPath):t.bootstrapInstall},yO=(e,t)=>{let r=hO(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=ss(r,n);return{state:e,action:e.present?"update":"install",recipe:r,executable:o.executable,refusedBecause:o.executable?[]:o.reasons,commands:is(r),context:n}},ra=async(e=ur,t=Oo())=>{let r=await Do(ur,t),n={owner:null,present:gO(r)},o=_l(e),s=new Map(r.map(a=>[a.id,a]));return{plans:o.filter(a=>e.includes(a)).map(a=>yO(s.get(a),n)),context:n}};var Zu=(e,t)=>({...as(e),action:"skipped",commands:e.commands,detail:t}),as=e=>({id:e.state.id,before:{present:e.state.present,onPath:e.state.onPath,version:e.state.version,manager:e.state.manager}}),dv=(e,t)=>e.action==="none"?Zu(e,`nothing to do: ${e.state.manager} installs are not managed from here`):t==="update"&&e.action==="install"?Zu(e,"not installed, and --update only updates \u2014 drop the flag to install it"):e.executable?null:{...as(e),action:"refused",commands:e.commands,detail:`refused (${e.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},vO=(e,t)=>t.ran?t.ok?{...as(e),action:e.action==="install"?"installed":"updated",commands:t.commands,detail:e.action==="install"?"installed":"updated"}:{...as(e),action:"failed",commands:t.commands,detail:`${t.failedStep??"a step"} ${t.detail??"failed"}`}:{...as(e),action:"refused",commands:t.commands,detail:`refused (${t.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},Qu=async e=>{let t=e.run??Xu,{plans:r}=await ra(e.ids,e.probeDeps),n=[];for(let o of r){let s=dv(o,e.mode);if(s!==null){n.push(s);continue}n.push(vO(o,t(o.recipe,o.context)))}return n},ed=async(e,t)=>{let{plans:r}=await ra(e,t);return r.map(n=>dv(n,"converge")??Zu(n,`would ${n.action} \u2014 nothing was run (--skip-tools)`))};import NO from"node:process";import{z as O}from"zod";var td={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,"token-perms":10,chrome:11,shell:12},wO=Object.keys(td).sort((e,t)=>td[e]-td[t]),pv={skipped:0,ok:1,changed:2,manual:3,warn:4,fail:5},mv=new Set(["manual","warn","fail"]),rd=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 Ne(e)}},kO=e=>e.reduce((t,r)=>pv[r]>pv[t]?r:t,"skipped"),gv=e=>e.message.trim(),bO=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 "),fv=e=>e.message===gn,RO=(e,t)=>{let[r]=e;return e.length===1&&r!==void 0?gv(r):e.length>1?bO(e):t?"activate with the last line below":"see below"},SO=(e,t)=>{if(t.length===0)return{name:e,status:"skipped",message:"did not run"};let r=t.map(i=>rd(i.outcome)),n=t.filter(i=>mv.has(rd(i.outcome))).map(gv),o=t.filter(i=>!mv.has(rd(i.outcome))&&!fv(i)),s={name:e,status:kO(r),message:RO(o,t.some(fv))};return n.length>0?{...s,notes:n}:s},EO=e=>({label:"Local setup",rows:wO.map(t=>SO(t,e.filter(r=>r.step===t)))}),PO=(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 Ne(e.action)}},xO=(e,t)=>{let r=PO(e,t),n={name:e.id,status:r,message:e.detail};return r==="manual"&&e.commands.length>0?{...n,notes:[...e.commands]}:n},TO=(e,t)=>({label:t.skipTools?"Tools (probe: nothing installed)":"Tools",rows:e.map(r=>xO(r,t))}),CO=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 Ne(e)}},$O=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 Ne(e)}},AO=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 Ne(e)}},OO=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 Ne(e.outcome)}},IO=(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 Ne(e)}},DO=e=>({label:"Portless service",rows:[{name:"link",status:CO(e.link),message:AO(e.link)},{name:"node",status:$O(e.node.outcome),message:OO(e.node)},IO(e.service,e.command)]}),hv=(e,t)=>[EO(e.init),TO(e.tools,t),DO(e.portless)],yv=e=>e.some(t=>t.rows.some(r=>r.status==="fail"));var _O=()=>{let{link:e,node:t}=Ts();return{link:e,node:t,target:{home:e.home,isGlobal:e.isGlobal,processStartTime:()=>null}}},MO=async e=>{let t=Hp(e.link).outcome,r=Kp(e.node),n=xs(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 Kh(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}},wv="--unattended cannot be combined with --tools or --update: an unattended run installs and updates nothing (it implies --skip-tools).",kv="--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.",jO=e=>{let t=Array.isArray(e.update)?e.update:void 0,r=e.update===!0||t!==void 0,n=e.unattended===!0,o=e.skipTools===!0||n;if(n&&(e.tools!==void 0||r))throw new Error(wv);if(o&&(e.tools!==void 0||r))throw new Error(kv);return{ids:e.tools??t??ur,mode:r?"update":"converge",skipTools:o}},vv=(e,t)=>e instanceof fn?e.step:t.at(-1)?.step??"zshrc",FO=async()=>{let e=[];try{await Cl(t=>{e.push(t)})}catch(t){e.push({step:vv(t,e),outcome:"failed",message:`The ${vv(t,e)} step failed: ${t instanceof Error?t.message:String(t)}`,level:"warn"})}return e},LO=(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}`}))},BO=async(e,t)=>{try{return e.skipTools?await ed(e.ids,t.probeDeps):await Qu({ids:e.ids,mode:e.mode,probeDeps:t.probeDeps,run:t.run})}catch(r){return LO(e.ids,r)}},UO=e=>({step:e.step,outcome:e.outcome,message:e.message}),na=async(e={})=>{let t=jO(e);Ge.withheld=e.unattended===!0;let r=await FO(),n=await BO(t,e),o=await MO(e.portlessDeps??_O()),s=hv({init:r,tools:n,portless:o},{skipTools:t.skipTools});rt({title:"infra-kit setup",sections:s},{ascii:e.ascii}),d.info(gn),yv(s)&&(NO.exitCode=1);let i={init:r.map(UO),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}},VO=O.object({step:O.enum(["zshrc","zshenv","migrations","user-config","guidance","worktrees","plugin-pointer","mcp-server","mcp-proxies","project-config","token-perms","chrome","shell"]).describe("Which init step this reports on"),outcome:O.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:O.string().describe("The same line a human running this would have read")}),WO=O.object({id:O.string().describe("Dependency id"),action:O.enum(["installed","updated","skipped","refused","failed"]).describe("What happened"),before:O.object({present:O.boolean(),onPath:O.boolean(),version:O.string().nullable(),manager:O.string()}).describe("The tool\u2019s state before this run"),commands:O.array(O.string()).describe("The exact commands, one per step \u2014 printed even when refused"),detail:O.string().describe("Why, in one line")}),GO=O.object({link:O.enum(["created","repointed","unchanged","skipped-local","skipped-unresolved","failed"]).describe("What the ~/.infra-kit/portless link step did"),node:O.enum(["created","refreshed","unchanged","skipped-local","skipped-platform","failed"]).describe("What the ~/.infra-kit/node step did"),service:O.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:O.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")}),JO={init:O.array(VO).describe("One entry per init step, in the order they ran"),tools:O.array(WO).describe("One result per requested dependency"),portlessService:GO.describe("The portless link, node, and system-service step \u2014 run on every setup, never gated on the tool options"),converged:O.boolean().describe("Whether the dependency step could act at all (false under skipTools)"),changed:O.boolean().describe("Whether anything was installed or updated"),report:O.array(O.object({label:O.string().describe("Section heading"),rows:O.array(O.object({name:O.string().describe("Init step, tool id, or portless part"),status:O.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:O.string().describe("The row message, as printed"),notes:O.array(O.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:O.boolean().describe("Whether no tool failed (a refusal is not a failure)")},KO={tools:O.array(O.enum(ur)).optional().describe("Which tools to act on. Omit for all six."),mode:O.enum(["converge","update"]).optional().describe("converge (default): install what is missing and update the rest. update: never install."),skipTools:O.boolean().optional().describe("Read-only: run the init half, then REPORT what each tool needs without installing anything.")},nd=E({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, check the agent-instruction files (never rewritten here: drift is reported with the `audit --fix` command that refreshes them), 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:KO,outputSchema:JO,requiresHumanConfirm:!0,handler:e=>na({tools:e.tools,update:e.mode==="update",skipTools:e.skipTools})});import{existsSync as Rv}from"node:fs";import Sv from"node:path";import nI from"node:process";import{z as bt}from"zod";import{createHash as HO}from"node:crypto";import{readFileSync as qO}from"node:fs";var Rr=e=>HO("sha256").update(qO(e)).digest("hex");import{readFileSync as eI,writeFileSync as tI}from"node:fs";import aa from"node:path";import{z as lt}from"zod";var Q="vendor",YO=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack"]),zO=new Set([".sync-manifest.json",".eslintcache","log.txt","routeTree.gen.ts"]),XO=[".tsbuildinfo"],od=e=>YO.has(e),sd=e=>zO.has(e)?!0:XO.some(t=>e.endsWith(t)),oa=e=>{let t=e.split("/"),r=t.pop()??"";return t.some(o=>od(o))||sd(r)};import{readdirSync as ZO}from"node:fs";import id from"node:path";var QO=e=>e.split(id.sep).join("/"),sa=e=>{let t=[],r=n=>{for(let o of ZO(n,{withFileTypes:!0})){let s=id.join(n,o.name);if(o.isDirectory()){if(od(o.name))continue;r(s);continue}sd(o.name)||t.push(QO(id.relative(e,s)))}};return r(e),t.sort()};var Ve=".sync-manifest.json",ia=1,rI=lt.object({schemaVersion:lt.number().optional(),source:lt.string(),commit:lt.string(),syncedAt:lt.string(),fileCount:lt.number(),files:lt.record(lt.string(),lt.string())}),ad=e=>(e.schemaVersion??ia)>ia,bv=(e,t)=>{let r={},n=t?[...new Set(t)].sort():sa(e);for(let o of n)try{r[o]=Rr(aa.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},cs=e=>{let t=aa.join(e,Ve),r;try{r=eI(t,"utf8")}catch{throw new Error(`Missing ${Ve} at ${t}`)}let n=rI.safeParse(JSON.parse(r));if(!n.success)throw new Error(`Invalid ${Ve} at ${t}: ${lt.prettifyError(n.error)}`);return n.data},cd=(e,t,r)=>{let n=bv(e,r),o={schemaVersion:ia,source:t.source,commit:t.commit,syncedAt:new Date().toISOString(),fileCount:Object.keys(n).length,files:n};return tI(aa.join(e,Ve),`${JSON.stringify(o,null,2)}
406
406
  `),o},ld=(e,t)=>{let r=Object.fromEntries(Object.entries(t.files).filter(([c])=>!oa(c))),n=sa(e),o=[],s=[];for(let c of n){if(!(c in r)){s.push(c);continue}Rr(aa.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 ud=30,dd=(e,t)=>{if(t.length!==0){d.info(`
407
- ${e} (${t.length}):`);for(let r of t.slice(0,ud))d.info(` ${r}`);t.length>ud&&d.info(` \u2026and ${t.length-ud} more`)}},ca=async(e={})=>{let t=e.cwd??await P(),r=Rv.join(t,Q),n={modified:[],added:[],removed:[],fileCount:0};if(!bv(r)){d.info(`\u2139\uFE0F No ${Q}/ folder found \u2014 nothing to check.`);let u={status:"skipped",ok:!0,...n};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}}if(!bv(Rv.join(r,Ve))){d.error(`\u274C Missing ${Q}/${Ve}. Re-run the vendor sync to generate it.`);let u={status:"missing-manifest",ok:!1,...n};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}}let o=as(r);if(ad(o)){d.error(`\u274C ${Q}/${Ve} has a newer schemaVersion (${String(o.schemaVersion)}) than this CLI supports. Upgrade infra-kit.`);let u={status:"unknown-schema",ok:!1,...n};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}}let{modified:s,added:i,removed:a}=ld(r,o),c=s.length>0||i.length>0||a.length>0;c?(d.error(`\u274C ${Q}/ has drifted from ${Q}/${Ve}.`),d.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),dd("Modified",s),dd("Added (not in manifest)",i),dd("Removed (in manifest, now missing)",a)):d.info(`\u2705 ${Q}/ 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}},rI={status:bt.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:bt.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:bt.number(),modified:bt.array(bt.string()),added:bt.array(bt.string()),removed:bt.array(bt.string())},pd=E({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:rI,handler:()=>ca({cwd:tI.cwd()})});import Sv from"node:process";import{z as cs}from"zod";var Ev=async e=>{try{return await e()}catch{return null}},la=async()=>{let e=U.version;d.info(e);let t=await Ev(P),r=t===null?null:await Ev(()=>Re(t)),n={version:e,cwd:Sv.cwd(),repoRoot:t,mainRepoRoot:r,projectDir:Sv.env.CLAUDE_PROJECT_DIR||null};return{content:k(JSON.stringify(n,null,2)),structuredContent:n}},md=E({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:cs.string().describe("Installed infra-kit CLI version (from package.json)"),cwd:cs.string().describe("The working directory of this process"),repoRoot:cs.string().nullable().describe("git toplevel of cwd \u2014 the worktree itself in a linked worktree; null when git cannot answer"),mainRepoRoot:cs.string().nullable().describe("The main checkout a linked worktree belongs to (equals repoRoot outside worktrees); null with repoRoot"),projectDir:cs.string().nullable().describe("CLAUDE_PROJECT_DIR as Claude Code set it for this process, or null")},handler:la});import jv from"@inquirer/confirm";import cI from"node:path";import{z as M}from"zod";import{$ as us}from"zx";import nI from"@inquirer/input";import xv from"@inquirer/select";import{$ as Jt}from"zx";var ls="dev",oI="main",fd="feature/",Tv=["new","local","remote"],ua=e=>{let t=e.trim().replace(/^feature\//,"").toLowerCase().replaceAll(/\s+/g,"-");return`${fd}${t}`},Cv=async()=>{let e=await Jt({nothrow:!0,quiet:!0})`git symbolic-ref --quiet --short refs/remotes/origin/HEAD`,t=e.exitCode===0?e.stdout.trim().replace(/^origin\//,""):"";return t===""?null:t},sI=2,gd=async()=>{let e=await Jt({nothrow:!0,quiet:!0})`git ls-remote --exit-code origin refs/heads/${ls}`;if(e.exitCode===0)return ls;if(e.exitCode!==sI)throw new g(void 0,{operation:"create feature worktree",remediation:"check the network and your access to origin, or pass --base explicitly",stderrExcerpt:e.stderr.trim()||`could not ask origin whether ${ls} exists`});return await Cv()??ls},$v=async e=>{let t=e?.trim();return t?t===ls||t===oI||t===await Cv()?t:we(me(t)):gd()},Av=async()=>I(e=>xv({message:"What kind of worktree?",choices:[{name:"Release \u2014 worktrees for open release branches",value:"release"},{name:"Feature \u2014 a new or existing feature/* branch",value:"feature"}]},e),{whenHeadless:{value:"release"}}),Ov=async()=>I(e=>nI({message:"Feature name (becomes feature/<name>):",required:!0,validate:t=>ua(t)===fd?"Enter a name":!0},e),{whenHeadless:{refuse:"feature"}}),Iv=async(e,t)=>e.length===0?t:I(r=>xv({message:"Base branch:",default:t,choices:[t,...e].map(n=>({name:n,value:n}))},r),{whenHeadless:{value:t}}),iI=async e=>{let t=await Jt({nothrow:!0,quiet:!0})`git check-ref-format --branch ${e}`;if(e===fd||t.exitCode!==0)throw new g(void 0,{operation:"create feature worktree",remediation:"pass a feature name made of letters, digits, `-`, `_`, `.` or `/`, e.g. --feature checkout-v2",stderrExcerpt:`"${e}" is not a valid branch name`})},Pv=async e=>(await Jt({nothrow:!0,quiet:!0})`git fetch origin ${e}`).exitCode===0,aI=async e=>(await Jt({nothrow:!0,quiet:!0})`git show-ref --verify --quiet refs/heads/${e}`).exitCode===0,Dv=async e=>{let{names:t,base:r}=e,n=[...new Set(t.map(ua))];for(let s of n)await iI(s);if(!await Pv(r))throw new g(void 0,{operation:"create feature worktree",remediation:"pass --base dev, --base main or an existing release branch (`infra-kit release list` lists them); a repo with neither dev nor a recorded default branch needs `git remote set-head origin --auto`",stderrExcerpt:`base branch origin/${r} not found`});let o=[];for(let s of n)await aI(s)?o.push({branch:s,base:r,source:"local"}):await Pv(s)?o.push({branch:s,base:r,source:"remote"}):o.push({branch:s,base:r,source:"new"});return o},Nv=async(e,t)=>{let{branch:r,base:n,source:o}=e;o==="local"?await Jt`git worktree add ${t} ${r}`:o==="remote"?await Jt`git worktree add --track -b ${r} ${t} origin/${r}`:await Jt`git worktree add --no-track -b ${r} ${t} origin/${n}`},_v=e=>e.source==="new"?` \u2022 ${e.branch}: new branch from origin/${e.base}`:` \u2022 ${e.branch}: existing ${e.source==="local"?"local":"remote"} branch (base not applied)`;var ds="create worktrees",lI=["already_open","orca_unreachable","orca_absent","orca_worktree_not_selectable","orca_error"],hd=()=>({orcaOpened:[],orcaSkipped:[],orcaHidden:[]}),da=async e=>{let{confirmedCommand:t,githubDesktop:r,orca:n}=e;await xe({operation:ds}),uI(e);try{let o=await P(),s=`${o}${le}`;await Mv(`${s}/${Cr.release}`),await Mv(`${s}/${Cr.feature}`);let i=await dI(e),a=i==="feature"?await mI(e):await pI(e);if(a===null){d.info("\u2139\uFE0F No open release branches found"),h.print();let D={kind:i,createdWorktrees:[],count:0,features:[],...hd()};return{content:k(JSON.stringify(D,null,2)),structuredContent:D}}let c=await W(),l=await fI(r,c),u=await gI(n,c),p=await Re(o),m=cI.basename(p),f=u?await hI({explicit:n!==void 0,mainRepoRoot:p}):null;await L(t,yI(f,m,a.previewLines)),t||h.addOption("--yes",!0);let y=f?await vI(f,p):null,b=await SI(a.targets,s);if(EI(b),l)for(let D of b)await us`github ${s}/${D}`,await us`sleep 5`;let w=y?await kI({registration:y,createdWorktrees:b,worktreeDir:s,mainRepoRoot:p,repoName:m,config:c}):hd();bI(w),h.print();let x={kind:i,createdWorktrees:b,count:b.length,features:a.features.filter(D=>b.includes(D.branch)),...w};return{content:k(JSON.stringify(x,null,2)),structuredContent:x}}catch(o){throw Se(o)||o instanceof C?o:(d.debug({err:o},"Error managing worktrees"),new g(o,{operation:ds,remediation:o instanceof g&&o.remediation||"verify branches don't already exist as worktrees: 'git worktree list'"}))}},uI=e=>{let t=e.all||e.versions!==void 0,r=e.feature!==void 0||e.base!==void 0;if(t&&r)throw new g(void 0,{operation:ds,remediation:"pass either --versions/--all (release worktrees) or --feature [--base] (feature worktrees)",stderrExcerpt:"--feature/--base cannot be combined with --versions/--all"})},dI=async e=>e.feature!==void 0||e.base!==void 0?"feature":e.all||e.versions!==void 0?"release":(h.setInteractive(),Av()),pI=async e=>{let{all:t,versions:r}=e,n=await fe("release"),o=[];if(r)o=r.split(",").map(a=>we(me(a.trim())));else{let a=await F(),c=a.map(l=>l.branch);if(c.length===0)return null;if(t)o=c;else{h.setInteractive();let l=new Map(a.map(p=>[p.branch,p.type])),u=await ae();o=await jt(ce({branches:c,descriptions:u,types:l}),{required:!0})}}t?h.addOption("--all",!0):h.addOption("--versions",vt(o));let{branchesToCreate:s}=RI({selectedReleaseBranches:o,currentWorktrees:n});return{targets:s.map(a=>({branch:a,add:c=>us`git worktree add ${c} ${a}`})),features:[],previewLines:[]}},mI=async e=>{let r=e.feature?.split(",").filter(l=>l.trim()!=="")??[],n=e.base;if(r.length===0&&(h.setInteractive(),r=[await Ov()],n===void 0)){let l=(await F()).map(u=>u.branch);n=await Iv(l,await gd())}let o=await $v(n),s=await Dv({names:r,base:o});h.addOption("--feature",s.map(l=>l.branch.replace(/^feature\//,"")).join(",")),h.addOption("--base",o);let i=await fe("feature"),a=s.filter(l=>i.includes(l.branch)?(d.info(`\u2139\uFE0F ${l.branch} is already checked out in a worktree`),!1):!0);return{targets:a.map(l=>({branch:l.branch,add:u=>Nv(l,u)})),features:a,previewLines:a.map(_v)}},fI=async(e,t)=>{let r=t.worktrees?.openInGithubDesktop,n=e??r??await I(o=>jv({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},gI=async(e,t)=>{let r=t.worktrees?.openInOrca,n=e??r??await I(o=>jv({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},Fv=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"},hI=async e=>{let{explicit:t,mainRepoRoot:r}=e,n=await Ct();if(n!=="ready"){let{reason:s,text:i}=Fv(n);if(t)throw d.warn({operation:ds},`\u26D4 --orca was passed but ${i}`),new C({status:"refused",reason:s,agentMode:_.source},2,{operation:ds,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 d.warn(`\u26A0\uFE0F ${i} \u2014 worktrees will be created but not opened in Orca`),{probe:n,registered:!1,visibility:void 0}}let o=await Nm(r);return{probe:n,registered:o.registered,visibility:o.visibility}},yI=(e,t,r)=>{let n=["Are you sure you want to proceed with these worktree changes?",...r];return e?.probe==="ready"&&!e.registered&&n.push(` \u2022 will register ${t} in Orca (orca repo add); its worktrees start hidden in Orca's sidebar until you choose Show`),n.join(`
408
- `)},vI=async(e,t)=>{if(e.probe!=="ready")return{kind:"skip",reason:Fv(e.probe).reason};if(e.registered)return{kind:"ready",visibility:e.visibility};try{let{visibility:r}=await _m(t);return{kind:"ready",visibility:r}}catch(r){return d.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 Ir?r.code:void 0}}},wI=e=>`Orca \u2192 ${e} \u2192 "hidden worktrees" card \u2192 Show, or Settings \u2192 General \u2192 Workspace \u2192 external-worktree sources`,kI=async e=>{let{registration:t,createdWorktrees:r,worktreeDir:n,mainRepoRoot:o,repoName:s,config:i}=e,a=hd();if(t.kind==="skip"){for(let p of r)a.orcaSkipped.push({branch:p,reason:t.reason,code:t.code});return a}let c=gm(i),l=r.length===1&&t.visibility!=="hide",u=jm();for(let p of r){let m=`${n}/${p}`;try{let{layout:f}=await Fm({cwd:m,title:Lm({branch:p}),focus:l,layout:"full",panes:c,poll:u});await Mm(o,m)?a.orcaOpened.push({branch:p,layout:f}):a.orcaHidden.push({branch:p,path:m,fix:wI(s)})}catch(f){d.warn({error:f,branch:p},`\u26A0\uFE0F Failed to open Orca terminals for ${p}`),f instanceof Ir&&f.code==="orca_worktree_not_selectable"?a.orcaSkipped.push({branch:p,reason:"orca_worktree_not_selectable"}):a.orcaSkipped.push({branch:p,reason:"orca_error",code:f instanceof Ir?f.code:void 0})}}return a},bI=e=>{for(let t of e.orcaOpened)d.info(`\u{1FA9F} Opened ${t.branch} in Orca (${t.layout})`);for(let t of e.orcaHidden)d.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})`:"";d.info(`\u21A9\uFE0F ${t.branch} not opened in Orca: ${t.reason}${r}`)}},Mv=async e=>{await us`mkdir -p ${e}`},RI=e=>{let{selectedReleaseBranches:t,currentWorktrees:r}=e,n=r.filter(s=>$r(s));return{branchesToCreate:t.filter(s=>!n.includes(s))}},SI=async(e,t)=>{let r=await Promise.allSettled(e.map(async o=>{let s=`${t}/${o.branch}`;return await o.add(s),await us({cwd:s})`pnpm install`,o.branch})),n=[];for(let[o,s]of r.entries())if(s.status==="fulfilled")n.push(s.value);else{let i=e[o]?.branch,a=new g(s.reason,{operation:`git worktree add for ${i}`,remediation:"check the branch name and that the parent dir is writable"});d.error({error:s.reason,msg:a.message})}return n},EI=e=>{if(e.length>0){d.info("\u2705 Created git worktrees:");for(let t of e)d.info(t);d.info("")}else d.info("\u2139\uFE0F No new git worktrees to create")},yd=E({name:"worktrees-add",description:`Create local git worktrees under the worktrees directory and run "pnpm install" in each: release worktrees for open release branches ("versions" / all=true), or feature worktrees ("feature", optional "base") \u2014 each name becomes a feature/<name> branch at <root>-worktrees/feature/<name>, cut from origin/<base> (default dev, or the default branch of a repo without dev; main; or any release branch) with no upstream, or checked out as-is when the branch already exists locally or on origin. Mutates the local filesystem. When invoked via MCP, pass "versions" (comma-separated), all=true, or "feature" \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:{feature:M.string().optional().describe('Comma-separated feature names (e.g. "checkout-v2" or "feature/checkout-v2"); each becomes a feature/<name> worktree. Cannot be combined with "versions" or "all".'),base:M.string().optional().describe(`Base for NEW feature branches: "dev" (default; the repo's default branch when it has no dev), "main", or a release ref ("1.4.0", "release/v1.4.0", "release/<name>"). Not applied to a feature branch that already exists. Implies a feature run.`),all:M.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:M.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.'),githubDesktop:M.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:M.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:{kind:M.enum(["release","feature"]).describe("Which kind of worktree the run created"),features:M.array(M.object({branch:M.string(),base:M.string(),source:M.enum(Tv)})).describe('Created feature worktrees: source "new" = cut from origin/<base>; "local" / "remote" = an existing branch checked out as-is (base not applied)'),createdWorktrees:M.array(M.string()).describe("List of created git worktree branches"),count:M.number().describe("Number of git worktrees created"),orcaOpened:M.array(M.object({branch:M.string(),layout:M.enum(["full","single-pane"])})).describe("Created worktrees that got an Orca terminal tab on a row the sidebar shows, with the layout applied"),orcaSkipped:M.array(M.object({branch:M.string(),reason:M.enum(lI),code:M.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:M.array(M.object({branch:M.string(),path:M.string(),fix:M.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:da});import{z as Kt}from"zod";var pa=async()=>{await W();let[e,t]=await Promise.all([fe("release"),fe("feature")]);if(e.length===0&&t.length===0){d.info("\u2139\uFE0F No active worktrees found");let s={worktrees:[],count:0,features:[]};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}}let r=e.length>0?await PI(e):[],n=[];r.length>0&&n.push(`\u{1F33F} Active worktrees:
407
+ ${e} (${t.length}):`);for(let r of t.slice(0,ud))d.info(` ${r}`);t.length>ud&&d.info(` \u2026and ${t.length-ud} more`)}},ca=async(e={})=>{let t=e.cwd??await P(),r=Sv.join(t,Q),n={modified:[],added:[],removed:[],fileCount:0};if(!Rv(r)){d.info(`\u2139\uFE0F No ${Q}/ folder found \u2014 nothing to check.`);let u={status:"skipped",ok:!0,...n};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}}if(!Rv(Sv.join(r,Ve))){d.error(`\u274C Missing ${Q}/${Ve}. Re-run the vendor sync to generate it.`);let u={status:"missing-manifest",ok:!1,...n};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}}let o=cs(r);if(ad(o)){d.error(`\u274C ${Q}/${Ve} has a newer schemaVersion (${String(o.schemaVersion)}) than this CLI supports. Upgrade infra-kit.`);let u={status:"unknown-schema",ok:!1,...n};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}}let{modified:s,added:i,removed:a}=ld(r,o),c=s.length>0||i.length>0||a.length>0;c?(d.error(`\u274C ${Q}/ has drifted from ${Q}/${Ve}.`),d.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),dd("Modified",s),dd("Added (not in manifest)",i),dd("Removed (in manifest, now missing)",a)):d.info(`\u2705 ${Q}/ 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}},oI={status:bt.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:bt.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:bt.number(),modified:bt.array(bt.string()),added:bt.array(bt.string()),removed:bt.array(bt.string())},pd=E({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:oI,handler:()=>ca({cwd:nI.cwd()})});import Ev from"node:process";import{z as ls}from"zod";var Pv=async e=>{try{return await e()}catch{return null}},la=async()=>{let e=U.version;d.info(e);let t=await Pv(P),r=t===null?null:await Pv(()=>Re(t)),n={version:e,cwd:Ev.cwd(),repoRoot:t,mainRepoRoot:r,projectDir:Ev.env.CLAUDE_PROJECT_DIR||null};return{content:k(JSON.stringify(n,null,2)),structuredContent:n}},md=E({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:ls.string().describe("Installed infra-kit CLI version (from package.json)"),cwd:ls.string().describe("The working directory of this process"),repoRoot:ls.string().nullable().describe("git toplevel of cwd \u2014 the worktree itself in a linked worktree; null when git cannot answer"),mainRepoRoot:ls.string().nullable().describe("The main checkout a linked worktree belongs to (equals repoRoot outside worktrees); null with repoRoot"),projectDir:ls.string().nullable().describe("CLAUDE_PROJECT_DIR as Claude Code set it for this process, or null")},handler:la});import Fv from"@inquirer/confirm";import uI from"node:path";import{z as M}from"zod";import{$ as ds}from"zx";import sI from"@inquirer/input";import Tv from"@inquirer/select";import{$ as Jt}from"zx";var us="dev",iI="main",fd="feature/",Cv=["new","local","remote"],ua=e=>{let t=e.trim().replace(/^feature\//,"").toLowerCase().replaceAll(/\s+/g,"-");return`${fd}${t}`},$v=async()=>{let e=await Jt({nothrow:!0,quiet:!0})`git symbolic-ref --quiet --short refs/remotes/origin/HEAD`,t=e.exitCode===0?e.stdout.trim().replace(/^origin\//,""):"";return t===""?null:t},aI=2,gd=async()=>{let e=await Jt({nothrow:!0,quiet:!0})`git ls-remote --exit-code origin refs/heads/${us}`;if(e.exitCode===0)return us;if(e.exitCode!==aI)throw new g(void 0,{operation:"create feature worktree",remediation:"check the network and your access to origin, or pass --base explicitly",stderrExcerpt:e.stderr.trim()||`could not ask origin whether ${us} exists`});return await $v()??us},Av=async e=>{let t=e?.trim();return t?t===us||t===iI||t===await $v()?t:ke(me(t)):gd()},Ov=async()=>I(e=>Tv({message:"What kind of worktree?",choices:[{name:"Release \u2014 worktrees for open release branches",value:"release"},{name:"Feature \u2014 a new or existing feature/* branch",value:"feature"}]},e),{whenHeadless:{value:"release"}}),Iv=async()=>I(e=>sI({message:"Feature name (becomes feature/<name>):",required:!0,validate:t=>ua(t)===fd?"Enter a name":!0},e),{whenHeadless:{refuse:"feature"}}),Dv=async(e,t)=>e.length===0?t:I(r=>Tv({message:"Base branch:",default:t,choices:[t,...e].map(n=>({name:n,value:n}))},r),{whenHeadless:{value:t}}),cI=async e=>{let t=await Jt({nothrow:!0,quiet:!0})`git check-ref-format --branch ${e}`;if(e===fd||t.exitCode!==0)throw new g(void 0,{operation:"create feature worktree",remediation:"pass a feature name made of letters, digits, `-`, `_`, `.` or `/`, e.g. --feature checkout-v2",stderrExcerpt:`"${e}" is not a valid branch name`})},xv=async e=>(await Jt({nothrow:!0,quiet:!0})`git fetch origin ${e}`).exitCode===0,lI=async e=>(await Jt({nothrow:!0,quiet:!0})`git show-ref --verify --quiet refs/heads/${e}`).exitCode===0,Nv=async e=>{let{names:t,base:r}=e,n=[...new Set(t.map(ua))];for(let s of n)await cI(s);if(!await xv(r))throw new g(void 0,{operation:"create feature worktree",remediation:"pass --base dev, --base main or an existing release branch (`infra-kit release list` lists them); a repo with neither dev nor a recorded default branch needs `git remote set-head origin --auto`",stderrExcerpt:`base branch origin/${r} not found`});let o=[];for(let s of n)await lI(s)?o.push({branch:s,base:r,source:"local"}):await xv(s)?o.push({branch:s,base:r,source:"remote"}):o.push({branch:s,base:r,source:"new"});return o},_v=async(e,t)=>{let{branch:r,base:n,source:o}=e;o==="local"?await Jt`git worktree add ${t} ${r}`:o==="remote"?await Jt`git worktree add --track -b ${r} ${t} origin/${r}`:await Jt`git worktree add --no-track -b ${r} ${t} origin/${n}`},Mv=e=>e.source==="new"?` \u2022 ${e.branch}: new branch from origin/${e.base}`:` \u2022 ${e.branch}: existing ${e.source==="local"?"local":"remote"} branch (base not applied)`;var ps="create worktrees",dI=["already_open","orca_unreachable","orca_absent","orca_worktree_not_selectable","orca_error"],hd=()=>({orcaOpened:[],orcaSkipped:[],orcaHidden:[]}),da=async e=>{let{confirmedCommand:t,githubDesktop:r,orca:n}=e;await xe({operation:ps}),pI(e);try{let o=await P(),s=`${o}${le}`;await jv(`${s}/${Cr.release}`),await jv(`${s}/${Cr.feature}`);let i=await mI(e),a=i==="feature"?await gI(e):await fI(e);if(a===null){d.info("\u2139\uFE0F No open release branches found"),h.print();let D={kind:i,createdWorktrees:[],count:0,features:[],...hd()};return{content:k(JSON.stringify(D,null,2)),structuredContent:D}}let c=await W(),l=await hI(r,c),u=await yI(n,c),p=await Re(o),m=uI.basename(p),f=u?await vI({explicit:n!==void 0,mainRepoRoot:p}):null;await L(t,wI(f,m,a.previewLines)),t||h.addOption("--yes",!0);let y=f?await kI(f,p):null,b=await PI(a.targets,s);if(xI(b),l)for(let D of b)await ds`github ${s}/${D}`,await ds`sleep 5`;let w=y?await RI({registration:y,createdWorktrees:b,worktreeDir:s,mainRepoRoot:p,repoName:m,config:c}):hd();SI(w),h.print();let x={kind:i,createdWorktrees:b,count:b.length,features:a.features.filter(D=>b.includes(D.branch)),...w};return{content:k(JSON.stringify(x,null,2)),structuredContent:x}}catch(o){throw Se(o)||o instanceof C?o:(d.debug({err:o},"Error managing worktrees"),new g(o,{operation:ps,remediation:o instanceof g&&o.remediation||"verify branches don't already exist as worktrees: 'git worktree list'"}))}},pI=e=>{let t=e.all||e.versions!==void 0,r=e.feature!==void 0||e.base!==void 0;if(t&&r)throw new g(void 0,{operation:ps,remediation:"pass either --versions/--all (release worktrees) or --feature [--base] (feature worktrees)",stderrExcerpt:"--feature/--base cannot be combined with --versions/--all"})},mI=async e=>e.feature!==void 0||e.base!==void 0?"feature":e.all||e.versions!==void 0?"release":(h.setInteractive(),Ov()),fI=async e=>{let{all:t,versions:r}=e,n=await fe("release"),o=[];if(r)o=r.split(",").map(a=>ke(me(a.trim())));else{let a=await F(),c=a.map(l=>l.branch);if(c.length===0)return null;if(t)o=c;else{h.setInteractive();let l=new Map(a.map(p=>[p.branch,p.type])),u=await ae();o=await jt(ce({branches:c,descriptions:u,types:l}),{required:!0})}}t?h.addOption("--all",!0):h.addOption("--versions",vt(o));let{branchesToCreate:s}=EI({selectedReleaseBranches:o,currentWorktrees:n});return{targets:s.map(a=>({branch:a,add:c=>ds`git worktree add ${c} ${a}`})),features:[],previewLines:[]}},gI=async e=>{let r=e.feature?.split(",").filter(l=>l.trim()!=="")??[],n=e.base;if(r.length===0&&(h.setInteractive(),r=[await Iv()],n===void 0)){let l=(await F()).map(u=>u.branch);n=await Dv(l,await gd())}let o=await Av(n),s=await Nv({names:r,base:o});h.addOption("--feature",s.map(l=>l.branch.replace(/^feature\//,"")).join(",")),h.addOption("--base",o);let i=await fe("feature"),a=s.filter(l=>i.includes(l.branch)?(d.info(`\u2139\uFE0F ${l.branch} is already checked out in a worktree`),!1):!0);return{targets:a.map(l=>({branch:l.branch,add:u=>_v(l,u)})),features:a,previewLines:a.map(Mv)}},hI=async(e,t)=>{let r=t.worktrees?.openInGithubDesktop,n=e??r??await I(o=>Fv({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},yI=async(e,t)=>{let r=t.worktrees?.openInOrca,n=e??r??await I(o=>Fv({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},Lv=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"},vI=async e=>{let{explicit:t,mainRepoRoot:r}=e,n=await Ct();if(n!=="ready"){let{reason:s,text:i}=Lv(n);if(t)throw d.warn({operation:ps},`\u26D4 --orca was passed but ${i}`),new C({status:"refused",reason:s,agentMode:_.source},2,{operation:ps,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 d.warn(`\u26A0\uFE0F ${i} \u2014 worktrees will be created but not opened in Orca`),{probe:n,registered:!1,visibility:void 0}}let o=await _m(r);return{probe:n,registered:o.registered,visibility:o.visibility}},wI=(e,t,r)=>{let n=["Are you sure you want to proceed with these worktree changes?",...r];return e?.probe==="ready"&&!e.registered&&n.push(` \u2022 will register ${t} in Orca (orca repo add); its worktrees start hidden in Orca's sidebar until you choose Show`),n.join(`
408
+ `)},kI=async(e,t)=>{if(e.probe!=="ready")return{kind:"skip",reason:Lv(e.probe).reason};if(e.registered)return{kind:"ready",visibility:e.visibility};try{let{visibility:r}=await Mm(t);return{kind:"ready",visibility:r}}catch(r){return d.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 Ir?r.code:void 0}}},bI=e=>`Orca \u2192 ${e} \u2192 "hidden worktrees" card \u2192 Show, or Settings \u2192 General \u2192 Workspace \u2192 external-worktree sources`,RI=async e=>{let{registration:t,createdWorktrees:r,worktreeDir:n,mainRepoRoot:o,repoName:s,config:i}=e,a=hd();if(t.kind==="skip"){for(let p of r)a.orcaSkipped.push({branch:p,reason:t.reason,code:t.code});return a}let c=hm(i),l=r.length===1&&t.visibility!=="hide",u=Fm();for(let p of r){let m=`${n}/${p}`;try{let{layout:f}=await Lm({cwd:m,title:Bm({branch:p}),focus:l,layout:"full",panes:c,poll:u});await jm(o,m)?a.orcaOpened.push({branch:p,layout:f}):a.orcaHidden.push({branch:p,path:m,fix:bI(s)})}catch(f){d.warn({error:f,branch:p},`\u26A0\uFE0F Failed to open Orca terminals for ${p}`),f instanceof Ir&&f.code==="orca_worktree_not_selectable"?a.orcaSkipped.push({branch:p,reason:"orca_worktree_not_selectable"}):a.orcaSkipped.push({branch:p,reason:"orca_error",code:f instanceof Ir?f.code:void 0})}}return a},SI=e=>{for(let t of e.orcaOpened)d.info(`\u{1FA9F} Opened ${t.branch} in Orca (${t.layout})`);for(let t of e.orcaHidden)d.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})`:"";d.info(`\u21A9\uFE0F ${t.branch} not opened in Orca: ${t.reason}${r}`)}},jv=async e=>{await ds`mkdir -p ${e}`},EI=e=>{let{selectedReleaseBranches:t,currentWorktrees:r}=e,n=r.filter(s=>$r(s));return{branchesToCreate:t.filter(s=>!n.includes(s))}},PI=async(e,t)=>{let r=await Promise.allSettled(e.map(async o=>{let s=`${t}/${o.branch}`;return await o.add(s),await ds({cwd:s})`pnpm install`,o.branch})),n=[];for(let[o,s]of r.entries())if(s.status==="fulfilled")n.push(s.value);else{let i=e[o]?.branch,a=new g(s.reason,{operation:`git worktree add for ${i}`,remediation:"check the branch name and that the parent dir is writable"});d.error({error:s.reason,msg:a.message})}return n},xI=e=>{if(e.length>0){d.info("\u2705 Created git worktrees:");for(let t of e)d.info(t);d.info("")}else d.info("\u2139\uFE0F No new git worktrees to create")},yd=E({name:"worktrees-add",description:`Create local git worktrees under the worktrees directory and run "pnpm install" in each: release worktrees for open release branches ("versions" / all=true), or feature worktrees ("feature", optional "base") \u2014 each name becomes a feature/<name> branch at <root>-worktrees/feature/<name>, cut from origin/<base> (default dev, or the default branch of a repo without dev; main; or any release branch) with no upstream, or checked out as-is when the branch already exists locally or on origin. Mutates the local filesystem. When invoked via MCP, pass "versions" (comma-separated), all=true, or "feature" \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:{feature:M.string().optional().describe('Comma-separated feature names (e.g. "checkout-v2" or "feature/checkout-v2"); each becomes a feature/<name> worktree. Cannot be combined with "versions" or "all".'),base:M.string().optional().describe(`Base for NEW feature branches: "dev" (default; the repo's default branch when it has no dev), "main", or a release ref ("1.4.0", "release/v1.4.0", "release/<name>"). Not applied to a feature branch that already exists. Implies a feature run.`),all:M.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:M.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.'),githubDesktop:M.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:M.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:{kind:M.enum(["release","feature"]).describe("Which kind of worktree the run created"),features:M.array(M.object({branch:M.string(),base:M.string(),source:M.enum(Cv)})).describe('Created feature worktrees: source "new" = cut from origin/<base>; "local" / "remote" = an existing branch checked out as-is (base not applied)'),createdWorktrees:M.array(M.string()).describe("List of created git worktree branches"),count:M.number().describe("Number of git worktrees created"),orcaOpened:M.array(M.object({branch:M.string(),layout:M.enum(["full","single-pane"])})).describe("Created worktrees that got an Orca terminal tab on a row the sidebar shows, with the layout applied"),orcaSkipped:M.array(M.object({branch:M.string(),reason:M.enum(dI),code:M.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:M.array(M.object({branch:M.string(),path:M.string(),fix:M.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:da});import{z as Kt}from"zod";var pa=async()=>{await W();let[e,t]=await Promise.all([fe("release"),fe("feature")]);if(e.length===0&&t.length===0){d.info("\u2139\uFE0F No active worktrees found");let s={worktrees:[],count:0,features:[]};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}}let r=e.length>0?await TI(e):[],n=[];r.length>0&&n.push(`\u{1F33F} Active worktrees:
409
409
 
410
- ${xI(r).join(`
410
+ ${CI(r).join(`
411
411
  `)}`),t.length>0&&n.push(`\u{1F9EA} Feature worktrees:
412
412
 
413
413
  ${t.join(`
414
414
  `)}`),d.info(n.join(`
415
415
 
416
- `));let o={worktrees:r,count:r.length,features:t};return{content:k(JSON.stringify(o,null,2)),structuredContent:o}},PI=async e=>{let[t,r]=await Promise.all([F(),ae()]),n=new Map(t.map(o=>[o.branch,o.type]));return e.flatMap(o=>{let s=q(o);if(!s)return[];let i=X(s),a=n.get(o)||"regular",c=r.get(ne(s))||null;return[{version:i,type:a,description:c}]})},xI=e=>{let t=Math.max(...e.map(r=>r.version.length));return e.map(r=>{let n=vo(r.version,r.type,t);return r.description?`${n} ${r.description}`:n})},vd=E({name:"worktrees-list",description:"List existing release-branch worktrees with version, release type (regular / hotfix), and Jira fix-version description, plus feature worktrees (feature/* branches). Read-only.",inputSchema:{},outputSchema:{worktrees:Kt.array(Kt.object({version:Kt.string().describe("Release version"),type:Kt.enum(["regular","hotfix"]).describe("Release type"),description:Kt.string().nullable().describe("Jira version description")})).describe("Release worktrees with details"),count:Kt.number().describe("Number of release worktrees"),features:Kt.array(Kt.string()).describe("Branches of feature worktrees (feature/<name>)")},handler:pa});import{z as We}from"zod";import TI from"node:fs/promises";import{$ as CI}from"zx";var Bv="remove this worktree",$I=2,AI=3,ma=async e=>{try{return await TI.realpath(e)}catch{return e}},Sr=(e,t)=>{throw new g(void 0,{operation:Bv,remediation:e,stderrExcerpt:t})},OI=e=>{if(e.startsWith("feature/"))return["--feature",e.slice(8)];let[t]=vt([e]);return $r(e)&&t?["--versions",t]:Sr("only feature/* and release worktrees created by `infra-kit worktrees add` can be removed with --self",`branch ${e} is neither a feature nor a release branch`)},II=async()=>{let e=await ma(await P()),t=await ma(await Re(e));e===t&&Sr("run --self from inside the worktree to remove, or name it with --feature / --versions","this is the main checkout, not a linked worktree");let r=null;for(let o of await qe(t))await ma(o.path)===e&&(r=o.branch);if(!r)return Sr("check out a branch in this worktree first",`no branch is checked out at ${e}`);let n=await ma(`${t}${le}/${r}`);return n!==e&&Sr("remove it with `git worktree remove` from the main checkout",`${e} is not an infra-kit worktree (expected ${n})`),{worktreePath:e,mainRoot:t,branch:r,targetArgs:OI(r)}},Lv=async e=>(await CI({quiet:!0})`git -C ${e} status --porcelain`).stdout.split(`
417
- `).filter(r=>r.trim().length>0),DI=async e=>{let[t,r]=await Promise.all([Lv(e.worktreePath),Lv(e.mainRoot)]);t.length>0&&Sr("commit or stash your changes (`git stash -u`), then retry",`uncommitted changes: ${t.join(", ")}`),r.length>0&&Sr(`commit or stash the changes in the main checkout ${e.mainRoot}, then retry`,`the main checkout has uncommitted changes: ${r.join(", ")}`);let n=await Ct();n!=="ready"&&Sr(`run \`infra-kit worktrees remove ${Ie(e.targetArgs)}\` from the main checkout ${e.mainRoot}`,`--self hands the removal to an Orca terminal, and Orca is ${n}`)},NI=async e=>{let t=Ie(["infra-kit","worktrees","remove",...e.targetArgs,"--yes"]),r=`sleep ${$I}; ${t} && { sleep ${AI}; exit; }`;try{return(await Om(["terminal","create","--worktree",`path:${e.mainRoot}`,"--title",`ik: remove ${e.branch}`,"--command",r])).terminal.handle}catch(n){throw n instanceof Ir?new g(n,{operation:Bv,remediation:`run \`infra-kit worktrees remove ${Ie(e.targetArgs)}\` from the main checkout ${e.mainRoot}`,stderrExcerpt:n.message}):n}},Uv=async e=>{let t=await II();await DI(t),h.addOption("--self",!0),await L(e,`Remove ${t.branch} at ${t.worktreePath} and close every Orca tab in it (this terminal included)?`),e||h.addOption("--yes",!0);let r=await NI(t);d.info(`\u27A1\uFE0F Removal of ${t.branch} handed off to Orca (main checkout tab "ik: remove ${t.branch}")`),h.print();let n={branch:t.branch,worktreePath:t.worktreePath,terminal:r};return{content:k(JSON.stringify({status:"handed_off",...n},null,2)),structuredContent:{removedWorktrees:[],failedWorktrees:[],count:0,handedOff:n}}};var _I=e=>{if(ve()){if(e.all)throw new C({status:"refused",agentMode:_.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&&!e.feature)throw new C({status:"argument_required",argument:"versions",agentMode:_.source},2,{operation:"remove worktrees",remediation:"pass --versions <refs> (comma-separated release versions/names) or --feature <names> on the re-run \u2014 `infra-kit worktrees list --json` lists them",stderrExcerpt:"worktrees remove under agent mode requires --versions or --feature"})}},MI=(e,t)=>{let r=e.filter(n=>!t.includes(n));if(r.length>0)throw new g(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(", ")}`})},jI=async(e,t)=>{let r=await js(t.map(n=>`${e}/${n}`));if(r!==null)throw new C({status:"refused",reason:"orca_caller_inside_target",agentMode:_.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`})},FI=e=>e?e.split(",").map(t=>we(me(t.trim()))):[],LI=e=>e?e.split(",").filter(t=>t.trim()!=="").map(ua):[],BI=e=>{let t=e.filter(n=>n.startsWith("feature/")),r=e.filter(n=>!t.includes(n));r.length>0&&h.addOption("--versions",vt(r)),t.length>0&&h.addOption("--feature",t.map(n=>n.replace(/^feature\//,"")).join(","))},fa=async e=>{let{confirmedCommand:t,all:r,versions:n,feature:o,self:s}=e;if(s){if(r||n||o)throw new g(void 0,{operation:"remove worktrees",remediation:"pass --self alone, or name targets with --versions / --feature",stderrExcerpt:"--self cannot be combined with --all, --versions or --feature"});return Uv(t)}await xe({operation:"remove worktrees"}),await W(),_I({all:r,versions:n,feature:o});try{let[i,a]=await Promise.all([fe("release"),fe("feature")]),c=[...i,...a];if(c.length===0){d.info("\u2139\uFE0F No active worktrees to remove"),h.print();let y={removedWorktrees:[],failedWorktrees:[],count:0};return{content:k(JSON.stringify(y,null,2)),structuredContent:y}}let l=await P(),u=`${l}${le}`,p=[];if(r)p=c;else if(n||o)p=[...FI(n),...LI(o)];else{h.setInteractive();let[y,b]=await Promise.all([ae(),F()]),w=new Map(b.map(x=>[x.branch,x.type]));p=await jt([...ce({branches:i,descriptions:y,types:w}),...a.map(x=>({value:x,label:x,type:"feature"}))],{required:!0})}MI(p,c);let m=p.length===c.length;m?h.addOption("--all",!0):BI(p),await jI(u,p),await L(t,"Are you sure you want to proceed with these worktree changes?"),t||h.addOption("--yes",!0);let f=await vr({branches:p,worktreeDir:u,projectRoot:l,pruneFolder:m});return Go(f),h.print(),Jo({result:f,operation:"remove worktrees"})}catch(i){throw Se(i)||i instanceof g?i:(d.error({error:i},"\u274C Error managing worktrees"),new g(i,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"}))}},wd=E({name:"worktrees-remove",description:'Remove local git worktrees for the named release branches ("versions") and/or feature branches ("feature"). Over MCP you MUST pass "versions" or "feature" (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 target must be an active worktree, or the call errors without removing anything. What survives: the release and feature 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:We.string().optional().describe('Comma-separated release versions or names to remove (e.g. "1.2.5, 1.2.6" or "checkout-redesign, 1.2.5"). This or "feature" is required: each must name an active worktree, or the call errors before removing anything.'),feature:We.string().optional().describe('Comma-separated feature names to remove (e.g. "checkout-v2" or "feature/checkout-v2"). This or "versions" is required; each must name an active feature worktree.'),confirm:We.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{removedWorktrees:We.array(We.string()).describe("List of removed git worktree branches"),failedWorktrees:We.array(We.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:We.number().describe("Number of git worktrees removed"),handedOff:We.object({branch:We.string(),worktreePath:We.string(),terminal:We.string()}).optional().describe("--self only: the worktree whose removal now runs in an Orca tab of the main checkout")},handler:fa});import{z as ps}from"zod";var ga=async e=>{let{confirmedCommand:t}=e;await xe({operation:"sync worktrees"}),await W();try{let r=await fe("release"),n=await P(),o=`${n}${le}`,s=await ri();await L(t,"Are you sure you want to proceed with these worktree changes?"),t||h.addOption("--yes",!0);let{branchesToRemove:i}=UI({releasePRsList:s,currentWorktrees:r}),a=await vr({branches:i,worktreeDir:o,projectRoot:n});return Go(a),h.print(),Jo({result:a,operation:"sync worktrees"})}catch(r){throw Se(r)||r instanceof g?r:(d.error({error:r},"\u274C Error managing worktrees"),new g(r,{operation:"sync worktrees with remote",remediation:"ensure 'gh auth status' is ok and you can reach origin"}))}},UI=e=>{let{releasePRsList:t,currentWorktrees:r}=e;return{branchesToRemove:r.filter(s=>$r(s)).filter(s=>!t.includes(s))}},kd=E({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:ps.array(ps.string()).describe("List of removed worktree branches"),failedWorktrees:ps.array(ps.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:ps.number().describe("Number of worktrees removed during sync")},handler:ga});var bd=[{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"}],mr=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["dev"],longRunning:!0},{cliName:"dev-status",menuGroup:"develop",mcpTool:Jc,mcpExposed:!0,mutating:!1,groupPath:["dev-status"]},{cliName:"e2e",menuGroup:"develop",mcpTool:iu,mcpExposed:!1,mutating:!0,groupPath:["e2e"]},{cliName:"merge-dev",menuGroup:"release",mcpTool:mu,mcpExposed:!0,mutating:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:Au,mcpExposed:!0,mutating:!1,groupPath:["release","list"]},{cliName:"release-create",menuGroup:"release",mcpTool:Gu,mcpExposed:!0,mutating:!0,groupPath:["release","create"]},{cliName:"release-edit",menuGroup:"release",mcpTool:Ku,mcpExposed:!0,mutating:!0,groupPath:["release","edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:Tu,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:$u,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:hu,mcpExposed:!1,mutating:!0,humanOnly:!0,groupPath:["release","deliver"]},{cliName:"release-remove",menuGroup:"release",mcpTool:Yu,mcpExposed:!0,mutating:!0,groupPath:["release","remove"]},{cliName:"local-deploy-all",menuGroup:null,mcpTool:Lu,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-all"]},{cliName:"local-deploy-selected",menuGroup:null,mcpTool:Bu,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-selected"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:yd,mcpExposed:!0,mutating:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:vd,mcpExposed:!0,mutating:!1,groupPath:["worktrees","list"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:wd,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:lu,mcpExposed:!0,mutating:!1,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:Gm,mcpExposed:!0,mutating:!1,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:ec,mcpExposed:!0,mutating:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:cu,mcpExposed:!0,mutating:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:uu,mcpExposed:!0,mutating:!1,groupPath:["env-token-list"]},{cliName:"config-get",menuGroup:"configuration",mcpTool:Wc,mcpExposed:!0,mutating:!1,groupPath:["config-get"]},{cliName:"config-set",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["config-set"]},{cliName:"config-unset",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["config-unset"]},{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:pd,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,groupPath:["vendor","sync"]},{cliName:"deploy-sync",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["deploy-sync"]},{cliName:"setup",menuGroup:"setup",mcpTool:nd,mcpExposed:!0,mutating:!0,groupPath:["setup"]},{cliName:"doctor",menuGroup:"setup",mcpTool:ql,mcpExposed:!0,mutating:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:Bc,mcpExposed:!0,mutating:!1,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:md,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:"environment",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 Rd=e=>mr.filter(t=>t.menuGroup===e),Sd=e=>mr.some(t=>t.longRunning===!0&&t.groupPath.join(" ")===e);var VI=(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},Vv=e=>bd.flatMap(({key:t,label:r})=>Rd(t).flatMap(n=>{let o=VI(e,n.groupPath);return o?[{name:n.groupPath.join(" "),description:o.description(),group:r}]:[]}));import Ed from"node:process";var WI="MODULE_TYPELESS_PACKAGE_JSON",GI=(e,t)=>typeof e=="object"&&e!==null?e.code:t,Wv=!1,Pd=()=>{if(Wv)return;Wv=!0;let e=Ed.emitWarning.bind(Ed);Ed.emitWarning=((t,...r)=>{GI(r[0],r[1])!==WI&&e(t,...r)})};import{Command as KN,InvalidArgumentError as HN,Option as Gw}from"commander";import{resolve as qN}from"node:path";import $e from"node:process";import{cd as YN}from"zx";import Gv from"node:process";import{$ as JI}from"zx";var xd=async()=>{let e=await Y(),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 Co(e.userProject,r),o=r?$o(n):"";d.info(`Project name: ${e.projectName}
416
+ `));let o={worktrees:r,count:r.length,features:t};return{content:k(JSON.stringify(o,null,2)),structuredContent:o}},TI=async e=>{let[t,r]=await Promise.all([F(),ae()]),n=new Map(t.map(o=>[o.branch,o.type]));return e.flatMap(o=>{let s=q(o);if(!s)return[];let i=X(s),a=n.get(o)||"regular",c=r.get(ne(s))||null;return[{version:i,type:a,description:c}]})},CI=e=>{let t=Math.max(...e.map(r=>r.version.length));return e.map(r=>{let n=wo(r.version,r.type,t);return r.description?`${n} ${r.description}`:n})},vd=E({name:"worktrees-list",description:"List existing release-branch worktrees with version, release type (regular / hotfix), and Jira fix-version description, plus feature worktrees (feature/* branches). Read-only.",inputSchema:{},outputSchema:{worktrees:Kt.array(Kt.object({version:Kt.string().describe("Release version"),type:Kt.enum(["regular","hotfix"]).describe("Release type"),description:Kt.string().nullable().describe("Jira version description")})).describe("Release worktrees with details"),count:Kt.number().describe("Number of release worktrees"),features:Kt.array(Kt.string()).describe("Branches of feature worktrees (feature/<name>)")},handler:pa});import{z as We}from"zod";import $I from"node:fs/promises";import{$ as AI}from"zx";var Uv="remove this worktree",OI=2,II=3,ma=async e=>{try{return await $I.realpath(e)}catch{return e}},Sr=(e,t)=>{throw new g(void 0,{operation:Uv,remediation:e,stderrExcerpt:t})},DI=e=>{if(e.startsWith("feature/"))return["--feature",e.slice(8)];let[t]=vt([e]);return $r(e)&&t?["--versions",t]:Sr("only feature/* and release worktrees created by `infra-kit worktrees add` can be removed with --self",`branch ${e} is neither a feature nor a release branch`)},NI=async()=>{let e=await ma(await P()),t=await ma(await Re(e));e===t&&Sr("run --self from inside the worktree to remove, or name it with --feature / --versions","this is the main checkout, not a linked worktree");let r=null;for(let o of await Ye(t))await ma(o.path)===e&&(r=o.branch);if(!r)return Sr("check out a branch in this worktree first",`no branch is checked out at ${e}`);let n=await ma(`${t}${le}/${r}`);return n!==e&&Sr("remove it with `git worktree remove` from the main checkout",`${e} is not an infra-kit worktree (expected ${n})`),{worktreePath:e,mainRoot:t,branch:r,targetArgs:DI(r)}},Bv=async e=>(await AI({quiet:!0})`git -C ${e} status --porcelain`).stdout.split(`
417
+ `).filter(r=>r.trim().length>0),_I=async e=>{let[t,r]=await Promise.all([Bv(e.worktreePath),Bv(e.mainRoot)]);t.length>0&&Sr("commit or stash your changes (`git stash -u`), then retry",`uncommitted changes: ${t.join(", ")}`),r.length>0&&Sr(`commit or stash the changes in the main checkout ${e.mainRoot}, then retry`,`the main checkout has uncommitted changes: ${r.join(", ")}`);let n=await Ct();n!=="ready"&&Sr(`run \`infra-kit worktrees remove ${Ie(e.targetArgs)}\` from the main checkout ${e.mainRoot}`,`--self hands the removal to an Orca terminal, and Orca is ${n}`)},MI=async e=>{let t=Ie(["infra-kit","worktrees","remove",...e.targetArgs,"--yes"]),r=`sleep ${OI}; ${t} && { sleep ${II}; exit; }`;try{return(await Im(["terminal","create","--worktree",`path:${e.mainRoot}`,"--title",`ik: remove ${e.branch}`,"--command",r])).terminal.handle}catch(n){throw n instanceof Ir?new g(n,{operation:Uv,remediation:`run \`infra-kit worktrees remove ${Ie(e.targetArgs)}\` from the main checkout ${e.mainRoot}`,stderrExcerpt:n.message}):n}},Vv=async e=>{let t=await NI();await _I(t),h.addOption("--self",!0),await L(e,`Remove ${t.branch} at ${t.worktreePath} and close every Orca tab in it (this terminal included)?`),e||h.addOption("--yes",!0);let r=await MI(t);d.info(`\u27A1\uFE0F Removal of ${t.branch} handed off to Orca (main checkout tab "ik: remove ${t.branch}")`),h.print();let n={branch:t.branch,worktreePath:t.worktreePath,terminal:r};return{content:k(JSON.stringify({status:"handed_off",...n},null,2)),structuredContent:{removedWorktrees:[],failedWorktrees:[],count:0,handedOff:n}}};var jI=e=>{if(we()){if(e.all)throw new C({status:"refused",agentMode:_.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&&!e.feature)throw new C({status:"argument_required",argument:"versions",agentMode:_.source},2,{operation:"remove worktrees",remediation:"pass --versions <refs> (comma-separated release versions/names) or --feature <names> on the re-run \u2014 `infra-kit worktrees list --json` lists them",stderrExcerpt:"worktrees remove under agent mode requires --versions or --feature"})}},FI=(e,t)=>{let r=e.filter(n=>!t.includes(n));if(r.length>0)throw new g(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(", ")}`})},LI=async(e,t)=>{let r=await js(t.map(n=>`${e}/${n}`));if(r!==null)throw new C({status:"refused",reason:"orca_caller_inside_target",agentMode:_.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`})},BI=e=>e?e.split(",").map(t=>ke(me(t.trim()))):[],UI=e=>e?e.split(",").filter(t=>t.trim()!=="").map(ua):[],VI=e=>{let t=e.filter(n=>n.startsWith("feature/")),r=e.filter(n=>!t.includes(n));r.length>0&&h.addOption("--versions",vt(r)),t.length>0&&h.addOption("--feature",t.map(n=>n.replace(/^feature\//,"")).join(","))},fa=async e=>{let{confirmedCommand:t,all:r,versions:n,feature:o,self:s}=e;if(s){if(r||n||o)throw new g(void 0,{operation:"remove worktrees",remediation:"pass --self alone, or name targets with --versions / --feature",stderrExcerpt:"--self cannot be combined with --all, --versions or --feature"});return Vv(t)}await xe({operation:"remove worktrees"}),await W(),jI({all:r,versions:n,feature:o});try{let[i,a]=await Promise.all([fe("release"),fe("feature")]),c=[...i,...a];if(c.length===0){d.info("\u2139\uFE0F No active worktrees to remove"),h.print();let y={removedWorktrees:[],failedWorktrees:[],count:0};return{content:k(JSON.stringify(y,null,2)),structuredContent:y}}let l=await P(),u=`${l}${le}`,p=[];if(r)p=c;else if(n||o)p=[...BI(n),...UI(o)];else{h.setInteractive();let[y,b]=await Promise.all([ae(),F()]),w=new Map(b.map(x=>[x.branch,x.type]));p=await jt([...ce({branches:i,descriptions:y,types:w}),...a.map(x=>({value:x,label:x,type:"feature"}))],{required:!0})}FI(p,c);let m=p.length===c.length;m?h.addOption("--all",!0):VI(p),await LI(u,p),await L(t,"Are you sure you want to proceed with these worktree changes?"),t||h.addOption("--yes",!0);let f=await vr({branches:p,worktreeDir:u,projectRoot:l,pruneFolder:m});return Jo(f),h.print(),Ko({result:f,operation:"remove worktrees"})}catch(i){throw Se(i)||i instanceof g?i:(d.error({error:i},"\u274C Error managing worktrees"),new g(i,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"}))}},wd=E({name:"worktrees-remove",description:'Remove local git worktrees for the named release branches ("versions") and/or feature branches ("feature"). Over MCP you MUST pass "versions" or "feature" (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 target must be an active worktree, or the call errors without removing anything. What survives: the release and feature 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:We.string().optional().describe('Comma-separated release versions or names to remove (e.g. "1.2.5, 1.2.6" or "checkout-redesign, 1.2.5"). This or "feature" is required: each must name an active worktree, or the call errors before removing anything.'),feature:We.string().optional().describe('Comma-separated feature names to remove (e.g. "checkout-v2" or "feature/checkout-v2"). This or "versions" is required; each must name an active feature worktree.'),confirm:We.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{removedWorktrees:We.array(We.string()).describe("List of removed git worktree branches"),failedWorktrees:We.array(We.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:We.number().describe("Number of git worktrees removed"),handedOff:We.object({branch:We.string(),worktreePath:We.string(),terminal:We.string()}).optional().describe("--self only: the worktree whose removal now runs in an Orca tab of the main checkout")},handler:fa});import{z as ms}from"zod";var ga=async e=>{let{confirmedCommand:t}=e;await xe({operation:"sync worktrees"}),await W();try{let r=await fe("release"),n=await P(),o=`${n}${le}`,s=await ri();await L(t,"Are you sure you want to proceed with these worktree changes?"),t||h.addOption("--yes",!0);let{branchesToRemove:i}=WI({releasePRsList:s,currentWorktrees:r}),a=await vr({branches:i,worktreeDir:o,projectRoot:n});return Jo(a),h.print(),Ko({result:a,operation:"sync worktrees"})}catch(r){throw Se(r)||r instanceof g?r:(d.error({error:r},"\u274C Error managing worktrees"),new g(r,{operation:"sync worktrees with remote",remediation:"ensure 'gh auth status' is ok and you can reach origin"}))}},WI=e=>{let{releasePRsList:t,currentWorktrees:r}=e;return{branchesToRemove:r.filter(s=>$r(s)).filter(s=>!t.includes(s))}},kd=E({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:ms.array(ms.string()).describe("List of removed worktree branches"),failedWorktrees:ms.array(ms.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:ms.number().describe("Number of worktrees removed during sync")},handler:ga});var bd=[{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"}],mr=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["dev"],longRunning:!0},{cliName:"dev-status",menuGroup:"develop",mcpTool:Jc,mcpExposed:!0,mutating:!1,groupPath:["dev-status"]},{cliName:"e2e",menuGroup:"develop",mcpTool:iu,mcpExposed:!1,mutating:!0,groupPath:["e2e"]},{cliName:"merge-dev",menuGroup:"release",mcpTool:mu,mcpExposed:!0,mutating:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:Au,mcpExposed:!0,mutating:!1,groupPath:["release","list"]},{cliName:"release-create",menuGroup:"release",mcpTool:Gu,mcpExposed:!0,mutating:!0,groupPath:["release","create"]},{cliName:"release-edit",menuGroup:"release",mcpTool:Ku,mcpExposed:!0,mutating:!0,groupPath:["release","edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:Tu,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:$u,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:hu,mcpExposed:!1,mutating:!0,humanOnly:!0,groupPath:["release","deliver"]},{cliName:"release-remove",menuGroup:"release",mcpTool:Yu,mcpExposed:!0,mutating:!0,groupPath:["release","remove"]},{cliName:"local-deploy-all",menuGroup:null,mcpTool:Lu,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-all"]},{cliName:"local-deploy-selected",menuGroup:null,mcpTool:Bu,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-selected"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:yd,mcpExposed:!0,mutating:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:vd,mcpExposed:!0,mutating:!1,groupPath:["worktrees","list"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:wd,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:lu,mcpExposed:!0,mutating:!1,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:Jm,mcpExposed:!0,mutating:!1,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:ec,mcpExposed:!0,mutating:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:cu,mcpExposed:!0,mutating:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:uu,mcpExposed:!0,mutating:!1,groupPath:["env-token-list"]},{cliName:"config-get",menuGroup:"configuration",mcpTool:Wc,mcpExposed:!0,mutating:!1,groupPath:["config-get"]},{cliName:"config-set",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["config-set"]},{cliName:"config-unset",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["config-unset"]},{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:pd,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,groupPath:["vendor","sync"]},{cliName:"deploy-sync",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["deploy-sync"]},{cliName:"setup",menuGroup:"setup",mcpTool:nd,mcpExposed:!0,mutating:!0,groupPath:["setup"]},{cliName:"doctor",menuGroup:"setup",mcpTool:ql,mcpExposed:!0,mutating:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:Bc,mcpExposed:!0,mutating:!1,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:md,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:"environment",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 Rd=e=>mr.filter(t=>t.menuGroup===e),Sd=e=>mr.some(t=>t.longRunning===!0&&t.groupPath.join(" ")===e);var GI=(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},Wv=e=>bd.flatMap(({key:t,label:r})=>Rd(t).flatMap(n=>{let o=GI(e,n.groupPath);return o?[{name:n.groupPath.join(" "),description:o.description(),group:r}]:[]}));import Ed from"node:process";var JI="MODULE_TYPELESS_PACKAGE_JSON",KI=(e,t)=>typeof e=="object"&&e!==null?e.code:t,Gv=!1,Pd=()=>{if(Gv)return;Gv=!0;let e=Ed.emitWarning.bind(Ed);Ed.emitWarning=((t,...r)=>{KI(r[0],r[1])!==JI&&e(t,...r)})};import{Command as XN,InvalidArgumentError as ZN,Option as Kw}from"commander";import{resolve as QN}from"node:path";import $e from"node:process";import{cd as e_}from"zx";import Jv from"node:process";import{$ as HI}from"zx";var xd=async()=>{let e=await Y(),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 $o(e.userProject,r),o=r?Ao(n):"";d.info(`Project name: ${e.projectName}
418
418
  `),d.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}`:"";d.info(`${a} ${i.label.padEnd(22)} ${v(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}},Td=async()=>{let e=await Y(),t=Gv.env.EDITOR||Gv.env.VISUAL||"vi",r=await on(e);r.createdConfig&&d.info(sn(r)),d.info(`Opening ${v(e.userProject)} in ${t} (per-machine override \u2014 every key except "mcp")`),await JI({stdio:"inherit"})`${t} ${e.userProject}`,Pt();let n={path:e.userProject,editor:t};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}};var Cd=async({key:e,global:t})=>{Zs(e,"config-unset");let r=t?"global":"project",{file:n,previous:o,changed:s}=await Qs(r,e,a=>e in a?Object.fromEntries(Object.entries(a).filter(([c])=>c!==e)):null);d.info(s?`Removed ${e} from the ${so[r]} (${v(n)})`:`${e} is not set in the ${so[r]} (${v(n)}) \u2014 nothing to remove`);let i={key:e,removed:s,previous:o??null,scope:r,path:n};return{content:k(JSON.stringify(i,null,2)),structuredContent:i}};import{DEPLOY_CONFIG_FILE as jd}from"@slip-stream-kit/config/internal";import Fd from"node:fs/promises";import Xv from"node:path";import{DEPLOY_CONFIG_FILE as $d,deployConfigSchema as KI}from"@slip-stream-kit/config/internal";import HI from"node:fs/promises";import qI from"node:path";import{pathToFileURL as YI}from"node:url";import{z as zI}from"zod";var Ad=async e=>{let t=qI.join(e,$d);try{await HI.access(t)}catch{return}let r=await import(YI(t).href);if(r.default===void 0)throw new Error(`${$d} at ${t} has no default export`);let n=KI.safeParse(r.default);if(!n.success)throw new Error(`Invalid ${$d} at ${t}:
420
- ${zI.prettifyError(n.error)}`);return n.data};var Hv="ArthurSaenz/infra-kit/.github/workflows/ik-deploy-service.yml@3f50266774b5dac9b7f8fe18f2dd652b692f33df";var Dd="skip_terraform_deploy",Id={all:{file:"deploy-all-v2.yml",title:"91 \u{1F9EA} Deploy all (v2)",concurrency:"deploy-all",v1File:"deploy-all.yml"},selected:{file:"deploy-selected-v2.yml",title:"92 \u{1F9EA} Deploy selected (v2)",concurrency:"deploy-selected",v1File:"deploy-selected-services.yml"}},ha=e=>e.replace(/^_/,"").replace(/(?:-jobs)?\.ya?ml$/,""),XI=(e,t)=>Object.entries(e.services).flatMap(([r,n])=>{if(t==="all"&&n.deployAll===!1)return[];let o=e.environments.filter(s=>(n.envs?.includes(s)??!0)&&!(n.skipEnvs?.includes(s)??!1));return o.length===0?[]:[{name:r,service:n,gate:o.length===e.environments.length?void 0:o}]}),pe=e=>`\${{ ${e} }}`,Od=e=>pe(`secrets[format('{0}_${e}', inputs.environment)]`),qv=e=>[...e.terraform,...e.preDeploy],Yv=e=>e.map(t=>`(needs.${t}.result == 'success' || needs.${t}.result == 'skipped')`),ZI=e=>[...Yv(e.terraform),...e.preDeploy.map(t=>`needs.${t}.result == 'success'`)],QI=(e,t,r)=>{let n=[];return t==="selected"&&n.push(`inputs.${e.name}`),e.gate!==void 0&&n.push(`contains(fromJSON('${JSON.stringify(e.gate)}'), inputs.environment)`),qv(r).length>0&&n.push("!cancelled()",...ZI(r)),n.length===0?void 0:pe(n.join(" && "))},Nd=e=>e.length===0?[]:[` needs: [ ${e.join(", ")} ]`],zv=e=>e===void 0?[]:[` if: ${e}`],_d=e=>[` uses: ./.github/workflows/${e}`," with:",` branch: ${pe("github.ref")}`,` environment: ${pe("inputs.environment")}`," secrets: inherit"],eD=(e,t)=>{let r=e.service.runner===void 0?[]:[` runner: ${e.service.runner}`],n=t.length===0?[]:[" extra-env: |",...t.map(o=>{let s=pe(`secrets.${o}`);return` ${o}=${s}`})];return[` uses: ${Hv}`," with:",` environment: ${pe("inputs.environment")}`,` ref: ${pe("github.ref")}`,` service: ${e.name}`,...r," secrets:",` aws-access-key-id: ${Od("AWS_ACCESS_KEY_ID")}`,` aws-secret-access-key: ${Od("AWS_SECRET_ACCESS_KEY")}`,` aws-region: ${Od("AWS_REGION")}`,` serverless-access-key: ${pe("secrets.SERVERLESS_ACCESS_KEY")}`,` slack-token: ${pe("secrets.SLACK_TOKEN")}`,` slack-channel: ${pe("secrets.SLACK_CHANNEL")}`,...n]},tD=(e,t,r,n)=>{let o=e.service.workflow===void 0?eD(e,n):_d(e.service.workflow);return["",` deploy-${e.name}:`,...Nd(qv(r)),...zv(QI(e,t,r)),...o]},Jv=(e,t)=>["",` ${e}:`," type: boolean",` description: '${t}'`," required: false"," default: false"],rD=(e,t,r)=>{let n=[" environment:"," type: choice"," description: 'Environment for deploy'"," required: true",` default: '${e.defaultEnvironment??e.environments[0]}'`," options:",...e.environments.map(i=>` - ${i}`)],o=(e.terraform??[]).length>0?Jv(Dd,"Skip terraform deployment"):[],s=t==="all"?[]:r.flatMap(i=>{let a=i.gate===void 0?"":` (${i.gate.join(", ")} only)`;return Jv(i.name,`Deploy ${i.name}${a}`)});return["on:"," workflow_dispatch:"," inputs:",...n,...o,...s]},nD=(e,t)=>{let{title:r,concurrency:n,v1File:o}=Id[t],s=(e.terraform??[]).length>0?pe(`inputs.${Dd} && '' \u2014 skip TF'' || ''''`):"";return["# Generated by `infra-kit deploy-sync` from infra-kit.deploy.ts: edit that file and re-run the command,","# a hand edit here is overwritten.",`name: '${r}'`,`run-name: '${r} [${pe("inputs.environment")}]${s}'`,"",`# Same group as ${o}, so a v1 run and a v2 run never deploy into one environment at once.`,"concurrency:",` group: ${n}-${pe("inputs.environment")}`," # false: a cancelled run would also kill an in-flight terraform apply."," cancel-in-progress: false",""]},oD=e=>{let t=pe(`!inputs.${Dd}`);return["",` ${ha(e)}:`,` if: ${t}`,..._d(e)]},sD=(e,t)=>{let r=t.length===0?void 0:pe(["!cancelled()",...Yv(t)].join(" && "));return["",` ${ha(e)}:`,...Nd(t),...zv(r),..._d(e)]},iD=(e,t)=>[""," notify-success:",...Nd(t),` if: ${pe("!cancelled() && contains(needs.*.result, 'success') && !contains(needs.*.result, 'failure')")}`,` uses: ./.github/workflows/${e}`," secrets: inherit"],Kv=(e,t)=>{let r=XI(e,t),n=e.terraform??[],o=e.preDeploy??[],s={terraform:n.map(ha),preDeploy:o.map(ha)},i=1+(n.length>0?1:0)+(t==="selected"?r.length:0);if(i>25)throw new Error(`${Id[t].file} would need ${i} dispatch inputs; GitHub allows 25. Mark services \`deployAll: false\` or split them.`);let a=r.map(u=>`deploy-${u.name}`),l=`${[...nD(e,t),...rD(e,t,r),"","permissions:"," contents: read","","jobs:",...n.flatMap(oD),...o.flatMap(u=>sD(u,s.terraform)),...r.flatMap(u=>tD(u,t,s,e.extraEnv??[])),...e.notifySuccess===void 0?[]:iD(e.notifySuccess,a)].join(`
419
+ `);for(let i of t){let a=i.exists?" [\u2713]":" [ ]",c=i.path===e.userProject&&o!==""?` ${o}`:"";d.info(`${a} ${i.label.padEnd(22)} ${v(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}},Td=async()=>{let e=await Y(),t=Jv.env.EDITOR||Jv.env.VISUAL||"vi",r=await on(e);r.createdConfig&&d.info(sn(r)),d.info(`Opening ${v(e.userProject)} in ${t} (per-machine override \u2014 every key except "mcp")`),await HI({stdio:"inherit"})`${t} ${e.userProject}`,Pt();let n={path:e.userProject,editor:t};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}};var Cd=async({key:e,global:t})=>{Zs(e,"config-unset");let r=t?"global":"project",{file:n,previous:o,changed:s}=await Qs(r,e,a=>e in a?Object.fromEntries(Object.entries(a).filter(([c])=>c!==e)):null);d.info(s?`Removed ${e} from the ${io[r]} (${v(n)})`:`${e} is not set in the ${io[r]} (${v(n)}) \u2014 nothing to remove`);let i={key:e,removed:s,previous:o??null,scope:r,path:n};return{content:k(JSON.stringify(i,null,2)),structuredContent:i}};import{DEPLOY_CONFIG_FILE as jd}from"@slip-stream-kit/config/internal";import Fd from"node:fs/promises";import Zv from"node:path";import{DEPLOY_CONFIG_FILE as $d,deployConfigSchema as qI}from"@slip-stream-kit/config/internal";import YI from"node:fs/promises";import zI from"node:path";import{pathToFileURL as XI}from"node:url";import{z as ZI}from"zod";var Ad=async e=>{let t=zI.join(e,$d);try{await YI.access(t)}catch{return}let r=await import(XI(t).href);if(r.default===void 0)throw new Error(`${$d} at ${t} has no default export`);let n=qI.safeParse(r.default);if(!n.success)throw new Error(`Invalid ${$d} at ${t}:
420
+ ${ZI.prettifyError(n.error)}`);return n.data};var qv="ArthurSaenz/infra-kit/.github/workflows/ik-deploy-service.yml@3f50266774b5dac9b7f8fe18f2dd652b692f33df";var Dd="skip_terraform_deploy",Id={all:{file:"deploy-all-v2.yml",title:"91 \u{1F9EA} Deploy all (v2)",concurrency:"deploy-all",v1File:"deploy-all.yml"},selected:{file:"deploy-selected-v2.yml",title:"92 \u{1F9EA} Deploy selected (v2)",concurrency:"deploy-selected",v1File:"deploy-selected-services.yml"}},ha=e=>e.replace(/^_/,"").replace(/(?:-jobs)?\.ya?ml$/,""),QI=(e,t)=>Object.entries(e.services).flatMap(([r,n])=>{if(t==="all"&&n.deployAll===!1)return[];let o=e.environments.filter(s=>(n.envs?.includes(s)??!0)&&!(n.skipEnvs?.includes(s)??!1));return o.length===0?[]:[{name:r,service:n,gate:o.length===e.environments.length?void 0:o}]}),pe=e=>`\${{ ${e} }}`,Od=e=>pe(`secrets[format('{0}_${e}', inputs.environment)]`),Yv=e=>[...e.terraform,...e.preDeploy],zv=e=>e.map(t=>`(needs.${t}.result == 'success' || needs.${t}.result == 'skipped')`),eD=e=>[...zv(e.terraform),...e.preDeploy.map(t=>`needs.${t}.result == 'success'`)],tD=(e,t,r)=>{let n=[];return t==="selected"&&n.push(`inputs.${e.name}`),e.gate!==void 0&&n.push(`contains(fromJSON('${JSON.stringify(e.gate)}'), inputs.environment)`),Yv(r).length>0&&n.push("!cancelled()",...eD(r)),n.length===0?void 0:pe(n.join(" && "))},Nd=e=>e.length===0?[]:[` needs: [ ${e.join(", ")} ]`],Xv=e=>e===void 0?[]:[` if: ${e}`],_d=e=>[` uses: ./.github/workflows/${e}`," with:",` branch: ${pe("github.ref")}`,` environment: ${pe("inputs.environment")}`," secrets: inherit"],rD=(e,t)=>{let r=e.service.runner===void 0?[]:[` runner: ${e.service.runner}`],n=t.length===0?[]:[" extra-env: |",...t.map(o=>{let s=pe(`secrets.${o}`);return` ${o}=${s}`})];return[` uses: ${qv}`," with:",` environment: ${pe("inputs.environment")}`,` ref: ${pe("github.ref")}`,` service: ${e.name}`,...r," secrets:",` aws-access-key-id: ${Od("AWS_ACCESS_KEY_ID")}`,` aws-secret-access-key: ${Od("AWS_SECRET_ACCESS_KEY")}`,` aws-region: ${Od("AWS_REGION")}`,` serverless-access-key: ${pe("secrets.SERVERLESS_ACCESS_KEY")}`,` slack-token: ${pe("secrets.SLACK_TOKEN")}`,` slack-channel: ${pe("secrets.SLACK_CHANNEL")}`,...n]},nD=(e,t,r,n)=>{let o=e.service.workflow===void 0?rD(e,n):_d(e.service.workflow);return["",` deploy-${e.name}:`,...Nd(Yv(r)),...Xv(tD(e,t,r)),...o]},Kv=(e,t)=>["",` ${e}:`," type: boolean",` description: '${t}'`," required: false"," default: false"],oD=(e,t,r)=>{let n=[" environment:"," type: choice"," description: 'Environment for deploy'"," required: true",` default: '${e.defaultEnvironment??e.environments[0]}'`," options:",...e.environments.map(i=>` - ${i}`)],o=(e.terraform??[]).length>0?Kv(Dd,"Skip terraform deployment"):[],s=t==="all"?[]:r.flatMap(i=>{let a=i.gate===void 0?"":` (${i.gate.join(", ")} only)`;return Kv(i.name,`Deploy ${i.name}${a}`)});return["on:"," workflow_dispatch:"," inputs:",...n,...o,...s]},sD=(e,t)=>{let{title:r,concurrency:n,v1File:o}=Id[t],s=(e.terraform??[]).length>0?pe(`inputs.${Dd} && '' \u2014 skip TF'' || ''''`):"";return["# Generated by `infra-kit deploy-sync` from infra-kit.deploy.ts: edit that file and re-run the command,","# a hand edit here is overwritten.",`name: '${r}'`,`run-name: '${r} [${pe("inputs.environment")}]${s}'`,"",`# Same group as ${o}, so a v1 run and a v2 run never deploy into one environment at once.`,"concurrency:",` group: ${n}-${pe("inputs.environment")}`," # false: a cancelled run would also kill an in-flight terraform apply."," cancel-in-progress: false",""]},iD=e=>{let t=pe(`!inputs.${Dd}`);return["",` ${ha(e)}:`,` if: ${t}`,..._d(e)]},aD=(e,t)=>{let r=t.length===0?void 0:pe(["!cancelled()",...zv(t)].join(" && "));return["",` ${ha(e)}:`,...Nd(t),...Xv(r),..._d(e)]},cD=(e,t)=>[""," notify-success:",...Nd(t),` if: ${pe("!cancelled() && contains(needs.*.result, 'success') && !contains(needs.*.result, 'failure')")}`,` uses: ./.github/workflows/${e}`," secrets: inherit"],Hv=(e,t)=>{let r=QI(e,t),n=e.terraform??[],o=e.preDeploy??[],s={terraform:n.map(ha),preDeploy:o.map(ha)},i=1+(n.length>0?1:0)+(t==="selected"?r.length:0);if(i>25)throw new Error(`${Id[t].file} would need ${i} dispatch inputs; GitHub allows 25. Mark services \`deployAll: false\` or split them.`);let a=r.map(u=>`deploy-${u.name}`),l=`${[...sD(e,t),...oD(e,t,r),"","permissions:"," contents: read","","jobs:",...n.flatMap(iD),...o.flatMap(u=>aD(u,s.terraform)),...r.flatMap(u=>nD(u,t,s,e.extraEnv??[])),...e.notifySuccess===void 0?[]:cD(e.notifySuccess,a)].join(`
421
421
  `).replace(`jobs:
422
422
 
423
423
  `,`jobs:
424
424
  `)}
425
- `;return{path:`.github/workflows/${Id[t].file}`,content:l}},Md=e=>[Kv(e,"all"),Kv(e,"selected")];var aD=async e=>{try{return await Fd.readFile(e,"utf-8")}catch{return}},ya=e=>({content:k(JSON.stringify(e,null,2)),structuredContent:e}),Ld=async(e={})=>{let t=e.cwd??await P(),r=await Ad(t);if(r===void 0)return(e.check?d.info.bind(d):d.error.bind(d))(`No ${jd} at ${t}, nothing to generate.`),ya({status:"missing-config",ok:!!e.check,files:[]});let n=await Promise.all(Md(r).map(async i=>{let a=Xv.join(t,i.path),c=await aD(a),l="unchanged";return c===void 0?l="created":c!==i.content&&(l="updated"),{...i,absolute:a,status:l}})),o=n.filter(i=>i.status!=="unchanged"),s=n.map(({path:i,status:a})=>({path:i,status:a}));if(o.length===0)return d.info(`\u2705 Deploy workflows match ${jd}.`),ya({status:"unchanged",ok:!0,files:s});if(e.check){d.error(`\u274C Deploy workflows differ from ${jd}; run \`infra-kit deploy-sync\` and commit:`);for(let i of o)d.error(` ${i.path} (${i.status==="created"?"missing":"differs"})`);return ya({status:"drift",ok:!1,files:s})}for(let i of o)await Fd.mkdir(Xv.dirname(i.absolute),{recursive:!0}),await Fd.writeFile(i.absolute,i.content),d.info(`\u270F\uFE0F ${i.status==="created"?"Created":"Updated"} ${i.path}`);return ya({status:"written",ok:!0,files:s})};var Zv="https://dashboard.doppler.com/workplace/projects",cD=(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}"): ${Zv}/${e}`],Bd=async({env:e})=>{let r=!!(await Je())?.envs[e];await Pm(e);let n=await Zt(),o=await Tt();r?d.info(`Removed the "${e}" service token from ${v(o)}.`):d.info(`No "${e}" service token was stored in ${v(o)} \u2014 nothing to remove.`);for(let i of cD(n,e))d.warn(i);let s={env:e,removed:r,storePath:o,revokeUrl:`${Zv}/${n}`};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}};import lD from"@inquirer/confirm";import uD from"@inquirer/input";import dD from"@inquirer/password";import pD from"@inquirer/select";import mD from"node:fs/promises";import lt from"node:process";import{$ as va}from"zx";var fD=async({stdin:e,fromEnv:t})=>{if(e)return{token:await Qv(),source:"stdin"};if(t){let n=lt.env[t];if(!n)throw new Error(`${t} is not set (or is empty) \u2014 nothing to store.`);return{token:n,source:"env"}}if(!lt.stdin.isTTY){let n=await Qv();if(n)return{token:n,source:"stdin"};if(!K())throw new Error("stdin is not a terminal and carried no token \u2014 pipe one in (`op read \u2026 | infra-kit env-token-set <env>`) or pass --from-env <VAR>.")}return h.setInteractive(),{token:(await I(n=>dD({message:"Paste the Doppler service token (input is hidden)",mask:!0},n),{output:lt.stderr,whenHeadless:{refuse:"stdin"}})).trim(),source:"prompt"}},Qv=async()=>{let e=[];lt.stdin.setEncoding("utf8");for await(let t of lt.stdin)e.push(t);return e.join("").trim()},Ud="DOPPLER_CONFIG",gD=3e4,hD=async(e,t,r)=>{let n=va.quiet;va.quiet=!0;let o;try{o=(await va({env:Wn(e)})`doppler secrets download --no-file --format json --project ${t} --config ${r}`.timeout(gD)).stdout}catch(s){throw yD(s,r)}finally{va.quiet=n}return Qa(o)},yD=(e,t)=>{let r=Yp(e)??(e instanceof Error?e.message:String(e));if(Tm(r)!=="auth")return e instanceof Error?e:new Error(String(e));let n=Cm(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(`
426
- `))},vD=e=>[`Could not verify this token's scope: the Doppler payload for "${e}" carries no ${Ud}.`,"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(`
427
- `),tw=async(e,t,r,n)=>{let o=await hD(e,t,r);Za(o,r);let s=o.some(([i])=>i===Ud);if(!s&&!n)throw new Error(vD(r));return s},ew="\0new-env",wD=async()=>{if(K()||!lt.stdin.isTTY)throw new C({status:"argument_required",argument:"env",agentMode:_.source},2,{operation:"env-token-set",remediation:"pass the environment as the positional argument on the re-run: `infra-kit env-token-set <env>`",stderrExcerpt:"<env> was not given and there is no terminal to pick it in"});let[e,t]=await Promise.all([Um(),Je()]),r=Math.max(0,...e.map(({env:s})=>s.length));h.setInteractive();let n=await I(s=>pD({message:"Which environment is the token for?",choices:[...e.map(({env:i})=>({name:`${i.padEnd(r)} ${t?.envs[i]?"set \u2014 replace":"not set"}`,value:i})),{name:"+ new env\u2026",value:ew}]},s),{output:lt.stderr,whenHeadless:"refuse"});return n!==ew?n:(await I(s=>uD({message:"Doppler config name",validate:i=>/^\S+$/.test(i.trim())||"Enter a config name without spaces"},s),{output:lt.stderr,whenHeadless:"refuse"})).trim()},kD=async(e,t,r)=>I(n=>lD({message:`Replace the "${e}" token ${ke(t)} with ${ke(r)}?`,default:!0},n),{output:lt.stderr,whenHeadless:"refuse"}),bD=(e,t,r,n)=>{switch(t){case"stored":return`Stored the "${e}" service token (${ke(r)})`;case"replaced":return`Replaced the "${e}" service token ${ke(n??"")} \u2192 ${ke(r)}`;case"unchanged":return`The "${e}" service token is already ${ke(r)} \u2014 nothing to write`;case"kept":return`Kept the existing "${e}" service token ${ke(n??"")} \u2014 nothing was written`;default:return Ne(t)}},Vd=async({env:e,stdin:t,fromEnv:r,force:n})=>{let o=await Zt(),s=e??await wD(),{token:i,source:a}=await fD({stdin:t,fromEnv:r});if(!i)throw new Error("No token provided \u2014 nothing was written.");let c=await tw(i,o,s,n),l=(await Je())?.envs[s],u;l===i?u="unchanged":l!==void 0&&a==="prompt"&&!await kD(s,l,i)?u="kept":(await Ja({[s]:i}),u=l===void 0?"stored":"replaced");let p=await Tt();d.info(`${bD(s,u,i,l)} in ${v(p)} (mode 0600).`),c||d.warn(`Scope was NOT verified (no ${Ud} in the payload) \u2014 accepted because --force was given.`);let m={env:s,status:u,source:a,redactedToken:ke(i),previousRedactedToken:l===void 0?null:ke(l),storePath:p,scopeVerified:c};return h.print(),{content:k(JSON.stringify(m,null,2)),structuredContent:m}},RD=e=>/^(["']).*\1$/.test(e)?e.slice(1,-1):e,rw=e=>{let t=e.split(/\r?\n/).flatMap((n,o)=>{let s=n.trim();if(s===""||s.startsWith("#"))return[];let i=s.indexOf("="),a=i>0?s.slice(0,i).trim():"",c=i>0?RD(s.slice(i+1).trim()):"";if(!/^\S+$/.test(a)||c==="")throw new Error(`Token file line ${o+1} is not \`<env>=<token>\` \u2014 nothing was written.`);return[{env:a,token:c}]});if(t.length===0)throw new Error("The token file holds no `<env>=<token>` lines \u2014 nothing was written.");let r=new Set;for(let{env:n}of t){if(r.has(n))throw new Error(`"${n}" appears twice in the token file \u2014 nothing was written.`);r.add(n)}return t},SD=e=>(e instanceof Error?e.message:String(e)).split(`
428
- `)[0]??"",ED=(e,t)=>e===void 0?"stored":e===t?"unchanged":"replaced",PD=async(e,t,r,n)=>{let o=ke(e.token);try{let s=await tw(e.token,t,e.env,n);return{env:e.env,status:ED(r,e.token),redactedToken:o,scopeVerified:s}}catch(s){return{env:e.env,status:"failed",redactedToken:o,scopeVerified:!1,error:SD(s)}}},Wd=async({fromFile:e,force:t})=>{let r=await Zt(),n=rw(await mD.readFile(e,"utf8")),o=await Je(),s=await Promise.all(n.map(p=>PD(p,r,o?.envs[p.env],t))),i=Object.fromEntries(n.filter((p,m)=>s[m]?.status==="stored"||s[m]?.status==="replaced").map(({env:p,token:m})=>[p,m]));Object.keys(i).length>0&&await Ja(i);let a=await Tt(),c=Math.max(...s.map(({env:p})=>p.length));d.info(`Token import from ${v(e)} \u2192 ${v(a)}:`);for(let p of s){let m=p.error?` ${p.error}`:"";d.info(` ${p.env.padEnd(c)} ${p.status.padEnd(9)} ${p.redactedToken}${m}`)}d.warn(`${v(e)} still holds live tokens in plain text \u2014 delete it.`);let l=s.filter(p=>p.status==="failed").length;l>0&&(lt.exitCode=1);let u={storePath:a,rows:s,failedCount:l};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}};var Gd=async(e,t,r=!0)=>{let{from:n,version:o,env:s,services:i,skipTerraform:a,yes:c,dryRun:l,printEnv:u}=e,p=await Pu(n);if(r&&h.addOption("--from",p),Eu(p,{"--version":o,"--skip-terraform":a,"--dry-run":l,"--print-env":u}),p==="local")throw new g(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"?Vi({version:o,env:s,skipTerraform:a,confirmedCommand:c}):Wi({version:o,env:s,services:i,skipTerraform:a,confirmedCommand:c})},Jd=async e=>Gd(e,"all"),Kd=async e=>Gd(e,"selected"),wa=async(e,t)=>{let r=`release deploy-${t} --from local`;return d.warn(`\`local deploy-${t}\` is deprecated and will be removed \u2014 use \`${r}\` instead.`),Gd({...e,from:"local"},t,!1)};import{VENDOR_CONFIG_FILE as ow}from"@slip-stream-kit/config/internal";import Hd from"node:fs/promises";import Tn from"node:path";import nw from"node:process";import{pathToFileURL as xD}from"node:url";var sw="~/projects",qd=async(e={})=>{if(e.init){await CD(e.cwd);return}await TD()},TD=async()=>{let e=dn(),t=await Z(e);if(d.info(`Factory config: ${v(e)} ${t?"[\u2713]":"[ ]"}`),!t){d.info("\nNot found \u2014 run `infra-kit vendor config --init` to scaffold it."),nw.exitCode=1;return}let{workspaceDir:r,source:n,targets:o}=await ki(),s=pn(r),i=await Z(s),a=Tn.join(s,n),c=await Z(a);d.info(`workspaceDir: ${r} (resolved: ${s}) ${i?"[\u2713 exists]":"[ ] not found"}`),d.info(`Source: ${c?"[\u2713]":"[ ]"} ${n} ${v(a)}${c?"":" (not found \u2014 clone it)"}`),d.info("Targets:");let l=i&&c;for(let u of o){let p=Tn.join(s,u),m=await Z(p);m||(l=!1);let f=m?"[\u2713]":"[ ]",y=m?"":" (not found \u2014 clone or remove)";d.info(` ${f} ${u} ${v(p)}${y}`)}l||(nw.exitCode=1)},CD=async e=>{let t=dn();if(await Z(t)){d.info(`Factory config already exists at ${v(t)} \u2014 leaving it untouched.`);return}let r=e??await P(),n=await $D(r);await Hd.mkdir(Tn.dirname(t),{recursive:!0}),await Hd.writeFile(t,AD(Tn.basename(r),n),"utf-8"),d.info(`\u2713 Created ${v(t)}`),n.length>0&&d.info(` Seeded ${n.length} target(s) from the source ${ow}.`),d.info(` Edit \`workspaceDir\` (placeholder: ${sw}) to point at where your repos live.`),d.info(` \`source\` is seeded with ${Tn.basename(r)} (this repo); change it if the source is another repo.`),n.length===0&&d.info(" Add at least one repo name to `targets` before running vendor sync/manifest/diff.")},$D=async e=>{try{let t=Tn.join(e,ow),r=await Hd.stat(t),s=(await import(`${xD(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[]},AD=(e,t)=>`${JSON.stringify({workspaceDir:sw,source:e,targets:t},null,2)}
429
- `;import{existsSync as _N}from"node:fs";import MN from"node:fs/promises";import Iw from"node:path";import Dw from"node:process";import{z as jN}from"zod";import{chmodSync as FD,copyFileSync as LD,lstatSync as BD,mkdirSync as gw,readdirSync as UD,readlinkSync as VD,rmdirSync as hw,symlinkSync as WD,unlinkSync as GD,writeFileSync as JD}from"node:fs";import be from"node:path";import{lstatSync as OD,readlinkSync as iw}from"node:fs";import ID from"node:path";var DD=new Set(["ENOENT","ENOTDIR"]),ka=e=>{let t;try{t=OD(e)}catch(r){if(DD.has(r.code??""))return null;throw r}return t.isSymbolicLink()?{kind:"link",text:iw(e)}:t.isFile()?{kind:"file",executable:(t.mode&64)!==0,sha:Rr(e)}:{kind:"other"}},aw=(e,t)=>{let r=ID.join(e,t.path),n=t.mode==="120000"?{kind:"link",text:iw(r)}:{kind:"file",executable:t.mode==="100755",sha:Rr(r)};return{...t,fingerprint:n}},cw=(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 ND}from"zx";var H=async(e,t,r={})=>{let{input:n,allowFailure:o=!1}=r,s=await ND({cwd:e,quiet:!0,input:n,nothrow:o})`git ${t}`;return s.exitCode===0?s.stdout:""},ba=e=>e.slice(0,7),ut=e=>e.split("\0").filter(t=>t.length>0);import _D from"node:path";var Yd=`${Q}/`,Ht=`${Q}/README.md`,ms=`${Q}/${Ve}`,uw=e=>e.startsWith(Yd),lw=e=>{let t=_D.posix.normalize(e);return t.endsWith("/")?t.slice(0,-1):t},dw=e=>{let t=lw(e.path),r=e.target===void 0?t:lw(e.target);return{path:t,target:r,vendored:uw(r),module:e.module??null}},pw=e=>e.copy.map(dw),fs=(e,t)=>t.length===0?!1:e.split("/").some(r=>t.includes(r)),gs=(e,t)=>e.filter(r=>!fs(r.path,t)),Ra=(e,t)=>e===t.path?t.target:`${t.target}${e.slice(t.path.length)}`,Cn=e=>[...new Set(e)].sort(),mw=e=>e.startsWith(Yd)?e.slice(Yd.length):null;var Sa=e=>`# vendor/ \u2014 mirrored from ${e}
425
+ `;return{path:`.github/workflows/${Id[t].file}`,content:l}},Md=e=>[Hv(e,"all"),Hv(e,"selected")];var lD=async e=>{try{return await Fd.readFile(e,"utf-8")}catch{return}},ya=e=>({content:k(JSON.stringify(e,null,2)),structuredContent:e}),Ld=async(e={})=>{let t=e.cwd??await P(),r=await Ad(t);if(r===void 0)return(e.check?d.info.bind(d):d.error.bind(d))(`No ${jd} at ${t}, nothing to generate.`),ya({status:"missing-config",ok:!!e.check,files:[]});let n=await Promise.all(Md(r).map(async i=>{let a=Zv.join(t,i.path),c=await lD(a),l="unchanged";return c===void 0?l="created":c!==i.content&&(l="updated"),{...i,absolute:a,status:l}})),o=n.filter(i=>i.status!=="unchanged"),s=n.map(({path:i,status:a})=>({path:i,status:a}));if(o.length===0)return d.info(`\u2705 Deploy workflows match ${jd}.`),ya({status:"unchanged",ok:!0,files:s});if(e.check){d.error(`\u274C Deploy workflows differ from ${jd}; run \`infra-kit deploy-sync\` and commit:`);for(let i of o)d.error(` ${i.path} (${i.status==="created"?"missing":"differs"})`);return ya({status:"drift",ok:!1,files:s})}for(let i of o)await Fd.mkdir(Zv.dirname(i.absolute),{recursive:!0}),await Fd.writeFile(i.absolute,i.content),d.info(`\u270F\uFE0F ${i.status==="created"?"Created":"Updated"} ${i.path}`);return ya({status:"written",ok:!0,files:s})};var Qv="https://dashboard.doppler.com/workplace/projects",uD=(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}"): ${Qv}/${e}`],Bd=async({env:e})=>{let r=!!(await Je())?.envs[e];await xm(e);let n=await Zt(),o=await Tt();r?d.info(`Removed the "${e}" service token from ${v(o)}.`):d.info(`No "${e}" service token was stored in ${v(o)} \u2014 nothing to remove.`);for(let i of uD(n,e))d.warn(i);let s={env:e,removed:r,storePath:o,revokeUrl:`${Qv}/${n}`};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}};import dD from"@inquirer/confirm";import pD from"@inquirer/input";import mD from"@inquirer/password";import fD from"@inquirer/select";import gD from"node:fs/promises";import ut from"node:process";import{$ as va}from"zx";var hD=async({stdin:e,fromEnv:t})=>{if(e)return{token:await ew(),source:"stdin"};if(t){let n=ut.env[t];if(!n)throw new Error(`${t} is not set (or is empty) \u2014 nothing to store.`);return{token:n,source:"env"}}if(!ut.stdin.isTTY){let n=await ew();if(n)return{token:n,source:"stdin"};if(!H())throw new Error("stdin is not a terminal and carried no token \u2014 pipe one in (`op read \u2026 | infra-kit env-token-set <env>`) or pass --from-env <VAR>.")}return h.setInteractive(),{token:(await I(n=>mD({message:"Paste the Doppler service token (input is hidden)",mask:!0},n),{output:ut.stderr,whenHeadless:{refuse:"stdin"}})).trim(),source:"prompt"}},ew=async()=>{let e=[];ut.stdin.setEncoding("utf8");for await(let t of ut.stdin)e.push(t);return e.join("").trim()},Ud="DOPPLER_CONFIG",yD=3e4,vD=async(e,t,r)=>{let n=va.quiet;va.quiet=!0;let o;try{o=(await va({env:Gn(e)})`doppler secrets download --no-file --format json --project ${t} --config ${r}`.timeout(yD)).stdout}catch(s){throw wD(s,r)}finally{va.quiet=n}return Qa(o)},wD=(e,t)=>{let r=zp(e)??(e instanceof Error?e.message:String(e));if(Cm(r)!=="auth")return e instanceof Error?e:new Error(String(e));let n=$m(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(`
426
+ `))},kD=e=>[`Could not verify this token's scope: the Doppler payload for "${e}" carries no ${Ud}.`,"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(`
427
+ `),rw=async(e,t,r,n)=>{let o=await vD(e,t,r);Za(o,r);let s=o.some(([i])=>i===Ud);if(!s&&!n)throw new Error(kD(r));return s},tw="\0new-env",bD=async()=>{if(H()||!ut.stdin.isTTY)throw new C({status:"argument_required",argument:"env",agentMode:_.source},2,{operation:"env-token-set",remediation:"pass the environment as the positional argument on the re-run: `infra-kit env-token-set <env>`",stderrExcerpt:"<env> was not given and there is no terminal to pick it in"});let[e,t]=await Promise.all([Vm(),Je()]),r=Math.max(0,...e.map(({env:s})=>s.length));h.setInteractive();let n=await I(s=>fD({message:"Which environment is the token for?",choices:[...e.map(({env:i})=>({name:`${i.padEnd(r)} ${t?.envs[i]?"set \u2014 replace":"not set"}`,value:i})),{name:"+ new env\u2026",value:tw}]},s),{output:ut.stderr,whenHeadless:"refuse"});return n!==tw?n:(await I(s=>pD({message:"Doppler config name",validate:i=>/^\S+$/.test(i.trim())||"Enter a config name without spaces"},s),{output:ut.stderr,whenHeadless:"refuse"})).trim()},RD=async(e,t,r)=>I(n=>dD({message:`Replace the "${e}" token ${be(t)} with ${be(r)}?`,default:!0},n),{output:ut.stderr,whenHeadless:"refuse"}),SD=(e,t,r,n)=>{switch(t){case"stored":return`Stored the "${e}" service token (${be(r)})`;case"replaced":return`Replaced the "${e}" service token ${be(n??"")} \u2192 ${be(r)}`;case"unchanged":return`The "${e}" service token is already ${be(r)} \u2014 nothing to write`;case"kept":return`Kept the existing "${e}" service token ${be(n??"")} \u2014 nothing was written`;default:return Ne(t)}},Vd=async({env:e,stdin:t,fromEnv:r,force:n})=>{let o=await Zt(),s=e??await bD(),{token:i,source:a}=await hD({stdin:t,fromEnv:r});if(!i)throw new Error("No token provided \u2014 nothing was written.");let c=await rw(i,o,s,n),l=(await Je())?.envs[s],u;l===i?u="unchanged":l!==void 0&&a==="prompt"&&!await RD(s,l,i)?u="kept":(await Ja({[s]:i}),u=l===void 0?"stored":"replaced");let p=await Tt();d.info(`${SD(s,u,i,l)} in ${v(p)} (mode 0600).`),c||d.warn(`Scope was NOT verified (no ${Ud} in the payload) \u2014 accepted because --force was given.`);let m={env:s,status:u,source:a,redactedToken:be(i),previousRedactedToken:l===void 0?null:be(l),storePath:p,scopeVerified:c};return h.print(),{content:k(JSON.stringify(m,null,2)),structuredContent:m}},ED=e=>/^(["']).*\1$/.test(e)?e.slice(1,-1):e,nw=e=>{let t=e.split(/\r?\n/).flatMap((n,o)=>{let s=n.trim();if(s===""||s.startsWith("#"))return[];let i=s.indexOf("="),a=i>0?s.slice(0,i).trim():"",c=i>0?ED(s.slice(i+1).trim()):"";if(!/^\S+$/.test(a)||c==="")throw new Error(`Token file line ${o+1} is not \`<env>=<token>\` \u2014 nothing was written.`);return[{env:a,token:c}]});if(t.length===0)throw new Error("The token file holds no `<env>=<token>` lines \u2014 nothing was written.");let r=new Set;for(let{env:n}of t){if(r.has(n))throw new Error(`"${n}" appears twice in the token file \u2014 nothing was written.`);r.add(n)}return t},PD=e=>(e instanceof Error?e.message:String(e)).split(`
428
+ `)[0]??"",xD=(e,t)=>e===void 0?"stored":e===t?"unchanged":"replaced",TD=async(e,t,r,n)=>{let o=be(e.token);try{let s=await rw(e.token,t,e.env,n);return{env:e.env,status:xD(r,e.token),redactedToken:o,scopeVerified:s}}catch(s){return{env:e.env,status:"failed",redactedToken:o,scopeVerified:!1,error:PD(s)}}},Wd=async({fromFile:e,force:t})=>{let r=await Zt(),n=nw(await gD.readFile(e,"utf8")),o=await Je(),s=await Promise.all(n.map(p=>TD(p,r,o?.envs[p.env],t))),i=Object.fromEntries(n.filter((p,m)=>s[m]?.status==="stored"||s[m]?.status==="replaced").map(({env:p,token:m})=>[p,m]));Object.keys(i).length>0&&await Ja(i);let a=await Tt(),c=Math.max(...s.map(({env:p})=>p.length));d.info(`Token import from ${v(e)} \u2192 ${v(a)}:`);for(let p of s){let m=p.error?` ${p.error}`:"";d.info(` ${p.env.padEnd(c)} ${p.status.padEnd(9)} ${p.redactedToken}${m}`)}d.warn(`${v(e)} still holds live tokens in plain text \u2014 delete it.`);let l=s.filter(p=>p.status==="failed").length;l>0&&(ut.exitCode=1);let u={storePath:a,rows:s,failedCount:l};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}};var Gd=async(e,t,r=!0)=>{let{from:n,version:o,env:s,services:i,skipTerraform:a,yes:c,dryRun:l,printEnv:u}=e,p=await Pu(n);if(r&&h.addOption("--from",p),Eu(p,{"--version":o,"--skip-terraform":a,"--dry-run":l,"--print-env":u}),p==="local")throw new g(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"?Vi({version:o,env:s,skipTerraform:a,confirmedCommand:c}):Wi({version:o,env:s,services:i,skipTerraform:a,confirmedCommand:c})},Jd=async e=>Gd(e,"all"),Kd=async e=>Gd(e,"selected"),wa=async(e,t)=>{let r=`release deploy-${t} --from local`;return d.warn(`\`local deploy-${t}\` is deprecated and will be removed \u2014 use \`${r}\` instead.`),Gd({...e,from:"local"},t,!1)};import{VENDOR_CONFIG_FILE as sw}from"@slip-stream-kit/config/internal";import Hd from"node:fs/promises";import Tn from"node:path";import ow from"node:process";import{pathToFileURL as CD}from"node:url";var iw="~/projects",qd=async(e={})=>{if(e.init){await AD(e.cwd);return}await $D()},$D=async()=>{let e=dn(),t=await Z(e);if(d.info(`Factory config: ${v(e)} ${t?"[\u2713]":"[ ]"}`),!t){d.info("\nNot found \u2014 run `infra-kit vendor config --init` to scaffold it."),ow.exitCode=1;return}let{workspaceDir:r,source:n,targets:o}=await ki(),s=pn(r),i=await Z(s),a=Tn.join(s,n),c=await Z(a);d.info(`workspaceDir: ${r} (resolved: ${s}) ${i?"[\u2713 exists]":"[ ] not found"}`),d.info(`Source: ${c?"[\u2713]":"[ ]"} ${n} ${v(a)}${c?"":" (not found \u2014 clone it)"}`),d.info("Targets:");let l=i&&c;for(let u of o){let p=Tn.join(s,u),m=await Z(p);m||(l=!1);let f=m?"[\u2713]":"[ ]",y=m?"":" (not found \u2014 clone or remove)";d.info(` ${f} ${u} ${v(p)}${y}`)}l||(ow.exitCode=1)},AD=async e=>{let t=dn();if(await Z(t)){d.info(`Factory config already exists at ${v(t)} \u2014 leaving it untouched.`);return}let r=e??await P(),n=await OD(r);await Hd.mkdir(Tn.dirname(t),{recursive:!0}),await Hd.writeFile(t,ID(Tn.basename(r),n),"utf-8"),d.info(`\u2713 Created ${v(t)}`),n.length>0&&d.info(` Seeded ${n.length} target(s) from the source ${sw}.`),d.info(` Edit \`workspaceDir\` (placeholder: ${iw}) to point at where your repos live.`),d.info(` \`source\` is seeded with ${Tn.basename(r)} (this repo); change it if the source is another repo.`),n.length===0&&d.info(" Add at least one repo name to `targets` before running vendor sync/manifest/diff.")},OD=async e=>{try{let t=Tn.join(e,sw),r=await Hd.stat(t),s=(await import(`${CD(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[]},ID=(e,t)=>`${JSON.stringify({workspaceDir:iw,source:e,targets:t},null,2)}
429
+ `;import{existsSync as BN}from"node:fs";import UN from"node:fs/promises";import Nw from"node:path";import _w from"node:process";import{z as VN}from"zod";import{chmodSync as BD,copyFileSync as UD,lstatSync as VD,mkdirSync as hw,readdirSync as WD,readlinkSync as GD,rmSync as JD,rmdirSync as yw,symlinkSync as KD,unlinkSync as HD,writeFileSync as qD}from"node:fs";import he from"node:path";import{lstatSync as DD,readlinkSync as aw}from"node:fs";import ND from"node:path";var _D=new Set(["ENOENT","ENOTDIR"]),ka=e=>{let t;try{t=DD(e)}catch(r){if(_D.has(r.code??""))return null;throw r}return t.isSymbolicLink()?{kind:"link",text:aw(e)}:t.isFile()?{kind:"file",executable:(t.mode&64)!==0,sha:Rr(e)}:{kind:"other"}},cw=(e,t)=>{let r=ND.join(e,t.path),n=t.mode==="120000"?{kind:"link",text:aw(r)}:{kind:"file",executable:t.mode==="100755",sha:Rr(r)};return{...t,fingerprint:n}},lw=(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 MD}from"zx";var J=async(e,t,r={})=>{let{input:n,allowFailure:o=!1}=r,s=await MD({cwd:e,quiet:!0,input:n,nothrow:o})`git ${t}`;return s.exitCode===0?s.stdout:""},ba=e=>e.slice(0,7),He=e=>e.split("\0").filter(t=>t.length>0);import jD from"node:path";var Yd=`${Q}/`,Ht=`${Q}/README.md`,fs=`${Q}/${Ve}`,dw=e=>e.startsWith(Yd),uw=e=>{let t=jD.posix.normalize(e);return t.endsWith("/")?t.slice(0,-1):t},pw=e=>{let t=uw(e.path),r=e.target===void 0?t:uw(e.target);return{path:t,target:r,vendored:dw(r),module:e.module??null}},mw=e=>e.copy.map(pw),gs=(e,t)=>t.length===0?!1:e.split("/").some(r=>t.includes(r)),hs=(e,t)=>e.filter(r=>!gs(r.path,t)),Ra=(e,t)=>e===t.path?t.target:`${t.target}${e.slice(t.path.length)}`,Cn=e=>[...new Set(e)].sort(),fw=e=>e.startsWith(Yd)?e.slice(Yd.length):null;var Sa=e=>`# vendor/ \u2014 mirrored from ${e}
430
430
 
431
431
  **DO NOT EDIT files in this folder here.**
432
432
 
@@ -437,19 +437,19 @@ fail \`ik vendor check\` in CI.
437
437
  To change a vendored package, edit it in \`${e}\` and re-run the sync there.
438
438
 
439
439
  See \`.sync-manifest.json\` for the source commit and per-file checksums.
440
- `;var MD=new Set(["100644","100755","120000"]),jD=(e,t)=>{let r=new Map;for(let n of ut(e)){let o=n.indexOf(" "),s=n.slice(0,n.indexOf(" ")),i=n.slice(o+1);o<0||!MD.has(s)||fs(i,t)||r.set(i,{path:i,mode:s})}return[...r.values()]},zd=async(e,t,r)=>{let n=await H(e,["--literal-pathspecs","ls-files","-z","-s","--",t]);return jD(n,r)},fw=async e=>ut(await H(e,["--literal-pathspecs","ls-files","-z","--",Q]));var $n=e=>["git","-C",e.root,"--literal-pathspecs","checkout","HEAD","--",...e.recoveryPaths],yw=e=>{let t=ka(e);t!==null&&(t.kind==="other"?hw(e):GD(e))},KD=(e,t,r)=>{let n=be.join(e,r.source),o=be.join(t,r.target);if(gw(be.dirname(o),{recursive:!0}),yw(o),r.mode==="120000"){WD(VD(n),o);return}LD(n,o),FD(o,r.mode==="100755"?493:420)},HD=async(e,t)=>{let r=new Set;for(let n of ut(await H(e,["ls-files","-z"]))){if(t.has(n))continue;let o=be.posix.dirname(n);for(;o!==".";)r.add(o),o=be.posix.dirname(o)}return r},qD=async(e,t)=>{if(t.length===0)return;let r=await HD(e,new Set(t)),n=[...new Set(t.map(o=>be.dirname(be.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)&&!(!BD(s,{throwIfNoEntry:!1})?.isDirectory()||UD(s).length>0||r.has(be.relative(e,s).split(be.sep).join("/")));)hw(s),s=be.dirname(s)}},vw=(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,Ht,...s].map(mw).filter(a=>a!==null&&!oa(a));return Cn(i)},ww=async(e,t,r,n)=>{let o=be.join(e,Q);gw(o,{recursive:!0}),JD(be.join(e,Ht),Sa(t.name));let s=vw(r,await fw(e),n);cd(o,{source:t.name,commit:t.headSha},s)},Xd=async({source:e,plan:t,onBeforeFirstWrite:r})=>{if(t.status!=="changed")return{touched:[],manifestWritten:!1};r?.($n(t));let n=be.resolve(t.root),o=t.entries.flatMap(a=>a.deletes);for(let a of o)yw(be.join(n,a));await qD(n,o);let s=t.entries.flatMap(a=>a.writes);for(let a of s)KD(e.root,n,a);let i=s.map(a=>a.target);return t.writeVendorMeta?(await ww(n,e,t.entries,o),{touched:Cn([...o,...i,Ht,ms]),manifestWritten:!0}):{touched:Cn([...o,...i]),manifestWritten:!1}},Zd=async(e,t)=>(await ww(e,t,[],[]),[Ht,ms]);var Qd=(e,t)=>`[ROOT] vendor: sync from ${e}@${ba(t)}`,YD=e=>{let{stdout:t,stderr:r}=e;return[t,r].filter(o=>typeof o=="string"&&o.trim().length>0).join(`
441
- `).trim()||String(e)},ep=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 H(e,["--literal-pathspecs","add","-A",...o],{input:n}),await H(e,["--literal-pathspecs","commit","--only","-m",r,...o],{input:n}),{ok:!0}}catch(s){return{ok:!1,output:YD(s)}}};var kw=20,zD=20,tp=(e,t)=>e.length<=t?[...e]:[...e.slice(0,t),`\u2026and ${e.length-t} more`],bw=(e,t,r)=>{let{entry:n}=e,o=new Set(t.tracked),s=[],i=[];for(let u of gs(e.files,r)){let p=Ra(u.path,n);if(s.push(p),cw(u.fingerprint,t.onDisk[p]??null))continue;let m=o.has(p)?"modified":"added";i.push({source:u.path,target:p,mode:u.mode,change:m})}let a=new Set(s),c=gs(t.tracked.map(u=>({path:u})),r).map(u=>u.path).filter(u=>!a.has(u)),l=i.filter(u=>u.change==="added").length;return{...n,targetPaths:s,writes:i,deletes:c,counts:{added:l,modified:i.length-l,removed:c.length}}},Er=(e,t,r,n=[])=>({name:e.name,root:e.root,status:t,message:r,notes:n,warnings:[],entries:[],writeVendorMeta:!1,recoveryPaths:[]}),rp=(e,t)=>e.entries.filter((r,n)=>t[n]!=="release").map(r=>r.entry.target),XD=(e,t,r,n)=>{let o=["git","-C",t.root,"--literal-pathspecs","status","--",...rp(e,r)];return Er(t,"fail",`blocked: ${n.length} uncommitted path(s) under synced paths`,[...tp(n,kw),Ie(o)])},ZD=(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=ba(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}`,...tp(e.lines,zD)],warnings:[]}},QD=e=>{let{added:t,modified:r,removed:n}=e.counts;return t+r+n===0?null:`${e.target}: ${t} added, ${r} modified, ${n} removed`},eN=e=>{let t=r=>e.reduce((n,o)=>n+o.counts[r],0);return`${t("added")} added, ${t("modified")} modified, ${t("removed")} removed`},tN=(e,t,r)=>{let n=e.flatMap(o=>[...o.writes.filter(i=>i.change==="modified").map(i=>i.target),...o.deletes]);return Cn([...n,...r?t.headVendorMeta:[]])},rN=e=>e.entries.filter(t=>t.scope==="release"&&t.tracked.length>0).map(t=>`${t.target}: not in vendorTarget.modules, left in place for this repo to own`),nN=(e,t)=>{let r=t.entries.map(f=>f.scope);if(t.dirty.length>0)return XD(e,t,r,t.dirty);if(t.pruneConflicts.length>0)return Er(t,"fail","blocked: a module this repo dropped is still a dependency",[...tp(t.pruneConflicts,kw)]);let n=e.entries.flatMap((f,y)=>{let b=t.entries[y]??{target:f.entry.target,scope:"sync",tracked:[],onDisk:{}};if(b.scope==="release")return[];let w=b.scope==="prune"?{...f,files:[]}:f;return[bw(w,b,e.exclude)]}),o=n.some(f=>f.vendored),s=n.some(f=>f.writes.length+f.deletes.length>0),i=o&&(!t.readmeCurrent||!t.manifestPresent),a={...Er(t,"ok","up to date"),branch:t.branch,entries:n,writeVendorMeta:o};if(!s&&!i)return a;let c=ZD(t.changelog,e.name),l=t.manifestSource!==null&&t.manifestSource!==e.name?[`vendor/ was last synced from ${t.manifestSource}, not ${e.name}: this sync replaces it`]:[],u=n.map(QD).filter(f=>f!==null),m=t.entries.some(f=>f.scope==="prune"&&f.tracked.length>0)?["vendored modules removed: run pnpm install to update the lockfile"]:[];return{...a,status:"changed",message:`${eN(n)} on ${t.branch}`,notes:[...u,...m,...rN(t),...i?["vendor/README.md and manifest rewritten"]:[],...c.notes],warnings:[...l,...c.warnings],recoveryPaths:tN(n,t,o)}},Ea=(e,t)=>{switch(t.kind){case"missing":return Er(t,"skipped",`not checked out at ${t.root}`);case"source":return Er(t,"skipped","this is the source repo");case"not-git":return Er(t,"fail",`not a git repo: ${t.reason}`);case"bad-selection":return Er(t,"fail",`vendorTarget: ${t.reason}`);case"repo":return nN(e,t)}};import{existsSync as lN,readFileSync as uN,realpathSync as Pa}from"node:fs";import xa from"node:path";import{readFileSync as oN}from"node:fs";import hs from"node:path";var sN=["dependencies","devDependencies","peerDependencies","optionalDependencies"],iN=e=>{let t=e.flatMap(({entry:r})=>r.module===null?[]:[r.module]);return[...new Set(t)].sort()},Rw=(e,t)=>{if(t.kind==="invalid")return{reason:t.reason};let r=iN(e);if(t.kind==="modules"){let n=t.modules.filter(o=>!r.includes(o));if(n.length>0){let o=r.length>0?r.join(", "):"none";return{reason:`unknown module(s) ${n.join(", ")} in vendorTarget.modules; the source offers: ${o}`}}}return e.map(({entry:n})=>n.module===null||t.kind==="all"||t.modules.includes(n.module)?"sync":n.vendored?"prune":"release")},Sw=e=>{try{return JSON.parse(oN(e,"utf8"))}catch{return null}},aN=(e,t)=>t.files.flatMap(r=>{let n=hs.posix.relative(t.entry.path,r.path);if(hs.posix.basename(n)!=="package.json"||n.split("/").length>2)return[];let o=Sw(hs.join(e,r.path))?.name;return typeof o=="string"?[o]:[]}),cN=e=>sN.flatMap(t=>{let r=e[t];return r!==null&&typeof r=="object"?Object.keys(r):[]}),Ew=async(e,t,r)=>{let n=new Map;for(let{facts:i}of r)for(let a of aN(e,i))n.set(a,i.entry.module??"");if(n.size===0)return[];let o=r.map(({target:i})=>`${i}/`);return ut(await H(t,["ls-files","-z","--","*package.json"])).filter(i=>{let a=o.some(c=>i.startsWith(c));return hs.posix.basename(i)==="package.json"&&!a}).flatMap(i=>{let a=Sw(hs.join(t,i));return a===null?[]:cN(a).filter(c=>n.has(c)).map(c=>`${i} depends on ${c}: add "${n.get(c)}" to vendorTarget.modules or drop the dependency`)})};var np=async(e,t)=>{let r=t.exclude??[],n=(await H(e,["rev-parse","HEAD"])).trim(),o=await Re(e),s=await Promise.all(pw(t).map(async i=>{let a=await zd(e,i.path,r);return{entry:i,files:a.map(c=>aw(e,c))}}));return{root:e,selfRoots:[...new Set([Pa(e),Pa(o)])],name:xa.basename(o),headSha:n,entries:s,exclude:r}},Ta=e=>{let t=ut(e)[Symbol.iterator](),r=[];for(let n of t)r.push(n.slice(3)),/^[RC]|^.[RC]/u.test(n)&&t.next();return r},dN=async(e,t,r)=>{let n=rp(e,t);if(n.length===0)return[];let o=await H(r,["--literal-pathspecs","status","--porcelain","-z","--untracked-files=all","--",...n]);return Ta(o).filter(s=>!fs(s,e.exclude))},pN=async(e,t,r)=>Promise.all(e.entries.map(async({entry:n,files:o},s)=>{let i=t[s],a=await zd(r,n.target,e.exclude),c={},l=i==="sync"?o:[];for(let u of gs(l,e.exclude)){let p=Ra(u.path,n);c[p]=ka(xa.join(r,p))}return{target:n.target,scope:i,tracked:a.map(u=>u.path),onDisk:c}})),mN=async e=>{try{return ut(await H(e,["--literal-pathspecs","ls-tree","-z","--name-only","HEAD","--",Ht,ms]))}catch{return[]}},fN=e=>{try{let{commit:t,source:r}=as(xa.join(e,Q));return{commit:t,source:r}}catch{return null}},gN=async(e,t,r)=>{if(r===null)return{kind:"unknown-sha"};if(await De(e.root,r)===null)return{kind:"unresolvable",sha:r};let n=e.entries.filter((i,a)=>t[a]==="sync").map(({entry:i})=>i.path);if(n.length===0)return{kind:"log",sha:r,lines:[]};let s=(await H(e.root,["--literal-pathspecs","log","--oneline",`${r}..HEAD`,"--",...n])).split(`
442
- `).filter(i=>i.length>0);return{kind:"log",sha:r,lines:s}},hN=(e,t)=>{try{return uN(xa.join(e,Ht),"utf8")===Sa(t)}catch{return!1}},yN=async e=>{try{return{toplevel:(await H(e,["rev-parse","--show-toplevel"])).trim()}}catch(t){return{reason:String(t.stderr??t).trim().split(`
443
- `)[0]??"git rev-parse failed"}}},vN=async e=>{try{return(await H(e,["rev-parse","--abbrev-ref","HEAD"])).trim()}catch{return"HEAD"}},Ca=async(e,t)=>{if(!lN(t.root))return{...t,kind:"missing"};let r=Pa(t.root);if(e.selfRoots.includes(r))return{...t,kind:"source"};let n=await yN(t.root);if("reason"in n)return{...t,kind:"not-git",reason:n.reason};if(Pa(n.toplevel)!==r)return{...t,kind:"not-git",reason:`it sits inside the repo at ${n.toplevel}`};let o=Rw(e.entries,t.selection??{kind:"all"});if("reason"in o)return{...t,kind:"bad-selection",reason:o.reason};let s=fN(t.root),i=s?.commit??null,[a,c,l,u,p]=await Promise.all([vN(t.root),dN(e,o,t.root),pN(e,o,t.root),mN(t.root),gN(e,o,i)]),m=l.flatMap((f,y)=>f.scope==="prune"&&f.tracked.length>0?[{facts:e.entries[y],target:f.target}]:[]);return{...t,kind:"repo",branch:a,dirty:c,entries:l,headVendorMeta:u,readmeCurrent:hN(t.root,e.name),manifestPresent:s!==null,manifestSource:s?.source??null,changelog:p,pruneConflicts:await Ew(e.root,t.root,m)}};var wN=20,kN=(e,t)=>!t.commit||e.status!=="changed"||e.branch===void 0?e.notes:[...e.notes,`--commit lands on ${e.branch}`],bN=(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:",Ie($n(r))]};let o=e.applied?`wrote ${r.message}`:r.message;return{name:n,status:r.status,message:o,notes:t.mode==="applied"?r.notes:kN(r,t)}},RN=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(`
444
- `).slice(0,wN)},SN=(e,t)=>{let r=e.plan.warnings.map(n=>({name:"changelog",status:"warn",message:n}));return{label:e.plan.name,rows:[bN(e,t),...r,...e.commit?[RN(e.commit)]:[]]}},EN={preview:"infra-kit vendor sync (preview)",check:"infra-kit vendor sync --check",applied:"infra-kit vendor sync"},op=(e,t,r)=>{let n=r.mode==="preview"?["re-run with --yes from a real terminal to apply"]:[];return{title:EN[r.mode],sections:[{label:"source",rows:[...e]},...t.map(o=>SN(o,r))],hints:n}},Pw=e=>e.sections.some(t=>t.rows.some(r=>r.status==="fail")),xw=(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 PN=20,sp=async(e,t)=>(await H(e,t,{allowFailure:!0})).trim(),xN=async e=>Ta(await H(e,["status","--porcelain","-z","--untracked-files=normal"])),TN=async e=>(await sp(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"]},CN=async e=>{let[t,r]=await Promise.all([sp(e,["symbolic-ref","--quiet","--short","refs/remotes/origin/HEAD"]),sp(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}`}},Tw=async e=>{let t=await xN(e);if(t.length>0){let n=t.slice(0,PN),o=t.length>n.length?`, and ${t.length-n.length} more`:"";throw new C({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([TN(e),CN(e)]);return[{name:"working tree",status:"ok",message:"clean"},...r.filter(n=>n!==null)]};import IN from"node:path";import{readFileSync as $N}from"node:fs";import AN from"node:path";import{z as ON}from"zod";var Cw=e=>{let t;try{t=$N(AN.join(e,"infra-kit.json"),"utf8")}catch{return{kind:"all"}}let r;try{r=JSON.parse(t)?.vendorTarget}catch(o){return{kind:"invalid",reason:`infra-kit.json is not valid JSON: ${o.message}`}}if(r===void 0)return{kind:"all"};let n=pm.safeParse(r);return n.success?{kind:"modules",modules:n.data.modules}:{kind:"invalid",reason:ON.prettifyError(n.error)}};var $w=(e,t)=>{let r=t.filter(s=>!e.targets.includes(s));if(r.length>0)throw new C({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=pn(e.workspaceDir);return(t.length>0?e.targets.filter(s=>t.includes(s)):e.targets).map(s=>{let i=IN.join(n,s);return{name:s,root:i,selection:Cw(i)}})},DN="rewrite vendor/README.md and vendor/.sync-manifest.json from the tracked vendor/ files",NN=async(e,t)=>{let r=await Ca(e,t),n=Ea(e,r);return r.kind!=="repo"||n.status==="fail"?n:{...n,status:"changed",message:`${DN} on ${r.branch}`,notes:[],warnings:[],branch:r.branch,entries:[],writeVendorMeta:!0,recoveryPaths:r.headVendorMeta}},Aw=async(e,t,r)=>Promise.all(t.map(async n=>r?NN(e,n):Ea(e,await Ca(e,n))));var Nw="sync vendored files",FN=e=>{let t=Iw.join(pn(e.workspaceDir),e.source);if(_N(t))return t;throw new C({status:"refused",reason:"source-missing",source:t},1,{operation:Nw,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'})},ip=(e,t)=>new C({status:"refused",reason:"not-a-vendor-source"},1,{operation:Nw,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`}),LN=async e=>{let t=Iw.join(e,"infra-kit.json"),r;try{r=JSON.parse(await MN.readFile(t,"utf8"))}catch(s){throw ip(t,`is unreadable: ${s instanceof Error?s.message:String(s)}`)}let n=r?.vendorSource;if(n==null)throw ip(t,"has no vendorSource block");let o=dm.safeParse(n);if(!o.success)throw ip(t,`has an invalid vendorSource: ${jN.prettifyError(o.error)}`);return o.data},Ow=(e,t)=>{Dw.stderr.write(`${e.name}: if this run dies, restore the tracked paths with:
440
+ `;var FD=new Set(["100644","100755","120000"]),LD=(e,t)=>{let r=new Map;for(let n of He(e)){let o=n.indexOf(" "),s=n.slice(0,n.indexOf(" ")),i=n.slice(o+1);o<0||!FD.has(s)||gs(i,t)||r.set(i,{path:i,mode:s})}return[...r.values()]},zd=async(e,t,r)=>{let n=await J(e,["--literal-pathspecs","ls-files","-z","-s","--",t]);return LD(n,r)},gw=async e=>He(await J(e,["--literal-pathspecs","ls-files","-z","--",Q]));var $n=e=>["git","-C",e.root,"--literal-pathspecs","checkout","HEAD","--",...e.recoveryPaths],vw=e=>{let t=ka(e);t!==null&&(t.kind==="other"?yw(e):HD(e))},YD=(e,t,r)=>{let n=he.join(e,r.source),o=he.join(t,r.target);if(hw(he.dirname(o),{recursive:!0}),vw(o),r.mode==="120000"){KD(GD(n),o);return}UD(n,o),BD(o,r.mode==="100755"?493:420)},zD=async(e,t)=>{let r=new Set;for(let n of He(await J(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},XD=async(e,t)=>{if(t.length===0)return;let r=await zD(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)&&!(!VD(s,{throwIfNoEntry:!1})?.isDirectory()||WD(s).length>0||r.has(he.relative(e,s).split(he.sep).join("/")));)yw(s),s=he.dirname(s)}},ww=(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,Ht,...s].map(fw).filter(a=>a!==null&&!oa(a));return Cn(i)},kw=async(e,t,r,n)=>{let o=he.join(e,Q);hw(o,{recursive:!0}),qD(he.join(e,Ht),Sa(t.name));let s=ww(r,await gw(e),n);cd(o,{source:t.name,commit:t.headSha},s)},Xd=async({source:e,plan:t,onBeforeFirstWrite:r})=>{if(t.status!=="changed")return{touched:[],manifestWritten:!1};r?.($n(t));let n=he.resolve(t.root),o=t.entries.flatMap(a=>a.deletes);for(let a of o)vw(he.join(n,a));await XD(n,o);for(let a of t.entries)a.pruned&&a.deletes.length>0&&JD(he.join(n,a.target),{recursive:!0,force:!0});let s=t.entries.flatMap(a=>a.writes);for(let a of s)YD(e.root,n,a);let i=s.map(a=>a.target);return t.writeVendorMeta?(await kw(n,e,t.entries,o),{touched:Cn([...o,...i,Ht,fs]),manifestWritten:!0}):{touched:Cn([...o,...i]),manifestWritten:!1}},Zd=async(e,t)=>(await kw(e,t,[],[]),[Ht,fs]);var Qd=(e,t)=>`[ROOT] vendor: sync from ${e}@${ba(t)}`,ZD=e=>{let{stdout:t,stderr:r}=e;return[t,r].filter(o=>typeof o=="string"&&o.trim().length>0).join(`
441
+ `).trim()||String(e)},ep=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 J(e,["--literal-pathspecs","add","-A",...o],{input:n}),await J(e,["--literal-pathspecs","commit","--only","-m",r,...o],{input:n}),{ok:!0}}catch(s){return{ok:!1,output:ZD(s)}}};var bw=20,QD=20,rp=(e,t)=>e.length<=t?[...e]:[...e.slice(0,t),`\u2026and ${e.length-t} more`],tp=(e,t,r)=>{let{entry:n}=e,o=new Set(t.tracked),s=[],i=[];for(let u of hs(e.files,r)){let p=Ra(u.path,n);if(s.push(p),lw(u.fingerprint,t.onDisk[p]??null))continue;let m=o.has(p)?"modified":"added";i.push({source:u.path,target:p,mode:u.mode,change:m})}let a=new Set(s),c=hs(t.tracked.map(u=>({path:u})),r).map(u=>u.path).filter(u=>!a.has(u)),l=i.filter(u=>u.change==="added").length;return{...n,targetPaths:s,writes:i,deletes:c,counts:{added:l,modified:i.length-l,removed:c.length},pruned:!1}},Er=(e,t,r,n=[])=>({name:e.name,root:e.root,status:t,message:r,notes:n,warnings:[],entries:[],writeVendorMeta:!1,recoveryPaths:[]}),np=(e,t)=>e.entries.filter((r,n)=>t[n]!=="release").map(r=>r.entry.target),eN=(e,t,r,n)=>{let o=["git","-C",t.root,"--literal-pathspecs","status","--",...np(e,r)];return Er(t,"fail",`blocked: ${n.length} uncommitted path(s) under synced paths`,[...rp(n,bw),Ie(o)])},tN=(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=ba(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}`,...rp(e.lines,QD)],warnings:[]}},rN=e=>{let{added:t,modified:r,removed:n}=e.counts;return t+r+n===0?null:`${e.target}: ${t} added, ${r} modified, ${n} removed`},nN=e=>{let t=r=>e.reduce((n,o)=>n+o.counts[r],0);return`${t("added")} added, ${t("modified")} modified, ${t("removed")} removed`},oN=(e,t,r)=>{let n=e.flatMap(o=>[...o.writes.filter(i=>i.change==="modified").map(i=>i.target),...o.deletes]);return Cn([...n,...r?t.headVendorMeta:[]])},sN=e=>e.entries.filter(t=>t.scope==="release"&&t.tracked.length>0).map(t=>`${t.target}: not in vendorTarget.modules, left in place for this repo to own`),iN=(e,t)=>{let r=t.entries.map(f=>f.scope);if(t.dirty.length>0)return eN(e,t,r,t.dirty);if(t.pruneConflicts.length>0)return Er(t,"fail","blocked: a module this repo dropped is still a dependency",[...rp(t.pruneConflicts,bw)]);let n=e.entries.flatMap((f,y)=>{let b=t.entries[y]??{target:f.entry.target,scope:"sync",tracked:[],onDisk:{}};return b.scope==="release"?[]:b.scope==="sync"?[tp(f,b,e.exclude)]:[{...tp({...f,files:[]},b,e.exclude),pruned:!0}]}),o=n.some(f=>f.vendored),s=n.some(f=>f.writes.length+f.deletes.length>0),i=o&&(!t.readmeCurrent||!t.manifestPresent),a={...Er(t,"ok","up to date"),branch:t.branch,entries:n,writeVendorMeta:o};if(!s&&!i)return a;let c=tN(t.changelog,e.name),l=t.manifestSource!==null&&t.manifestSource!==e.name?[`vendor/ was last synced from ${t.manifestSource}, not ${e.name}: this sync replaces it`]:[],u=n.map(rN).filter(f=>f!==null),m=t.entries.some(f=>f.scope==="prune"&&f.tracked.length>0)?["vendored modules removed: run pnpm install to update the lockfile"]:[];return{...a,status:"changed",message:`${nN(n)} on ${t.branch}`,notes:[...u,...m,...sN(t),...i?["vendor/README.md and manifest rewritten"]:[],...c.notes],warnings:[...l,...c.warnings],recoveryPaths:oN(n,t,o)}},Ea=(e,t)=>{switch(t.kind){case"missing":return Er(t,"skipped",`not checked out at ${t.root}`);case"source":return Er(t,"skipped","this is the source repo");case"not-git":return Er(t,"fail",`not a git repo: ${t.reason}`);case"bad-selection":return Er(t,"fail",`vendorTarget: ${t.reason}`);case"repo":return iN(e,t)}};import{existsSync as fN,readFileSync as gN,realpathSync as Pa}from"node:fs";import xa from"node:path";import{readFileSync as Rw}from"node:fs";import An from"node:path";var aN=["dependencies","devDependencies","peerDependencies","optionalDependencies"],cN=e=>{let t=e.flatMap(({entry:r})=>r.module===null?[]:[r.module]);return[...new Set(t)].sort()},Sw=(e,t)=>{if(t.kind==="invalid")return{reason:t.reason};let r=cN(e);if(t.kind==="modules"){let n=t.modules.filter(o=>!r.includes(o));if(n.length>0){let o=r.length>0?r.join(", "):"none";return{reason:`unknown module(s) ${n.join(", ")} in vendorTarget.modules; the source offers: ${o}`}}}return e.map(({entry:n})=>n.module===null||t.kind==="all"||t.modules.includes(n.module)?"sync":n.vendored?"prune":"release")},Ew=e=>{try{return JSON.parse(Rw(e,"utf8"))}catch{return null}},lN=(e,t)=>t.files.flatMap(r=>{let n=An.posix.relative(t.entry.path,r.path);if(An.posix.basename(n)!=="package.json"||n.split("/").length>2)return[];let o=Ew(An.join(e,r.path))?.name;return typeof o=="string"?[o]:[]}),uN=e=>aN.flatMap(t=>{let r=e[t];return r!==null&&typeof r=="object"?Object.keys(r):[]}),Pw=(e,t)=>{let r=e.indexOf(t);for(;r>=0;){if(!/[\w-]/.test(e[r+t.length]??""))return!0;r=e.indexOf(t,r+1)}return!1},dN=["*.sh","*.yml","*.yaml"],pN=(e,t,r)=>{let n=uN(t).includes(r)?[`${e} depends on ${r}`]:[],o=t.scripts!==null&&typeof t.scripts=="object"?t.scripts:{};for(let[s,i]of Object.entries(o))typeof i=="string"&&Pw(i,r)&&n.push(`${e} script "${s}" runs ${r}`);return n},mN=async(e,t,r)=>{let n=["grep","-z","-l","-F","-e",t,"--",...dN];return He(await J(e,n,{allowFailure:!0})).filter(s=>r(s)&&Pw(Rw(An.join(e,s),"utf8"),t)).map(s=>`${s} uses ${t}`)},xw=async(e,t,r)=>{let n=new Map;for(let{facts:c}of r)for(let l of lN(e,c))n.set(l,c.entry.module??"");if(n.size===0)return[];let o=r.map(({target:c})=>`${c}/`),s=c=>!o.some(l=>c.startsWith(l)),i=He(await J(t,["ls-files","-z","--","*package.json"])).filter(c=>An.posix.basename(c)==="package.json"&&s(c)),a=[];for(let[c,l]of n){let u=i.flatMap(p=>{let m=Ew(An.join(t,p));return m===null?[]:pN(p,m,c)});u.push(...await mN(t,c,s));for(let p of u)a.push(`${p}: add "${l}" to vendorTarget.modules or stop using it`)}return a.sort()};var op=async(e,t)=>{let r=t.exclude??[],n=(await J(e,["rev-parse","HEAD"])).trim(),o=await Re(e),s=await Promise.all(mw(t).map(async i=>{let a=await zd(e,i.path,r);return{entry:i,files:a.map(c=>cw(e,c))}}));return{root:e,selfRoots:[...new Set([Pa(e),Pa(o)])],name:xa.basename(o),headSha:n,entries:s,exclude:r}},Ta=e=>{let t=He(e)[Symbol.iterator](),r=[];for(let n of t)r.push(n.slice(3)),/^[RC]|^.[RC]/u.test(n)&&t.next();return r},hN=async(e,t,r)=>{let n=np(e,t);if(n.length===0)return[];let o=await J(r,["--literal-pathspecs","status","--porcelain","-z","--untracked-files=all","--",...n]);return Ta(o).filter(s=>!gs(s,e.exclude))},yN=async(e,t,r)=>Promise.all(e.entries.map(async({entry:n,files:o},s)=>{let i=t[s],a=await zd(r,n.target,e.exclude),c={},l=i==="sync"?o:[];for(let u of hs(l,e.exclude)){let p=Ra(u.path,n);c[p]=ka(xa.join(r,p))}return{target:n.target,scope:i,tracked:a.map(u=>u.path),onDisk:c}})),vN=async e=>{try{return He(await J(e,["--literal-pathspecs","ls-tree","-z","--name-only","HEAD","--",Ht,fs]))}catch{return[]}},wN=e=>{try{let{commit:t,source:r}=cs(xa.join(e,Q));return{commit:t,source:r}}catch{return null}},kN=async(e,t,r)=>{if(r===null)return{kind:"unknown-sha"};if(await De(e.root,r)===null)return{kind:"unresolvable",sha:r};let n=e.entries.filter((i,a)=>t[a]==="sync").map(({entry:i})=>i.path);if(n.length===0)return{kind:"log",sha:r,lines:[]};let s=(await J(e.root,["--literal-pathspecs","log","--oneline",`${r}..HEAD`,"--",...n])).split(`
442
+ `).filter(i=>i.length>0);return{kind:"log",sha:r,lines:s}},bN=(e,t)=>{try{return gN(xa.join(e,Ht),"utf8")===Sa(t)}catch{return!1}},RN=async e=>{try{return{toplevel:(await J(e,["rev-parse","--show-toplevel"])).trim()}}catch(t){return{reason:String(t.stderr??t).trim().split(`
443
+ `)[0]??"git rev-parse failed"}}},SN=async e=>{try{return(await J(e,["rev-parse","--abbrev-ref","HEAD"])).trim()}catch{return"HEAD"}},Ca=async(e,t)=>{if(!fN(t.root))return{...t,kind:"missing"};let r=Pa(t.root);if(e.selfRoots.includes(r))return{...t,kind:"source"};let n=await RN(t.root);if("reason"in n)return{...t,kind:"not-git",reason:n.reason};if(Pa(n.toplevel)!==r)return{...t,kind:"not-git",reason:`it sits inside the repo at ${n.toplevel}`};let o=Sw(e.entries,t.selection??{kind:"all"});if("reason"in o)return{...t,kind:"bad-selection",reason:o.reason};let s=wN(t.root),i=s?.commit??null,[a,c,l,u,p]=await Promise.all([SN(t.root),hN(e,o,t.root),yN(e,o,t.root),vN(t.root),kN(e,o,i)]),m=l.flatMap((f,y)=>f.scope==="prune"&&f.tracked.length>0?[{facts:e.entries[y],target:f.target}]:[]);return{...t,kind:"repo",branch:a,dirty:c,entries:l,headVendorMeta:u,readmeCurrent:bN(t.root,e.name),manifestPresent:s!==null,manifestSource:s?.source??null,changelog:p,pruneConflicts:await xw(e.root,t.root,m)}};var EN=20,PN=(e,t)=>!t.commit||e.status!=="changed"||e.branch===void 0?e.notes:[...e.notes,`--commit lands on ${e.branch}`],xN=(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:",Ie($n(r))]};let o=e.applied?`wrote ${r.message}`:r.message;return{name:n,status:r.status,message:o,notes:t.mode==="applied"?r.notes:PN(r,t)}},TN=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(`
444
+ `).slice(0,EN)},CN=(e,t)=>{let r=e.plan.warnings.map(n=>({name:"changelog",status:"warn",message:n}));return{label:e.plan.name,rows:[xN(e,t),...r,...e.commit?[TN(e.commit)]:[]]}},$N={preview:"infra-kit vendor sync (preview)",check:"infra-kit vendor sync --check",applied:"infra-kit vendor sync"},sp=(e,t,r)=>{let n=r.mode==="preview"?["re-run with --yes from a real terminal to apply"]:[];return{title:$N[r.mode],sections:[{label:"source",rows:[...e]},...t.map(o=>CN(o,r))],hints:n}},Tw=e=>e.sections.some(t=>t.rows.some(r=>r.status==="fail")),Cw=(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 AN=20,ip=async(e,t)=>(await J(e,t,{allowFailure:!0})).trim(),ON=async e=>Ta(await J(e,["status","--porcelain","-z","--untracked-files=normal"])),IN=async e=>(await ip(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"]},DN=async e=>{let[t,r]=await Promise.all([ip(e,["symbolic-ref","--quiet","--short","refs/remotes/origin/HEAD"]),ip(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}`}},$w=async e=>{let t=await ON(e);if(t.length>0){let n=t.slice(0,AN),o=t.length>n.length?`, and ${t.length-n.length} more`:"";throw new C({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([IN(e),DN(e)]);return[{name:"working tree",status:"ok",message:"clean"},...r.filter(n=>n!==null)]};import jN from"node:path";import{readFileSync as NN}from"node:fs";import _N from"node:path";import{z as MN}from"zod";var Aw=e=>{let t;try{t=NN(_N.join(e,"infra-kit.json"),"utf8")}catch{return{kind:"all"}}let r;try{r=JSON.parse(t)?.vendorTarget}catch(o){return{kind:"invalid",reason:`infra-kit.json is not valid JSON: ${o.message}`}}if(r===void 0)return{kind:"all"};let n=mm.safeParse(r);return n.success?{kind:"modules",modules:n.data.modules}:{kind:"invalid",reason:MN.prettifyError(n.error)}};var Ow=(e,t)=>{let r=t.filter(s=>!e.targets.includes(s));if(r.length>0)throw new C({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=pn(e.workspaceDir);return(t.length>0?e.targets.filter(s=>t.includes(s)):e.targets).map(s=>{let i=jN.join(n,s);return{name:s,root:i,selection:Aw(i)}})},FN="rewrite vendor/README.md and vendor/.sync-manifest.json from the tracked vendor/ files",LN=async(e,t)=>{let r=await Ca(e,t),n=Ea(e,r);return r.kind!=="repo"||n.status==="fail"?n:{...n,status:"changed",message:`${FN} on ${r.branch}`,notes:[],warnings:[],branch:r.branch,entries:[],writeVendorMeta:!0,recoveryPaths:r.headVendorMeta}},Iw=async(e,t,r)=>Promise.all(t.map(async n=>r?LN(e,n):Ea(e,await Ca(e,n))));var Mw="sync vendored files",WN=e=>{let t=Nw.join(pn(e.workspaceDir),e.source);if(BN(t))return t;throw new C({status:"refused",reason:"source-missing",source:t},1,{operation:Mw,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'})},ap=(e,t)=>new C({status:"refused",reason:"not-a-vendor-source"},1,{operation:Mw,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`}),GN=async e=>{let t=Nw.join(e,"infra-kit.json"),r;try{r=JSON.parse(await UN.readFile(t,"utf8"))}catch(s){throw ap(t,`is unreadable: ${s instanceof Error?s.message:String(s)}`)}let n=r?.vendorSource;if(n==null)throw ap(t,"has no vendorSource block");let o=pm.safeParse(n);if(!o.success)throw ap(t,`has an invalid vendorSource: ${VN.prettifyError(o.error)}`);return o.data},Dw=(e,t)=>{_w.stderr.write(`${e.name}: if this run dies, restore the tracked paths with:
445
445
  ${Ie(t)}
446
- `)},BN=async(e,t,r)=>r?(Ow(t,$n(t)),Zd(t.root,e)):(await Xd({source:e,plan:t,onBeforeFirstWrite:o=>{Ow(t,o)}})).touched,UN=async(e,t,r)=>{if(t.status!=="changed")return{plan:t,applied:!1};let n;try{n=await BN(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 ep(t.root,n,Qd(e.name,e.headSha));return{plan:t,applied:!0,commit:o}},VN=async(e,t,r)=>{let n=[];for(let o of t)n.push(await UN(e,o,r));return n},_w=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})),ap=({mode:e,report:t,outcomes:r,source:n,print:o})=>{o&&tt(t);let s=r.map(a=>a.plan);return{structuredContent:{mode:e,source:{root:n.root,name:n.name,headSha:n.headSha},targets:_w(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:Pw(t),report:t.sections}}},WN=async e=>{let t=await ki(),r=FN(t),n=await Tw(r),o=await LN(r),s=$w(t,e.targets??[]),i=await np(r,o),a=await Aw(i,s,!!e.manifestOnly);return{source:i,sourceRows:n,plans:a}},cp=async(e={})=>{let{source:t,sourceRows:r,plans:n}=await WN(e),o=n.map(m=>({plan:m,applied:!1})),s={commit:e.commit,manifestOnly:e.manifestOnly},i=e.check?"check":"preview",a=op(r,o,{...s,mode:i}),c=!n.some(m=>m.status==="changed");if(e.check||c)return ap({mode:i,report:a,outcomes:o,source:t,print:!0});let l=!e.confirmedCommand&&!K();if(l&&!Dw.stdin.isTTY)return tt(a),ap({mode:"preview",report:a,outcomes:o,source:t,print:!1});l&&tt({...a,hints:[]}),await L(e.confirmedCommand,`Sync vendored files from ${t.name} into these targets?`,{plan:_w(n),throwOnDecline:!0});let u=await VN(t,n,e),p=op(r,u,{...s,mode:"applied"});if(l){let m=u.filter(f=>f.applied).map(f=>f.plan.name);tt(xw(a,p,m))}return ap({mode:"applied",report:p,outcomes:u,source:t,print:!l})};var $a=(e,t=!0)=>({line:e,reproducible:t});import Aa from"node:fs";import GN from"node:os";import JN from"node:path";import Lw from"node:process";var Oa="INFRA_KIT_SESSION_REPORT",lp=null,Mw=!1,jw=[],Bw=(e=Lw.env)=>{Mw||(lp=e[Oa]??null,Mw=!0,delete e[Oa])};var Uw=(e,t)=>{if(!lp)return;let r=e.summary??(jw.length>0?[...jw]:void 0),n={...e,...r?{summary:r}:{}},o=t?.write??((s,i)=>{Aa.writeFileSync(s,i)});try{o(lp,JSON.stringify(n))}catch{}},Fw=0,Vw=e=>{let t=e?.tmpdir?.()??GN.tmpdir(),r=e?.pid??Lw.pid;return Fw+=1,JN.join(t,`infra-kit-session-${r}-${Fw}.json`)},Ww=(e,t)=>{if(!(t?.exists??(i=>Aa.existsSync(i)))(e))return null;let n=t?.read??(i=>Aa.readFileSync(i,"utf-8")),o=t?.unlink??(i=>Aa.unlinkSync(i)),s;try{s=n(e)}catch{return null}finally{try{o(e)}catch{}}try{return JSON.parse(s)}catch{return null}};var up=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(up)};var dp=e=>{e.options.some(r=>r.long==="--debug")||e.option("--debug","Raise the log level to debug (logs stay on stderr)"),e.commands.forEach(dp)};var zN=(e,t)=>[...t,e],XN=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 lg(()=>Li({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&&($e.exitCode=1)}),Jw=e=>($e.stdout.write(`${e.structuredContent.filePath}
447
- `),$(e)),ZN=e=>e.description("List all release branches").action(async()=>{$(await Gi())}),QN=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".',zN,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let n=t.release.map(Vl),o=n.length>0?n:void 0;$(await Yi({releases:o,confirmedCommand:t.yes}))}),e_=e=>{if(e==="")return e;try{return dr(e)}catch(t){throw t instanceof wn?new HN(t.message):t}},t_=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)',e_).option("-y, --yes","Skip confirmation prompt").action(async t=>{$(await zi({version:t.version,description:t.description,releaseDate:t.releaseDate,confirmedCommand:t.yes}))}),Kw=e=>e.option("-f, --from <where>",`Where the deploy runs: ${Wt.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"),r_=e=>Kw(e).description("Deploy every service to any environment, in CI or from this machine").action(async t=>{$(await Jd({from:t.from,version:t.version,env:t.env,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),n_=e=>Kw(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 Kd({from:t.from,version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),o_=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 Ui({version:t.version,confirmedCommand:t.yes}))}),s_=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 Qi({version:t.version,moveIssuesTo:t.moveIssuesTo,skipJira:t.skipJira,confirmedCommand:t.yes}))}),i_=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{$(await ga({confirmedCommand:t.yes}))}),a_=e=>e.description("Add git worktrees for release branches or feature 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("-f, --feature <names>","Feature worktrees by comma, each on a feature/<name> branch, e.g. checkout-v2").option("-b, --base <branch>","Base for new feature branches: dev (default; the default branch without one), main, or a release, e.g. 1.4.0").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=>{$(await da({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature,base:t.base,githubDesktop:t.githubDesktop,orca:t.orca}))}),c_=e=>e.description("List all git worktrees with detailed information").action(async()=>{$(await pa())}),l_=e=>e.description("Remove git worktrees for release or feature branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release and feature worktrees").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-f, --feature <names>","Feature worktrees by comma, e.g. checkout-v2").option("--self","Remove the worktree this runs in, closing its Orca tabs (handed off to Orca)").action(async t=>{$(await fa({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature,self:t.self}))}),u_=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 qd({init:t.init}))}),d_=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await ca();$(t),t.structuredContent.ok||($e.exitCode=1)}),p_=e=>e.description("Mirror vendorSource files from the ~/.infra-kit/vendor.json source into every target, from any directory").argument("[targets...]","Narrow to these target names from ~/.infra-kit/vendor.json").option("-y, --yes","Apply the previewed plan").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 cp({targets:t,confirmedCommand:r.yes,check:r.check,commit:r.commit,manifestOnly:r.manifestOnly})}catch(a){if(!pt(a))throw a;d.info("Operation cancelled.");return}$(n);let{failed:o,changed:s,mode:i}=n.structuredContent;(o||i==="check"&&s)&&($e.exitCode=1)}),m_=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{$(await xd())}),f_=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{$(await Td())}),g_=new Set(["version"]),Ia=e=>{let t=[];for(let r=e;r&&r.parent;r=r.parent)t.unshift(r.name());return t.join(" ")},pp=()=>{let e=new KN().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");XN(t.command("merge-dev")),ZN(t.command("list")),QN(t.command("create")),t_(t.command("edit")),r_(t.command("deploy-all")),n_(t.command("deploy-selected")),o_(t.command("deliver")),s_(t.command("remove"));let r=e.command("worktrees").description("Git worktree management commands");a_(r.command("add")),c_(r.command("list")),l_(r.command("remove")),i_(r.command("sync"));let n=e.command("config").description("Manage infra-kit configuration files");m_(n.command("path")),f_(n.command("edit")),e.command("config-get").description("Print the fully merged infra-kit config (project + user-global + per-project override layers)").argument("[key]","Print only this top-level key (e.g. worktrees)").action(async a=>{$(await ei({key:a}))}),e.command("config-set").description("Set a top-level key in this project\u2019s per-machine config override (validated before it is kept)").argument("<key>","Top-level config key (e.g. protectedEnvs, worktrees)").argument("<value>",`JSON value, or a bare string (e.g. cli-only, '{"openInOrca":true}')`).option("--global","Write ~/.infra-kit/infra-kit.json (every project on this machine) instead").action(async(a,c,l)=>{$(await Vc({key:a,value:c,global:l.global}))}),e.command("config-unset").description("Remove a top-level key from this project\u2019s per-machine config override").argument("<key>","Top-level config key").option("--global","Remove it from ~/.infra-kit/infra-kit.json instead").action(async(a,c)=>{$(await Cd({key:a,global:c.global}))});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 wa({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 wa({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){d.error("--design requires --fix (it scaffolds DESIGN.md; there is nothing to scaffold without a fix run)"),$e.exitCode=1;return}let c=await Xs({all:a.all,root:a.root,fix:a.fix,design:a.design});$(c);let{allPassed:l,fixed:u}=c.structuredContent,p=(u??[]).some(m=>m.action==="failed");(!l||p)&&($e.exitCode=1)}),e.command("deploy-sync").description("Generate the deploy-all / deploy-selected workflows from infra-kit.deploy.ts").option("--check","Compare only; exit 1 when the committed workflows differ from the manifest").action(async a=>{let c=await Ld({check:a.check});$(c),c.structuredContent.ok||($e.exitCode=1)});let i=e.command("vendor").description("Mirror and verify the vendored starter files");return d_(i.command("check")),u_(i.command("config")),p_(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 Ai({fix:!!a.fix});zt.enabled||Zc(c.structuredContent.checks,{ascii:!!a.ascii}),c.structuredContent.checks.some(u=>u.name==="plugin installed"&&u.status==="fail")&&($e.exitCode=1),$(c)}),e.command("dev").description("Run local dev servers for an app (or every app); api + ui").argument("[app]","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"),u=!!($e.stdout.isTTY&&$e.stdin.isTTY);await l({...c,appName:a},u,zt.enabled)}),e.command("dev-status").description("Show what `infra-kit dev` currently has running (reads dev-context fragments; starts nothing)").action(async()=>{$(await ti())}),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)=>{$(await Ni({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)").addOption(new Gw("--unattended","Background run: no tool installs, no writes to git-tracked files").hideHelp()).addOption(new Gw("--auto","Unattended setup for the machine and every infra-kit project, once per version").hideHelp()).action(async a=>{if(a.auto){$(await zu());return}$(await na({tools:a.tools,update:a.update,skipTools:a.skipTools,ascii:!!a.ascii,unattended:a.unattended}))}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{$(await la())}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{$(await ji())}),e.command("env-list").description("List available Doppler configs for the detected project, and whether a service token resolves for each").action(async()=>{$(await Wm())}),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). Omitted: the picker opens on defaultEnv; headless runs load it").action(async a=>{Jw(await Xa({config:a.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{Jw(await Mi())}),e.command("env-token-set").description("Add or replace the Doppler service token for an env (masked prompt or piped stdin; validated against Doppler before writing)").argument("[env]","Environment / Doppler config the token is scoped to (e.g. dev); omitted \u2192 picker, incl. a new env").option("--stdin","Read the token from stdin (implied when stdin is piped, e.g. `op read \u2026 | ik env-token-set dev`)").option("--from-env <var>","Read the token from the named environment variable (the NAME, never the value)").option("--from-file <path>","Import several tokens from a `<env>=<token>` file, each validated on its own").option("--force","Store even when the token\u2019s scope could not be verified. Never overrides a real mismatch.").action(async(a,c)=>{if(c.fromFile){if(a||c.stdin||c.fromEnv)throw new Error("--from-file names its envs itself \u2014 drop <env>, --stdin and --from-env.");$(await Wd({fromFile:c.fromFile,force:c.force}));return}$(await Vd({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 Fi({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 Bd({env:a}))}),e.commands.forEach(qp),up(e),dp(e),e.hook("preAction",async(a,c)=>{let{C:l}=e.opts();l!==void 0&&YN(qN($e.cwd(),l)),h.start(Ia(c)),zt.enabled=!!c.optsWithGlobals().json,zt.enabled&&(d.level="warn"),_.source=Cs({env:$e.env,stdinIsTTY:$e.stdin.isTTY===!0,flag:!!c.optsWithGlobals().agent}),g_.has(Ia(c))||await Rl()}),e.hook("postAction",(a,c)=>{let l=Ia(c);if(Sd(l))return;let p=h.snapshot()?.formattedOptions??"",m=p?` ${p}`:"",f=`infra-kit ${l}${m}`;Uw({equivalent:$a(f,!0)})}),e};import h_ from"node:process";var y_={exit:h_.exit,emit:$,logger:d},Hw=(e,t=y_)=>Se(e)?(t.logger.info("Operation cancelled."),t.exit(0)):e instanceof C?(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 mp=(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 v_ from"node:fs";import fp from"node:path";import An from"node:process";var zw=new Set([...um,In,"XDG_CACHE_HOME","CLAUDE_PROJECT_DIR","CLAUDE_PLUGIN_ROOT"]),Xw=null,Da=new Set,gp=null,qw=!1;var Yw=e=>{try{return v_.statSync(e)}catch{return null}},w_=()=>{if(qw)return null;try{return Tr()}catch{return qw=!0,d.debug(`session-env: ${In} unset \u2014 no overlay`),null}},k_=e=>{let t=fp.join(e,Pr),r=fp.join(e,vs),n=Yw(t),o=Yw(r);return n&&!(o&&o.mtimeMs>n.mtimeMs)?Pp(fp.join(e,ws),An.cwd())?{kind:"load",file:t,signature:`load:${n.ino}:${n.mtimeMs}:${n.size}`}:{kind:"none",signature:"none"}:o?{kind:"clear",file:r,signature:`clear:${o.ino}:${o.mtimeMs}`}:{kind:"none",signature:"none"}},b_=e=>e.kind==="load"?{kind:"load",vars:Sp(e.file),signature:e.signature}:e.kind==="clear"?{kind:"clear",unset:Ep(e.file),signature:e.signature}:e;var R_=()=>{let e=w_();if(e===null)return{kind:"no-session"};let t=k_(e);return t.signature===gp?null:b_(t)},S_=()=>{for(let e of Da){let t=Xw[e];t===void 0?delete An.env[e]:An.env[e]=t}Da.clear()},E_=(e,t,r)=>{if(zw.has(t)){e.skipped.push(t);return}An.env[t]=r,Da.add(t),e.set.push(t)},P_=(e,t)=>{if(zw.has(t)){e.skipped.push(t);return}delete An.env[t],Da.add(t),e.unset.push(t)},x_=e=>{let t={set:[],unset:[],skipped:[]};if(e.kind==="load")for(let[r,n]of Object.entries(e.vars))E_(t,r,n);if(e.kind==="clear")for(let r of e.unset)P_(t,r);return t},T_=e=>e.kind==="load"?`load, ${Object.keys(e.vars).length} vars`:e.kind,hp=(e=R_())=>{if(Xw??={...An.env},e===null||e.kind==="no-session"||e.signature===gp)return{set:[],unset:[],changed:!1};S_();let{set:t,unset:r,skipped:n}=x_(e);return gp=e.signature,n.length>0&&d.warn(`session-env: skipped protected names [${n.join(", ")}]`),d.debug(`session-env applied: set [${t.join(", ")}] unset [${r.join(", ")}] (${T_(e)})`),{set:t,unset:r,changed:!0}};import{chalkStderr as q_}from"chalk";import{spawn as Y_}from"node:child_process";import Ae from"node:process";import{Chalk as C_}from"chalk";var On=new C_({level:1}),He={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."},$_={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"}},Zw={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},Qw={unicode:"\u2500",ascii:"-"},A_=3,yp=e=>e,O_={ok:e=>On.green(e),findings:e=>On.yellow(e),failed:e=>On.red(e),cancelled:e=>On.gray(e)},wp=e=>e?{dim:t=>On.dim(t),bold:t=>On.bold(t)}:{dim:yp,bold:yp},I_=(e,t)=>e?O_[t]:yp,vp=e=>[...e].length,D_=(e,t)=>{if(t==null)return e;let r=Math.max(0,t-1);return vp(e)<=r?e:[...e].slice(0,r).join("")},ek=e=>{let t=wp(e.color===!0).dim,r=$_[e.canSuspend?"suspend":"plain"],n=e.ascii===!0?r.ascii:r.unicode;return t(D_(n,e.width))},tk=(e,t={})=>{let r=wp(t.color===!0);return`${r.dim(He.reproPrefix.trim())} ${r.bold(e)}`},N_=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,__=(e,t)=>e==="findings"?t!=null?`${t} ${He.findingsSuffix}`:He.findingsPlain:{ok:He.ok,failed:He.failed,cancelled:He.cancelled}[e],M_=(e,t,r,n)=>{if(t==null)return"";let o=t-2-e;return o<A_?"":` ${n(r.repeat(o))}`},rk=e=>{let t=e.color===!0,r=wp(t),n=I_(t,e.outcome),o=e.ascii===!0,s=e.equivalent.reproducible?He.reproPrefix:He.nonReproPrefix,i=o?Zw[e.outcome].ascii:Zw[e.outcome].unicode,a=__(e.outcome,e.findingsCount),c=[N_(e.durationMs)],l=e.summary?.[0]?.split(`
448
- `)[0];l!=null&&l.length>0&&c.push(l);let u=`${i} ${a}`,p=`${He.sep}${c.join(He.sep)}`,m=vp(u)+vp(p),f=M_(m,e.width,o?Qw.ascii:Qw.unicode,r.dim),y=[`${n(u)}${r.dim(p)}${f}`];return e.showEquivalent!==!1&&y.unshift(`${r.dim(s.trim())} ${r.bold(e.equivalent.line)}`),e.envNotice===!0&&y.push(r.dim(He.envNotice)),y.join(`
449
- `)};var j_=new Set([130,143]),nk=(e,t,r,n=!1)=>r?t!=null||e===0?"ok":"findings":n&&e!=null&&j_.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import F_ from"node:process";var L_={3:"quit",4:"quit",26:"suspend",27:"quit"},B_=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":L_[t]??"continue"},U_=150,V_="\r\x1B[2K",W_=`\r
450
- `,ok=(e,t)=>{sk(e),e.stdin.on("data",t),e.listener=t},sk=e=>{e.listener!==null&&(e.stdin.off("data",e.listener),e.listener=null)},ik=(e,t)=>{km(),e.stdin.setRawMode(!0),e.stdin.isPaused()&&e.stdin.resume(),ok(e,t)},ak=e=>{e.hintOnScreen&&(e.hintOnScreen=!1,e.deps.write(V_)),sk(e),e.stdin.isTTY===!0&&e.stdin.isRaw===!0&&e.stdin.setRawMode(!1),bm()},G_=e=>{e.settled||(e.settled=!0,ak(e))},ck=(e,t)=>{let r=ek({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},J_=async e=>{await new Promise(t=>{setTimeout(t,e)})},K_=(e,t,r)=>{ak(e),t(),ik(e,r),ck(e,W_)},H_=async e=>new Promise(t=>{let r=n=>{let o=B_(n),s=e.deps.suspend;if(o==="quit"){t("quit");return}if(o==="suspend"&&s!==void 0){K_(e,s,r);return}t("palette")};ok(e,r),ck(e,"")}),lk=async(e,t)=>{if(e.quitRequested())return"quit";let r=t.stdin??F_.stdin;if(r.isTTY!==!0)return"palette";let n={deps:t,stdin:r,listener:null,hintOnScreen:!1,settled:!1};try{return ik(n,()=>{}),e.armed(),await J_(t.drainMs??U_),await H_(n)}finally{G_(n)}};import uk from"node:process";var qt={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},dk=(e,t)=>{let r=t?.write??(s=>{uk.stderr.write(s)}),n=t?.stdin??uk.stdin,o=[qt.saveCursor,qt.scrollRegion,qt.restoreCursor,qt.column,qt.sgr,qt.cursor,qt.wrap];e.entersAltScreen===!0&&o.push(qt.primaryBuffer),r(o.join("")),n.isTTY===!0&&n.isRaw===!0&&n.setRawMode?.(!1)};var pk=e=>`infra-kit ${e.groupPath.join(" ")}`,z_=()=>{X_();let e=Ae.stderr.columns;return e!=null&&e>0?e:void 0},X_=()=>{let e=Ae.stderr;typeof e._refreshSize=="function"&&e._refreshSize()},Z_=e=>new Promise(t=>{e.on("exit",(r,n)=>{t({code:r,signal:n})}),e.on("error",()=>{t({code:1,signal:null})})}),Q_=async(e,t,r)=>{let n=Vw(),o={...t.env,[Oa]:n,INFRA_KIT_NO_AUTO_UPDATE:"1"},s=t.now(),i={code:1,signal:null};r();try{let p=t.spawn(Ae.execPath,[t.cliPath,...e.groupPath],{stdio:"inherit",env:o});i=await Z_(p)}catch{i={code:1,signal:null}}finally{t.resetTerminal({entersAltScreen:e.entersAltScreen})}let a=Ww(n),c=nk(i.code,i.signal,a!=null,e.longRunning),l=pk(e),u=a?.equivalent??$a(l,!0);return rk({equivalent:u,outcome:c,durationMs:t.now()-s,summary:a?.summary,envNotice:e.sessionEnvNotice,ascii:t.ascii,color:t.color,width:t.columns(),showEquivalent:!(u.reproducible&&u.line===l)})},eM=1e3,tM=(e,t)=>e!=null&&t-e<=eM,kp=e=>{e.resetTerminal(),e.exit(0)},rM=(e,t)=>{let r=null,n=!1,o=()=>{let c=e();if(c==="child"){r=t.now();return}c!=="pause"&&kp(t)},s=()=>{let c=e();if(c==="palette"){kp(t);return}if(!tM(r,t.now())){if(c==="pause"){kp(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}},mk=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),nM=Ae.platform==="win32"?void 0:()=>{Rm()},oM=(e,t)=>r=>lk(r,{write:e,columns:t.columns,ascii:t.ascii,color:t.color,suspend:nM}),fk=async(e,t)=>{let r={spawn:t.spawn??Y_,now:t.now??(()=>Date.now()),env:t.env??Ae.env,cliPath:t.cliPath,ascii:t.ascii??!(Ae.stdout.isTTY&&Ae.env.TERM!=="dumb"),color:t.color??q_.level>0,columns:t.columns??z_,resetTerminal:t.resetTerminal??(u=>{dk(u)})},n=t.write??(u=>Ae.stderr.write(u)),o="palette",s=t.signals??{register:(u,p)=>{Ae.on(u,p)},unregister:(u,p)=>{Ae.off(u,p)},exit:u=>{Ae.exit(u)},raise:u=>{Ae.kill(Ae.pid,u)},now:()=>Date.now(),resetTerminal:()=>{o==="pause"&&n("\r\x1B[2K"),r.resetTerminal({entersAltScreen:!1})}},i={dispose:()=>{},childStarted:()=>{},quitRequested:()=>!1},a=t.installSignals===!1?i:rM(()=>o,s),c={armed:()=>{o="pause"},quitRequested:()=>a.quitRequested()},l=t.afterRun??oM(n,r);try{for(;;){if(a.quitRequested())return;o="palette";let u=await t.renderPalette(e);if(u==null)return;let p=t.resolveCommand(u);if(!p)continue;let m=tk(pk(p),{color:r.color});n(`
446
+ `)},JN=async(e,t,r)=>r?(Dw(t,$n(t)),Zd(t.root,e)):(await Xd({source:e,plan:t,onBeforeFirstWrite:o=>{Dw(t,o)}})).touched,KN=async(e,t,r)=>{if(t.status!=="changed")return{plan:t,applied:!1};let n;try{n=await JN(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 ep(t.root,n,Qd(e.name,e.headSha));return{plan:t,applied:!0,commit:o}},HN=async(e,t,r)=>{let n=[];for(let o of t)n.push(await KN(e,o,r));return n},jw=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})),cp=({mode:e,report:t,outcomes:r,source:n,print:o})=>{o&&rt(t);let s=r.map(a=>a.plan);return{structuredContent:{mode:e,source:{root:n.root,name:n.name,headSha:n.headSha},targets:jw(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:Tw(t),report:t.sections}}},qN=async e=>{let t=await ki(),r=WN(t),n=await $w(r),o=await GN(r),s=Ow(t,e.targets??[]),i=await op(r,o),a=await Iw(i,s,!!e.manifestOnly);return{source:i,sourceRows:n,plans:a}},lp=async(e={})=>{let{source:t,sourceRows:r,plans:n}=await qN(e),o=n.map(m=>({plan:m,applied:!1})),s={commit:e.commit,manifestOnly:e.manifestOnly},i=e.check?"check":"preview",a=sp(r,o,{...s,mode:i}),c=!n.some(m=>m.status==="changed");if(e.check||c)return cp({mode:i,report:a,outcomes:o,source:t,print:!0});let l=!e.confirmedCommand&&!H();if(l&&!_w.stdin.isTTY)return rt(a),cp({mode:"preview",report:a,outcomes:o,source:t,print:!1});l&&rt({...a,hints:[]}),await L(e.confirmedCommand,`Sync vendored files from ${t.name} into these targets?`,{plan:jw(n),throwOnDecline:!0});let u=await HN(t,n,e),p=sp(r,u,{...s,mode:"applied"});if(l){let m=u.filter(f=>f.applied).map(f=>f.plan.name);rt(Cw(a,p,m))}return cp({mode:"applied",report:p,outcomes:u,source:t,print:!l})};var $a=(e,t=!0)=>({line:e,reproducible:t});import Aa from"node:fs";import YN from"node:os";import zN from"node:path";import Uw from"node:process";var Oa="INFRA_KIT_SESSION_REPORT",up=null,Fw=!1,Lw=[],Vw=(e=Uw.env)=>{Fw||(up=e[Oa]??null,Fw=!0,delete e[Oa])};var Ww=(e,t)=>{if(!up)return;let r=e.summary??(Lw.length>0?[...Lw]:void 0),n={...e,...r?{summary:r}:{}},o=t?.write??((s,i)=>{Aa.writeFileSync(s,i)});try{o(up,JSON.stringify(n))}catch{}},Bw=0,Gw=e=>{let t=e?.tmpdir?.()??YN.tmpdir(),r=e?.pid??Uw.pid;return Bw+=1,zN.join(t,`infra-kit-session-${r}-${Bw}.json`)},Jw=(e,t)=>{if(!(t?.exists??(i=>Aa.existsSync(i)))(e))return null;let n=t?.read??(i=>Aa.readFileSync(i,"utf-8")),o=t?.unlink??(i=>Aa.unlinkSync(i)),s;try{s=n(e)}catch{return null}finally{try{o(e)}catch{}}try{return JSON.parse(s)}catch{return null}};var dp=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(dp)};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 t_=(e,t)=>[...t,e],r_=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 ug(()=>Li({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&&($e.exitCode=1)}),Hw=e=>($e.stdout.write(`${e.structuredContent.filePath}
447
+ `),$(e)),n_=e=>e.description("List all release branches").action(async()=>{$(await Gi())}),o_=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".',t_,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let n=t.release.map(Vl),o=n.length>0?n:void 0;$(await Yi({releases:o,confirmedCommand:t.yes}))}),s_=e=>{if(e==="")return e;try{return dr(e)}catch(t){throw t instanceof wn?new ZN(t.message):t}},i_=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)',s_).option("-y, --yes","Skip confirmation prompt").action(async t=>{$(await zi({version:t.version,description:t.description,releaseDate:t.releaseDate,confirmedCommand:t.yes}))}),qw=e=>e.option("-f, --from <where>",`Where the deploy runs: ${Wt.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"),a_=e=>qw(e).description("Deploy every service to any environment, in CI or from this machine").action(async t=>{$(await Jd({from:t.from,version:t.version,env:t.env,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),c_=e=>qw(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 Kd({from:t.from,version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),l_=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 Ui({version:t.version,confirmedCommand:t.yes}))}),u_=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 Qi({version:t.version,moveIssuesTo:t.moveIssuesTo,skipJira:t.skipJira,confirmedCommand:t.yes}))}),d_=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{$(await ga({confirmedCommand:t.yes}))}),p_=e=>e.description("Add git worktrees for release branches or feature 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("-f, --feature <names>","Feature worktrees by comma, each on a feature/<name> branch, e.g. checkout-v2").option("-b, --base <branch>","Base for new feature branches: dev (default; the default branch without one), main, or a release, e.g. 1.4.0").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=>{$(await da({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature,base:t.base,githubDesktop:t.githubDesktop,orca:t.orca}))}),m_=e=>e.description("List all git worktrees with detailed information").action(async()=>{$(await pa())}),f_=e=>e.description("Remove git worktrees for release or feature branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release and feature worktrees").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-f, --feature <names>","Feature worktrees by comma, e.g. checkout-v2").option("--self","Remove the worktree this runs in, closing its Orca tabs (handed off to Orca)").action(async t=>{$(await fa({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature,self:t.self}))}),g_=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 qd({init:t.init}))}),h_=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await ca();$(t),t.structuredContent.ok||($e.exitCode=1)}),y_=e=>e.description("Mirror vendorSource files from the ~/.infra-kit/vendor.json source into every target, from any directory").argument("[targets...]","Narrow to these target names from ~/.infra-kit/vendor.json").option("-y, --yes","Apply the previewed plan").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 lp({targets:t,confirmedCommand:r.yes,check:r.check,commit:r.commit,manifestOnly:r.manifestOnly})}catch(a){if(!pt(a))throw a;d.info("Operation cancelled.");return}$(n);let{failed:o,changed:s,mode:i}=n.structuredContent;(o||i==="check"&&s)&&($e.exitCode=1)}),v_=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{$(await xd())}),w_=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{$(await Td())}),k_=new Set(["version"]),Ia=e=>{let t=[];for(let r=e;r&&r.parent;r=r.parent)t.unshift(r.name());return t.join(" ")},mp=()=>{let e=new XN().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");r_(t.command("merge-dev")),n_(t.command("list")),o_(t.command("create")),i_(t.command("edit")),a_(t.command("deploy-all")),c_(t.command("deploy-selected")),l_(t.command("deliver")),u_(t.command("remove"));let r=e.command("worktrees").description("Git worktree management commands");p_(r.command("add")),m_(r.command("list")),f_(r.command("remove")),d_(r.command("sync"));let n=e.command("config").description("Manage infra-kit configuration files");v_(n.command("path")),w_(n.command("edit")),e.command("config-get").description("Print the fully merged infra-kit config (project + user-global + per-project override layers)").argument("[key]","Print only this top-level key (e.g. worktrees)").action(async a=>{$(await ei({key:a}))}),e.command("config-set").description("Set a top-level key in this project\u2019s per-machine config override (validated before it is kept)").argument("<key>","Top-level config key (e.g. protectedEnvs, worktrees)").argument("<value>",`JSON value, or a bare string (e.g. cli-only, '{"openInOrca":true}')`).option("--global","Write ~/.infra-kit/infra-kit.json (every project on this machine) instead").action(async(a,c,l)=>{$(await Vc({key:a,value:c,global:l.global}))}),e.command("config-unset").description("Remove a top-level key from this project\u2019s per-machine config override").argument("<key>","Top-level config key").option("--global","Remove it from ~/.infra-kit/infra-kit.json instead").action(async(a,c)=>{$(await Cd({key:a,global:c.global}))});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 wa({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 wa({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){d.error("--design requires --fix (it scaffolds DESIGN.md; there is nothing to scaffold without a fix run)"),$e.exitCode=1;return}let c=await Xs({all:a.all,root:a.root,fix:a.fix,design:a.design});$(c);let{allPassed:l,fixed:u}=c.structuredContent,p=(u??[]).some(m=>m.action==="failed");(!l||p)&&($e.exitCode=1)}),e.command("deploy-sync").description("Generate the deploy-all / deploy-selected workflows from infra-kit.deploy.ts").option("--check","Compare only; exit 1 when the committed workflows differ from the manifest").action(async a=>{let c=await Ld({check:a.check});$(c),c.structuredContent.ok||($e.exitCode=1)});let i=e.command("vendor").description("Mirror and verify the vendored starter files");return h_(i.command("check")),g_(i.command("config")),y_(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 Ai({fix:!!a.fix});zt.enabled||Zc(c.structuredContent.checks,{ascii:!!a.ascii}),c.structuredContent.checks.some(u=>u.name==="plugin installed"&&u.status==="fail")&&($e.exitCode=1),$(c)}),e.command("dev").description("Run local dev servers for an app (or every app); api + ui").argument("[app]","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"),u=!!($e.stdout.isTTY&&$e.stdin.isTTY);await l({...c,appName:a},u,zt.enabled)}),e.command("dev-status").description("Show what `infra-kit dev` currently has running (reads dev-context fragments; starts nothing)").action(async()=>{$(await ti())}),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)=>{$(await Ni({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)").addOption(new Kw("--unattended","Background run: no tool installs, no writes to git-tracked files").hideHelp()).addOption(new Kw("--auto","Unattended setup for the machine and every infra-kit project, once per version").hideHelp()).action(async a=>{if(a.auto){$(await zu());return}$(await na({tools:a.tools,update:a.update,skipTools:a.skipTools,ascii:!!a.ascii,unattended:a.unattended}))}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{$(await la())}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{$(await ji())}),e.command("env-list").description("List available Doppler configs for the detected project, and whether a service token resolves for each").action(async()=>{$(await Gm())}),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). Omitted: the picker opens on defaultEnv; headless runs load it").action(async a=>{Hw(await Xa({config:a.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{Hw(await Mi())}),e.command("env-token-set").description("Add or replace the Doppler service token for an env (masked prompt or piped stdin; validated against Doppler before writing)").argument("[env]","Environment / Doppler config the token is scoped to (e.g. dev); omitted \u2192 picker, incl. a new env").option("--stdin","Read the token from stdin (implied when stdin is piped, e.g. `op read \u2026 | ik env-token-set dev`)").option("--from-env <var>","Read the token from the named environment variable (the NAME, never the value)").option("--from-file <path>","Import several tokens from a `<env>=<token>` file, each validated on its own").option("--force","Store even when the token\u2019s scope could not be verified. Never overrides a real mismatch.").action(async(a,c)=>{if(c.fromFile){if(a||c.stdin||c.fromEnv)throw new Error("--from-file names its envs itself \u2014 drop <env>, --stdin and --from-env.");$(await Wd({fromFile:c.fromFile,force:c.force}));return}$(await Vd({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 Fi({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 Bd({env:a}))}),e.commands.forEach(Yp),dp(e),pp(e),e.hook("preAction",async(a,c)=>{let{C:l}=e.opts();l!==void 0&&e_(QN($e.cwd(),l)),h.start(Ia(c)),zt.enabled=!!c.optsWithGlobals().json,zt.enabled&&(d.level="warn"),_.source=Cs({env:$e.env,stdinIsTTY:$e.stdin.isTTY===!0,flag:!!c.optsWithGlobals().agent}),k_.has(Ia(c))||await Rl()}),e.hook("postAction",(a,c)=>{let l=Ia(c);if(Sd(l))return;let p=h.snapshot()?.formattedOptions??"",m=p?` ${p}`:"",f=`infra-kit ${l}${m}`;Ww({equivalent:$a(f,!0)})}),e};import b_ from"node:process";var R_={exit:b_.exit,emit:$,logger:d},Yw=(e,t=R_)=>Se(e)?(t.logger.info("Operation cancelled."),t.exit(0)):e instanceof C?(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 fp=(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 S_ from"node:fs";import gp from"node:path";import On from"node:process";var Zw=new Set([...dm,Dn,"XDG_CACHE_HOME","CLAUDE_PROJECT_DIR","CLAUDE_PLUGIN_ROOT"]),Qw=null,Da=new Set,hp=null,zw=!1;var Xw=e=>{try{return S_.statSync(e)}catch{return null}},E_=()=>{if(zw)return null;try{return Tr()}catch{return zw=!0,d.debug(`session-env: ${Dn} unset \u2014 no overlay`),null}},P_=e=>{let t=gp.join(e,Pr),r=gp.join(e,vs),n=Xw(t),o=Xw(r);return n&&!(o&&o.mtimeMs>n.mtimeMs)?xp(gp.join(e,ws),On.cwd())?{kind:"load",file:t,signature:`load:${n.ino}:${n.mtimeMs}:${n.size}`}:{kind:"none",signature:"none"}:o?{kind:"clear",file:r,signature:`clear:${o.ino}:${o.mtimeMs}`}:{kind:"none",signature:"none"}},x_=e=>e.kind==="load"?{kind:"load",vars:Ep(e.file),signature:e.signature}:e.kind==="clear"?{kind:"clear",unset:Pp(e.file),signature:e.signature}:e;var T_=()=>{let e=E_();if(e===null)return{kind:"no-session"};let t=P_(e);return t.signature===hp?null:x_(t)},C_=()=>{for(let e of Da){let t=Qw[e];t===void 0?delete On.env[e]:On.env[e]=t}Da.clear()},$_=(e,t,r)=>{if(Zw.has(t)){e.skipped.push(t);return}On.env[t]=r,Da.add(t),e.set.push(t)},A_=(e,t)=>{if(Zw.has(t)){e.skipped.push(t);return}delete On.env[t],Da.add(t),e.unset.push(t)},O_=e=>{let t={set:[],unset:[],skipped:[]};if(e.kind==="load")for(let[r,n]of Object.entries(e.vars))$_(t,r,n);if(e.kind==="clear")for(let r of e.unset)A_(t,r);return t},I_=e=>e.kind==="load"?`load, ${Object.keys(e.vars).length} vars`:e.kind,yp=(e=T_())=>{if(Qw??={...On.env},e===null||e.kind==="no-session"||e.signature===hp)return{set:[],unset:[],changed:!1};C_();let{set:t,unset:r,skipped:n}=O_(e);return hp=e.signature,n.length>0&&d.warn(`session-env: skipped protected names [${n.join(", ")}]`),d.debug(`session-env applied: set [${t.join(", ")}] unset [${r.join(", ")}] (${I_(e)})`),{set:t,unset:r,changed:!0}};import{chalkStderr as Q_}from"chalk";import{spawn as eM}from"node:child_process";import Ae from"node:process";import{Chalk as D_}from"chalk";var In=new D_({level:1}),qe={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."},N_={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"}},ek={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},tk={unicode:"\u2500",ascii:"-"},__=3,vp=e=>e,M_={ok:e=>In.green(e),findings:e=>In.yellow(e),failed:e=>In.red(e),cancelled:e=>In.gray(e)},kp=e=>e?{dim:t=>In.dim(t),bold:t=>In.bold(t)}:{dim:vp,bold:vp},j_=(e,t)=>e?M_[t]:vp,wp=e=>[...e].length,F_=(e,t)=>{if(t==null)return e;let r=Math.max(0,t-1);return wp(e)<=r?e:[...e].slice(0,r).join("")},rk=e=>{let t=kp(e.color===!0).dim,r=N_[e.canSuspend?"suspend":"plain"],n=e.ascii===!0?r.ascii:r.unicode;return t(F_(n,e.width))},nk=(e,t={})=>{let r=kp(t.color===!0);return`${r.dim(qe.reproPrefix.trim())} ${r.bold(e)}`},L_=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,B_=(e,t)=>e==="findings"?t!=null?`${t} ${qe.findingsSuffix}`:qe.findingsPlain:{ok:qe.ok,failed:qe.failed,cancelled:qe.cancelled}[e],U_=(e,t,r,n)=>{if(t==null)return"";let o=t-2-e;return o<__?"":` ${n(r.repeat(o))}`},ok=e=>{let t=e.color===!0,r=kp(t),n=j_(t,e.outcome),o=e.ascii===!0,s=e.equivalent.reproducible?qe.reproPrefix:qe.nonReproPrefix,i=o?ek[e.outcome].ascii:ek[e.outcome].unicode,a=B_(e.outcome,e.findingsCount),c=[L_(e.durationMs)],l=e.summary?.[0]?.split(`
448
+ `)[0];l!=null&&l.length>0&&c.push(l);let u=`${i} ${a}`,p=`${qe.sep}${c.join(qe.sep)}`,m=wp(u)+wp(p),f=U_(m,e.width,o?tk.ascii:tk.unicode,r.dim),y=[`${n(u)}${r.dim(p)}${f}`];return e.showEquivalent!==!1&&y.unshift(`${r.dim(s.trim())} ${r.bold(e.equivalent.line)}`),e.envNotice===!0&&y.push(r.dim(qe.envNotice)),y.join(`
449
+ `)};var V_=new Set([130,143]),sk=(e,t,r,n=!1)=>r?t!=null||e===0?"ok":"findings":n&&e!=null&&V_.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import W_ from"node:process";var G_={3:"quit",4:"quit",26:"suspend",27:"quit"},J_=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":G_[t]??"continue"},K_=150,H_="\r\x1B[2K",q_=`\r
450
+ `,ik=(e,t)=>{ak(e),e.stdin.on("data",t),e.listener=t},ak=e=>{e.listener!==null&&(e.stdin.off("data",e.listener),e.listener=null)},ck=(e,t)=>{bm(),e.stdin.setRawMode(!0),e.stdin.isPaused()&&e.stdin.resume(),ik(e,t)},lk=e=>{e.hintOnScreen&&(e.hintOnScreen=!1,e.deps.write(H_)),ak(e),e.stdin.isTTY===!0&&e.stdin.isRaw===!0&&e.stdin.setRawMode(!1),Rm()},Y_=e=>{e.settled||(e.settled=!0,lk(e))},uk=(e,t)=>{let r=rk({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},z_=async e=>{await new Promise(t=>{setTimeout(t,e)})},X_=(e,t,r)=>{lk(e),t(),ck(e,r),uk(e,q_)},Z_=async e=>new Promise(t=>{let r=n=>{let o=J_(n),s=e.deps.suspend;if(o==="quit"){t("quit");return}if(o==="suspend"&&s!==void 0){X_(e,s,r);return}t("palette")};ik(e,r),uk(e,"")}),dk=async(e,t)=>{if(e.quitRequested())return"quit";let r=t.stdin??W_.stdin;if(r.isTTY!==!0)return"palette";let n={deps:t,stdin:r,listener:null,hintOnScreen:!1,settled:!1};try{return ck(n,()=>{}),e.armed(),await z_(t.drainMs??K_),await Z_(n)}finally{Y_(n)}};import pk from"node:process";var qt={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},mk=(e,t)=>{let r=t?.write??(s=>{pk.stderr.write(s)}),n=t?.stdin??pk.stdin,o=[qt.saveCursor,qt.scrollRegion,qt.restoreCursor,qt.column,qt.sgr,qt.cursor,qt.wrap];e.entersAltScreen===!0&&o.push(qt.primaryBuffer),r(o.join("")),n.isTTY===!0&&n.isRaw===!0&&n.setRawMode?.(!1)};var fk=e=>`infra-kit ${e.groupPath.join(" ")}`,tM=()=>{rM();let e=Ae.stderr.columns;return e!=null&&e>0?e:void 0},rM=()=>{let e=Ae.stderr;typeof e._refreshSize=="function"&&e._refreshSize()},nM=e=>new Promise(t=>{e.on("exit",(r,n)=>{t({code:r,signal:n})}),e.on("error",()=>{t({code:1,signal:null})})}),oM=async(e,t,r)=>{let n=Gw(),o={...t.env,[Oa]:n,INFRA_KIT_NO_AUTO_UPDATE:"1"},s=t.now(),i={code:1,signal:null};r();try{let p=t.spawn(Ae.execPath,[t.cliPath,...e.groupPath],{stdio:"inherit",env:o});i=await nM(p)}catch{i={code:1,signal:null}}finally{t.resetTerminal({entersAltScreen:e.entersAltScreen})}let a=Jw(n),c=sk(i.code,i.signal,a!=null,e.longRunning),l=fk(e),u=a?.equivalent??$a(l,!0);return ok({equivalent:u,outcome:c,durationMs:t.now()-s,summary:a?.summary,envNotice:e.sessionEnvNotice,ascii:t.ascii,color:t.color,width:t.columns(),showEquivalent:!(u.reproducible&&u.line===l)})},sM=1e3,iM=(e,t)=>e!=null&&t-e<=sM,bp=e=>{e.resetTerminal(),e.exit(0)},aM=(e,t)=>{let r=null,n=!1,o=()=>{let c=e();if(c==="child"){r=t.now();return}c!=="pause"&&bp(t)},s=()=>{let c=e();if(c==="palette"){bp(t);return}if(!iM(r,t.now())){if(c==="pause"){bp(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}},gk=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),cM=Ae.platform==="win32"?void 0:()=>{Sm()},lM=(e,t)=>r=>dk(r,{write:e,columns:t.columns,ascii:t.ascii,color:t.color,suspend:cM}),hk=async(e,t)=>{let r={spawn:t.spawn??eM,now:t.now??(()=>Date.now()),env:t.env??Ae.env,cliPath:t.cliPath,ascii:t.ascii??!(Ae.stdout.isTTY&&Ae.env.TERM!=="dumb"),color:t.color??Q_.level>0,columns:t.columns??tM,resetTerminal:t.resetTerminal??(u=>{mk(u)})},n=t.write??(u=>Ae.stderr.write(u)),o="palette",s=t.signals??{register:(u,p)=>{Ae.on(u,p)},unregister:(u,p)=>{Ae.off(u,p)},exit:u=>{Ae.exit(u)},raise:u=>{Ae.kill(Ae.pid,u)},now:()=>Date.now(),resetTerminal:()=>{o==="pause"&&n("\r\x1B[2K"),r.resetTerminal({entersAltScreen:!1})}},i={dispose:()=>{},childStarted:()=>{},quitRequested:()=>!1},a=t.installSignals===!1?i:aM(()=>o,s),c={armed:()=>{o="pause"},quitRequested:()=>a.quitRequested()},l=t.afterRun??lM(n,r);try{for(;;){if(a.quitRequested())return;o="palette";let u=await t.renderPalette(e);if(u==null)return;let p=t.resolveCommand(u);if(!p)continue;let m=nk(fk(p),{color:r.color});n(`
451
451
  ${m}
452
- `),a.childStarted();let f=await Q_(p,r,()=>{o="child"});if(n(`
452
+ `),a.childStarted();let f=await oM(p,r,()=>{o="child"});if(n(`
453
453
  ${f}
454
- `),await l(c)==="quit")return}}finally{a.dispose()}};Pd();Bw();var vk=pp(),hk=async(e=Oe.argv)=>{hp(),vm(e);try{await vk.parseAsync(e)}catch(t){Hw(t)}},lM=()=>{try{if(Oe.env.INFRA_KIT_NO_LOCATION_WARN||Oe.argv.includes("--json"))return;$p({selfRealPath:aM(yk(import.meta.url)),cwd:Oe.cwd(),env:Oe.env,realpath:ye,home:cM(),exists:iM})&&d.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};lM();Hp((e,t)=>{d.debug(e,t)});El(U.version);var wk=()=>Vv(vk.commands),uM=async()=>{let e=wk(),t=null;try{if(Oe.stdout.isTTY&&Oe.stdin.isTTY){let{runCommandPalette:r}=await import("./boot-LC2ESPY6.js");t=await r(e)}else{let r=mp(e.map(o=>[o.name,o.description])),n=e.flatMap((o,s)=>[...e[s-1]?.group===o.group?[]:[new gk(" "),new gk(`\u2014 ${o.group} \u2014`)],{name:r[s]??o.name,value:o.name}]);t=await I(o=>sM({message:"Select a command to run",choices:n},o),{output:Oe.stderr})}}catch(r){if(!Se(r))throw r}return t},dM=async()=>{let{runCommandPalette:e}=await import("./boot-LC2ESPY6.js"),t=yk(import.meta.url),r=new Map(mr.map(n=>[n.groupPath.join(" "),n]));await fk(wk(),{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(Oe.argv.length<=2){let e={stdoutIsTTY:!!Oe.stdout.isTTY,stdinIsTTY:!!Oe.stdin.isTTY,stderrIsTTY:!!Oe.stderr.isTTY};if(mk(Oe.env,e))await dM();else{let t=await uM();t&&await hk(["node","infra-kit",...t.split(" ")])}}else await hk();
454
+ `),await l(c)==="quit")return}}finally{a.dispose()}};Pd();Vw();var kk=mp(),vk=async(e=Oe.argv)=>{yp(),wm(e);try{await kk.parseAsync(e)}catch(t){Yw(t)}},fM=()=>{try{if(Oe.env.INFRA_KIT_NO_LOCATION_WARN||Oe.argv.includes("--json"))return;Ap({selfRealPath:pM(wk(import.meta.url)),cwd:Oe.cwd(),env:Oe.env,realpath:ve,home:mM(),exists:dM})&&d.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};fM();qp((e,t)=>{d.debug(e,t)});El(U.version);var bk=()=>Wv(kk.commands),gM=async()=>{let e=bk(),t=null;try{if(Oe.stdout.isTTY&&Oe.stdin.isTTY){let{runCommandPalette:r}=await import("./boot-LC2ESPY6.js");t=await r(e)}else{let r=fp(e.map(o=>[o.name,o.description])),n=e.flatMap((o,s)=>[...e[s-1]?.group===o.group?[]:[new yk(" "),new yk(`\u2014 ${o.group} \u2014`)],{name:r[s]??o.name,value:o.name}]);t=await I(o=>uM({message:"Select a command to run",choices:n},o),{output:Oe.stderr})}}catch(r){if(!Se(r))throw r}return t},hM=async()=>{let{runCommandPalette:e}=await import("./boot-LC2ESPY6.js"),t=wk(import.meta.url),r=new Map(mr.map(n=>[n.groupPath.join(" "),n]));await hk(bk(),{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(Oe.argv.length<=2){let e={stdoutIsTTY:!!Oe.stdout.isTTY,stdinIsTTY:!!Oe.stdin.isTTY,stderrIsTTY:!!Oe.stderr.isTTY};if(gk(Oe.env,e))await hM();else{let t=await gM();t&&await vk(["node","infra-kit",...t.split(" ")])}}else await vk();
455
455
  //# sourceMappingURL=cli.js.map