infra-kit 0.15.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
- import{a as Up,d as Yp,f as bs,h as xr,i as Rs,j as tm,k as rm,l as nm,m as om,n as sm,o as im,p as am,q as cm,t as Ta,u as um,v as be}from"./chunk-ZTAUGYJF.js";import{b as Lp,d as Bp,k as Wp,n as Vp}from"./chunk-Y3RW74TE.js";import{a as mt,b as ep,c as ga,d as tp,e as rp,f as np,g as op,h as Pn,i as sp,j as ip,k as ap,l as cp,m as lp,n as En,o as dp,p as up,q as pp,r as mp,s as ha,t as ls,u as ft,v as fp,w as ds,x as gp}from"./chunk-IT6XJWTW.js";import{a as de,b as q,c as wt,d as ys,e as ba,f as vs,g as Ra,h as Cn,i as Gt,j as ws,k as Fp,l as $n,m as An,n as Sa,o as Pa,q as Ea}from"./chunk-MH37P7W4.js";import{b as Sn,c as as,d as fa,e as Yu,f as cs,g as zu,i as Xu,k as Zu,m as he,o as Qu}from"./chunk-AWFGP6GY.js";import{a as qp}from"./chunk-TVG47UHG.js";import{B as $a,F as Aa,G as Oa,a as k,b as S,c as zp,d as Xp,e as Kt,f as Zp,g as Ht,h as em,i as lm,j as On,k as bt,l as Tr,m as Je,n as Ss,o as Rt,p as dm,q as Ps,r as pm,s as mm,t as Ge,x as Ca,z as In}from"./chunk-PP3ZZKB3.js";import{a as h,b as ot,c as Jp,d as Gp,e as O,f as ks,g as V,i as kt,j as Be,k as xa,l as Qp}from"./chunk-4RZM53X7.js";import{$ as yt,A as Rp,B as Sp,C as Pp,D as fs,E as gs,F as $e,G as xn,H as Er,I as hs,J as Ep,K as xp,L as Tp,M as va,N as wa,O as Cp,P as u,Q as Ae,R as Z,S as v,T as $p,U as Ap,V as Op,W as Dp,X as Np,Y as ht,Z as _p,_ as ka,a as Jt,aa as Mp,b as A,ba as jp,c as hp,ca as H,d as N,da as M,e as ye,ea as Tn,f as J,fa as vt,g as us,ga as x,h as yp,i as f,j as vp,k as ps,l as G,m as pe,n as ve,o as wp,p as ya,q as re,r as X,s as ms,t as kp,u as gt,v as me,w as T,x as Le,y as Pr,z as bp}from"./chunk-EZ4DIT5A.js";import{a as Ip}from"./chunk-MFAFQVTW.js";import{a as K}from"./chunk-3UE375II.js";import{a as kr,b as ts,c as rs,d as bn,e as Uu,f as br,g as ns,h as os,i as Ju,j as ss,k as is,l as Gu,m as Ku,n as Hu,o as Rr,p as Rn,q as ge,r as qu,s as Sr}from"./chunk-I23MDR4X.js";import{a as Kp,b as Hp}from"./chunk-QWVLAZ6N.js";import bD,{Separator as Qv}from"@inquirer/select";import{existsSync as RD,realpathSync as SD}from"node:fs";import{homedir as PD}from"node:os";import Ce from"node:process";import{fileURLToPath as tw}from"node:url";import rf from"node:process";import{z as De}from"zod";import bm from"node:fs";import Ar from"node:path";import{packageConfigSchema as hm}from"@slip-stream-kit/config/internal";import ym from"node:fs/promises";import Es from"node:path";import{pathToFileURL as dw}from"node:url";import{z as vm}from"zod";import fm from"node:path";var Dn=["frontend","backend","lib","e2e","mobile"],ow={ui:"frontend",api:"backend",tests:"e2e"},sw="mobile-app",iw=[{type:"e2e",packages:["@playwright/test"]},{type:"mobile",packages:["@capacitor/core","@capacitor/cli"]},{type:"backend",packages:["serverless"]}],aw=(e,t)=>{let r=fm.relative(t,e).split(fm.sep).filter(s=>s!==""&&s!=="."),[n,,o]=r;if(r.length===3&&n==="apps"&&o!==void 0){let s=ow[o];if(s)return s}return r.at(-1)===sw?"mobile":null},cw=e=>{let t=new Set([...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{}),...Object.keys(e.peerDependencies??{})]);for(let n of iw)if(n.packages.some(o=>t.has(o)))return n.type;return t.has("vite")&&t.has("react")&&!!e.scripts?.dev?"frontend":null},Nn=({packageDir:e,repoRoot:t,pkgJson:r,declaredType:n})=>n??aw(e,t)??cw(r)??"lib";var St={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},gm=2e3,Ia={"e2e-test":"pnpm exec playwright test","e2e-test-ui":"pnpm exec playwright test --ui","e2e-test-ui-demo":`E2E_SLOW_MO=\${E2E_SLOW_MO:-${gm}} 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"},_n={requiredScripts:["build","dev","test","qa","infra-kit-check","fix"],requiredFiles:["turbo.json","pnpm-workspace.yaml"],turboTasks:["build","test","ts-check","eslint-check","prettier-check","infra-kit-check"]},Mn=(e,t=St)=>({requiredScripts:e.requiredScripts??[...t.requiredScripts],requiredFiles:e.requiredFiles??[...t.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...t.turboTasks]});import lw from"node:fs/promises";var Re=async e=>{try{return await lw.access(e),!0}catch{return!1}};var ne="infra-kit.config.ts",qt=async e=>{try{let t=await ym.readFile(Es.join(e,"package.json"),"utf-8");return JSON.parse(t)}catch{return{}}},Da=async e=>{let t=await ym.stat(e),o=(await import(`${dw(e).href}?mtime=${Number(t.mtimeMs)}`)).default;if(o===void 0)throw new Error(`${ne} at ${e} has no default export`);return typeof o=="function"?await o():o},Yt=async e=>{let t=Es.join(e,ne);if(await Re(t))try{let n=(await Da(t))?.type;return Dn.find(o=>o===n)}catch{return}},jn=async(e,t=St)=>{let r=Es.join(e,ne);if(!await Re(r))throw new Error(`${ne} not found at ${r}`);let n=await Da(r),o=hm.safeParse(n);if(!o.success)throw new Error(`Invalid ${ne} at ${r}: ${vm.prettifyError(o.error)}`);return Mn(o.data,t)},Cr=async e=>{let t=Es.join(e,ne);if(!await Re(t))return;let r=hm.safeParse(await Da(t));if(!r.success)throw new Error(`Invalid ${ne} at ${t}: ${vm.prettifyError(r.error)}`);return r.data};import wm from"node:fs/promises";import xs from"node:path";import uw from"yaml";var pw="pnpm-workspace.yaml",mw=async e=>(await wm.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(r=>r.isDirectory()).map(r=>xs.join(e,r.name)),fw=async(e,t)=>{let r=[];for(let n of e){if(t==="*"){r.push(...await mw(n));continue}let o=xs.join(n,t);await Re(o)&&r.push(o)}return r},gw=async(e,t)=>{let r=[e];for(let n of t.split("/"))r=await fw(r,n);return r},Se=async e=>{let t=await wm.readFile(xs.join(e,pw),"utf-8"),n=((uw.parse(t)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),o=new Set;for(let s of n){let i=await gw(e,s);for(let a of i)await Re(xs.join(a,"package.json"))&&o.add(a)}return[...o].sort()};import Fn from"node:path";var Ln=async e=>{let t=Fn.resolve(e);for(;t!==Fn.dirname(t);){if(await Re(Fn.join(t,"package.json")))return t;t=Fn.dirname(t)}if(await Re(Fn.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 Ke=(e,t,r)=>{let n=e.indexOf(t),o=e.indexOf(r);return n!==-1&&o!==-1&&o>=n},Pt=(e,t,r)=>{let n=e.indexOf(t),o=e.indexOf(r);if(n===-1||o===-1||o<n)return null;let s=e.slice(0,n).replace(/\n+$/,""),i=e.slice(o+r.length).replace(/^\n+/,"");return s+(i?`
3
- ${i}`:"")},Na=(e,t)=>{let r=e.indexOf(t);if(r===-1)return null;let o=e.slice(r+t.length).match(/^([^\s>]+)/);return o?o[1]:null},km=(e,t,r)=>`${e}
2
+ import{a as Kp,d as Zp,f as $r,g as om,h as St,i as Ps,j as sm,k as im,l as am,m as cm,n as lm,o as dm,p as um,q as pm,t as $a,u as gm,v as Re}from"./chunk-UPOI7HEW.js";import{b as Vp,d as Up,k as Jp,n as Gp}from"./chunk-Y3RW74TE.js";import{a as Ae,b as np,c as ya,d as op,e as sp,f as ip,g as ap,h as Tn,i as cp,j as lp,k as dp,l as up,m as pp,n as Cn,o as mp,p as fp,q as gp,r as hp,s as va,t as ms,u as yt,v as yp,w as fs,x as vp}from"./chunk-IT6XJWTW.js";import{a as ue,b as q,c as bt,d as ks,e as Sa,f as bs,g as Pa,h as On,i as Ht,j as Rs,k as Wp,l as In,m as Dn,n as Ea,o as xa,q as Ta}from"./chunk-MH37P7W4.js";import{b as xn,c as us,d as ha,e as Zu,f as ps,g as Qu,i as ep,k as tp,m as he,o as rp}from"./chunk-AWFGP6GY.js";import{a as Xp}from"./chunk-TVG47UHG.js";import{B as Oa,F as Ia,G as Da,a as k,b as S,c as Qp,d as em,e as qt,f as tm,g as Yt,h as nm,i as mm,j as Nn,k as Pt,l as Ar,m as He,n as Es,o as Et,p as fm,q as xs,r as hm,s as ym,t as qe,x as Aa,z as _n}from"./chunk-RRPSOI5X.js";import{a as h,b as at,c as Hp,d as qp,e as O,f as Ss,g as B,i as Rt,j as Ve,k as Ca,l as rm}from"./chunk-RHYVJTUE.js";import{$ as wt,A as Ep,B as xp,C as Tp,D as ys,E as vs,F as Oe,G as $n,H as Cr,I as ws,J as Cp,K as $p,L as Ap,M as ka,N as ba,O as Op,P as u,Q as Ie,R as Z,S as v,T as Ip,U as Dp,V as Np,W as Mp,X as jp,Y as vt,Z as Fp,_ as Ra,a as Kt,aa as Lp,b as A,ba as Bp,c as wp,ca as H,d as N,da as M,e as ye,ea as An,f as J,fa as kt,g as gs,ga as C,h as kp,i as f,j as bp,k as hs,l as G,m as me,n as ve,o as Rp,p as wa,q as re,r as X,s as xr,t as Sp,u as Ke,v as fe,w as T,x as be,y as Tr,z as Pp}from"./chunk-4WWNBCEI.js";import{a as _p}from"./chunk-MFAFQVTW.js";import{a as K}from"./chunk-TEZPDT3Q.js";import{a as Rr,b as ss,c as is,d as Pn,e as Ku,f as Sr,g as as,h as cs,i as Hu,j as ls,k as ds,l as qu,m as Yu,n as zu,o as Pr,p as En,q as de,r as Xu,s as Er}from"./chunk-I23MDR4X.js";import{a as Yp,b as zp}from"./chunk-QWVLAZ6N.js";import MD,{Separator as iw}from"@inquirer/select";import{existsSync as jD,realpathSync as FD}from"node:fs";import{homedir as LD}from"node:os";import $e from"node:process";import{fileURLToPath as cw}from"node:url";import af from"node:process";import{z as _e}from"zod";import Em from"node:fs";import Dr from"node:path";import{packageConfigSchema as km}from"@slip-stream-kit/config/internal";import bm from"node:fs/promises";import Ts from"node:path";import{pathToFileURL as yw}from"node:url";import{z as Rm}from"zod";import vm from"node:path";var Mn=["frontend","backend","lib","e2e","mobile"],uw={ui:"frontend",api:"backend",tests:"e2e"},pw="mobile-app",mw=[{type:"e2e",packages:["@playwright/test"]},{type:"mobile",packages:["@capacitor/core","@capacitor/cli"]},{type:"backend",packages:["serverless"]}],fw=(e,t)=>{let r=vm.relative(t,e).split(vm.sep).filter(s=>s!==""&&s!=="."),[n,,o]=r;if(r.length===3&&n==="apps"&&o!==void 0){let s=uw[o];if(s)return s}return r.at(-1)===pw?"mobile":null},gw=e=>{let t=new Set([...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{}),...Object.keys(e.peerDependencies??{})]);for(let n of mw)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??fw(e,t)??gw(r)??"lib";var xt={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},wm=2e3,Na={"e2e-test":"pnpm exec playwright test","e2e-test-ui":"pnpm exec playwright test --ui","e2e-test-ui-demo":`E2E_SLOW_MO=\${E2E_SLOW_MO:-${wm}} 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"},Fn={requiredScripts:["build","dev","test","qa","infra-kit-check","fix"],requiredFiles:["turbo.json","pnpm-workspace.yaml"],turboTasks:["build","test","ts-check","eslint-check","prettier-check","infra-kit-check"]},Ln=(e,t=xt)=>({requiredScripts:e.requiredScripts??[...t.requiredScripts],requiredFiles:e.requiredFiles??[...t.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...t.turboTasks]});import hw from"node:fs/promises";var Se=async e=>{try{return await hw.access(e),!0}catch{return!1}};var ne="infra-kit.config.ts",zt=async e=>{try{let t=await bm.readFile(Ts.join(e,"package.json"),"utf-8");return JSON.parse(t)}catch{return{}}},_a=async e=>{let t=await bm.stat(e),o=(await import(`${yw(e).href}?mtime=${Number(t.mtimeMs)}`)).default;if(o===void 0)throw new Error(`${ne} at ${e} has no default export`);return typeof o=="function"?await o():o},Xt=async e=>{let t=Ts.join(e,ne);if(await Se(t))try{let n=(await _a(t))?.type;return Mn.find(o=>o===n)}catch{return}},Bn=async(e,t=xt)=>{let r=Ts.join(e,ne);if(!await Se(r))throw new Error(`${ne} not found at ${r}`);let n=await _a(r),o=km.safeParse(n);if(!o.success)throw new Error(`Invalid ${ne} at ${r}: ${Rm.prettifyError(o.error)}`);return Ln(o.data,t)},Or=async e=>{let t=Ts.join(e,ne);if(!await Se(t))return;let r=km.safeParse(await _a(t));if(!r.success)throw new Error(`Invalid ${ne} at ${t}: ${Rm.prettifyError(r.error)}`);return r.data};import Sm from"node:fs/promises";import Cs from"node:path";import vw from"yaml";var ww="pnpm-workspace.yaml",kw=async e=>(await Sm.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(r=>r.isDirectory()).map(r=>Cs.join(e,r.name)),bw=async(e,t)=>{let r=[];for(let n of e){if(t==="*"){r.push(...await kw(n));continue}let o=Cs.join(n,t);await Se(o)&&r.push(o)}return r},Rw=async(e,t)=>{let r=[e];for(let n of t.split("/"))r=await bw(r,n);return r},Pe=async e=>{let t=await Sm.readFile(Cs.join(e,ww),"utf-8"),n=((vw.parse(t)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),o=new Set;for(let s of n){let i=await Rw(e,s);for(let a of i)await Se(Cs.join(a,"package.json"))&&o.add(a)}return[...o].sort()};import Wn from"node:path";var Vn=async e=>{let t=Wn.resolve(e);for(;t!==Wn.dirname(t);){if(await Se(Wn.join(t,"package.json")))return t;t=Wn.dirname(t)}if(await Se(Wn.join(t,"package.json")))return t;throw new Error(`No package.json found in or above ${e} \u2014 cd into a package directory, or pass --root to audit a monorepo root`)};var Ye=(e,t,r)=>{let n=e.indexOf(t),o=e.indexOf(r);return n!==-1&&o!==-1&&o>=n},Tt=(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}`:"")},Ma=(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},Pm=(e,t,r)=>`${e}
4
4
  ${t}
5
- ${r}`,$r=({content:e,body:t,startMarker:r,endMarker:n,placement:o="replace-in-place"})=>{let s=km(r,t,n),i=Ke(e,r,n);if(o==="replace-in-place"&&i){let l=e.indexOf(r),d=e.indexOf(n)+n.length;return e.slice(0,l)+s+e.slice(d)}let c=(i?Pt(e,r,n)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
5
+ ${r}`,Ir=({content:e,body:t,startMarker:r,endMarker:n,placement:o="replace-in-place"})=>{let s=Pm(r,t,n),i=Ye(e,r,n);if(o==="replace-in-place"&&i){let l=e.indexOf(r),d=e.indexOf(n)+n.length;return e.slice(0,l)+s+e.slice(d)}let c=(i?Tt(e,r,n)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
6
6
  ${s}
7
7
  `:`${s}
8
- `};var Oe="<!-- infra-kit:begin -->",He="<!-- infra-kit:end -->",_a="<!-- infra-kit:version ",qe="<!-- infra-kit:package:begin -->",st="<!-- infra-kit:package:end -->",zt="<!-- infra-kit:package:version ";var hw=e=>{let t=e.indexOf(qe)+qe.length;return e.slice(t,e.indexOf(st))},yw=e=>{let t=e.indexOf(zt);if(t===-1)return null;let r=e.slice(t+zt.length).match(/^\S+\s+([^\s>]+)/)?.[1];return Dn.find(n=>n===r)??null},Xt=e=>{if(e===null)return{state:"missing"};if(!Ke(e,qe,st))return e.includes(qe)||e.includes(st)?{state:"malformed"}:Ke(e,Oe,He)?{state:"foreign-block"}:{state:"no-block"};let t=hw(e);if(t.trim()==="")return{state:"malformed"};let r={state:"ok"},n=Na(t,zt),o=yw(t);return n!==null&&(r.version=n),o!==null&&(r.type=o),r};import vw from"node:fs";var Zt=e=>{try{return vw.readFileSync(e,"utf-8")}catch{return null}};var Rm="pnpm-workspace.yaml",ww="CLAUDE.md",ja=e=>{let t=Ar.resolve(e);for(;t!==Ar.dirname(t);){if(bm.existsSync(Ar.join(t,Rm)))return t;t=Ar.dirname(t)}return bm.existsSync(Ar.join(t,Rm))?t:null},Ma=new Map,Ts=()=>{Ma.clear()},kw=async e=>{let t;try{t=await Se(e)}catch{return{adopted:!1,workspaceRoot:e}}for(let r of t){let n=Ar.join(r,ww),o=Zt(n);if(o!==null&&Xt(o).state==="ok")return{adopted:!0,workspaceRoot:e,evidencePath:n}}return{adopted:!1,workspaceRoot:e}},Or=async e=>{if(e===null)return{adopted:!1,workspaceRoot:null};let t=Ma.get(e);if(t)return t;let r=await kw(e);return Ma.set(e,r),r};import Qt from"node:fs";import Et from"node:path";var Sm=`---
8
+ `};var De="<!-- infra-kit:begin -->",ze="<!-- infra-kit:end -->",ja="<!-- infra-kit:version ",Xe="<!-- infra-kit:package:begin -->",ct="<!-- infra-kit:package:end -->",Zt="<!-- infra-kit:package:version ";var Sw=e=>{let t=e.indexOf(Xe)+Xe.length;return e.slice(t,e.indexOf(ct))},Pw=e=>{let t=e.indexOf(Zt);if(t===-1)return null;let r=e.slice(t+Zt.length).match(/^\S+\s+([^\s>]+)/)?.[1];return Mn.find(n=>n===r)??null},Qt=e=>{if(e===null)return{state:"missing"};if(!Ye(e,Xe,ct))return e.includes(Xe)||e.includes(ct)?{state:"malformed"}:Ye(e,De,ze)?{state:"foreign-block"}:{state:"no-block"};let t=Sw(e);if(t.trim()==="")return{state:"malformed"};let r={state:"ok"},n=Ma(t,Zt),o=Pw(t);return n!==null&&(r.version=n),o!==null&&(r.type=o),r};import Ew from"node:fs";var er=e=>{try{return Ew.readFileSync(e,"utf-8")}catch{return null}};var xm="pnpm-workspace.yaml",xw="CLAUDE.md",La=e=>{let t=Dr.resolve(e);for(;t!==Dr.dirname(t);){if(Em.existsSync(Dr.join(t,xm)))return t;t=Dr.dirname(t)}return Em.existsSync(Dr.join(t,xm))?t:null},Fa=new Map,$s=()=>{Fa.clear()},Tw=async e=>{let t;try{t=await Pe(e)}catch{return{adopted:!1,workspaceRoot:e}}for(let r of t){let n=Dr.join(r,xw),o=er(n);if(o!==null&&Qt(o).state==="ok")return{adopted:!0,workspaceRoot:e,evidencePath:n}}return{adopted:!1,workspaceRoot:e}},Nr=async e=>{if(e===null)return{adopted:!1,workspaceRoot:null};let t=Fa.get(e);if(t)return t;let r=await Tw(e);return Fa.set(e,r),r};import tr from"node:fs";import Ct from"node:path";var Tm=`---
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 Pm=`# {{packageName}}
77
+ `;var Cm=`# {{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 Em="# {{packageName}}\n\nWorkspace package at `{{relDir}}` \u2014 type: **{{type}}**.\nThis block is generated by `infra-kit audit --fix` \u2014 edit text _outside_ the markers, never inside.\n\n## Read first\n\n- {{readmeBullet}}\n- `infra-kit.config.ts` \u2014 the audit rules this package must satisfy.\n\n## Checks\n\n- `infra-kit audit` \u2014 validate this package against its infra-kit rules.\n- `pnpm run ts-check && pnpm run eslint-check && pnpm run test` \u2014 this package only.\n- `pnpm run qa` at the repo root \u2014 the full gate; run it before claiming completion.\n\n## Rules\n\n- Specs run on Playwright. The `e2e-test*` scripts and the `E2E_SLOW_MO` / trace settings in `playwright.config.ts` are shared across repos and checked by `infra-kit audit` \u2014 never rename or fork them locally.\n- {{e2eDocBullet}}\n- `e2e-test-ui-demo` (visible browser, one worker) is for showing a flow to a person. It sets `E2E_SLOW_MO=2000` \u2014 2 s before every action \u2014 unless the variable is already set; debug with `e2e-test-ui` instead, and everywhere else `E2E_SLOW_MO` stays unset, which the config reads as 0.\n- 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.\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 xm="# {{packageName}}\n\nWorkspace package at `{{relDir}}` \u2014 type: **{{type}}**.\nThis block is generated by `infra-kit audit --fix` \u2014 edit text _outside_ the markers, never inside.\n\n## Read first\n\n- {{readmeBullet}}\n- `DESIGN.md` \u2014 the visual language (colors, typography, spacing, components). It is the source of truth for UI decisions; if it is absent, ask before inventing one.\n- `infra-kit.config.ts` \u2014 the audit rules this package must satisfy.\n\n## Checks\n\n- `infra-kit audit` \u2014 validate this package against its infra-kit rules.\n- `pnpm run ts-check && pnpm run eslint-check && pnpm run test` \u2014 this package only.\n- `pnpm run qa` at the repo root \u2014 the full gate; run it before claiming completion.\n\n## Rules\n\n- Start the app with `infra-kit dev`, never a bare `vite` \u2014 dev URLs are proxied and port-free.\n- Backend calls go through the path prefixes declared in `dev.proxy` in `infra-kit.config.ts`. Never hardcode an API base URL or a port.\n- 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 Tm=`# {{packageName}}
98
+ `;var $m="# {{packageName}}\n\nWorkspace package at `{{relDir}}` \u2014 type: **{{type}}**.\nThis block is generated by `infra-kit audit --fix` \u2014 edit text _outside_ the markers, never inside.\n\n## Read first\n\n- {{readmeBullet}}\n- `infra-kit.config.ts` \u2014 the audit rules this package must satisfy.\n\n## Checks\n\n- `infra-kit audit` \u2014 validate this package against its infra-kit rules.\n- `pnpm run ts-check && pnpm run eslint-check && pnpm run test` \u2014 this package only.\n- `pnpm run qa` at the repo root \u2014 the full gate; run it before claiming completion.\n\n## Rules\n\n- Specs run on Playwright. The `e2e-test*` scripts and the `E2E_SLOW_MO` / trace settings in `playwright.config.ts` are shared across repos and checked by `infra-kit audit` \u2014 never rename or fork them locally.\n- {{e2eDocBullet}}\n- `e2e-test-ui-demo` (visible browser, one worker) is for showing a flow to a person. It sets `E2E_SLOW_MO=2000` \u2014 2 s before every action \u2014 unless the variable is already set; debug with `e2e-test-ui` instead, and everywhere else `E2E_SLOW_MO` stays unset, which the config reads as 0.\n- 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.\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 Am="# {{packageName}}\n\nWorkspace package at `{{relDir}}` \u2014 type: **{{type}}**.\nThis block is generated by `infra-kit audit --fix` \u2014 edit text _outside_ the markers, never inside.\n\n## Read first\n\n- {{readmeBullet}}\n- `DESIGN.md` \u2014 the visual language (colors, typography, spacing, components). It is the source of truth for UI decisions; if it is absent, ask before inventing one.\n- `infra-kit.config.ts` \u2014 the audit rules this package must satisfy.\n\n## Checks\n\n- `infra-kit audit` \u2014 validate this package against its infra-kit rules.\n- `pnpm run ts-check && pnpm run eslint-check && pnpm run test` \u2014 this package only.\n- `pnpm run qa` at the repo root \u2014 the full gate; run it before claiming completion.\n\n## Rules\n\n- Start the app with `infra-kit dev`, never a bare `vite` \u2014 dev URLs are proxied and port-free.\n- Backend calls go through the path prefixes declared in `dev.proxy` in `infra-kit.config.ts`. Never hardcode an API base URL or a port.\n- 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 Om=`# {{packageName}}
99
99
 
100
100
  Workspace package at \`{{relDir}}\` \u2014 type: **{{type}}**.
101
101
  This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_ the markers, never inside.
@@ -117,7 +117,7 @@ This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_
117
117
  - Changing that map is a breaking change for every dependent package.
118
118
  - Run \`pnpm run build\` before a dependent package can see a change.
119
119
  - No app-specific logic belongs here.
120
- `;var Cm=`# {{packageName}}
120
+ `;var Im=`# {{packageName}}
121
121
 
122
122
  Workspace package at \`{{relDir}}\` \u2014 type: **{{type}}**.
123
123
  This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_ the markers, never inside.
@@ -139,41 +139,41 @@ This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_
139
139
  - The native shell is Capacitor; its settings live in \`capacitor.config.*\`.
140
140
  - The web build feeds the native shell, so a device run needs a rebuild first.
141
141
  - Use the tokens in \`DESIGN.md\` rather than ad-hoc colors, spacing, or type scales.
142
- `;var $m="# infra-kit\n\nThis repository uses the **infra-kit** CLI for environment, worktree, and release workflows.\nThis block is generated by `ik audit --fix --root` \u2014 edit text _outside_ the markers, never inside.\n\n## Commands (`ik` = `pnpm exec infra-kit`)\n\n- `ik env-load -c <config>` / `ik env-clear` / `ik env-status` \u2014 load, clear, or inspect Doppler env vars for a config (e.g. `dev`). Source the returned file to apply.\n- `ik dev [preset|app]` / `ik dev-status` \u2014 run this worktree's dev servers, or report what is running. An app (`ik dev client`) runs its api and ui plus every backend its proxy routes can run locally; a `devServersPresets` name runs that preset; no name runs every app. Names are per-repo: an unknown one is refused with the presets and apps as choices, never guess one.\n- `ik e2e [--app <app>]` \u2014 run an app's Playwright suite locally: against this worktree's dev server when it runs, otherwise the package's `infraKitE2e()` Playwright config starts `ik dev <app> --reuse` for the run and stops it after. Plain `playwright test` / `pnpm e2e-test` behave the same way. `--cloud` runs against the deployed app instead \u2014 the URL the loaded env (`ik env-load -c <env>`) holds in the target app's `deployedUrlEnv` \u2014 previews, and needs `--yes`; `--dry-run` prints the target.\n- `ik worktrees add` / `worktrees list` / `worktrees remove` / `worktrees sync` \u2014 manage release and feature git worktrees. `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. 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`. There is no MCP server; the `/infra-kit:*` skills are the entry points and they run the CLI on `PATH`.\n- A confirm-gated command (`release create|remove|edit|merge-dev|deploy-all|deploy-selected`, `release merge-dev --continue|--abort`, `worktrees add|remove|sync`, `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 Ir={"root/body":$m.trimEnd(),"package/frontend":xm.trimEnd(),"package/backend":Pm.trimEnd(),"package/lib":Tm.trimEnd(),"package/e2e":Em.trimEnd(),"package/mobile":Cm.trimEnd(),"design/skeleton":Sm.trimEnd()};var Fa=/\{\{(\w+)\}\}/g,Cw=/^- \{\{(\w+)\}\}$/,$w=e=>new Set([...e.matchAll(Fa)].map(t=>t[1])),Aw=(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(", ")}`)},Ow=(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(", ")}`)},Iw=(e,t)=>e.filter(r=>{let n=Cw.exec(r);return n===null||t[n[1]]!==""}),Dw=(e,t)=>{for(let r of e)for(let n of r.matchAll(Fa)){let o=t[n[1]];if(o!==void 0&&o.includes(`
143
- `)&&n.index!==0)throw new Error(`renderTemplate: multi-line value for {{${n[1]}}} must start its line (found at column ${n.index})`)}},Dr=(e,t)=>{let r=$w(e);Ow(r,t),Aw(r,t);let n=Iw(e.split(`
144
- `),t);return Dw(n,t),n.join(`
145
- `).replace(Fa,(o,s)=>t[s])};var Nw="name: TODO",La=e=>{let t=Dr(Ir["design/skeleton"],{packageName:e}),r=`name: ${e}`;return`${t.replace(Nw,()=>r)}
146
- `};var _w=(e,t)=>`${zt}${e} ${t} -->`,Mw="`README.md` \u2014 what this package is and how to run it.",Ba="docs/e2e-playwright.md",jw=`\`${Ba}\` at the repo root \u2014 env setup, run modes, \`E2E_SLOW_MO\`, traces after a failure.`,Wa=e=>{let{version:t,type:r,packageName:n,relDir:o,hasReadme:s,hasE2eDoc:i}=e,a=Dr(Ir[`package/${r}`],{packageName:n,relDir:o,type:r,readmeBullet:s?Mw:"",...r==="e2e"?{e2eDocBullet:i?jw:""}:{}});return[_w(t,r),"",a].join(`
147
- `)};var Fw=e=>`${_a}${e} -->`,Va=e=>{let t=Dr(Ir["root/body"],{});return[Fw(e),"",t].join(`
148
- `)};import Nr from"node:fs";import Lw from"node:path";var Cs=e=>{let t;try{t=Nr.lstatSync(e)}catch{return}if(t.isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},Bn=(e,t)=>{Cs(e);let r=Nr.existsSync(e)?Nr.readFileSync(e,"utf-8"):null;return r===t?"unchanged":(Nr.mkdirSync(Lw.dirname(e),{recursive:!0}),Nr.writeFileSync(e,t,"utf-8"),r===null?"created":"updated")},Ua=(e,t,r)=>{let n=Nr.readFileSync(e,"utf-8");if(!Ke(n,t,r))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},Am=(e,t,r)=>Ke(e,t,r)?{before:e.slice(0,e.indexOf(t)),after:e.slice(e.indexOf(r)+r.length)}:null,Ja=(e,t,r,n)=>{let o=Am(e,r,n),s=Am(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 As="<!-- infra-kit:import:begin -->",Os="<!-- infra-kit:import:end -->",Bw="AGENTS.md",Om="CLAUDE.md",Ww="README.md",Ga="DESIGN.md",Vw=["frontend","mobile"],Uw=e=>Qt.existsSync(e)?Qt.readFileSync(e,"utf-8"):null,Ka=(e,t)=>{try{return Qt.readdirSync(e).includes(t)}catch{return!1}},$s=(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},Im=({filePath:e,body:t,startMarker:r,endMarker:n,prepare:o})=>{let s=Uw(e),i=s===null?"":o?.(s)??s,a=$r({content:i,body:t,startMarker:r,endMarker:n,placement:"replace-in-place"}),c=Bn(e,a);return Ua(e,r,n),s!==null&&Ja(i,a,r,n),c},Jw=e=>{if(!Qt.existsSync(e))return"unchanged";Cs(e);let t=Qt.readFileSync(e,"utf-8"),r=Pt(t,Oe,He);return r===null?"unchanged":r.trim()===""?(Qt.rmSync(e),"removed"):Bn(e,r)},Gw=(e,t)=>Im({filePath:e,body:Va(t),startMarker:Oe,endMarker:He,prepare:r=>Pt(r,As,Os)??r}),Wn=async(e,{version:t})=>{let r=Et.join(e,Om),n=Et.join(e,Bw),o=[];try{o.push({path:r,action:Gw(r,t)})}catch(s){o.push($s(r,s))}try{o.push({path:n,action:Jw(n)})}catch(s){o.push($s(n,s))}return o},Kw=(e,t,r)=>{if(!Vw.includes(r)||Ka(e,Ga))return null;let n=Et.join(e,Ga);try{return{path:n,action:Bn(n,La(t)),type:r}}catch(o){return $s(n,o,r)}},Vn=async(e,{repoRoot:t,version:r,design:n,declaredType:o})=>{let s=Et.join(e,Om),i=await qt(e),a=i.name??Et.basename(e),c=Nn({packageDir:e,repoRoot:t,pkgJson:i,declaredType:o}),l=Wa({version:r,type:c,packageName:a,relDir:Et.relative(t,e).split(Et.sep).join("/"),hasReadme:Ka(e,Ww),hasDesign:Ka(e,Ga),hasE2eDoc:Qt.existsSync(Et.join(t,Ba))}),d=[];try{d.push({path:s,action:Im({filePath:s,body:l,startMarker:qe,endMarker:st}),type:c})}catch(p){d.push($s(s,p,c))}if(n){let p=Kw(e,a,c);p&&d.push(p)}return d};import mk from"node:path";import Dm from"node:path";var Ha="agent-guidance",Un="CLAUDE.md",Hw="\u2014 run: infra-kit audit --fix",qw={missing:`${Un} missing`,"no-block":`${Un} has no infra-kit block (expected ${qe} \u2026 ${st})`,malformed:`${Un} block is malformed (end marker precedes start, or body is empty)`,"foreign-block":`${Un} carries the ROOT infra-kit block (${Oe}); a package needs the package block`},Yw=e=>e.adopted?` (workspace adopted: ${Dm.relative(e.workspaceRoot,e.evidencePath)} carries a package block)`:"",qa=(e,t)=>{let r=Xt(Zt(Dm.join(e,Un)));if(r.state==="ok"){let s=r.version??"unknown",i=r.type??"unknown";return{name:Ha,status:"pass",message:`present (block from infra-kit ${s}, type ${i})`}}let n=`${qw[r.state]} ${Hw}`,o=r.state==="missing"?`${n}${Yw(t)}`:n;return t.adopted?{name:Ha,status:"fail",message:o}:{name:Ha,status:"pass",message:`not yet adopted \u2014 ${o}`}};import zw from"node:path";var Ya=async(e,t=St)=>{try{let r=await jn(e,t);return{check:{name:ne,status:"pass",message:"present and valid"},rules:r}}catch(r){return{check:{name:ne,status:"fail",message:r.message},rules:null}}},Nm="infra-kit.json",Xw=async e=>await Re(zw.join(e,ne))?{name:ne,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,za=async(e,t=_n)=>{let r=await Xw(e),n=r?[r]:[];try{let{audit:o={}}=await M();return{checks:[{name:Nm,status:"pass",message:"present and valid"},...n],rules:Mn(o,t)}}catch(o){return{checks:[{name:Nm,status:"fail",message:o.message},...n],rules:null}}};import Is from"node:fs/promises";import _r from"node:path";import{$ as Zw}from"zx";var Jn="playwright.config.ts",Qw=[{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')"}],_m=e=>Object.entries(Ia).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"}}),Mm=async e=>{let t=_r.join(e,Jn),r=await Is.readFile(t,"utf-8").catch(()=>null);return r===null?[{name:`e2e-config:${Jn}`,status:"fail",message:`missing ${Jn}`}]:Qw.map(n=>{let o=`e2e-config:${n.name}`;return n.pattern.test(r)?{name:o,status:"pass",message:"present"}:{name:o,status:"fail",message:`${Jn} lacks the shared e2e convention \u2014 expected: ${n.expected}`}})},ek=/['"`](?:[^'"`\n]*\/)?\.auth['"/`]/u,tk=/\.[cm]?[jt]sx?$/u,Xa=async(e,t)=>(await Is.readdir(e,{recursive:t,withFileTypes:!0}).catch(()=>[])).filter(n=>n.isFile()&&tk.test(n.name)).map(n=>_r.join(n.parentPath,n.name)),rk=async e=>{let t=await Xa(_r.join(e,"src"),!0);for(let r of[_r.join(e,Jn),...t]){let n=await Is.readFile(r,"utf-8").catch(()=>"");if(ek.test(n))return!0}return!1},jm=async e=>{let t="e2e-auth:gitignored";if(!await rk(e))return{name:t,status:"pass",message:"no saved auth state referenced"};let r=await Zw({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}`}},Za="E2E__BASIC_AUTH_USERNAME",Qa="E2E__BASIC_AUTH_PASSWORD",nk=/\bE2E_\w*BASIC_AUTH_\w+/gu,ok=/_(?:USER(?:NAME)?|PASS(?:WORD)?)$/u,sk=/\/\*[\s\S]*?\*\//gu,ik=/(^|[^:])\/\/[^\n]*/gu,ak=e=>/USER(?:NAME)?$/u.test(e)?Za:Qa,ck=e=>e.replace(sk,"").replace(ik,"$1"),Fm=async e=>{let t="e2e-env:basic-auth",r=[...await Xa(e,!1),...await Xa(_r.join(e,"src"),!0)],n=[];for(let o of r){let s=await Is.readFile(o,"utf-8").catch(()=>""),i=new Set([...ck(s).matchAll(nk)].map(a=>a[0]).filter(a=>ok.test(a)&&a!==Za&&a!==Qa));for(let a of i)n.push(`${a} \u2192 ${ak(a)} (${_r.relative(e,o)})`)}return n.length===0?{name:t,status:"pass",message:`basic auth read only from ${Za} / ${Qa}`}:{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("; ")}`}},ec=async(e,t)=>[..._m(t),...await Mm(e),await jm(e),await Fm(e)];import lk from"node:fs/promises";import dk from"node:path";var tc=async(e,t)=>Promise.all(t.map(async r=>{let n=await lk.stat(dk.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 rc=(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 uk from"node:fs/promises";import pk from"node:path";var Mr="turbo.json",nc=async(e,t)=>{if(t.length===0)return[];let r;try{let o=await uk.readFile(pk.join(e,Mr),"utf-8");r=JSON.parse(o)}catch(o){return[{name:Mr,status:"fail",message:`cannot read/parse ${Mr}: ${o.message}`}]}let n=r.tasks;return n===null||typeof n!="object"?[{name:Mr,status:"fail",message:`no "tasks" object defined in ${Mr}`}]: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 ${Mr}`}})};var fk=async(e,t)=>{let{check:r,rules:n}=await Ya(e,t);return{checks:[r],rules:n}},gk={adopted:!1,workspaceRoot:null},hk=async(e,t,r)=>Nn({packageDir:e,repoRoot:r??e,pkgJson:t,declaredType:await Yt(e)}),oc=async(e,t=St,r={})=>{let n=await qt(e),o=n.name??mk.basename(e),{checks:s,rules:i}=r.isRoot?await za(e,t):await fk(e,t);r.isRoot||s.push(qa(e,r.adoption??gk)),i&&(s.push(...rc(n.scripts??{},i.requiredScripts)),s.push(...await tc(e,i.requiredFiles)),s.push(...await nc(e,i.turboTasks))),!r.isRoot&&await hk(e,n,r.repoRoot)==="e2e"&&s.push(...await ec(e,n.scripts??{}));let a=s.every(c=>c.status==="pass");return{packageDir:e,packageName:o,checks:s,passed:a}};var sc=["plugin","marketplace","add",wt],ic=["plugin","install",q,"--scope","project"],Lm=(e,t)=>Gt({projectPath:e,home:t}).kind==="installed",ac=e=>((e??"").split(`
149
- `).find(r=>r.trim().length>0)??"").trim(),yk=(e,t)=>{if(Cn(t))return null;u.debug({msg:`Running: ${ys} ${sc.join(" ")}`});let r=e({args:sc});return r.ok?null:{step:"marketplace",error:ac(r.output)}},vk=(e,t)=>{u.debug({msg:`Running: ${ys} ${vs.join(" ")}`});let r=e({args:vs,cwd:t});return r.ok?{status:"updated"}:{status:"update-failed",error:ac(r.output)}},cc=e=>{let{projectRoot:t,home:r}=e,n=e.run??Ra;if(!n({args:ba}).ok)return{status:"claude-missing"};if(Lm(t,r))return e.cliIsStale?.()===!0?{status:"skipped-cli-stale"}:vk(n,t);let o=yk(n,r);if(o!==null)return{status:"failed",...o};u.debug({msg:`Running: ${ys} ${ic.join(" ")}`});let s=n({args:ic,cwd:t});return s.ok?Lm(t,r)?{status:"installed"}:{status:"unverified"}:{status:"failed",step:"install",error:ac(s.output)}};import wk from"node:fs";import kk from"node:path";var Ie=".mcp.json",Ye="mcpServers",bk="infra-kit",Rk=["mcp"],Sk="/infra-kit/dist/mcp.js",lc=" ",er=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Bm=e=>{if(!er(e))return!1;let{command:t,args:r}=e;return Array.isArray(r)?t===bk&&r[0]===Rk[0]?!0:r.some(n=>typeof n=="string"&&n.endsWith(Sk)):!1},Wm=e=>/\n([ \t]+)"/.exec(e)?.[1]??lc,dc=e=>{try{return{kind:"raw",raw:wk.readFileSync(e,"utf-8")}}catch(t){return t.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable",error:t}}},uc=e=>{try{return JSON.parse(e)}catch{return}},pc=e=>e instanceof Error?e.message:String(e),Gn=e=>{let t=dc(kk.join(e,Ie));if(t.kind==="absent")return{kind:"missing-file"};if(t.kind==="unreadable")return{kind:"unparseable"};let r=uc(t.raw);if(!er(r)||!er(r[Ye]))return{kind:"unparseable"};let n=r[Ye];if(de in n)return{kind:"stale"};let o=Object.keys(n).find(s=>Bm(n[s]));return o===void 0?{kind:"absent"}:{kind:"wrong-key",key:o}};import Ds from"node:fs";import Pk from"node:path";var it=`claude plugin install ${q} --scope project`,jr=`claude plugin update ${q} --scope project`,mc=`claude plugin marketplace add ${wt}`,Um=" ",Jm=()=>({source:{source:"github",repo:wt}}),Ek=()=>({extraKnownMarketplaces:{[de]:Jm()},enabledPlugins:{[q]:!0}}),Gm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),xk=e=>/\n([ \t]+)"/.exec(e)?.[1]??Um,Vm=(e,t,r,n)=>{let o=e[t];return o===void 0?(e[t]={[r]:n},`${t}.${r}`):!Gm(o)||r in o?null:(o[r]=n,`${t}.${r}`)},Tk=e=>[Vm(e,"extraKnownMarketplaces",de,Jm()),Vm(e,"enabledPlugins",q,!0)].filter(r=>r!==null),Ck=e=>{try{return Ds.readFileSync(e,"utf-8")}catch{return null}},$k=e=>(Ds.mkdirSync(Pk.dirname(e),{recursive:!0}),Ds.writeFileSync(e,`${JSON.stringify(Ek(),null,Um)}
150
- `,"utf-8"),{status:"created",path:e,added:[`extraKnownMarketplaces.${de}`,`enabledPlugins.${q}`]}),fc=e=>{let t=Ck(e);if(t===null)return $k(e);let r;try{r=JSON.parse(t)}catch{r=void 0}if(!Gm(r))return u.warn(`Could not parse ${e} \u2014 left it untouched. Add "${q}" to enabledPlugins by hand, or fix the JSON and re-run: infra-kit setup --skip-tools`),{status:"unparseable",path:e,added:[]};let n=Tk(r);if(n.length===0)return{status:"unchanged",path:e,added:[]};let o=xk(t),s=t.endsWith(`
142
+ `;var Dm="# infra-kit\n\nThis repository uses the **infra-kit** CLI for environment, worktree, and release workflows.\nThis block is generated by `ik audit --fix --root` \u2014 edit text _outside_ the markers, never inside.\n\n## Commands (`ik` = `pnpm exec infra-kit`)\n\n- `ik env-load -c <config>` / `ik env-clear` / `ik env-status` \u2014 load, clear, or inspect Doppler env vars for a config (e.g. `dev`). Source the returned file to apply.\n- `ik dev [preset|app]` / `ik dev-status` \u2014 run this worktree's dev servers, or report what is running. An app (`ik dev client`) runs its api and ui plus every backend its proxy routes can run locally; a `devServersPresets` name runs that preset; no name runs every app. Names are per-repo: an unknown one is refused with the presets and apps as choices, never guess one.\n- `ik e2e [--app <app>]` \u2014 run an app's Playwright suite locally: against this worktree's dev server when it runs, otherwise the package's `infraKitE2e()` Playwright config starts `ik dev <app> --reuse` for the run and stops it after. Plain `playwright test` / `pnpm e2e-test` behave the same way. `--cloud` runs against the deployed app instead \u2014 the URL the loaded env (`ik env-load -c <env>`) holds in the target app's `deployedUrlEnv` \u2014 previews, and needs `--yes`; `--dry-run` prints the target.\n- `ik worktrees add` / `worktrees list` / `worktrees remove` / `worktrees sync` \u2014 manage release and feature git worktrees. `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`. There is no MCP server; the `/infra-kit:*` skills are the entry points and they run the CLI on `PATH`.\n- A confirm-gated command (`release create|remove|edit|merge-dev|deploy-all|deploy-selected`, `release merge-dev --continue|--abort`, `worktrees add|remove|sync`, `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 _r={"root/body":Dm.trimEnd(),"package/frontend":Am.trimEnd(),"package/backend":Cm.trimEnd(),"package/lib":Om.trimEnd(),"package/e2e":$m.trimEnd(),"package/mobile":Im.trimEnd(),"design/skeleton":Tm.trimEnd()};var Ba=/\{\{(\w+)\}\}/g,_w=/^- \{\{(\w+)\}\}$/,Mw=e=>new Set([...e.matchAll(Ba)].map(t=>t[1])),jw=(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(", ")}`)},Fw=(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(", ")}`)},Lw=(e,t)=>e.filter(r=>{let n=_w.exec(r);return n===null||t[n[1]]!==""}),Bw=(e,t)=>{for(let r of e)for(let n of r.matchAll(Ba)){let o=t[n[1]];if(o!==void 0&&o.includes(`
143
+ `)&&n.index!==0)throw new Error(`renderTemplate: multi-line value for {{${n[1]}}} must start its line (found at column ${n.index})`)}},Mr=(e,t)=>{let r=Mw(e);Fw(r,t),jw(r,t);let n=Lw(e.split(`
144
+ `),t);return Bw(n,t),n.join(`
145
+ `).replace(Ba,(o,s)=>t[s])};var Ww="name: TODO",Wa=e=>{let t=Mr(_r["design/skeleton"],{packageName:e}),r=`name: ${e}`;return`${t.replace(Ww,()=>r)}
146
+ `};var Vw=(e,t)=>`${Zt}${e} ${t} -->`,Uw="`README.md` \u2014 what this package is and how to run it.",Va="docs/e2e-playwright.md",Jw=`\`${Va}\` at the repo root \u2014 env setup, run modes, \`E2E_SLOW_MO\`, traces after a failure.`,Ua=e=>{let{version:t,type:r,packageName:n,relDir:o,hasReadme:s,hasE2eDoc:i}=e,a=Mr(_r[`package/${r}`],{packageName:n,relDir:o,type:r,readmeBullet:s?Uw:"",...r==="e2e"?{e2eDocBullet:i?Jw:""}:{}});return[Vw(t,r),"",a].join(`
147
+ `)};var Gw=e=>`${ja}${e} -->`,Ja=e=>{let t=Mr(_r["root/body"],{});return[Gw(e),"",t].join(`
148
+ `)};import jr from"node:fs";import Kw from"node:path";var As=e=>{let t;try{t=jr.lstatSync(e)}catch{return}if(t.isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},Un=(e,t)=>{As(e);let r=jr.existsSync(e)?jr.readFileSync(e,"utf-8"):null;return r===t?"unchanged":(jr.mkdirSync(Kw.dirname(e),{recursive:!0}),jr.writeFileSync(e,t,"utf-8"),r===null?"created":"updated")},Ga=(e,t,r)=>{let n=jr.readFileSync(e,"utf-8");if(!Ye(n,t,r))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},Nm=(e,t,r)=>Ye(e,t,r)?{before:e.slice(0,e.indexOf(t)),after:e.slice(e.indexOf(r)+r.length)}:null,Ka=(e,t,r,n)=>{let o=Nm(e,r,n),s=Nm(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 Is="<!-- infra-kit:import:begin -->",Ds="<!-- infra-kit:import:end -->",Hw="AGENTS.md",_m="CLAUDE.md",qw="README.md",Ha="DESIGN.md",Yw=["frontend","mobile"],zw=e=>tr.existsSync(e)?tr.readFileSync(e,"utf-8"):null,qa=(e,t)=>{try{return tr.readdirSync(e).includes(t)}catch{return!1}},Os=(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},Mm=({filePath:e,body:t,startMarker:r,endMarker:n,prepare:o})=>{let s=zw(e),i=s===null?"":o?.(s)??s,a=Ir({content:i,body:t,startMarker:r,endMarker:n,placement:"replace-in-place"}),c=Un(e,a);return Ga(e,r,n),s!==null&&Ka(i,a,r,n),c},Xw=e=>{if(!tr.existsSync(e))return"unchanged";As(e);let t=tr.readFileSync(e,"utf-8"),r=Tt(t,De,ze);return r===null?"unchanged":r.trim()===""?(tr.rmSync(e),"removed"):Un(e,r)},Zw=(e,t)=>Mm({filePath:e,body:Ja(t),startMarker:De,endMarker:ze,prepare:r=>Tt(r,Is,Ds)??r}),Jn=async(e,{version:t})=>{let r=Ct.join(e,_m),n=Ct.join(e,Hw),o=[];try{o.push({path:r,action:Zw(r,t)})}catch(s){o.push(Os(r,s))}try{o.push({path:n,action:Xw(n)})}catch(s){o.push(Os(n,s))}return o},Qw=(e,t,r)=>{if(!Yw.includes(r)||qa(e,Ha))return null;let n=Ct.join(e,Ha);try{return{path:n,action:Un(n,Wa(t)),type:r}}catch(o){return Os(n,o,r)}},Gn=async(e,{repoRoot:t,version:r,design:n,declaredType:o})=>{let s=Ct.join(e,_m),i=await zt(e),a=i.name??Ct.basename(e),c=jn({packageDir:e,repoRoot:t,pkgJson:i,declaredType:o}),l=Ua({version:r,type:c,packageName:a,relDir:Ct.relative(t,e).split(Ct.sep).join("/"),hasReadme:qa(e,qw),hasDesign:qa(e,Ha),hasE2eDoc:tr.existsSync(Ct.join(t,Va))}),d=[];try{d.push({path:s,action:Mm({filePath:s,body:l,startMarker:Xe,endMarker:ct}),type:c})}catch(p){d.push(Os(s,p,c))}if(n){let p=Qw(e,a,c);p&&d.push(p)}return d};import kk from"node:path";import jm from"node:path";var Ya="agent-guidance",Kn="CLAUDE.md",ek="\u2014 run: infra-kit audit --fix",tk={missing:`${Kn} missing`,"no-block":`${Kn} has no infra-kit block (expected ${Xe} \u2026 ${ct})`,malformed:`${Kn} block is malformed (end marker precedes start, or body is empty)`,"foreign-block":`${Kn} carries the ROOT infra-kit block (${De}); a package needs the package block`},rk=e=>e.adopted?` (workspace adopted: ${jm.relative(e.workspaceRoot,e.evidencePath)} carries a package block)`:"",za=(e,t)=>{let r=Qt(er(jm.join(e,Kn)));if(r.state==="ok"){let s=r.version??"unknown",i=r.type??"unknown";return{name:Ya,status:"pass",message:`present (block from infra-kit ${s}, type ${i})`}}let n=`${tk[r.state]} ${ek}`,o=r.state==="missing"?`${n}${rk(t)}`:n;return t.adopted?{name:Ya,status:"fail",message:o}:{name:Ya,status:"pass",message:`not yet adopted \u2014 ${o}`}};import nk from"node:path";var Xa=async(e,t=xt)=>{try{let r=await Bn(e,t);return{check:{name:ne,status:"pass",message:"present and valid"},rules:r}}catch(r){return{check:{name:ne,status:"fail",message:r.message},rules:null}}},Fm="infra-kit.json",ok=async e=>await Se(nk.join(e,ne))?{name:ne,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,Za=async(e,t=Fn)=>{let r=await ok(e),n=r?[r]:[];try{let{audit:o={}}=await M();return{checks:[{name:Fm,status:"pass",message:"present and valid"},...n],rules:Ln(o,t)}}catch(o){return{checks:[{name:Fm,status:"fail",message:o.message},...n],rules:null}}};import Ns from"node:fs/promises";import Fr from"node:path";import{$ as sk}from"zx";var Hn="playwright.config.ts",ik=[{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')"}],Lm=e=>Object.entries(Na).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"}}),Bm=async e=>{let t=Fr.join(e,Hn),r=await Ns.readFile(t,"utf-8").catch(()=>null);return r===null?[{name:`e2e-config:${Hn}`,status:"fail",message:`missing ${Hn}`}]:ik.map(n=>{let o=`e2e-config:${n.name}`;return n.pattern.test(r)?{name:o,status:"pass",message:"present"}:{name:o,status:"fail",message:`${Hn} lacks the shared e2e convention \u2014 expected: ${n.expected}`}})},ak=/['"`](?:[^'"`\n]*\/)?\.auth['"/`]/u,ck=/\.[cm]?[jt]sx?$/u,Qa=async(e,t)=>(await Ns.readdir(e,{recursive:t,withFileTypes:!0}).catch(()=>[])).filter(n=>n.isFile()&&ck.test(n.name)).map(n=>Fr.join(n.parentPath,n.name)),lk=async e=>{let t=await Qa(Fr.join(e,"src"),!0);for(let r of[Fr.join(e,Hn),...t]){let n=await Ns.readFile(r,"utf-8").catch(()=>"");if(ak.test(n))return!0}return!1},Wm=async e=>{let t="e2e-auth:gitignored";if(!await lk(e))return{name:t,status:"pass",message:"no saved auth state referenced"};let r=await sk({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}`}},ec="E2E__BASIC_AUTH_USERNAME",tc="E2E__BASIC_AUTH_PASSWORD",dk=/\bE2E_\w*BASIC_AUTH_\w+/gu,uk=/_(?:USER(?:NAME)?|PASS(?:WORD)?)$/u,pk=/\/\*[\s\S]*?\*\//gu,mk=/(^|[^:])\/\/[^\n]*/gu,fk=e=>/USER(?:NAME)?$/u.test(e)?ec:tc,gk=e=>e.replace(pk,"").replace(mk,"$1"),Vm=async e=>{let t="e2e-env:basic-auth",r=[...await Qa(e,!1),...await Qa(Fr.join(e,"src"),!0)],n=[];for(let o of r){let s=await Ns.readFile(o,"utf-8").catch(()=>""),i=new Set([...gk(s).matchAll(dk)].map(a=>a[0]).filter(a=>uk.test(a)&&a!==ec&&a!==tc));for(let a of i)n.push(`${a} \u2192 ${fk(a)} (${Fr.relative(e,o)})`)}return n.length===0?{name:t,status:"pass",message:`basic auth read only from ${ec} / ${tc}`}:{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("; ")}`}},rc=async(e,t)=>[...Lm(t),...await Bm(e),await Wm(e),await Vm(e)];import hk from"node:fs/promises";import yk from"node:path";var nc=async(e,t)=>Promise.all(t.map(async r=>{let n=await hk.stat(yk.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 oc=(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 vk from"node:fs/promises";import wk from"node:path";var Lr="turbo.json",sc=async(e,t)=>{if(t.length===0)return[];let r;try{let o=await vk.readFile(wk.join(e,Lr),"utf-8");r=JSON.parse(o)}catch(o){return[{name:Lr,status:"fail",message:`cannot read/parse ${Lr}: ${o.message}`}]}let n=r.tasks;return n===null||typeof n!="object"?[{name:Lr,status:"fail",message:`no "tasks" object defined in ${Lr}`}]:t.map(o=>{let s=o in n||`//#${o}`in n;return{name:`turbo:${o}`,status:s?"pass":"fail",message:s?"defined":`missing turbo task "${o}" in ${Lr}`}})};var bk=async(e,t)=>{let{check:r,rules:n}=await Xa(e,t);return{checks:[r],rules:n}},Rk={adopted:!1,workspaceRoot:null},Sk=async(e,t,r)=>jn({packageDir:e,repoRoot:r??e,pkgJson:t,declaredType:await Xt(e)}),ic=async(e,t=xt,r={})=>{let n=await zt(e),o=n.name??kk.basename(e),{checks:s,rules:i}=r.isRoot?await Za(e,t):await bk(e,t);r.isRoot||s.push(za(e,r.adoption??Rk)),i&&(s.push(...oc(n.scripts??{},i.requiredScripts)),s.push(...await nc(e,i.requiredFiles)),s.push(...await sc(e,i.turboTasks))),!r.isRoot&&await Sk(e,n,r.repoRoot)==="e2e"&&s.push(...await rc(e,n.scripts??{}));let a=s.every(c=>c.status==="pass");return{packageDir:e,packageName:o,checks:s,passed:a}};var ac=["plugin","marketplace","add",bt],cc=["plugin","install",q,"--scope","project"],Um=(e,t)=>Ht({projectPath:e,home:t}).kind==="installed",lc=e=>((e??"").split(`
149
+ `).find(r=>r.trim().length>0)??"").trim(),Pk=(e,t)=>{if(On(t))return null;u.debug({msg:`Running: ${ks} ${ac.join(" ")}`});let r=e({args:ac});return r.ok?null:{step:"marketplace",error:lc(r.output)}},Ek=(e,t)=>{u.debug({msg:`Running: ${ks} ${bs.join(" ")}`});let r=e({args:bs,cwd:t});return r.ok?{status:"updated"}:{status:"update-failed",error:lc(r.output)}},dc=e=>{let{projectRoot:t,home:r}=e,n=e.run??Pa;if(!n({args:Sa}).ok)return{status:"claude-missing"};if(Um(t,r))return e.cliIsStale?.()===!0?{status:"skipped-cli-stale"}:Ek(n,t);let o=Pk(n,r);if(o!==null)return{status:"failed",...o};u.debug({msg:`Running: ${ks} ${cc.join(" ")}`});let s=n({args:cc,cwd:t});return s.ok?Um(t,r)?{status:"installed"}:{status:"unverified"}:{status:"failed",step:"install",error:lc(s.output)}};import xk from"node:fs";import Tk from"node:path";var Ne=".mcp.json",Ze="mcpServers",Ck="infra-kit",$k=["mcp"],Ak="/infra-kit/dist/mcp.js",uc=" ",rr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Jm=e=>{if(!rr(e))return!1;let{command:t,args:r}=e;return Array.isArray(r)?t===Ck&&r[0]===$k[0]?!0:r.some(n=>typeof n=="string"&&n.endsWith(Ak)):!1},Gm=e=>/\n([ \t]+)"/.exec(e)?.[1]??uc,pc=e=>{try{return{kind:"raw",raw:xk.readFileSync(e,"utf-8")}}catch(t){return t.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable",error:t}}},mc=e=>{try{return JSON.parse(e)}catch{return}},fc=e=>e instanceof Error?e.message:String(e),qn=e=>{let t=pc(Tk.join(e,Ne));if(t.kind==="absent")return{kind:"missing-file"};if(t.kind==="unreadable")return{kind:"unparseable"};let r=mc(t.raw);if(!rr(r)||!rr(r[Ze]))return{kind:"unparseable"};let n=r[Ze];if(ue in n)return{kind:"stale"};let o=Object.keys(n).find(s=>Jm(n[s]));return o===void 0?{kind:"absent"}:{kind:"wrong-key",key:o}};import _s from"node:fs";import Ok from"node:path";var lt=`claude plugin install ${q} --scope project`,Br=`claude plugin update ${q} --scope project`,gc=`claude plugin marketplace add ${bt}`,Hm=" ",qm=()=>({source:{source:"github",repo:bt}}),Ik=()=>({extraKnownMarketplaces:{[ue]:qm()},enabledPlugins:{[q]:!0}}),Ym=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Dk=e=>/\n([ \t]+)"/.exec(e)?.[1]??Hm,Km=(e,t,r,n)=>{let o=e[t];return o===void 0?(e[t]={[r]:n},`${t}.${r}`):!Ym(o)||r in o?null:(o[r]=n,`${t}.${r}`)},Nk=e=>[Km(e,"extraKnownMarketplaces",ue,qm()),Km(e,"enabledPlugins",q,!0)].filter(r=>r!==null),_k=e=>{try{return _s.readFileSync(e,"utf-8")}catch{return null}},Mk=e=>(_s.mkdirSync(Ok.dirname(e),{recursive:!0}),_s.writeFileSync(e,`${JSON.stringify(Ik(),null,Hm)}
150
+ `,"utf-8"),{status:"created",path:e,added:[`extraKnownMarketplaces.${ue}`,`enabledPlugins.${q}`]}),hc=e=>{let t=_k(e);if(t===null)return Mk(e);let r;try{r=JSON.parse(t)}catch{r=void 0}if(!Ym(r))return u.warn(`Could not parse ${e} \u2014 left it untouched. Add "${q}" to enabledPlugins by hand, or fix the JSON and re-run: infra-kit setup --skip-tools`),{status:"unparseable",path:e,added:[]};let n=Nk(r);if(n.length===0)return{status:"unchanged",path:e,added:[]};let o=Dk(t),s=t.endsWith(`
151
151
  `)?`
152
- `:"";return Ds.writeFileSync(e,`${JSON.stringify(r,null,o)}${s}`,"utf-8"),{status:"added",path:e,added:n}};import Ik from"node:path";import Dk from"node:process";import gc from"node:fs/promises";import Km from"node:path";var Ak="infra-kit.json",Hm=["requiredScripts","requiredFiles","turbo"],Kn=(e,t)=>[{path:e,action:"failed",message:t}],Ok=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),qm=async e=>{let t=Km.join(e,ne),r=Km.join(e,Ak),n;try{n=await Cr(e)}catch(c){return Kn(t,c.message)}if(!n)return[];let o={...n},s=Object.keys(o).filter(c=>!Hm.includes(c));if(s.length>0)return Kn(t,`declares ${s.join(", ")}, which mean nothing at the repo root \u2014 remove them, then re-run`);let i=Object.fromEntries(Hm.filter(c=>o[c]!==void 0).map(c=>[c,o[c]])),a=[];if(Object.keys(i).length>0)try{let c=await gc.stat(r),l=await gc.readFile(r,"utf8"),d=JSON.parse(l);if(!Ok(d))return Kn(r,"is not a JSON object");if("audit"in d)return Kn(r,`already has an "audit" block \u2014 merge ${ne}'s rules into it by hand, then delete ${ne}`);await Ap({path:r,raw:l,migrated:{...d,audit:i},expectedMtimeMs:c.mtimeMs}),a.push({path:r,action:"updated"})}catch(c){return Kn(r,c.message)}try{await gc.rm(t),a.push({path:t,action:"removed"})}catch(c){a.push({path:t,action:"failed",message:c.message})}return a};var Nk=["unchanged","created"],_k=["unchanged","created","updated","removed","failed"],Ym=async(e,t,r)=>{let n=await Yt(e);return Vn(e,{repoRoot:t,version:K.version,design:r,declaredType:n})},Mk=async(e,t)=>{if(e.root)return[...await qm(t),...await Wn(t,{version:K.version})];if(e.all){let n=[];for(let o of await Se(t))n.push(...await Ym(o,t,e.design));return n}let r=await Ln(e.cwd??Dk.cwd());return Ym(r,t,e.design)},jk=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 ${_k.filter(n=>Nk.includes(n)||(t.get(n)??0)>0).map(n=>`${t.get(n)??0} ${n}`).join(", ")} (infra-kit ${K.version})`},Fk=(e,t)=>{for(let r of e){if(r.action==="unchanged")continue;let n=Ik.relative(t,r.path),o=r.type?` (${r.type})`:"",s=r.action==="failed"&&r.message?` \u2014 ${r.message}`:"";u.info(` ${r.action.padEnd(9)} ${n}${o}${s}`)}u.info(jk(e))},Lk=e=>{let t={path:e.path,action:e.action};return e.type&&(t.type=e.type),t},zm=async(e,t)=>{let r=await T();Ts();let n=await Or(t),o=await Mk(e,r);Fk(o,r),Ts();let s=await Or(t),i=!e.all&&!e.root;return{fixed:o.map(Lk),adoptionFlipped:i&&!n.adopted&&s.adopted}};import Zm from"node:fs";import Qm from"node:path";var hc="ik-mcp",Xm=(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:hc,args:r}};var Ns="run `infra-kit setup` (or `infra-kit audit --root --fix`)",Bk=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((r,n)=>r===t[n]),yc=e=>er(e)&&e.command===hc,Wk=(e,t)=>({...e??{},type:t.type,command:t.command,args:t.args}),Vk=(e,t,r)=>{let n=[],o={...e},s=!1;for(let[i,a]of Object.entries(t)){let c=Xm(i,a),l=e[i];if(l!==void 0&&!yc(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 ${Ns}, or drop mcp.${i} from infra-kit.json`});continue}if(yc(l)&&l.type===c.type&&Bk(l.args,c.args)){n.push({name:i,status:"unchanged",message:""});continue}if(r){o[i]=Wk(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: ${Ns}`:`"${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: ${Ns}`})}for(let[i,a]of Object.entries(e))Object.hasOwn(t,i)||!yc(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}},Uk=(e,t,r)=>{let n=r===null?lc:Wm(r),o=r===null||r.endsWith(`
152
+ `:"";return _s.writeFileSync(e,`${JSON.stringify(r,null,o)}${s}`,"utf-8"),{status:"added",path:e,added:n}};import Lk from"node:path";import Bk from"node:process";import yc from"node:fs/promises";import zm from"node:path";var jk="infra-kit.json",Xm=["requiredScripts","requiredFiles","turbo"],Yn=(e,t)=>[{path:e,action:"failed",message:t}],Fk=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Zm=async e=>{let t=zm.join(e,ne),r=zm.join(e,jk),n;try{n=await Or(e)}catch(c){return Yn(t,c.message)}if(!n)return[];let o={...n},s=Object.keys(o).filter(c=>!Xm.includes(c));if(s.length>0)return Yn(t,`declares ${s.join(", ")}, which mean nothing at the repo root \u2014 remove them, then re-run`);let i=Object.fromEntries(Xm.filter(c=>o[c]!==void 0).map(c=>[c,o[c]])),a=[];if(Object.keys(i).length>0)try{let c=await yc.stat(r),l=await yc.readFile(r,"utf8"),d=JSON.parse(l);if(!Fk(d))return Yn(r,"is not a JSON object");if("audit"in d)return Yn(r,`already has an "audit" block \u2014 merge ${ne}'s rules into it by hand, then delete ${ne}`);await Dp({path:r,raw:l,migrated:{...d,audit:i},expectedMtimeMs:c.mtimeMs}),a.push({path:r,action:"updated"})}catch(c){return Yn(r,c.message)}try{await yc.rm(t),a.push({path:t,action:"removed"})}catch(c){a.push({path:t,action:"failed",message:c.message})}return a};var Wk=["unchanged","created"],Vk=["unchanged","created","updated","removed","failed"],Qm=async(e,t,r)=>{let n=await Xt(e);return Gn(e,{repoRoot:t,version:K.version,design:r,declaredType:n})},Uk=async(e,t)=>{if(e.root)return[...await Zm(t),...await Jn(t,{version:K.version})];if(e.all){let n=[];for(let o of await Pe(t))n.push(...await Qm(o,t,e.design));return n}let r=await Vn(e.cwd??Bk.cwd());return Qm(r,t,e.design)},Jk=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 ${Vk.filter(n=>Wk.includes(n)||(t.get(n)??0)>0).map(n=>`${t.get(n)??0} ${n}`).join(", ")} (infra-kit ${K.version})`},Gk=(e,t)=>{for(let r of e){if(r.action==="unchanged")continue;let n=Lk.relative(t,r.path),o=r.type?` (${r.type})`:"",s=r.action==="failed"&&r.message?` \u2014 ${r.message}`:"";u.info(` ${r.action.padEnd(9)} ${n}${o}${s}`)}u.info(Jk(e))},Kk=e=>{let t={path:e.path,action:e.action};return e.type&&(t.type=e.type),t},ef=async(e,t)=>{let r=await T();$s();let n=await Nr(t),o=await Uk(e,r);Gk(o,r),$s();let s=await Nr(t),i=!e.all&&!e.root;return{fixed:o.map(Kk),adoptionFlipped:i&&!n.adopted&&s.adopted}};import rf from"node:fs";import nf from"node:path";var vc="ik-mcp",tf=(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:vc,args:r}};var Ms="run `infra-kit setup` (or `infra-kit audit --root --fix`)",Hk=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((r,n)=>r===t[n]),wc=e=>rr(e)&&e.command===vc,qk=(e,t)=>({...e??{},type:t.type,command:t.command,args:t.args}),Yk=(e,t,r)=>{let n=[],o={...e},s=!1;for(let[i,a]of Object.entries(t)){let c=tf(i,a),l=e[i];if(l!==void 0&&!wc(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 ${Ms}, or drop mcp.${i} from infra-kit.json`});continue}if(wc(l)&&l.type===c.type&&Hk(l.args,c.args)){n.push({name:i,status:"unchanged",message:""});continue}if(r){o[i]=qk(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: ${Ms}`:`"${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: ${Ms}`})}for(let[i,a]of Object.entries(e))Object.hasOwn(t,i)||!wc(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}},zk=(e,t,r)=>{let n=r===null?uc:Gm(r),o=r===null||r.endsWith(`
153
153
  `)?`
154
- `:"";try{return Zm.mkdirSync(Qm.dirname(e),{recursive:!0}),Zm.writeFileSync(e,`${JSON.stringify(t,null,n)}${o}`,"utf-8"),!0}catch(s){return u.warn(`Could not write ${e} (${pc(s)}) \u2014 the ik-mcp entries were not updated.`),!1}},_s=({projectRoot:e,proxies:t,write:r})=>{let n=Qm.join(e,Ie),o=dc(n);if(o.kind==="unreadable")return u.warn(`Could not read ${n} (${pc(o.error)}) \u2014 left it untouched.`),{status:"unreadable",path:n,entries:[],wrote:!1};let s=o.kind==="raw"?o.raw:null,i=s===null?{}:uc(s);if(!er(i))return u.warn(`Could not parse ${n} \u2014 left it untouched. Fix the JSON, then ${Ns}.`),{status:"unparseable",path:n,entries:[],wrote:!1};let a=i[Ye];if(a!==void 0&&!er(a))return u.warn(`${n} has a "${Ye}" that is not an object \u2014 left it untouched.`),{status:"unparseable",path:n,entries:[],wrote:!1};let c=Vk(a??{},t,r);if(!c.changed)return{status:"ok",path:n,entries:c.entries,wrote:!1};let l=Uk(n,{...i,[Ye]:c.servers},s);return{status:l?"ok":"failed",path:n,entries:c.entries,wrote:l}};var ef=async(e,t)=>{let r;try{r=(await M()).mcp}catch{return null}if(!r||Object.keys(r).length===0)return null;let n=_s({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 Jk=(e,t)=>[...t.map(r=>({name:`devServersPresets:config:${r.app}`,status:"fail",message:`could not load apps/${r.app}/ui/infra-kit.config.ts (referenced by a preset proxy override): ${r.message}`})),...e.map(r=>({name:`devServersPresets:${r.preset}`,status:"fail",message:r.message}))],tf=async e=>{let t=(await M()).devServersPresets;if(!t||Object.keys(t).length===0)return null;let r=Wp(t);if(r.length>0){let d=r.map(p=>({name:`devServersPresets:${p.preset}`,status:"fail",message:p.message}));return{packageDir:e,packageName:"devServersPresets",checks:d,passed:!1}}let n=Lp(e),o=Bp(e),s={api:n.map(d=>d.name),ui:o.map(d=>d.name)},{ctx:i,loadErrors:a}=await Up(e,t,s,n),c=Jk(Vp(t,i),a),l=c.length===0?[{name:"devServersPresets:proxy-locality",status:"pass",message:"every local proxy override resolves to a backend the preset launches"}]:c;return{packageDir:e,packageName:"devServersPresets",checks:l,passed:c.length===0}};var Gk="workspace adopted \u2014 every other package now needs a CLAUDE.md: run infra-kit audit --fix --all",Kk=async e=>e.root?[{dir:await T(),baseline:_n,isRoot:!0}]:e.all?(await Se(await T())).map(r=>({dir:r})):[{dir:await Ln(e.cwd??rf.cwd())}],Hk=async e=>e.root||e.all?await T():e.cwd??rf.cwd(),qk=async()=>{try{return await T()}catch{return}},Yk=e=>{let t=0,r=0;for(let i of e)for(let a of i.checks)t+=1,a.status!=="pass"&&(r+=1,u.info(`[FAIL] ${i.packageName} ${a.name}: ${a.message}`));let n=e.every(i=>i.passed),o=(i,a)=>`${i} ${a}${i===1?"":"s"}`,s=`${o(t,"check")}, ${o(e.length,"target")}`;return u.info(n?`\u2705 audit passed \u2014 ${s}`:`\u274C audit failed \u2014 ${r}/${s}`),n},zk=async(e,t)=>{let{fixed:r,adoptionFlipped:n}=await zm(e,t);return n&&u.info(Gk),r},Xk=e=>{if(Gn(e).kind!=="stale")return null;let t=`${Ie} still registers "${de}" \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 "${de}" entry by hand in a PR, keeping its siblings`;return u.info(`[INFO] mcp mcp:legacy-key: ${t}`),{packageDir:e,packageName:"mcp",checks:[{name:"mcp:legacy-key",status:"pass",message:t}],passed:!0}},Ms=async(e={})=>{let t=ja(await Hk(e)),r=e.fix?await zk(e,t):void 0,n=await Kk(e),o=await Or(t),s=await qk(),i=[];for(let l of n)i.push(await oc(l.dir,l.baseline,{adoption:o,isRoot:l.isRoot,repoRoot:s}));if(e.root){let l=await tf(n[0].dir);l&&i.push(l);let d=await ef(n[0].dir,e.fix===!0);d&&i.push(d);let p=Xk(n[0].dir);p&&i.push(p)}let c={allPassed:Yk(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}},Zk={all:De.boolean().optional().describe("Audit every non-vendor workspace package"),root:De.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},Qk={allPassed:De.boolean().describe("Whether every audited package passed all checks"),packages:De.array(De.object({name:De.string(),passed:De.boolean(),checks:De.array(De.object({name:De.string(),status:De.enum(["pass","fail"]),message:De.string()}))})).describe("Per-package check results")},vc=S({name:"audit",description:"Audit packages against infra-kit.config.ts rules (config present and valid, required scripts, required files, and turbo tasks for the root). Defaults to the current package; all=true audits every non-vendor workspace package; root=true audits the monorepo root.",inputSchema:Zk,outputSchema:Qk,handler:e=>Ms({all:e.all,root:e.root})});import{z as xt}from"zod";import wc from"node:fs/promises";import eb from"node:path";var Fr=()=>Object.keys(Np.shape),tb=new Set(["protectedEnvs"]),Hn={project:"per-project override",global:"user-global override"},js=(e,t)=>{if(ye()&&tb.has(e))throw new x({status:"refused",agentMode:N.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(!Fr().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: ${Fr().join(", ")}.`)}},nf=e=>{try{return JSON.parse(e)}catch{return e}},rb=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),nb=async e=>{let t;try{t=await wc.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(!rb(r))throw new Error(`${v(e)} is not a JSON object \u2014 fix it with \`infra-kit config edit\`.`);return{raw:t,data:r}},ob=async(e,t)=>{t===null?await wc.rm(e,{force:!0}):Rn(e,t,420),Tn()},Fs=async(e,t,r)=>{let n=await H(),o=e==="global"?n.userGlobal:n.userProject,{raw:s,data:i}=await nb(o),a=i[t],c=r({...i});if(c===null)return{file:o,previous:a,changed:!1};await wc.mkdir(eb.dirname(o),{recursive:!0}),Rn(o,`${JSON.stringify(c,null,2)}
155
- `,420),Tn();try{await M({autoMigrate:"off"})}catch(l){throw await ob(o,s),new Error(`${l.message}
156
- ${v(o)} was left unchanged.`)}return{file:o,previous:a,changed:!0}},kc=async({key:e,value:t,global:r})=>{js(e,"config-set");let n=r?"global":"project",o=nf(t),{file:s,previous:i}=await Fs(n,e,c=>({...c,[e]:o}));u.info(`Set ${e} = ${JSON.stringify(o)} in the ${Hn[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 Ls=async({key:e}={})=>{let[t,r]=await Promise.all([M(),H()]),n=t;if(e===void 0){let s=Object.keys(t).sort();u.info(`Merged config for ${r.projectName} \u2014 ${s.length} section(s): ${s.join(", ")}`),u.info(` source: ${r.main}`)}else{if(!Fr().includes(e))throw new Error(`Unknown config key "${e}". Top-level keys: ${Fr().join(", ")}.`);u.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}},sb={config:xt.record(xt.string(),xt.unknown()).describe("The fully resolved infra-kit configuration \u2014 the same object every command sees at runtime, after the project infra-kit.json, the user-global, and the user-scope per-project override layers are merged (later layers win). Top-level sections include envManagement, ide, worktrees, dev, devServersPresets, and protectedEnvs."),configPath:xt.string().describe("Absolute path to the project-level infra-kit.json (the base layer / committed source of truth)."),key:xt.string().optional().describe("The top-level key asked for, when one was."),value:xt.unknown().optional().describe("The merged value of `key` (null when no layer sets it)."),projectName:xt.string().describe("Repository name the config is keyed to (the main-repo basename; shared across all worktrees of the repo).")},bc=S({name:"config-get",description:"Return the fully merged infra-kit configuration (project + user-global + per-project override layers) as it is resolved at runtime. Read-only introspection \u2014 makes no changes; use `config-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:xt.string().optional().describe("Report only this top-level key as `value` (e.g. `ide`).")},outputSchema:sb,handler:e=>Ls(e)});import ub from"node:fs";import{z as oe}from"zod";import Yn from"node:fs";import Lr from"node:path";import ib from"node:process";var ab=Lr.join(".infra-kit","dev-context"),cb=".infra-kit",of=(e,t)=>{let r=Lr.resolve(e);for(;;){let n=Lr.join(r,t);if(Yn.existsSync(n))return n;let o=Lr.dirname(r);if(o===r)return;r=o}},lb=e=>{let t=of(e,ab);if(t)return t;let r=of(e,cb);return r?Lr.join(r,"dev-context"):void 0},Rc=e=>typeof e=="number"&&Number.isFinite(e)?e:0,qn=e=>typeof e=="string"?e:"",db=(e,t,r)=>{let n=Lr.join(e,t);try{let o=Yn.statSync(n),s=JSON.parse(Yn.readFileSync(n,"utf-8"));if(typeof s!="object"||s===null)return null;let i=s;return{app:t.replace(/\.json$/,""),package:qn(i.package),port:Rc(i.port),alias:qn(i.alias),origin:qn(i.origin),release:qn(i.release),env:qn(i.env),pid:Rc(i.pid),writtenAt:Rc(i.writtenAt),mtimeMs:Math.round(o.mtimeMs),ageMs:Math.max(0,Math.round(r-o.mtimeMs))}}catch{return null}},zn=(e=ib.cwd())=>{let t=Date.now(),r=lb(e);if(!r||!Yn.existsSync(r))return{session:"none",fragmentDir:r,readAt:t,apps:[]};let n;try{n=Yn.readdirSync(r).filter(s=>s.endsWith(".json"))}catch{return{session:"none",fragmentDir:r,readAt:t,apps:[]}}let o=n.map(s=>db(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 Bs=async(e={})=>{let t=e.now??Date.now,r=e.isListening??Pn,n=zn(e.cwd),o=t(),s=await Promise.all(n.apps.map(async p=>{let m=Math.max(0,Math.round((o-p.mtimeMs)/1e3)),g=await r(p.port);return{app:p.app,package:p.package,port:p.port,pid:p.pid,alias:p.alias,origin:p.origin,release:p.release,env:p.env||null,writtenAt:p.writtenAt>0?new Date(p.writtenAt).toISOString():null,fragmentMtime:new Date(p.mtimeMs).toISOString(),ageSeconds:m,live:g}})),i=s.length>0,a=n.fragmentDir??null,c=a!==null&&(ub.statSync(a,{throwIfNoEntry:!1})?.isDirectory()??!1),l=a===null?"nothing (no .infra-kit anchor exists up-tree)":a;if(i){u.info(`infra-kit dev: ${s.length} app(s) with a dev-context fragment in ${l}:`);for(let p of s){let m=p.live?"live":"NOT responding",g=`written ${p.ageSeconds}s ago`;u.info(` ${p.app} (${p.package}) \u2192 ${p.origin} on :${p.port} \u2014 ${m}, ${g}`)}}else{let p=c?"no readable fragment found there":"that directory does not exist";u.info(`No active infra-kit dev session \u2014 searched ${l} (${p}).`)}let d={active:i,apps:s,contextDir:a,contextDirExists:c};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}},pb={active:oe.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:oe.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:oe.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:oe.array(oe.object({app:oe.string().describe("App folder name (the fragment filename without .json)."),package:oe.string().describe("The app package name the vite helper reads to decide a local route."),port:oe.number().describe("The actual bound port the dev server is listening on."),pid:oe.number().describe("PID of the dev-server process that wrote the fragment (ownership / staleness metadata)."),alias:oe.string().describe("Registered portless hostname for the app."),origin:oe.string().describe("Authoritative local origin the vite helper proxies to for this app."),release:oe.string().describe("Release slug the runner recorded for this worktree."),env:oe.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:oe.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:oe.string().describe("ISO 8601 filesystem mtime of the fragment file \u2014 the AUTHORITATIVE freshness signal."),ageSeconds:oe.number().describe("Seconds since the fragment was last written on disk. A large value with live:false means a stale/abandoned fragment."),live:oe.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.")},Sc=S({name:"dev-status",description:"Report what `infra-kit dev` currently has running by READING the on-disk dev-context fragments (never starts a server). Advisory + read-only: surfaces each app\u2019s package, bound port, portless alias, local origin, fragment freshness (mtime / ageSeconds), and a live TCP liveness probe of the port. The fragment directory is found by searching UPWARD from the working directory, so this agrees with the `infra-kit://dev-context` resource and with the vite helper\u2019s routing decision; `contextDir` / `contextDirExists` report where it looked and whether that directory is real. Returns { active: false, apps: [] } when no dev session is active.",inputSchema:{},outputSchema:pb,handler:()=>Bs()});import{spawnSync as Vg}from"node:child_process";import Y from"node:fs";import xl from"node:os";import ce from"node:path";import We from"node:process";import{z as ae}from"zod";import{execFileSync as mb}from"node:child_process";var sf=(e,t)=>{let r=e.filter(n=>!n.live).map(n=>n.name);return t?{prunable:[],withheld:r}:{prunable:r,withheld:[]}},fb=[/\binfra-kit\s+dev\b/,/cli\.js\s+dev\b/,/dev-server\.(?:js|ts)\b/],gb=e=>fb.some(t=>t.test(e)),hb="/bin/ps",yb=()=>mb(hb,["-eo","command="],{encoding:"utf8",maxBuffer:8<<20}).split(`
157
- `),af=(e=yb)=>{try{return e().some(gb)}catch{return!0}};import{Chalk as vb}from"chalk";import Pc from"node:process";var Ec={unicode:{ok:"\u2713",changed:"+",skipped:"-",manual:">",warn:"!",fail:"\u2717",separator:"\xB7",rule:"\u2500"},ascii:{ok:"ok",changed:"++",skipped:"--",manual:">>",warn:"!?",fail:"!!",separator:"-",rule:"-"}},wb=new Set(["warn","fail"]),kb=24,Br=" ",cf=" ",bb=(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:[""]},lf=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},Rb=e=>{let t=new vb({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)}},df=(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),Sb=(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=df(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}},Pb=(e,t,r,n)=>{let o=Sb(lf(e.rows),e.rows.length,t,r),s=Math.max(1,n-Br.length-e.label.length-o.plainWidth);return`${Br}${t.header(e.label)}${" ".repeat(s)}${o.text}`},Eb=(e,t,r,n,o)=>{let s=wb.has(e.status),i=n.ok.length,a=e.name.padEnd(t),c=r[e.status],l=s?c(a):a,d=cf.length+i+1+t+2,p=Math.max(kb,o-d),[m,...g]=bb(e.message,p),y=" ".repeat(d),R=$=>s?$:r.dim($);return[`${cf}${c(n[e.status])} ${l} ${R(m??"")}`.trimEnd(),...g.map($=>`${y}${R($)}`),...(e.notes??[]).map($=>`${y}${$}`.trimEnd())]},xb=(e,t,r,n,o)=>{let s=lf(t),i=n.rule.repeat(Math.max(12,Math.min(o-Br.length,56))),a=df(s,()=>"warned"),c=[r.ok(`${s.ok} passed`),...a.map(d=>r[d.status](d.plain))].join(` ${n.separator} `),l=(e.hints??[]).map(d=>` ${r.dim(d)}`);return[`${Br}${r.dim(i)}`,`${Br}${c}${l.join("")}`]},xc=(e,t={})=>{let r=t.width??80,n=Rb(t.color??!1),o=t.unicode??!0?Ec.unicode:Ec.ascii,s=e.sections.filter(d=>d.rows.length>0),i=s.flatMap(d=>d.rows),a=n.bold(e.title);if(i.length===0)return[a,"",`${Br}${n.dim(e.emptyMessage??"Nothing ran.")}`];let c=Math.max(...i.map(d=>d.name.length)),l=s.flatMap(d=>[Pb(d,n,o,r),...d.rows.flatMap(p=>Eb(p,c,n,o,r)),""]);return[a,"",...l,...xb(e,i,n,o,r)]},Tb=new Set(["","0","false","none"]),Cb=["LC_ALL","LC_CTYPE","LANG"],$b=(e,t)=>e.NO_COLOR!==void 0&&e.NO_COLOR!==""?!1:e.FORCE_COLOR!==void 0?!Tb.has(e.FORCE_COLOR.toLowerCase()):!!t.isTTY,Ab=(e,t)=>{if(t)return!1;let r=Cb.map(n=>e[n]).find(n=>n!==void 0&&n!=="");return r===void 0?!0:/UTF-?8/i.test(r)},Tc=(e={})=>{let t=e.env??Pc.env,r=e.stream??Pc.stderr;return{color:$b(t,r),unicode:Ab(t,e.ascii??!1),width:r.columns??80}},ze=(e,t={})=>{(t.write??(n=>{Pc.stderr.write(n)}))(`${xc(e,Tc(t)).join(`
154
+ `:"";try{return rf.mkdirSync(nf.dirname(e),{recursive:!0}),rf.writeFileSync(e,`${JSON.stringify(t,null,n)}${o}`,"utf-8"),!0}catch(s){return u.warn(`Could not write ${e} (${fc(s)}) \u2014 the ik-mcp entries were not updated.`),!1}},js=({projectRoot:e,proxies:t,write:r})=>{let n=nf.join(e,Ne),o=pc(n);if(o.kind==="unreadable")return u.warn(`Could not read ${n} (${fc(o.error)}) \u2014 left it untouched.`),{status:"unreadable",path:n,entries:[],wrote:!1};let s=o.kind==="raw"?o.raw:null,i=s===null?{}:mc(s);if(!rr(i))return u.warn(`Could not parse ${n} \u2014 left it untouched. Fix the JSON, then ${Ms}.`),{status:"unparseable",path:n,entries:[],wrote:!1};let a=i[Ze];if(a!==void 0&&!rr(a))return u.warn(`${n} has a "${Ze}" that is not an object \u2014 left it untouched.`),{status:"unparseable",path:n,entries:[],wrote:!1};let c=Yk(a??{},t,r);if(!c.changed)return{status:"ok",path:n,entries:c.entries,wrote:!1};let l=zk(n,{...i,[Ze]:c.servers},s);return{status:l?"ok":"failed",path:n,entries:c.entries,wrote:l}};var of=async(e,t)=>{let r;try{r=(await M()).mcp}catch{return null}if(!r||Object.keys(r).length===0)return null;let n=js({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 Xk=(e,t)=>[...t.map(r=>({name:`devServersPresets:config:${r.app}`,status:"fail",message:`could not load apps/${r.app}/ui/infra-kit.config.ts (referenced by a preset proxy override): ${r.message}`})),...e.map(r=>({name:`devServersPresets:${r.preset}`,status:"fail",message:r.message}))],sf=async e=>{let t=(await M()).devServersPresets;if(!t||Object.keys(t).length===0)return null;let r=Jp(t);if(r.length>0){let d=r.map(p=>({name:`devServersPresets:${p.preset}`,status:"fail",message:p.message}));return{packageDir:e,packageName:"devServersPresets",checks:d,passed:!1}}let n=Vp(e),o=Up(e),s={api:n.map(d=>d.name),ui:o.map(d=>d.name)},{ctx:i,loadErrors:a}=await Kp(e,t,s,n),c=Xk(Gp(t,i),a),l=c.length===0?[{name:"devServersPresets:proxy-locality",status:"pass",message:"every local proxy override resolves to a backend the preset launches"}]:c;return{packageDir:e,packageName:"devServersPresets",checks:l,passed:c.length===0}};var Zk="workspace adopted \u2014 every other package now needs a CLAUDE.md: run infra-kit audit --fix --all",Qk=async e=>e.root?[{dir:await T(),baseline:Fn,isRoot:!0}]:e.all?(await Pe(await T())).map(r=>({dir:r})):[{dir:await Vn(e.cwd??af.cwd())}],eb=async e=>e.root||e.all?await T():e.cwd??af.cwd(),tb=async()=>{try{return await T()}catch{return}},rb=e=>{let t=0,r=0;for(let i of e)for(let a of i.checks)t+=1,a.status!=="pass"&&(r+=1,u.info(`[FAIL] ${i.packageName} ${a.name}: ${a.message}`));let n=e.every(i=>i.passed),o=(i,a)=>`${i} ${a}${i===1?"":"s"}`,s=`${o(t,"check")}, ${o(e.length,"target")}`;return u.info(n?`\u2705 audit passed \u2014 ${s}`:`\u274C audit failed \u2014 ${r}/${s}`),n},nb=async(e,t)=>{let{fixed:r,adoptionFlipped:n}=await ef(e,t);return n&&u.info(Zk),r},ob=e=>{if(qn(e).kind!=="stale")return null;let t=`${Ne} still registers "${ue}" \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 "${ue}" entry by hand in a PR, keeping its siblings`;return u.info(`[INFO] mcp mcp:legacy-key: ${t}`),{packageDir:e,packageName:"mcp",checks:[{name:"mcp:legacy-key",status:"pass",message:t}],passed:!0}},Fs=async(e={})=>{let t=La(await eb(e)),r=e.fix?await nb(e,t):void 0,n=await Qk(e),o=await Nr(t),s=await tb(),i=[];for(let l of n)i.push(await ic(l.dir,l.baseline,{adoption:o,isRoot:l.isRoot,repoRoot:s}));if(e.root){let l=await sf(n[0].dir);l&&i.push(l);let d=await of(n[0].dir,e.fix===!0);d&&i.push(d);let p=ob(n[0].dir);p&&i.push(p)}let c={allPassed:rb(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}},sb={all:_e.boolean().optional().describe("Audit every non-vendor workspace package"),root:_e.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},ib={allPassed:_e.boolean().describe("Whether every audited package passed all checks"),packages:_e.array(_e.object({name:_e.string(),passed:_e.boolean(),checks:_e.array(_e.object({name:_e.string(),status:_e.enum(["pass","fail"]),message:_e.string()}))})).describe("Per-package check results")},kc=S({name:"audit",description:"Audit packages against infra-kit.config.ts rules (config present and valid, required scripts, required files, and turbo tasks for the root). Defaults to the current package; all=true audits every non-vendor workspace package; root=true audits the monorepo root.",inputSchema:sb,outputSchema:ib,handler:e=>Fs({all:e.all,root:e.root})});import{z as $t}from"zod";import bc from"node:fs/promises";import ab from"node:path";var Wr=()=>Object.keys(jp.shape),cb=new Set(["protectedEnvs"]),zn={project:"per-project override",global:"user-global override"},Ls=(e,t)=>{if(ye()&&cb.has(e))throw new C({status:"refused",agentMode:N.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(!Wr().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: ${Wr().join(", ")}.`)}},cf=e=>{try{return JSON.parse(e)}catch{return e}},lb=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),db=async e=>{let t;try{t=await bc.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(!lb(r))throw new Error(`${v(e)} is not a JSON object \u2014 fix it with \`infra-kit config edit\`.`);return{raw:t,data:r}},ub=async(e,t)=>{t===null?await bc.rm(e,{force:!0}):En(e,t,420),An()},Bs=async(e,t,r)=>{let n=await H(),o=e==="global"?n.userGlobal:n.userProject,{raw:s,data:i}=await db(o),a=i[t],c=r({...i});if(c===null)return{file:o,previous:a,changed:!1};await bc.mkdir(ab.dirname(o),{recursive:!0}),En(o,`${JSON.stringify(c,null,2)}
155
+ `,420),An();try{await M({autoMigrate:"off"})}catch(l){throw await ub(o,s),new Error(`${l.message}
156
+ ${v(o)} was left unchanged.`)}return{file:o,previous:a,changed:!0}},Rc=async({key:e,value:t,global:r})=>{Ls(e,"config-set");let n=r?"global":"project",o=cf(t),{file:s,previous:i}=await Bs(n,e,c=>({...c,[e]:o}));u.info(`Set ${e} = ${JSON.stringify(o)} in the ${zn[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 Ws=async({key:e}={})=>{let[t,r]=await Promise.all([M(),H()]),n=t;if(e===void 0){let s=Object.keys(t).sort();u.info(`Merged config for ${r.projectName} \u2014 ${s.length} section(s): ${s.join(", ")}`),u.info(` source: ${r.main}`)}else{if(!Wr().includes(e))throw new Error(`Unknown config key "${e}". Top-level keys: ${Wr().join(", ")}.`);u.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}},pb={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, ide, worktrees, dev, devServersPresets, 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).")},Sc=S({name:"config-get",description:"Return the fully merged infra-kit configuration (project + user-global + per-project override layers) as it is resolved at runtime. Read-only introspection \u2014 makes no changes; use `config-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:pb,handler:e=>Ws(e)});import vb from"node:fs";import{z as oe}from"zod";import Zn from"node:fs";import Vr from"node:path";import mb from"node:process";var fb=Vr.join(".infra-kit","dev-context"),gb=".infra-kit",lf=(e,t)=>{let r=Vr.resolve(e);for(;;){let n=Vr.join(r,t);if(Zn.existsSync(n))return n;let o=Vr.dirname(r);if(o===r)return;r=o}},hb=e=>{let t=lf(e,fb);if(t)return t;let r=lf(e,gb);return r?Vr.join(r,"dev-context"):void 0},Pc=e=>typeof e=="number"&&Number.isFinite(e)?e:0,Xn=e=>typeof e=="string"?e:"",yb=(e,t,r)=>{let n=Vr.join(e,t);try{let o=Zn.statSync(n),s=JSON.parse(Zn.readFileSync(n,"utf-8"));if(typeof s!="object"||s===null)return null;let i=s;return{app:t.replace(/\.json$/,""),package:Xn(i.package),port:Pc(i.port),alias:Xn(i.alias),origin:Xn(i.origin),release:Xn(i.release),env:Xn(i.env),pid:Pc(i.pid),writtenAt:Pc(i.writtenAt),mtimeMs:Math.round(o.mtimeMs),ageMs:Math.max(0,Math.round(r-o.mtimeMs))}}catch{return null}},Qn=(e=mb.cwd())=>{let t=Date.now(),r=hb(e);if(!r||!Zn.existsSync(r))return{session:"none",fragmentDir:r,readAt:t,apps:[]};let n;try{n=Zn.readdirSync(r).filter(s=>s.endsWith(".json"))}catch{return{session:"none",fragmentDir:r,readAt:t,apps:[]}}let o=n.map(s=>yb(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 Vs=async(e={})=>{let t=e.now??Date.now,r=e.isListening??Tn,n=Qn(e.cwd),o=t(),s=await Promise.all(n.apps.map(async p=>{let m=Math.max(0,Math.round((o-p.mtimeMs)/1e3)),g=await r(p.port);return{app:p.app,package:p.package,port:p.port,pid:p.pid,alias:p.alias,origin:p.origin,release:p.release,env:p.env||null,writtenAt:p.writtenAt>0?new Date(p.writtenAt).toISOString():null,fragmentMtime:new Date(p.mtimeMs).toISOString(),ageSeconds:m,live:g}})),i=s.length>0,a=n.fragmentDir??null,c=a!==null&&(vb.statSync(a,{throwIfNoEntry:!1})?.isDirectory()??!1),l=a===null?"nothing (no .infra-kit anchor exists up-tree)":a;if(i){u.info(`infra-kit dev: ${s.length} app(s) with a dev-context fragment in ${l}:`);for(let p of s){let m=p.live?"live":"NOT responding",g=`written ${p.ageSeconds}s ago`;u.info(` ${p.app} (${p.package}) \u2192 ${p.origin} on :${p.port} \u2014 ${m}, ${g}`)}}else{let p=c?"no readable fragment found there":"that directory does not exist";u.info(`No active infra-kit dev session \u2014 searched ${l} (${p}).`)}let d={active:i,apps:s,contextDir:a,contextDirExists:c};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}},wb={active:oe.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:oe.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:oe.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:oe.array(oe.object({app:oe.string().describe("App folder name (the fragment filename without .json)."),package:oe.string().describe("The app package name the vite helper reads to decide a local route."),port:oe.number().describe("The actual bound port the dev server is listening on."),pid:oe.number().describe("PID of the dev-server process that wrote the fragment (ownership / staleness metadata)."),alias:oe.string().describe("Registered portless hostname for the app."),origin:oe.string().describe("Authoritative local origin the vite helper proxies to for this app."),release:oe.string().describe("Release slug the runner recorded for this worktree."),env:oe.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:oe.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:oe.string().describe("ISO 8601 filesystem mtime of the fragment file \u2014 the AUTHORITATIVE freshness signal."),ageSeconds:oe.number().describe("Seconds since the fragment was last written on disk. A large value with live:false means a stale/abandoned fragment."),live:oe.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.")},Ec=S({name:"dev-status",description:"Report what `infra-kit dev` currently has running by READING the on-disk dev-context fragments (never starts a server). Advisory + read-only: surfaces each app\u2019s package, bound port, portless alias, local origin, fragment freshness (mtime / ageSeconds), and a live TCP liveness probe of the port. The fragment directory is found by searching UPWARD from the working directory, so this agrees with the `infra-kit://dev-context` resource and with the vite helper\u2019s routing decision; `contextDir` / `contextDirExists` report where it looked and whether that directory is real. Returns { active: false, apps: [] } when no dev session is active.",inputSchema:{},outputSchema:wb,handler:()=>Vs()});import{spawnSync as Kg}from"node:child_process";import Y from"node:fs";import Cl from"node:os";import ce from"node:path";import Ue from"node:process";import{z as ae}from"zod";import{execFileSync as kb}from"node:child_process";var df=(e,t)=>{let r=e.filter(n=>!n.live).map(n=>n.name);return t?{prunable:[],withheld:r}:{prunable:r,withheld:[]}},bb=[/\binfra-kit\s+dev\b/,/cli\.js\s+dev\b/,/dev-server\.(?:js|ts)\b/],Rb=e=>bb.some(t=>t.test(e)),Sb="/bin/ps",Pb=()=>kb(Sb,["-eo","command="],{encoding:"utf8",maxBuffer:8<<20}).split(`
157
+ `),uf=(e=Pb)=>{try{return e().some(Rb)}catch{return!0}};import{Chalk as Eb}from"chalk";import xc from"node:process";var Tc={unicode:{ok:"\u2713",changed:"+",skipped:"-",manual:">",warn:"!",fail:"\u2717",separator:"\xB7",rule:"\u2500"},ascii:{ok:"ok",changed:"++",skipped:"--",manual:">>",warn:"!?",fail:"!!",separator:"-",rule:"-"}},xb=new Set(["warn","fail"]),Tb=24,Ur=" ",pf=" ",Cb=(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:[""]},mf=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},$b=e=>{let t=new Eb({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)}},ff=(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),Ab=(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=ff(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}},Ob=(e,t,r,n)=>{let o=Ab(mf(e.rows),e.rows.length,t,r),s=Math.max(1,n-Ur.length-e.label.length-o.plainWidth);return`${Ur}${t.header(e.label)}${" ".repeat(s)}${o.text}`},Ib=(e,t,r,n,o)=>{let s=xb.has(e.status),i=n.ok.length,a=e.name.padEnd(t),c=r[e.status],l=s?c(a):a,d=pf.length+i+1+t+2,p=Math.max(Tb,o-d),[m,...g]=Cb(e.message,p),y=" ".repeat(d),R=x=>s?x:r.dim(x);return[`${pf}${c(n[e.status])} ${l} ${R(m??"")}`.trimEnd(),...g.map(x=>`${y}${R(x)}`),...(e.notes??[]).map(x=>`${y}${x}`.trimEnd())]},Db=(e,t,r,n,o)=>{let s=mf(t),i=n.rule.repeat(Math.max(12,Math.min(o-Ur.length,56))),a=ff(s,()=>"warned"),c=[r.ok(`${s.ok} passed`),...a.map(d=>r[d.status](d.plain))].join(` ${n.separator} `),l=(e.hints??[]).map(d=>` ${r.dim(d)}`);return[`${Ur}${r.dim(i)}`,`${Ur}${c}${l.join("")}`]},Cc=(e,t={})=>{let r=t.width??80,n=$b(t.color??!1),o=t.unicode??!0?Tc.unicode:Tc.ascii,s=e.sections.filter(d=>d.rows.length>0),i=s.flatMap(d=>d.rows),a=n.bold(e.title);if(i.length===0)return[a,"",`${Ur}${n.dim(e.emptyMessage??"Nothing ran.")}`];let c=Math.max(...i.map(d=>d.name.length)),l=s.flatMap(d=>[Ob(d,n,o,r),...d.rows.flatMap(p=>Ib(p,c,n,o,r)),""]);return[a,"",...l,...Db(e,i,n,o,r)]},Nb=new Set(["","0","false","none"]),_b=["LC_ALL","LC_CTYPE","LANG"],Mb=(e,t)=>e.NO_COLOR!==void 0&&e.NO_COLOR!==""?!1:e.FORCE_COLOR!==void 0?!Nb.has(e.FORCE_COLOR.toLowerCase()):!!t.isTTY,jb=(e,t)=>{if(t)return!1;let r=_b.map(n=>e[n]).find(n=>n!==void 0&&n!=="");return r===void 0?!0:/UTF-?8/i.test(r)},$c=(e={})=>{let t=e.env??xc.env,r=e.stream??xc.stderr;return{color:Mb(t,r),unicode:jb(t,e.ascii??!1),width:r.columns??80}},Qe=(e,t={})=>{(t.write??(n=>{xc.stderr.write(n)}))(`${Cc(e,$c(t)).join(`
158
158
  `)}
159
- `)};var Ob="Tools & CLIs",Ib="Shell & integration",Db="Project config",Nb="Doppler env tokens",_b="Dev proxy (portless)",Mb="Claude Code plugin",jb=`portless serving TLS on :${ht}`,Cc=[[Ob,["brew installed","git installed","gh installed","gh authenticated","doppler installed","aws installed","package manager installed","typescript-language-server installed","orca installed","ide installed"]],[Ib,["zshrc init block","zshenv session block","pnpm enableGlobalVirtualStore","CLAUDE.md block"]],[Db,["infra-kit config valid","user override path","legacy user-global config","merge-dev resolutions"]],[Nb,["tokens.json present","env tokens configured","tokens.json perms"]],[_b,["portless installed","portless node","portless service target",jb,"portless CA chain valid","portless CA trusted","portless routes"]],[Mb,["claude CLI","marketplace registered","plugin installed","plugin version","plugin MCP server","CLI version","claude in chrome","Agent mode","Agent allowlist"]]],uf="Other",Fb=Cc.map(([e])=>e),Lb=new Map(Cc.flatMap(([e,t])=>t.map(r=>[r,e]))),iF=Cc.flatMap(([,e])=>e),$c=new Set(["portless routes","tokens.json perms"]),Bb=e=>{let t=new Map;for(let n of e){let o=Lb.get(n.name)??uf,s=t.get(o);s?s.push(n):t.set(o,[n])}return[...Fb,uf].flatMap(n=>{let o=t.get(n);return o&&o.length>0?[{label:n,checks:o}]:[]})};var Wb=e=>{switch(e){case"pass":return"ok";case"fail":return"fail";case"warn":return"warn";case"skip":return"skipped";default:return Ae(e)}},Vb=e=>{let t=e.filter(r=>r.status==="fail"&&$c.has(r.name)).length;return{title:"infra-kit doctor",emptyMessage:"No checks ran.",sections:Bb(e).map(r=>({label:r.label,rows:r.checks.map(n=>({name:n.name,status:Wb(n.status),message:n.message}))})),hints:t>0?[`${t} fixable \u2014 run \`infra-kit doctor --fix\``]:[]}};var Ac=(e,t={})=>{ze(Vb(e),t)};var Ub=e=>e.replace(/&apos;/g,"'").replace(/&quot;/g,'"').replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&amp;/g,"&"),Jb=e=>[...e.matchAll(/<string>([\s\S]*?)<\/string>/g)].map(t=>Ub(t[1])),Gb=e=>{let t=e.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/);return t===null?null:Jb(t[1])},Kb=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},Hb=e=>{let t=e.split(`
160
- `).find(r=>r.startsWith("ExecStart="));return t===void 0?null:Kb(t.slice(10))},pf=(e,t)=>{try{return e==="darwin"?Gb(t):e==="linux"?Hb(t):null}catch{return null}};import{Buffer as If}from"node:buffer";import Ee from"node:fs/promises";import Ze from"node:path";import Df from"node:process";import{$ as Xs}from"zx";import qb from"node:process";var Xn=class extends Error{name="PromptCancelledError";constructor(){super("Prompt cancelled")}};var mf=e=>{let t={operation:"interactive branch selection",remediation:"pass the branch selection explicitly (`--version`/`--versions`/`--all`) for non-interactive, --json, or --agent runs"};if(J())throw new x({status:"argument_required",argument:e,agentMode:N.source},2,t);if(!qb.stdin.isTTY)throw new f(void 0,t)},Tt=async e=>{mf("version");let{runBranchPicker:t}=await import("./boot-LC2ESPY6.js"),r=await t(e);if(r===null)throw new Xn;return r},Ct=async(e,t)=>{mf("versions");let{runBranchMultiPicker:r}=await import("./boot-LC2ESPY6.js"),n=await r(e,t);if(n===null)throw new Xn;return n};import{$ as kf}from"zx";import{$ as yF}from"zx";import{$ as Vr}from"zx";import{$ as ff}from"zx";var Oc=async e=>{let{operation:t}=e;try{await ff({quiet:!0})`git rev-parse --git-dir`}catch(r){throw new f(r,{operation:t,remediation:"run this from inside a git repository"})}try{await ff({quiet:!0})`git remote get-url origin`}catch(r){throw new f(r,{operation:t,remediation:"this repository has no `origin` remote to fetch from or push to"})}},zb=4,Wr=async e=>{let{operation:t}=e,r=await bp();if(r.length===0)return;u.error(`working tree has uncommitted changes:
159
+ `)};var Fb="Tools & CLIs",Lb="Shell & integration",Bb="Project config",Wb="Doppler env tokens",Vb="Dev proxy (portless)",Ub="Claude Code plugin",Jb=`portless serving TLS on :${vt}`,Ac=[[Fb,["brew installed","git installed","gh installed","gh authenticated","doppler installed","aws installed","package manager installed","typescript-language-server installed","orca installed","ide installed"]],[Lb,["zshrc init block","zshenv session block","pnpm enableGlobalVirtualStore","CLAUDE.md block"]],[Bb,["infra-kit config valid","user override path","legacy user-global config","merge-dev resolutions"]],[Wb,["tokens.json present","env tokens configured","tokens.json perms"]],[Vb,["portless installed","portless node","portless service target",Jb,"portless CA chain valid","portless CA trusted","portless routes"]],[Ub,["claude CLI","marketplace registered","plugin installed","plugin version","plugin MCP server","CLI version","claude in chrome","Agent mode","Agent allowlist"]]],gf="Other",Gb=Ac.map(([e])=>e),Kb=new Map(Ac.flatMap(([e,t])=>t.map(r=>[r,e]))),bF=Ac.flatMap(([,e])=>e),Oc=new Set(["portless routes","tokens.json perms"]),Hb=e=>{let t=new Map;for(let n of e){let o=Kb.get(n.name)??gf,s=t.get(o);s?s.push(n):t.set(o,[n])}return[...Gb,gf].flatMap(n=>{let o=t.get(n);return o&&o.length>0?[{label:n,checks:o}]:[]})};var qb=e=>{switch(e){case"pass":return"ok";case"fail":return"fail";case"warn":return"warn";case"skip":return"skipped";default:return Ie(e)}},Yb=e=>{let t=e.filter(r=>r.status==="fail"&&Oc.has(r.name)).length;return{title:"infra-kit doctor",emptyMessage:"No checks ran.",sections:Hb(e).map(r=>({label:r.label,rows:r.checks.map(n=>({name:n.name,status:qb(n.status),message:n.message}))})),hints:t>0?[`${t} fixable \u2014 run \`infra-kit doctor --fix\``]:[]}};var Ic=(e,t={})=>{Qe(Yb(e),t)};var zb=e=>e.replace(/&apos;/g,"'").replace(/&quot;/g,'"').replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&amp;/g,"&"),Xb=e=>[...e.matchAll(/<string>([\s\S]*?)<\/string>/g)].map(t=>zb(t[1])),Zb=e=>{let t=e.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/);return t===null?null:Xb(t[1])},Qb=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},eR=e=>{let t=e.split(`
160
+ `).find(r=>r.startsWith("ExecStart="));return t===void 0?null:Qb(t.slice(10))},hf=(e,t)=>{try{return e==="darwin"?Zb(t):e==="linux"?eR(t):null}catch{return null}};import{Buffer as Mf}from"node:buffer";import xe from"node:fs/promises";import tt from"node:path";import jf from"node:process";import{$ as Qs}from"zx";import tR from"node:process";var eo=class extends Error{name="PromptCancelledError";constructor(){super("Prompt cancelled")}};var yf=e=>{let t={operation:"interactive branch selection",remediation:"pass the branch selection explicitly (`--version`/`--versions`/`--all`) for non-interactive, --json, or --agent runs"};if(J())throw new C({status:"argument_required",argument:e,agentMode:N.source},2,t);if(!tR.stdin.isTTY)throw new f(void 0,t)},At=async e=>{yf("version");let{runBranchPicker:t}=await import("./boot-LC2ESPY6.js"),r=await t(e);if(r===null)throw new eo;return r},Ot=async(e,t)=>{yf("versions");let{runBranchMultiPicker:r}=await import("./boot-LC2ESPY6.js"),n=await r(e,t);if(n===null)throw new eo;return n};import{$ as Pf}from"zx";import{$ as IF}from"zx";import{$ as Gr}from"zx";import{$ as vf}from"zx";var Dc=async e=>{let{operation:t}=e;try{await vf({quiet:!0})`git rev-parse --git-dir`}catch(r){throw new f(r,{operation:t,remediation:"run this from inside a git repository"})}try{await vf({quiet:!0})`git remote get-url origin`}catch(r){throw new f(r,{operation:t,remediation:"this repository has no `origin` remote to fetch from or push to"})}},nR=4,Jr=async e=>{let{operation:t}=e,r=await Pp();if(r.length===0)return;u.error(`working tree has uncommitted changes:
161
161
  ${r.join(`
162
- `)}`);let n=r.slice(0,zb),o=r.length-n.length,s=o>0?`${n.join(", ")} (+${o} more)`:n.join(", ");throw new f(void 0,{operation:t,remediation:"commit or stash your changes (`git stash -u`), then retry",stderrExcerpt:`working tree has uncommitted changes: ${s}`})},Zn=async e=>{let{operation:t,base:r}=e;if(await Pr()===r)return;let n=(await gt(await T())).find(o=>o.branch===r);if(n)throw new f(void 0,{operation:t,remediation:"close or remove that worktree, or run the release from it",stderrExcerpt:`base branch "${r}" is checked out in the worktree at ${n.path}`})},Pe=async e=>{let{operation:t}=e;if(await Sp())throw new f(void 0,{operation:t,remediation:"run this from the main repository checkout, not a linked git worktree",stderrExcerpt:"command run from inside a linked worktree"});await Wr({operation:t})};var Xb=e=>e.map(t=>({pr:t,id:G(t.headRefName)})).filter(t=>t.id!==null).sort((t,r)=>kp(t.id,r.id,{a:t.pr.createdAt,b:r.pr.createdAt})).map(t=>t.pr),Qn=200,gf=(e,t)=>{e.length<Qn||u.warn({source:t,limit:Qn},`\u26A0\uFE0F ${t} returned ${Qn} PRs \u2014 the page is full, so older release PRs may be missing`)},Zb=async()=>{let[e,t]=await Promise.all([Vr`gh pr list --limit ${Qn} --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,Vr`gh pr list --limit ${Qn} --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName,createdAt`]),r=JSON.parse(e.stdout),n=JSON.parse(t.stdout);gf(r,"release PR discovery (base dev)"),gf(n,"hotfix PR discovery (base main)");let o=new Set(r.map(c=>c.headRefName)),s=new Set(n.filter(c=>o.has(c.headRefName)).map(c=>c.headRefName)),i=[...n,...r],a=new Set;return i.filter(c=>a.has(c.headRefName)?!1:(a.add(c.headRefName),!0)).map(c=>({...c,dualBase:s.has(c.headRefName)}))},eo="find open release PRs",hf=async()=>{try{let e=await Zb();if(e.length===0)throw new f(void 0,{operation:eo,remediation:"open a release PR first, or check you are in the right repo"});return Xb(e)}catch(e){throw e instanceof f?e:(u.debug({err:e},"Error fetching release PRs"),new f(e,{operation:"fetch release PRs"}))}},Ws=async()=>(await hf()).map(t=>t.headRefName),Qb=e=>{let t=to(e.baseRefName);if(t===null)throw new f(void 0,{operation:"classify release PRs",remediation:"discovery returned a PR outside the dev/main base set \u2014 this is an infra-kit bug, please report it",stderrExcerpt:`${e.headRefName} (#${e.number}) targets ${e.baseRefName}`});let r=Ic(e.title)!==t;return(r||e.dualBase)&&u.warn({branch:e.headRefName,title:e.title,baseRefName:e.baseRefName},e.dualBase?`\u26A0\uFE0F ${e.headRefName} has open PRs to both dev and main \u2014 treated as a hotfix (base main)`:`\u26A0\uFE0F ${e.headRefName} is titled "${e.title}" but targets ${e.baseRefName} \u2014 treated as ${t} by its base`),{branch:e.headRefName,number:e.number,title:e.title,createdAt:e.createdAt,baseRefName:e.baseRefName,type:t,titleMismatch:r,dualBase:e.dualBase}},F=async()=>(await hf()).map(Qb),Vs=async e=>{let{branch:t,body:r}=e;try{await Vr({quiet:!0})`gh pr edit ${t} --body ${r}`}catch(n){throw u.error({error:n,branch:t},`Error updating release PR body for ${t}`),n}},eR=async(e,t)=>{let r=Vr({quiet:!0,nothrow:!0}),n=await r`git ls-remote --heads origin ${e}`,o=n.exitCode!==0,s=n.stdout.trim().length>0;if(o||s){u.error({branchName:e},o?`could not reach origin to check whether ${e} was pushed \u2014 the branch is left in place; check with \`git ls-remote --heads origin ${e}\` before deleting anything`:`release branch ${e} exists on origin without a PR \u2014 left in place; delete it with \`git push origin --delete ${e}\` once you are sure`);return}await r`git switch ${t}`,(await r`git branch -D ${e}`).exitCode!==0&&u.error({branchName:e},`could not remove the local branch ${e} after a failed release \u2014 delete it with \`git branch -D ${e}\` before retrying`)},Us=async e=>{let{id:t,jiraVersionUrl:r,type:n,description:o,baseSha:s}=e,i=wp(t,n),a=Xe(n),c=Vr({quiet:!0}),l=ve(t),d=ro(r,o);try{await Wr({operation:`create release branch ${l}`});let p=(await c`git rev-parse HEAD`).stdout.trim();if(p!==s)throw new f(void 0,{operation:`create release branch ${l}`,remediation:"something moved the checkout mid-run \u2014 re-run the release",stderrExcerpt:`expected to be on ${s.slice(0,8)} (${a}) but HEAD is ${p.slice(0,8)}`});await c`git checkout -b ${l}`;try{await c`git commit --allow-empty-message --allow-empty --message ''`,await c`git push -u origin ${l}`;let m=await c`gh pr create --title ${i} --body ${d} --base ${a} --head ${l}`;return{branchName:l,prUrl:m.stdout.trim()}}catch(m){throw await eR(l,a),m}}catch(p){throw u.error({error:p,branchName:l},`Error creating release branch ${l}`),p}finally{await Vr({quiet:!0,nothrow:!0})`git switch ${a}`}};import{$ as Dc}from"zx";var Ur=async e=>{let t=await Dc`gh pr list --head ${e} --state all --json number,state,title,baseRefName,headRefName --limit 1`;return JSON.parse(t.stdout)[0]??null},Nc=async e=>{let t=await Dc`gh pr list --head ${e} --state open --limit 5 --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)},_c=async e=>{try{let t=await Dc`gh pr view ${e} --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)}catch(t){throw new f(t,{operation:`fetch PR #${e}`,remediation:`check it exists with \`gh pr view ${e}\``})}};import oo from"node:process";var tR="x-seraph-loginreason",rR="AUTHENTICATED_FAILED",nR=(e,t=160)=>{let r=e.split(`
163
- `,1)[0].trim();return r.length>t?`${r.slice(0,t)}\u2026`:r},vf=(e,t)=>t===rR||e===401?"auth":e===403?"forbidden":e===404?"not-found-or-forbidden":"other",yf=(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}`,Jr=class extends Error{status;kind;body;context;constructor(t){let r=vf(t.status,t.seraphLoginReason),n=nR(t.body);super(n===""?`${t.context}: ${yf(r,t.status)}`:`${t.context}: ${yf(r,t.status)}. Jira said: ${n}`),this.name="JiraApiError",this.status=t.status,this.kind=r,this.body=t.body,this.context=t.context}},no=e=>e instanceof Jr,wf=e=>e.headers.get(tR);var Gr=async(e,t)=>{if(e.ok)return;let r=await e.text(),n=new Jr({status:e.status,seraphLoginReason:wf(e),body:r,context:t});throw u.debug({status:e.status,kind:n.kind,body:r},t),n},tr=(e,t)=>`${e.baseUrl}/projects/${t.projectId}/versions/${t.id}/tab/release-report-all-issues`,Mc=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 Gr(l,"Failed to create Jira version"),{success:!0,version:await l.json()}},Kr=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 Gr(a,"Failed to get Jira project versions"),await a.json()},at=async(e,t)=>(await Kr(t)).find(o=>o.name===e)||null,Hr=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 Gr(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}},jc=async(e,t)=>{let{versionName:r}=e,n=await at(r,t);if(!n)throw new Error(`Version "${r}" not found in Jira project`);return await Hr({versionId:n.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},t)},qr=async()=>{let e=oo.env.JIRA_BASE_URL,t=oo.env.JIRA_TOKEN||oo.env.JIRA_API_TOKEN,r=oo.env.JIRA_PROJECT_ID,n=oo.env.JIRA_EMAIL,o=[];if(e||o.push("JIRA_BASE_URL (e.g., https://your-domain.atlassian.net)"),t||o.push("JIRA_TOKEN or JIRA_API_TOKEN (your Jira API token)"),r||o.push("JIRA_PROJECT_ID (numeric project ID)"),n||o.push("JIRA_EMAIL (your Jira email address)"),o.length>0){let i=["Jira configuration is required but incomplete.","Please configure the following environment variables:",...o.map(a=>` - ${a}`),"","You can set these in your .env file or as environment variables."].join(`
164
- `);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}},ct=async()=>{try{return await qr()}catch(e){return u.warn({err:e},"Jira configuration not available, skipping Jira integration"),null}};var Js=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 Gr(a,"Failed to get Jira version issue counts");let c=await a.json();return{issuesFixedCount:c.issuesFixedCount,issuesAffectedCount:c.issuesAffectedCount}},Fc=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 Gr(c,"Failed to remove Jira version")};var bf="dev",Rf={regular:"dev",hotfix:"main"},Xe=e=>Rf[e],to=e=>{let t=Object.entries(Rf).find(([,r])=>r===e);return t?t[0]:null},ro=(e,t)=>(t??"").trim()!==""?`${e}
162
+ `)}`);let n=r.slice(0,nR),o=r.length-n.length,s=o>0?`${n.join(", ")} (+${o} more)`:n.join(", ");throw new f(void 0,{operation:t,remediation:"commit or stash your changes (`git stash -u`), then retry",stderrExcerpt:`working tree has uncommitted changes: ${s}`})},to=async e=>{let{operation:t,base:r}=e;if(await Tr()===r)return;let n=(await Ke(await T())).find(o=>o.branch===r);if(n)throw new f(void 0,{operation:t,remediation:"close or remove that worktree, or run the release from it",stderrExcerpt:`base branch "${r}" is checked out in the worktree at ${n.path}`})},Ee=async e=>{let{operation:t}=e;if(await xp())throw new f(void 0,{operation:t,remediation:"run this from the main repository checkout, not a linked git worktree",stderrExcerpt:"command run from inside a linked worktree"});await Jr({operation:t})};var oR=e=>e.map(t=>({pr:t,id:G(t.headRefName)})).filter(t=>t.id!==null).sort((t,r)=>Sp(t.id,r.id,{a:t.pr.createdAt,b:r.pr.createdAt})).map(t=>t.pr),ro=200,wf=(e,t)=>{e.length<ro||u.warn({source:t,limit:ro},`\u26A0\uFE0F ${t} returned ${ro} PRs \u2014 the page is full, so older release PRs may be missing`)},sR=async()=>{let[e,t]=await Promise.all([Gr`gh pr list --limit ${ro} --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,Gr`gh pr list --limit ${ro} --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName,createdAt`]),r=JSON.parse(e.stdout),n=JSON.parse(t.stdout);wf(r,"release PR discovery (base dev)"),wf(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)}))},no="find open release PRs",kf=async()=>{try{let e=await sR();if(e.length===0)throw new f(void 0,{operation:no,remediation:"open a release PR first, or check you are in the right repo"});return oR(e)}catch(e){throw e instanceof f?e:(u.debug({err:e},"Error fetching release PRs"),new f(e,{operation:"fetch release PRs"}))}},Us=async()=>(await kf()).map(t=>t.headRefName),iR=e=>{let t=oo(e.baseRefName);if(t===null)throw new f(void 0,{operation:"classify release PRs",remediation:"discovery returned a PR outside the dev/main base set \u2014 this is an infra-kit bug, please report it",stderrExcerpt:`${e.headRefName} (#${e.number}) targets ${e.baseRefName}`});let r=Nc(e.title)!==t;return(r||e.dualBase)&&u.warn({branch:e.headRefName,title:e.title,baseRefName:e.baseRefName},e.dualBase?`\u26A0\uFE0F ${e.headRefName} has open PRs to both dev and main \u2014 treated as a hotfix (base main)`:`\u26A0\uFE0F ${e.headRefName} is titled "${e.title}" but targets ${e.baseRefName} \u2014 treated as ${t} by its base`),{branch:e.headRefName,number:e.number,title:e.title,createdAt:e.createdAt,baseRefName:e.baseRefName,type:t,titleMismatch:r,dualBase:e.dualBase}},F=async()=>(await kf()).map(iR),Js=async e=>{let{branch:t,body:r}=e;try{await Gr({quiet:!0})`gh pr edit ${t} --body ${r}`}catch(n){throw u.error({error:n,branch:t},`Error updating release PR body for ${t}`),n}},aR=async(e,t)=>{let r=Gr({quiet:!0,nothrow:!0}),n=await r`git ls-remote --heads origin ${e}`,o=n.exitCode!==0,s=n.stdout.trim().length>0;if(o||s){u.error({branchName:e},o?`could not reach origin to check whether ${e} was pushed \u2014 the branch is left in place; check with \`git ls-remote --heads origin ${e}\` before deleting anything`:`release branch ${e} exists on origin without a PR \u2014 left in place; delete it with \`git push origin --delete ${e}\` once you are sure`);return}await r`git switch ${t}`,(await r`git branch -D ${e}`).exitCode!==0&&u.error({branchName:e},`could not remove the local branch ${e} after a failed release \u2014 delete it with \`git branch -D ${e}\` before retrying`)},Gs=async e=>{let{id:t,jiraVersionUrl:r,type:n,description:o,baseSha:s}=e,i=Rp(t,n),a=et(n),c=Gr({quiet:!0}),l=ve(t),d=so(r,o);try{await Jr({operation:`create release branch ${l}`});let p=(await c`git rev-parse HEAD`).stdout.trim();if(p!==s)throw new f(void 0,{operation:`create release branch ${l}`,remediation:"something moved the checkout mid-run \u2014 re-run the release",stderrExcerpt:`expected to be on ${s.slice(0,8)} (${a}) but HEAD is ${p.slice(0,8)}`});await c`git checkout -b ${l}`;try{await c`git commit --allow-empty-message --allow-empty --message ''`,await c`git push -u origin ${l}`;let m=await c`gh pr create --title ${i} --body ${d} --base ${a} --head ${l}`;return{branchName:l,prUrl:m.stdout.trim()}}catch(m){throw await aR(l,a),m}}catch(p){throw u.error({error:p,branchName:l},`Error creating release branch ${l}`),p}finally{await Gr({quiet:!0,nothrow:!0})`git switch ${a}`}};import{$ as _c}from"zx";var Kr=async e=>{let t=await _c`gh pr list --head ${e} --state all --json number,state,title,baseRefName,headRefName --limit 1`;return JSON.parse(t.stdout)[0]??null},Mc=async e=>{let t=await _c`gh pr list --head ${e} --state open --limit 5 --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)},jc=async e=>{try{let t=await _c`gh pr view ${e} --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)}catch(t){throw new f(t,{operation:`fetch PR #${e}`,remediation:`check it exists with \`gh pr view ${e}\``})}};import ao from"node:process";var cR="x-seraph-loginreason",lR="AUTHENTICATED_FAILED",dR=(e,t=160)=>{let r=e.split(`
163
+ `,1)[0].trim();return r.length>t?`${r.slice(0,t)}\u2026`:r},Rf=(e,t)=>t===lR||e===401?"auth":e===403?"forbidden":e===404?"not-found-or-forbidden":"other",bf=(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}`,Hr=class extends Error{status;kind;body;context;constructor(t){let r=Rf(t.status,t.seraphLoginReason),n=dR(t.body);super(n===""?`${t.context}: ${bf(r,t.status)}`:`${t.context}: ${bf(r,t.status)}. Jira said: ${n}`),this.name="JiraApiError",this.status=t.status,this.kind=r,this.body=t.body,this.context=t.context}},io=e=>e instanceof Hr,Sf=e=>e.headers.get(cR);var qr=async(e,t)=>{if(e.ok)return;let r=await e.text(),n=new Hr({status:e.status,seraphLoginReason:Sf(e),body:r,context:t});throw u.debug({status:e.status,kind:n.kind,body:r},t),n},nr=(e,t)=>`${e.baseUrl}/projects/${t.projectId}/versions/${t.id}/tab/release-report-all-issues`,Fc=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 qr(l,"Failed to create Jira version"),{success:!0,version:await l.json()}},Yr=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 qr(a,"Failed to get Jira project versions"),await a.json()},dt=async(e,t)=>(await Yr(t)).find(o=>o.name===e)||null,zr=async(e,t)=>{let{baseUrl:r,token:n,email:o}=t,s={};e.released!==void 0&&(s.released=e.released),e.archived!==void 0&&(s.archived=e.archived),e.releaseDate!==void 0&&(s.releaseDate=e.releaseDate),e.description!==void 0&&(s.description=e.description);let i=`${r}/rest/api/3/version/${e.versionId}`,a=btoa(`${o}:${n}`),c=await fetch(i,{method:"PUT",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${a}`},body:JSON.stringify(s)});await qr(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}},Lc=async(e,t)=>{let{versionName:r}=e,n=await dt(r,t);if(!n)throw new Error(`Version "${r}" not found in Jira project`);return await zr({versionId:n.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},t)},Xr=async()=>{let e=ao.env.JIRA_BASE_URL,t=ao.env.JIRA_TOKEN||ao.env.JIRA_API_TOKEN,r=ao.env.JIRA_PROJECT_ID,n=ao.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(`
164
+ `);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}},ut=async()=>{try{return await Xr()}catch(e){return u.warn({err:e},"Jira configuration not available, skipping Jira integration"),null}};var Ks=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 qr(a,"Failed to get Jira version issue counts");let c=await a.json();return{issuesFixedCount:c.issuesFixedCount,issuesAffectedCount:c.issuesAffectedCount}},Bc=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 qr(c,"Failed to remove Jira version")};var Ef="dev",xf={regular:"dev",hotfix:"main"},et=e=>xf[e],oo=e=>{let t=Object.entries(xf).find(([,r])=>r===e);return t?t[0]:null},so=(e,t)=>(t??"").trim()!==""?`${e}
165
165
 
166
166
  ${t}`:`${e}
167
- `,Lc=async(e="regular")=>{let t=Xe(e),r=kf({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 kf({quiet:!0,nothrow:!0})`git rev-list --left-right --count origin/${t}...${t}`,[s="?",i="?"]=o.exitCode===0?o.stdout.trim().split(/\s+/):[],a=i!=="0"||s!=="0";throw new f(n,{operation:`fast-forward ${t} onto origin/${t}`,remediation:a?`your local ${t} has diverged \u2014 rebase or reset it to origin/${t}, then retry`:`check your access to origin and that ${t} tracks it, then retry`,...a?{stderrExcerpt:`local ${t} is ${i} commit(s) ahead and ${s} behind origin/${t}`}:{}})}return(await r`git rev-parse HEAD`).stdout.trim()},oR=async e=>{let{versionName:t,jiraConfig:r,description:n,releaseDate:o}=e,s=await at(t,r);if(!s)return(await Mc({name:t,projectId:r.projectId,description:n||"",released:!1,archived:!1,...o===void 0?{}:{releaseDate:o}},r)).version;if(s.released||s.archived)throw new f(void 0,{operation:`reuse Jira fix version "${t}"`,remediation:"pick a different version, or un-release it in Jira first",stderrExcerpt:`fix version "${t}" is already ${s.released?"released":"archived"}`});let i=n||"",a={...i!==""&&i!==(s.description??"")?{description:i}:{},...o!==void 0&&o!==(s.releaseDate??"")?{releaseDate:o}:{}};if(Object.keys(a).length===0)return s;let c=await Hr({versionId:s.id,...a},r);return{...s,...a,...a.releaseDate===void 0?{}:{releaseDate:c.version.releaseDate}}},Bc=async e=>{let{id:t,jiraConfig:r,description:n,releaseDate:o,type:s="regular",baseSha:i}=e,a=re(t),c=await oR({versionName:a,jiraConfig:r,description:n,...o===void 0?{}:{releaseDate:o}}),l=tr(r,c),d=await Us({id:t,jiraVersionUrl:l,type:s,description:n,baseSha:i});return{version:X(t),type:s,branchName:d.branchName,prUrl:d.prUrl,jiraVersionUrl:l,releaseDate:c.releaseDate||null}},Gs=async()=>{let e=new Map,t=await ct();if(!t)return e;try{let r=await Kr(t);for(let n of r)e.set(n.name,{description:n.description||null,releaseDate:n.releaseDate||null})}catch(r){u.warn({err:r},"Jira descriptions unavailable \u2014 the release list will render without them. If this persists, check JIRA_EMAIL / JIRA_TOKEN.")}return e},se=async()=>{let e=await Gs();return new Map([...e].flatMap(([t,{description:r}])=>r?[[t,r]]:[]))},so=(e,t,r)=>{let n=r?" ".repeat(r-e.length+3):" ",o=`[${t}]`.padEnd(11);return`${e}${n}${o}`},Ic=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",Ks=e=>e.flatMap(t=>{let r=G(t);return r?[{branch:t,id:r,label:X(r)}]:[]}),lt=e=>{try{return ve(pe(e))}catch(t){throw new f(t,{operation:`resolve release ref "${e}"`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")',stderrExcerpt:t instanceof Error?t.message:String(t)})}},io=e=>{if(e===bf)return bf;let t=G(e);return t?X(t):e},rr=e=>e.flatMap(t=>{let r=G(t);return r?[X(r)]:[]}),sR=(e,t)=>t?t.get(e)||"regular":void 0,ie=e=>{let{branches:t,descriptions:r,types:n}=e;return Ks(t).map(({branch:o,id:s,label:i})=>({value:o,label:i,description:r.get(re(s)),type:sR(o,n)}))};import Sf from"node:fs/promises";import iR from"node:path";import{$ as Wc}from"zx";var W="pnpm-lock.yaml",aR=/^(?:<{7}|={7}|>{7})(?:\s|$)/m,Ef=async(e,t)=>{let r=iR.join(e,W),n=`${t}:${W}`;try{let o=await Wc({cwd:e,quiet:!0})`git show ${n}`;await Sf.writeFile(r,o.stdout)}catch(o){return{ok:!1,reason:`dev has no ${W} to start from: ${Pf(o)}`}}try{await Wc({cwd:e,quiet:!0})`pnpm install --lockfile-only --ignore-scripts --no-frozen-lockfile`}catch(o){return{ok:!1,reason:`pnpm could not merge ${W}: ${Pf(o)}`}}return aR.test(await Sf.readFile(r,"utf8"))?{ok:!1,reason:`${W} still carries conflict markers after pnpm ran`}:(await Wc({cwd:e,quiet:!0})`git add -- ${W}`,{ok:!0})},Pf=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim()};import{$ as nr}from"zx";var Vc="Merge remote-tracking branch 'origin/dev' into ",xf=e=>String(e.stderr??e.message??e).trim(),cR=async e=>{try{return(await nr({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[]}},lR=async(e,t)=>{let r=xf(t),n=await cR(e);return n.length>0?{status:"conflict",conflictPaths:n,reason:r}:await Tp(e)?{status:"hook-failed",reason:r}:{status:"error",reason:r}},Tf=async e=>{let{cwd:t,worktreePath:r,branches:n}=e,o=[],s=await $e(t,"origin/dev");if(!s)return n.map(i=>({branch:i,status:"error",reason:"origin/dev does not resolve"}));for(let i of n){let a=Date.now(),c=await dR({cwd:t,worktreePath:r,branch:i,devSha:s});o.push({...c,durationMs:Date.now()-a})}return o},dR=async e=>{let{cwd:t,worktreePath:r,branch:n,devSha:o}=e,s=`origin/${n}`;if(!await $e(t,s))return{branch:n,status:"error",reason:`${s} does not exist on origin`};if(await xn(t,"origin/dev",s))return{branch:n,status:"up-to-date"};try{await va(r),await nr({cwd:r,quiet:!0})`git checkout --detach ${s}`;let i=`${Vc}${n}`;await nr({cwd:r,quiet:!0})`git merge origin/dev --no-edit -m ${i}`;let a=(await nr({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 lR(r,i)}}finally{await wa(r)}},Cf=e=>e.flatMap(t=>t.mergeSha?[{branch:t.branch,sha:t.mergeSha}]:[]),$f="pnpm install --frozen-lockfile",Af=async e=>{let{worktreePath:t,refs:r,command:n}=e,o=[],s=new Map;for(let i of r)try{await va(t),await nr({cwd:t,quiet:!0})`git checkout --detach ${i.sha}`,await nr({cwd:t,quiet:!0})`sh -c ${n}`,o.push(i)}catch(a){s.set(i.branch,xf(a))}finally{await wa(t)}return{kept:o,failed:s}},ao=async(e,t,r="origin/dev")=>{await nr({cwd:e,quiet:!0})`git fetch origin --prune`;let n=[],o=[];for(let s of t)await xn(e,r,`origin/${s.branch}`)?o.push(s.branch):n.push(s);return{kept:n,nowUpToDate:o}};import Uc from"node:process";var Hs=new Set,qs=e=>(Hs.add(e),()=>{Hs.delete(e)}),uR=async()=>{for(let e of[...Hs])try{await e()}catch(t){u.warn({error:t,msg:"cleanup failed during shutdown"})}Hs.clear()},pR=["SIGINT","SIGTERM"],Of=async(e,t={})=>{let{register:r=(i,a)=>{Uc.on(i,a)},unregister:n=(i,a)=>{Uc.off(i,a)},exit:o=i=>{Uc.exit(i)}}=t,s=new Map;for(let i of pR){let a=()=>{uR().then(()=>{o(Yp(i))})};s.set(i,a),r(i,a)}try{return await e()}finally{for(let[i,a]of s)n(i,a)}};var mR="pnpm install --frozen-lockfile --ignore-scripts",fR="pnpm install --frozen-lockfile",Nf=64*1024,Lf=4096,lo=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim().slice(-Lf)},j=async(e,t)=>(await Xs({cwd:e,quiet:!0})`git ${t}`).stdout,Jc=e=>e.split(`
169
- `).map(t=>t.trim()).filter(t=>t.length>0),Zs=e=>e.split("\0").filter(t=>t.length>0),Ys=async(e,t)=>{try{return(await j(e,["rev-parse","-q","--verify",t])).trim()||null}catch{return null}},Bf=async e=>Ze.resolve(e,(await j(e,["rev-parse","--git-common-dir"])).trim()),Gc=e=>e.then(()=>!0,()=>!1),co=()=>({results:[],atomicPush:{attempted:!1,aborted:!1},declined:!1}),Kc=e=>e?.length===1&&e[0]===W,Wf=async e=>Ze.join(await Bf(e),"infra-kit","merge-dev-resolutions"),Hc=async(e,t)=>Ze.join(await Wf(e),`${Ep(t)}.json`),Vf=async e=>{try{return JSON.parse(await Ee.readFile(e,"utf8"))}catch{return null}},zr=async(e,t)=>{let r=await Hc(e,t.branch);await Ee.mkdir(Ze.dirname(r),{recursive:!0}),await Ee.writeFile(r,`${JSON.stringify(t,null,2)}
170
- `)},Uf=async e=>{let t=await Wf(e),r=await Ee.readdir(t).catch(()=>[]);return(await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(o=>Vf(Ze.join(t,o))))).filter(o=>o!==null)},Jf=async e=>Promise.all((await Uf(e)).map(async t=>({branch:t.branch,worktreePath:t.worktreePath,createdAt:t.createdAt,worktreeExists:await Gc(Ee.stat(t.worktreePath))}))),_f=(e,t)=>({worktreePath:e.worktreePath,baseSha:e.baseSha,devSha:e.devSha,conflictPaths:e.conflictPaths,lockfileOnly:e.lockfileOnly,rererePreResolved:e.rererePreResolved,state:t}),qc=async(e,t,r)=>{await j(e,["worktree","remove","--force",r]).catch(()=>Ee.rm(r,{recursive:!0,force:!0})),await Ee.rm(await Hc(e,t),{force:!0}).catch(()=>{}),await j(e,["worktree","prune"]).catch(()=>{})},Gf=async e=>Zs(await j(e,["diff","--name-only","-z","--diff-filter=U"])),zs=async e=>Zs(await j(e,["status","--porcelain","-z","--untracked-files=all","--ignored=matching"])).filter(r=>r.startsWith("!! ")).map(r=>r.slice(3)),gR=async(e,t)=>{let r=(await j(e,["config","--type=bool","--get","rerere.enabled"]).catch(()=>"")).trim(),n=await Gc(Ee.stat(Ze.join(await Bf(e),"rr-cache")));if(r==="false"||r===""&&!n)return[];let o=new Set(Jc(await j(e,["rerere","remaining"])));return t.filter(s=>!o.has(s))},Kf=e=>e.split("/").includes("node_modules"),Qs=async(e,t)=>{let r=new Set(t.conflictPaths),n=new Set([...t.ignoredAtHandoff,...t.ignoredByVerify??[]]),o=Zs(await j(e,["diff","--cached","--name-only","-z","--no-renames",t.autoMergeTree])),s=[...await hR(e),...o].filter(a=>!r.has(a)),i=(await zs(e)).filter(a=>!n.has(a)&&!Kf(a));return[...new Set([...s,...i,...await yR(e)])].sort()},hR=async e=>{let t=Zs(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},yR=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)),vR=async e=>{let t=`:(exclude)${W}`;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 f(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()}},wR=async(e,t)=>{let r=[];for(let n of t)(await Gc(Ee.lstat(Ze.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])},Mf=async e=>(await j(e,["write-tree"])).trim(),Hf=async e=>(await j(e,["rev-list","--parents","-n","1","HEAD"])).trim().split(" ").slice(1),kR=e=>e?`${fR} && ${e}`:mR,bR=async(e,t)=>{try{return await Xs({cwd:e,quiet:!0})`sh -c ${t}`,{command:t,ok:!0}}catch(r){return{command:t,ok:!1,reason:lo(r)}}},qf=async(e,t)=>{let r=(await j(e,["diff","--cached","--stat",t.autoMergeTree])).trim(),n=async l=>(await j(e,["diff","--cached","--stat",l,"--",W])).trim(),o=t.conflictPaths.includes(W)?{vsDev:await n(t.devSha),vsBase:await n(t.baseSha)}:void 0,s=await j(e,["diff","--cached",t.autoMergeTree,"--",".",`:(exclude)${W}`]),i=new Set(t.rererePreResolved),a=s.split(/^(?=diff --git )/m).map(l=>{let d=/^diff --git a\/(.*) b\//.exec(l)?.[1];return d&&i.has(d)?`# rerere (recorded resolution)
173
- ${l}`:l}).join(""),c=If.byteLength(a)>Nf;return{diffStat:r,...o?{lockfileDiffStat:o}:{},resolutionDiff:c?If.from(a).subarray(0,Nf).toString():a,resolutionDiffTruncated:c}},Yf=async e=>{let{cwd:t,branches:r,devSha:n}=e,o=new Map;for(let s of r)o.set(s,await RR(t,s,n));return o},RR=async(e,t,r)=>{let n=await Vf(await Hc(e,t));if(n)return{resolution:_f(n,"exists"),reason:`resolution-exists: ${n.worktreePath} \u2014 finish it with --continue or drop it with --abort`};let o=await $e(e,`origin/${t}`);if(!o)return{reason:`origin/${t} does not exist on origin`};let s=xp(e,t),i=()=>qc(e,t,s),a=qs(i);try{await j(e,["worktree","prune"]),await Ee.mkdir(Ze.dirname(s),{recursive:!0}),await j(e,["worktree","add","--detach",s,o]),await Xs({cwd:s,quiet:!0})`git merge --no-commit ${r} -m ${Vc+t}`.catch(()=>{});let c=await Gf(s);if(c.length===0)return await i(),{reason:"the merge no longer conflicts \u2014 re-run release merge-dev"};let l=await Ys(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 d=await gR(s,c),p=Kc(c),m={branch:t,worktreePath:s,baseSha:o,devSha:r,conflictPaths:c,autoMergeTree:l,rererePreResolved:d,ignoredAtHandoff:await zs(s),lockfileOnly:p,cliVersion:K.version,createdAt:new Date().toISOString()};return await zr(e,m),{resolution:_f(m,p?"lockfile-only":"needs-agent")}}catch(c){return await i(),{reason:lo(c)}}finally{a()}},zf=async e=>{let{cwd:t,versions:r,all:n}=e,o=await Uf(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=ve(pe(c)),d=o.find(p=>p.branch===l);if(!d)throw new f(void 0,{operation:`select the resolution for "${c}"`,stderrExcerpt:`${l} has no resolution in progress`,remediation:s.length>0?`pass one of: ${s.join(", ")}`:"start one with release merge-dev --keep-conflicts"});return d});if(n||o.length===0)return o;let i=await Ct(ie({branches:s,descriptions:new Map}),{required:!0});return o.filter(a=>i.includes(a.branch))},SR=async(e,t)=>{let r=await Ee.realpath(t).catch(()=>null);if(!r)return!1;let n=await gt(e);for(let o of n)if(await Ee.realpath(o.path).catch(()=>o.path)===r)return!0;return!1},Yr=(e,t,r,n)=>({...e,blocked:{code:t,detail:r,...n&&n.length>0?{paths:n}:{}}}),Xf=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 SR(e,n))return Yr(o,"parents-mismatch",`the resolution worktree ${n} is gone \u2014 run --abort, then start again`);let s=await Ys(n,"HEAD"),i=await Ys(n,"MERGE_HEAD");return s===t.baseSha&&i===t.devSha?CR(e,t,o,r):PR(t,o,s,i)},PR=async(e,t,r,n)=>{let o=e.worktreePath;if(r!==null&&r===e.unapprovedCommit)return Yr(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 Hf(o),i=n?null:await Ys(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 Yr(t,"parents-mismatch",`expected HEAD ${e.baseSha} merging ${e.devSha}, or an approved merge commit of the two; found ${l}`)}let c=await Qs(o,e);return c.length>0?Yr(t,"out-of-scope-edit","only the conflicted paths may change",c):{...t,committed:!0,mergeSha:r,treeSha:i,lockfileMerged:e.conflictPaths.includes(W),...await qf(o,e)}},jf=async(e,t)=>{let r=Jc(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},ER=async(e,t)=>{let r=t.worktreePath,n=await jf(r,W),o=t.lockfileBlob,s=await Ef(r,t.devSha);if(!s.ok)return{code:"verify-failed",detail:s.reason,paths:[W]};let i=await jf(r,W);if(i!==null&&i!==o&&(t.lockfileBlob=i,await zr(e,t)),n!==null&&n!==i)return n===o?{code:"tree-changed",detail:`rebuilding ${W} from dev resolved differently than the last preview (the registry moved) \u2014 preview again`,paths:[W]}:{code:"out-of-scope-edit",detail:`${W} was staged by something other than the CLI; it has been rebuilt from dev \u2014 preview again`,paths:[W]};let a=await Qs(r,t);return a.length>0?{code:"out-of-scope-edit",detail:"merging the lockfile changed other paths",paths:a}:null},xR=async(e,t)=>{let r=t.worktreePath;await wR(r,t.conflictPaths.filter(i=>i!==W));let n=await Qs(r,t);if(n.length>0)return{code:"out-of-scope-edit",detail:"only the conflicted paths may change",paths:n};let o=(await Gf(r)).filter(i=>i!==W);if(o.length>0)return{code:"unmerged-paths",detail:"these paths are still unmerged",paths:o};let s;try{s=await vR(r)}catch(i){return{code:"markers-remaining",detail:`the marker check could not run: ${lo(i)}`}}return s.length>0?{code:"markers-remaining",detail:"conflict markers are still staged",paths:s}:t.conflictPaths.includes(W)?ER(e,t):null},TR=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 zs(o)),i=await bR(o,n);if(!i.ok)return i;let a=(await zs(o)).filter(c=>!s.has(c)&&!Kf(c)&&Ze.posix.basename(c)!==".gitignore");return t.ignoredByVerify=[...new Set([...t.ignoredByVerify??[],...a])],await zr(e,t),i},CR=async(e,t,r,n)=>{let o=t.worktreePath,s=await xR(e,t);if(s)return{...r,blocked:s};let i=t.conflictPaths.includes(W),a=await Mf(o),c=await TR(e,t,a,kR(n)),l={...r,treeSha:a,lockfileMerged:i,verify:c};if(!c.ok)return Yr(l,"verify-failed",c.reason??"the verify command failed");let d=await Qs(o,t),p=Jc(await j(o,["diff","--name-only"]));return d.length>0||p.length>0||await Mf(o)!==a?Yr(l,"verify-mutated-tree","the verify step changed the tree",[...new Set([...d,...p])]):(c.reused||(t.verified={treeSha:a,command:c.command},await zr(e,t)),{...l,...await qf(o,t)})},$R=12e4,AR=async(e,t=$R)=>{let r=Xs({cwd:e,quiet:!0,detached:!0,stdio:["ignore","pipe","pipe"],env:{...Df.env,GIT_TERMINAL_PROMPT:"0"}})`git commit --no-edit --cleanup=strip`,n=!1,o=setTimeout(()=>{n=!0;let s=r.child?.pid;try{s&&Df.kill(-s,"SIGKILL")}catch{}},t);try{return await r,{ok:!0}}catch(s){if(!n)return{ok:!1,reason:lo(s)};let i=(await j(e,["rev-parse","--git-path","index.lock"])).trim();return await Ee.rm(Ze.resolve(e,i),{force:!0}),{ok:!1,reason:`git commit timed out after ${t}ms`}}finally{clearTimeout(o)}},OR={"verify-failed":"verify-failed","tree-changed":"tree-changed"},IR=e=>{let t=e.blocked;return{branch:e.branch,status:OR[t.code]??"blocked",conflictPaths:e.conflictPaths,pushed:!1,reason:[`${t.code}: ${t.detail}`,...t.paths?[`(${t.paths.join(", ")})`]:[]].join(" "),blocked:t}},DR=async(e,t,r,n)=>{let o=r.worktreePath,s=(d,p,m={})=>({branch:t.branch,status:d,conflictPaths:t.conflictPaths,pushed:!1,reason:p,...m});if(!n)return s("tree-changed",`not approved: the preview this --yes came from had no ready tree for ${t.branch} \u2014 preview again`);if(t.treeSha!==n)return s("tree-changed",`the resolution is tree ${t.treeSha} but the approved tree is ${n} \u2014 preview again`);if(t.committed&&t.mergeSha)return{sha:t.mergeSha};let i=await AR(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 zr(e,r),s("tree-changed",`a commit hook rewrote the tree (${c}, approved ${t.treeSha}) \u2014 run --abort, then hand off again`,{mergeSha:a});let l=await Hf(o);if(l.length!==2||l[0]!==r.baseSha||l[1]!==r.devSha){let d={code:"parents-mismatch",detail:`commit parents are ${l.join(" ")}, expected ${r.baseSha} ${r.devSha}`};return s("blocked",`parents-mismatch: ${d.detail}`,{mergeSha:a,blocked:d})}return{sha:a}},NR=async(e,t,r)=>{let n=(c,l,d)=>({branch:t.branch,status:c,mergeSha:r,conflictPaths:t.conflictPaths,pushed:!1,...l?{reason:l}:{},...d?{blocked:d}:{}}),o;try{o=(await ao(e,[{branch:t.branch,sha:r}],t.devSha)).nowUpToDate}catch(c){let l={code:"parents-mismatch",detail:`origin/${t.branch}: ${lo(c)}`};return n("blocked",`parents-mismatch: ${l.detail}`,l)}if(o.includes(t.branch))return n("up-to-date",`origin/${t.branch} already carries ${t.devSha}`);let s=await $e(e,`origin/${t.branch}`);if(s===t.baseSha)return"keep";let i=s!==null&&await xn(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)},_R=e=>{u.info(`
174
- \u{1F4CB} Resolution preview:`);for(let t of e)t.blocked?u.info(` ${t.branch} \u2014 BLOCKED ${t.blocked.code}: ${t.blocked.detail}`):u.info(` ${t.branch} \u2014 ready${t.committed?" (already committed)":""}: tree ${t.treeSha}`)},Zf=async e=>{let{cwd:t,versions:r,all:n,verify:o,trees:s=new Map,confirmedCommand:i}=e,a=await zf({cwd:t,versions:r,all:n});if(a.length===0)return u.info("\u2139\uFE0F No merge-dev resolutions in progress"),co();if(i)return Ff(t,a,o,s);let c=[];for(let m of a){let g=await Xf(t,m,o);!g.blocked&&!g.committed&&g.treeSha&&(m.previewedTree=g.treeSha,await zr(t,m)),c.push(g)}_R(c);let l={branches:c},d=c.filter(m=>!m.blocked&&m.treeSha!==void 0);if(d.length===0)throw new x({status:"refused",plan:l,agentMode:N.source},2,{operation:"continue the merge-dev resolutions",stderrExcerpt:"every selected resolution is blocked",remediation:"fix the paths each row names, then preview again \u2014 or drop it with --abort"});let p=new Map(d.map(m=>[m.branch,m.treeSha]));try{await V(i,`Commit and push the resolved merges for: ${[...p.keys()].join(", ")}?`,{plan:l,throwOnDecline:!0,rerun:MR(p)})}catch(m){if(!ot(m))throw m;return{...co(),declined:!0}}return Ff(t,a,o,p)},Qf=e=>{let t=new Map,r=(Array.isArray(e)?e:[e??""]).flatMap(n=>n.split(","));for(let n of r.map(o=>o.trim())){if(n.length===0)continue;let o=/^(.+)=([0-9a-f]{40,64})$/.exec(n);if(!o?.[1]||!o[2])throw new f(void 0,{operation:"read --tree",stderrExcerpt:`"${n}" is not <branch>=<tree sha>`,remediation:"run the rerun a --continue preview printed, unchanged"});t.set(o[1],o[2])}return t},MR=e=>{let t=[],r=!1;for(let o of Gp())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"]},jR=async(e,t,r,n)=>{let o=await Xf(e,t,r);if(o.blocked)return IR(o);let s=await DR(e,o,t,n);if(!("sha"in s))return s;let i=await NR(e,t,s.sha);return i==="keep"?s:i},FR=async(e,t)=>{if(t.length===0)return{results:[],atomicPush:{attempted:!1,aborted:!1}};let r=t.map(s=>({branch:s.record.branch,sha:s.sha}));u.info(`
175
- \u2B06\uFE0F Pushing atomically: ${r.map(s=>s.branch).join(", ")}`);let n=await hs(e,r),o=[];for(let s of t){let i=n.pushed||await Er(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(-Lf)}})}return{results:o,atomicPush:{attempted:!0,aborted:!n.pushed,abortedBy:n.stderr?.split(`
176
- `)[0]}}},Ff=async(e,t,r,n)=>{let o=[],s=[];for(let d of t){let p=await jR(e,d,r,n.get(d.branch));"sha"in p?s.push({record:d,sha:p.sha}):o.push(p)}let i=await FR(e,s),a=[...o,...i.results],c=t.filter(d=>a.some(p=>p.branch===d.branch&&(p.pushed||p.status==="up-to-date")));for(let d of c)await qc(e,d.branch,d.worktreePath);let l=t.map(d=>d.branch);return a.sort((d,p)=>l.indexOf(d.branch)-l.indexOf(p.branch)),{results:a,atomicPush:i.atomicPush,declined:!1}},eg=async e=>{let{cwd:t,versions:r,all:n,confirmedCommand:o}=e,s=await zf({cwd:t,versions:r,all:n});if(s.length===0)return u.info("\u2139\uFE0F No merge-dev resolutions in progress"),co();let i={branches:s.map(a=>({branch:a.branch,worktreePath:a.worktreePath}))};try{await V(o,`Discard the resolution worktrees for: ${s.map(a=>a.branch).join(", ")}?`,{plan:i,throwOnDecline:!0})}catch(a){if(!ot(a))throw a;return{...co(),declined:!0}}for(let a of s)await qc(t,a.branch,a.worktreePath),u.info(`\u{1F5D1}\uFE0F Discarded the resolution for ${a.branch}`);return{...co(),results:s.map(a=>({branch:a.branch,status:"aborted",conflictPaths:a.conflictPaths,pushed:!1}))}};import LR from"node:fs";import BR from"node:os";import WR from"node:path";var VR="infra-kit.json",UR="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)",JR="Skipped agent-instruction files \u2014 no infra-kit.json at the repo root (the plugin pointer, the plugin install and .mcp.json are unaffected)",uo=async()=>{let e;try{e=await T()}catch{return null}let t=e.trim();return t===""||t===BR.homedir()?null:t},tg=async()=>{let e=await uo();return e===null&&u.info(UR),e},GR=async()=>{let e=await uo();return e===null?null:LR.existsSync(WR.join(e,VR))?e:(u.info(JR),null)};var KR=async e=>{try{return await Se(e)}catch(t){return u.debug({err:t,msg:"Skipped per-package agent guidance \u2014 no workspace packages could be discovered."}),[]}},rg=async()=>{let e=await GR(),t=K.version;if(e===null)return{skipped:!0,root:null,version:t,written:[]};let r=[...await Wn(e,{version:t})];for(let n of await KR(e)){let o=await Yt(n);r.push(...await Vn(n,{repoRoot:e,version:t,declaredType:o}))}return{skipped:!1,root:e,version:t,written:r}};import ue from"node:fs";import nl from"node:os";import fe from"node:path";import ol from"node:process";import ti from"node:fs/promises";import HR from"node:path";import qR from"node:process";var ng=` // "envManagement": { // required in layer 1; provider-tagged
167
+ `,Wc=async(e="regular")=>{let t=et(e),r=Pf({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 Pf({quiet:!0,nothrow:!0})`git rev-list --left-right --count origin/${t}...${t}`,[s="?",i="?"]=o.exitCode===0?o.stdout.trim().split(/\s+/):[],a=i!=="0"||s!=="0";throw new f(n,{operation:`fast-forward ${t} onto origin/${t}`,remediation:a?`your local ${t} has diverged \u2014 rebase or reset it to origin/${t}, then retry`:`check your access to origin and that ${t} tracks it, then retry`,...a?{stderrExcerpt:`local ${t} is ${i} commit(s) ahead and ${s} behind origin/${t}`}:{}})}return(await r`git rev-parse HEAD`).stdout.trim()},uR=async e=>{let{versionName:t,jiraConfig:r,description:n,releaseDate:o}=e,s=await dt(t,r);if(!s)return(await Fc({name:t,projectId:r.projectId,description:n||"",released:!1,archived:!1,...o===void 0?{}:{releaseDate:o}},r)).version;if(s.released||s.archived)throw new f(void 0,{operation:`reuse Jira fix version "${t}"`,remediation:"pick a different version, or un-release it in Jira first",stderrExcerpt:`fix version "${t}" is already ${s.released?"released":"archived"}`});let i=n||"",a={...i!==""&&i!==(s.description??"")?{description:i}:{},...o!==void 0&&o!==(s.releaseDate??"")?{releaseDate:o}:{}};if(Object.keys(a).length===0)return s;let c=await zr({versionId:s.id,...a},r);return{...s,...a,...a.releaseDate===void 0?{}:{releaseDate:c.version.releaseDate}}},Vc=async e=>{let{id:t,jiraConfig:r,description:n,releaseDate:o,type:s="regular",baseSha:i}=e,a=re(t),c=await uR({versionName:a,jiraConfig:r,description:n,...o===void 0?{}:{releaseDate:o}}),l=nr(r,c),d=await Gs({id:t,jiraVersionUrl:l,type:s,description:n,baseSha:i});return{version:X(t),type:s,branchName:d.branchName,prUrl:d.prUrl,jiraVersionUrl:l,releaseDate:c.releaseDate||null}},Hs=async()=>{let e=new Map,t=await ut();if(!t)return e;try{let r=await Yr(t);for(let n of r)e.set(n.name,{description:n.description||null,releaseDate:n.releaseDate||null})}catch(r){u.warn({err:r},"Jira descriptions unavailable \u2014 the release list will render without them. If this persists, check JIRA_EMAIL / JIRA_TOKEN.")}return e},se=async()=>{let e=await Hs();return new Map([...e].flatMap(([t,{description:r}])=>r?[[t,r]]:[]))},co=(e,t,r)=>{let n=r?" ".repeat(r-e.length+3):" ",o=`[${t}]`.padEnd(11);return`${e}${n}${o}`},Nc=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",qs=e=>e.flatMap(t=>{let r=G(t);return r?[{branch:t,id:r,label:X(r)}]:[]}),pt=e=>{try{return ve(me(e))}catch(t){throw new f(t,{operation:`resolve release ref "${e}"`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")',stderrExcerpt:t instanceof Error?t.message:String(t)})}},lo=e=>{if(e===Ef)return Ef;let t=G(e);return t?X(t):e},mt=e=>e.flatMap(t=>{let r=G(t);return r?[X(r)]:[]}),pR=(e,t)=>t?t.get(e)||"regular":void 0,ie=e=>{let{branches:t,descriptions:r,types:n}=e;return qs(t).map(({branch:o,id:s,label:i})=>({value:o,label:i,description:r.get(re(s)),type:pR(o,n)}))};import Tf from"node:fs/promises";import mR from"node:path";import{$ as Uc}from"zx";var V="pnpm-lock.yaml",fR=/^(?:<{7}|={7}|>{7})(?:\s|$)/m,$f=async(e,t)=>{let r=mR.join(e,V),n=`${t}:${V}`;try{let o=await Uc({cwd:e,quiet:!0})`git show ${n}`;await Tf.writeFile(r,o.stdout)}catch(o){return{ok:!1,reason:`dev has no ${V} to start from: ${Cf(o)}`}}try{await Uc({cwd:e,quiet:!0})`pnpm install --lockfile-only --ignore-scripts --no-frozen-lockfile`}catch(o){return{ok:!1,reason:`pnpm could not merge ${V}: ${Cf(o)}`}}return fR.test(await Tf.readFile(r,"utf8"))?{ok:!1,reason:`${V} still carries conflict markers after pnpm ran`}:(await Uc({cwd:e,quiet:!0})`git add -- ${V}`,{ok:!0})},Cf=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim()};import{$ as or}from"zx";var Jc="Merge remote-tracking branch 'origin/dev' into ",Af=e=>String(e.stderr??e.message??e).trim(),gR=async e=>{try{return(await or({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[]}},hR=async(e,t)=>{let r=Af(t),n=await gR(e);return n.length>0?{status:"conflict",conflictPaths:n,reason:r}:await Ap(e)?{status:"hook-failed",reason:r}:{status:"error",reason:r}},Of=async e=>{let{cwd:t,worktreePath:r,branches:n}=e,o=[],s=await Oe(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 yR({cwd:t,worktreePath:r,branch:i,devSha:s});o.push({...c,durationMs:Date.now()-a})}return o},yR=async e=>{let{cwd:t,worktreePath:r,branch:n,devSha:o}=e,s=`origin/${n}`;if(!await Oe(t,s))return{branch:n,status:"error",reason:`${s} does not exist on origin`};if(await $n(t,"origin/dev",s))return{branch:n,status:"up-to-date"};try{await ka(r),await or({cwd:r,quiet:!0})`git checkout --detach ${s}`;let i=`${Jc}${n}`;await or({cwd:r,quiet:!0})`git merge origin/dev --no-edit -m ${i}`;let a=(await or({cwd:r,quiet:!0})`git rev-parse HEAD`).stdout.trim();return{branch:n,status:a===o?"fast-forward":"merged",mergeSha:a}}catch(i){return{branch:n,...await hR(r,i)}}finally{await ba(r)}},If=e=>e.flatMap(t=>t.mergeSha?[{branch:t.branch,sha:t.mergeSha}]:[]),Df="pnpm install --frozen-lockfile",Nf=async e=>{let{worktreePath:t,refs:r,command:n}=e,o=[],s=new Map;for(let i of r)try{await ka(t),await or({cwd:t,quiet:!0})`git checkout --detach ${i.sha}`,await or({cwd:t,quiet:!0})`sh -c ${n}`,o.push(i)}catch(a){s.set(i.branch,Af(a))}finally{await ba(t)}return{kept:o,failed:s}},uo=async(e,t,r="origin/dev")=>{await or({cwd:e,quiet:!0})`git fetch origin --prune`;let n=[],o=[];for(let s of t)await $n(e,r,`origin/${s.branch}`)?o.push(s.branch):n.push(s);return{kept:n,nowUpToDate:o}};import Gc from"node:process";var Ys=new Set,zs=e=>(Ys.add(e),()=>{Ys.delete(e)}),vR=async()=>{for(let e of[...Ys])try{await e()}catch(t){u.warn({error:t,msg:"cleanup failed during shutdown"})}Ys.clear()},wR=["SIGINT","SIGTERM"],_f=async(e,t={})=>{let{register:r=(i,a)=>{Gc.on(i,a)},unregister:n=(i,a)=>{Gc.off(i,a)},exit:o=i=>{Gc.exit(i)}}=t,s=new Map;for(let i of wR){let a=()=>{vR().then(()=>{o(Zp(i))})};s.set(i,a),r(i,a)}try{return await e()}finally{for(let[i,a]of s)n(i,a)}};var kR="pnpm install --frozen-lockfile --ignore-scripts",bR="pnpm install --frozen-lockfile",Ff=64*1024,Uf=4096,mo=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim().slice(-Uf)},j=async(e,t)=>(await Qs({cwd:e,quiet:!0})`git ${t}`).stdout,Kc=e=>e.split(`
169
+ `).map(t=>t.trim()).filter(t=>t.length>0),ei=e=>e.split("\0").filter(t=>t.length>0),Xs=async(e,t)=>{try{return(await j(e,["rev-parse","-q","--verify",t])).trim()||null}catch{return null}},Jf=async e=>tt.resolve(e,(await j(e,["rev-parse","--git-common-dir"])).trim()),Hc=e=>e.then(()=>!0,()=>!1),po=()=>({results:[],atomicPush:{attempted:!1,aborted:!1},declined:!1}),qc=e=>e?.length===1&&e[0]===V,Gf=async e=>tt.join(await Jf(e),"infra-kit","merge-dev-resolutions"),Yc=async(e,t)=>tt.join(await Gf(e),`${Cp(t)}.json`),Kf=async e=>{try{return JSON.parse(await xe.readFile(e,"utf8"))}catch{return null}},Qr=async(e,t)=>{let r=await Yc(e,t.branch);await xe.mkdir(tt.dirname(r),{recursive:!0}),await xe.writeFile(r,`${JSON.stringify(t,null,2)}
170
+ `)},Hf=async e=>{let t=await Gf(e),r=await xe.readdir(t).catch(()=>[]);return(await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(o=>Kf(tt.join(t,o))))).filter(o=>o!==null)},qf=async e=>Promise.all((await Hf(e)).map(async t=>({branch:t.branch,worktreePath:t.worktreePath,createdAt:t.createdAt,worktreeExists:await Hc(xe.stat(t.worktreePath))}))),Lf=(e,t)=>({worktreePath:e.worktreePath,baseSha:e.baseSha,devSha:e.devSha,conflictPaths:e.conflictPaths,lockfileOnly:e.lockfileOnly,rererePreResolved:e.rererePreResolved,state:t}),zc=async(e,t,r)=>{await j(e,["worktree","remove","--force",r]).catch(()=>xe.rm(r,{recursive:!0,force:!0})),await xe.rm(await Yc(e,t),{force:!0}).catch(()=>{}),await j(e,["worktree","prune"]).catch(()=>{})},Yf=async e=>ei(await j(e,["diff","--name-only","-z","--diff-filter=U"])),Zs=async e=>ei(await j(e,["status","--porcelain","-z","--untracked-files=all","--ignored=matching"])).filter(r=>r.startsWith("!! ")).map(r=>r.slice(3)),RR=async(e,t)=>{let r=(await j(e,["config","--type=bool","--get","rerere.enabled"]).catch(()=>"")).trim(),n=await Hc(xe.stat(tt.join(await Jf(e),"rr-cache")));if(r==="false"||r===""&&!n)return[];let o=new Set(Kc(await j(e,["rerere","remaining"])));return t.filter(s=>!o.has(s))},zf=e=>e.split("/").includes("node_modules"),ti=async(e,t)=>{let r=new Set(t.conflictPaths),n=new Set([...t.ignoredAtHandoff,...t.ignoredByVerify??[]]),o=ei(await j(e,["diff","--cached","--name-only","-z","--no-renames",t.autoMergeTree])),s=[...await SR(e),...o].filter(a=>!r.has(a)),i=(await Zs(e)).filter(a=>!n.has(a)&&!zf(a));return[...new Set([...s,...i,...await PR(e)])].sort()},SR=async e=>{let t=ei(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},PR=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)),ER=async e=>{let t=`:(exclude)${V}`;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 f(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()}},xR=async(e,t)=>{let r=[];for(let n of t)(await Hc(xe.lstat(tt.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])},Bf=async e=>(await j(e,["write-tree"])).trim(),Xf=async e=>(await j(e,["rev-list","--parents","-n","1","HEAD"])).trim().split(" ").slice(1),TR=e=>e?`${bR} && ${e}`:kR,CR=async(e,t)=>{try{return await Qs({cwd:e,quiet:!0})`sh -c ${t}`,{command:t,ok:!0}}catch(r){return{command:t,ok:!1,reason:mo(r)}}},Zf=async(e,t)=>{let r=(await j(e,["diff","--cached","--stat",t.autoMergeTree])).trim(),n=async l=>(await j(e,["diff","--cached","--stat",l,"--",V])).trim(),o=t.conflictPaths.includes(V)?{vsDev:await n(t.devSha),vsBase:await n(t.baseSha)}:void 0,s=await j(e,["diff","--cached",t.autoMergeTree,"--",".",`:(exclude)${V}`]),i=new Set(t.rererePreResolved),a=s.split(/^(?=diff --git )/m).map(l=>{let d=/^diff --git a\/(.*) b\//.exec(l)?.[1];return d&&i.has(d)?`# rerere (recorded resolution)
173
+ ${l}`:l}).join(""),c=Mf.byteLength(a)>Ff;return{diffStat:r,...o?{lockfileDiffStat:o}:{},resolutionDiff:c?Mf.from(a).subarray(0,Ff).toString():a,resolutionDiffTruncated:c}},Qf=async e=>{let{cwd:t,branches:r,devSha:n}=e,o=new Map;for(let s of r)o.set(s,await $R(t,s,n));return o},$R=async(e,t,r)=>{let n=await Kf(await Yc(e,t));if(n)return{resolution:Lf(n,"exists"),reason:`resolution-exists: ${n.worktreePath} \u2014 finish it with --continue or drop it with --abort`};let o=await Oe(e,`origin/${t}`);if(!o)return{reason:`origin/${t} does not exist on origin`};let s=$p(e,t),i=()=>zc(e,t,s),a=zs(i);try{await j(e,["worktree","prune"]),await xe.mkdir(tt.dirname(s),{recursive:!0}),await j(e,["worktree","add","--detach",s,o]),await Qs({cwd:s,quiet:!0})`git merge --no-commit ${r} -m ${Jc+t}`.catch(()=>{});let c=await Yf(s);if(c.length===0)return await i(),{reason:"the merge no longer conflicts \u2014 re-run release merge-dev"};let l=await Xs(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 d=await RR(s,c),p=qc(c),m={branch:t,worktreePath:s,baseSha:o,devSha:r,conflictPaths:c,autoMergeTree:l,rererePreResolved:d,ignoredAtHandoff:await Zs(s),lockfileOnly:p,cliVersion:K.version,createdAt:new Date().toISOString()};return await Qr(e,m),{resolution:Lf(m,p?"lockfile-only":"needs-agent")}}catch(c){return await i(),{reason:mo(c)}}finally{a()}},eg=async e=>{let{cwd:t,versions:r,all:n}=e,o=await Hf(t),s=o.map(a=>a.branch);if(r!==void 0)return(Array.isArray(r)?r:r.split(",")).map(c=>c.trim()).filter(c=>c.length>0).map(c=>{let l=ve(me(c)),d=o.find(p=>p.branch===l);if(!d)throw new f(void 0,{operation:`select the resolution for "${c}"`,stderrExcerpt:`${l} has no resolution in progress`,remediation:s.length>0?`pass one of: ${s.join(", ")}`:"start one with release merge-dev --keep-conflicts"});return d});if(n||o.length===0)return o;let i=await Ot(ie({branches:s,descriptions:new Map}),{required:!0});return o.filter(a=>i.includes(a.branch))},AR=async(e,t)=>{let r=await xe.realpath(t).catch(()=>null);if(!r)return!1;let n=await Ke(e);for(let o of n)if(await xe.realpath(o.path).catch(()=>o.path)===r)return!0;return!1},Zr=(e,t,r,n)=>({...e,blocked:{code:t,detail:r,...n&&n.length>0?{paths:n}:{}}}),tg=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 AR(e,n))return Zr(o,"parents-mismatch",`the resolution worktree ${n} is gone \u2014 run --abort, then start again`);let s=await Xs(n,"HEAD"),i=await Xs(n,"MERGE_HEAD");return s===t.baseSha&&i===t.devSha?_R(e,t,o,r):OR(t,o,s,i)},OR=async(e,t,r,n)=>{let o=e.worktreePath;if(r!==null&&r===e.unapprovedCommit)return Zr(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 Xf(o),i=n?null:await Xs(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 Zr(t,"parents-mismatch",`expected HEAD ${e.baseSha} merging ${e.devSha}, or an approved merge commit of the two; found ${l}`)}let c=await ti(o,e);return c.length>0?Zr(t,"out-of-scope-edit","only the conflicted paths may change",c):{...t,committed:!0,mergeSha:r,treeSha:i,lockfileMerged:e.conflictPaths.includes(V),...await Zf(o,e)}},Wf=async(e,t)=>{let r=Kc(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},IR=async(e,t)=>{let r=t.worktreePath,n=await Wf(r,V),o=t.lockfileBlob,s=await $f(r,t.devSha);if(!s.ok)return{code:"verify-failed",detail:s.reason,paths:[V]};let i=await Wf(r,V);if(i!==null&&i!==o&&(t.lockfileBlob=i,await Qr(e,t)),n!==null&&n!==i)return n===o?{code:"tree-changed",detail:`rebuilding ${V} from dev resolved differently than the last preview (the registry moved) \u2014 preview again`,paths:[V]}:{code:"out-of-scope-edit",detail:`${V} was staged by something other than the CLI; it has been rebuilt from dev \u2014 preview again`,paths:[V]};let a=await ti(r,t);return a.length>0?{code:"out-of-scope-edit",detail:"merging the lockfile changed other paths",paths:a}:null},DR=async(e,t)=>{let r=t.worktreePath;await xR(r,t.conflictPaths.filter(i=>i!==V));let n=await ti(r,t);if(n.length>0)return{code:"out-of-scope-edit",detail:"only the conflicted paths may change",paths:n};let o=(await Yf(r)).filter(i=>i!==V);if(o.length>0)return{code:"unmerged-paths",detail:"these paths are still unmerged",paths:o};let s;try{s=await ER(r)}catch(i){return{code:"markers-remaining",detail:`the marker check could not run: ${mo(i)}`}}return s.length>0?{code:"markers-remaining",detail:"conflict markers are still staged",paths:s}:t.conflictPaths.includes(V)?IR(e,t):null},NR=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 Zs(o)),i=await CR(o,n);if(!i.ok)return i;let a=(await Zs(o)).filter(c=>!s.has(c)&&!zf(c)&&tt.posix.basename(c)!==".gitignore");return t.ignoredByVerify=[...new Set([...t.ignoredByVerify??[],...a])],await Qr(e,t),i},_R=async(e,t,r,n)=>{let o=t.worktreePath,s=await DR(e,t);if(s)return{...r,blocked:s};let i=t.conflictPaths.includes(V),a=await Bf(o),c=await NR(e,t,a,TR(n)),l={...r,treeSha:a,lockfileMerged:i,verify:c};if(!c.ok)return Zr(l,"verify-failed",c.reason??"the verify command failed");let d=await ti(o,t),p=Kc(await j(o,["diff","--name-only"]));return d.length>0||p.length>0||await Bf(o)!==a?Zr(l,"verify-mutated-tree","the verify step changed the tree",[...new Set([...d,...p])]):(c.reused||(t.verified={treeSha:a,command:c.command},await Qr(e,t)),{...l,...await Zf(o,t)})},MR=12e4,jR=async(e,t=MR)=>{let r=Qs({cwd:e,quiet:!0,detached:!0,stdio:["ignore","pipe","pipe"],env:{...jf.env,GIT_TERMINAL_PROMPT:"0"}})`git commit --no-edit --cleanup=strip`,n=!1,o=setTimeout(()=>{n=!0;let s=r.child?.pid;try{s&&jf.kill(-s,"SIGKILL")}catch{}},t);try{return await r,{ok:!0}}catch(s){if(!n)return{ok:!1,reason:mo(s)};let i=(await j(e,["rev-parse","--git-path","index.lock"])).trim();return await xe.rm(tt.resolve(e,i),{force:!0}),{ok:!1,reason:`git commit timed out after ${t}ms`}}finally{clearTimeout(o)}},FR={"verify-failed":"verify-failed","tree-changed":"tree-changed"},LR=e=>{let t=e.blocked;return{branch:e.branch,status:FR[t.code]??"blocked",conflictPaths:e.conflictPaths,pushed:!1,reason:[`${t.code}: ${t.detail}`,...t.paths?[`(${t.paths.join(", ")})`]:[]].join(" "),blocked:t}},BR=async(e,t,r,n)=>{let o=r.worktreePath,s=(d,p,m={})=>({branch:t.branch,status:d,conflictPaths:t.conflictPaths,pushed:!1,reason:p,...m});if(!n)return s("tree-changed",`not approved: the preview this --yes came from had no ready tree for ${t.branch} \u2014 preview again`);if(t.treeSha!==n)return s("tree-changed",`the resolution is tree ${t.treeSha} but the approved tree is ${n} \u2014 preview again`);if(t.committed&&t.mergeSha)return{sha:t.mergeSha};let i=await jR(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 Qr(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 Xf(o);if(l.length!==2||l[0]!==r.baseSha||l[1]!==r.devSha){let d={code:"parents-mismatch",detail:`commit parents are ${l.join(" ")}, expected ${r.baseSha} ${r.devSha}`};return s("blocked",`parents-mismatch: ${d.detail}`,{mergeSha:a,blocked:d})}return{sha:a}},WR=async(e,t,r)=>{let n=(c,l,d)=>({branch:t.branch,status:c,mergeSha:r,conflictPaths:t.conflictPaths,pushed:!1,...l?{reason:l}:{},...d?{blocked:d}:{}}),o;try{o=(await uo(e,[{branch:t.branch,sha:r}],t.devSha)).nowUpToDate}catch(c){let l={code:"parents-mismatch",detail:`origin/${t.branch}: ${mo(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 Oe(e,`origin/${t.branch}`);if(s===t.baseSha)return"keep";let i=s!==null&&await $n(e,s,t.baseSha),a={code:"parents-mismatch",detail:`origin/${t.branch} ${i?"was rewound":"moved"} to ${s??"nothing"} since the hand-off at ${t.baseSha}`};return n("blocked",`parents-mismatch: ${a.detail}`,a)},VR=e=>{u.info(`
174
+ \u{1F4CB} Resolution preview:`);for(let t of e)t.blocked?u.info(` ${t.branch} \u2014 BLOCKED ${t.blocked.code}: ${t.blocked.detail}`):u.info(` ${t.branch} \u2014 ready${t.committed?" (already committed)":""}: tree ${t.treeSha}`)},rg=async e=>{let{cwd:t,versions:r,all:n,verify:o,trees:s=new Map,confirmedCommand:i}=e,a=await eg({cwd:t,versions:r,all:n});if(a.length===0)return u.info("\u2139\uFE0F No merge-dev resolutions in progress"),po();if(i)return Vf(t,a,o,s);let c=[];for(let m of a){let g=await tg(t,m,o);!g.blocked&&!g.committed&&g.treeSha&&(m.previewedTree=g.treeSha,await Qr(t,m)),c.push(g)}VR(c);let l={branches:c},d=c.filter(m=>!m.blocked&&m.treeSha!==void 0);if(d.length===0)throw new C({status:"refused",plan:l,agentMode:N.source},2,{operation:"continue the merge-dev resolutions",stderrExcerpt:"every selected resolution is blocked",remediation:"fix the paths each row names, then preview again \u2014 or drop it with --abort"});let p=new Map(d.map(m=>[m.branch,m.treeSha]));try{await B(i,`Commit and push the resolved merges for: ${[...p.keys()].join(", ")}?`,{plan:l,throwOnDecline:!0,rerun:UR(p)})}catch(m){if(!at(m))throw m;return{...po(),declined:!0}}return Vf(t,a,o,p)},ng=e=>{let t=new Map,r=(Array.isArray(e)?e:[e??""]).flatMap(n=>n.split(","));for(let n of r.map(o=>o.trim())){if(n.length===0)continue;let o=/^(.+)=([0-9a-f]{40,64})$/.exec(n);if(!o?.[1]||!o[2])throw new f(void 0,{operation:"read --tree",stderrExcerpt:`"${n}" is not <branch>=<tree sha>`,remediation:"run the rerun a --continue preview printed, unchanged"});t.set(o[1],o[2])}return t},UR=e=>{let t=[],r=!1;for(let o of qp())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"]},JR=async(e,t,r,n)=>{let o=await tg(e,t,r);if(o.blocked)return LR(o);let s=await BR(e,o,t,n);if(!("sha"in s))return s;let i=await WR(e,t,s.sha);return i==="keep"?s:i},GR=async(e,t)=>{if(t.length===0)return{results:[],atomicPush:{attempted:!1,aborted:!1}};let r=t.map(s=>({branch:s.record.branch,sha:s.sha}));u.info(`
175
+ \u2B06\uFE0F Pushing atomically: ${r.map(s=>s.branch).join(", ")}`);let n=await ws(e,r),o=[];for(let s of t){let i=n.pushed||await Cr(e,s.record.branch)===s.sha;o.push({branch:s.record.branch,status:i?"merged":"push-aborted",mergeSha:s.sha,conflictPaths:s.record.conflictPaths,pushed:i,...i?{}:{reason:n.stderr?.trim().slice(-Uf)}})}return{results:o,atomicPush:{attempted:!0,aborted:!n.pushed,abortedBy:n.stderr?.split(`
176
+ `)[0]}}},Vf=async(e,t,r,n)=>{let o=[],s=[];for(let d of t){let p=await JR(e,d,r,n.get(d.branch));"sha"in p?s.push({record:d,sha:p.sha}):o.push(p)}let i=await GR(e,s),a=[...o,...i.results],c=t.filter(d=>a.some(p=>p.branch===d.branch&&(p.pushed||p.status==="up-to-date")));for(let d of c)await zc(e,d.branch,d.worktreePath);let l=t.map(d=>d.branch);return a.sort((d,p)=>l.indexOf(d.branch)-l.indexOf(p.branch)),{results:a,atomicPush:i.atomicPush,declined:!1}},og=async e=>{let{cwd:t,versions:r,all:n,confirmedCommand:o}=e,s=await eg({cwd:t,versions:r,all:n});if(s.length===0)return u.info("\u2139\uFE0F No merge-dev resolutions in progress"),po();let i={branches:s.map(a=>({branch:a.branch,worktreePath:a.worktreePath}))};try{await B(o,`Discard the resolution worktrees for: ${s.map(a=>a.branch).join(", ")}?`,{plan:i,throwOnDecline:!0})}catch(a){if(!at(a))throw a;return{...po(),declined:!0}}for(let a of s)await zc(t,a.branch,a.worktreePath),u.info(`\u{1F5D1}\uFE0F Discarded the resolution for ${a.branch}`);return{...po(),results:s.map(a=>({branch:a.branch,status:"aborted",conflictPaths:a.conflictPaths,pushed:!1}))}};import KR from"node:fs";import HR from"node:os";import qR from"node:path";var YR="infra-kit.json",zR="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)",XR="Skipped agent-instruction files \u2014 no infra-kit.json at the repo root (the plugin pointer, the plugin install and .mcp.json are unaffected)",fo=async()=>{let e;try{e=await T()}catch{return null}let t=e.trim();return t===""||t===HR.homedir()?null:t},sg=async()=>{let e=await fo();return e===null&&u.info(zR),e},ZR=async()=>{let e=await fo();return e===null?null:KR.existsSync(qR.join(e,YR))?e:(u.info(XR),null)};var QR=async e=>{try{return await Pe(e)}catch(t){return u.debug({err:t,msg:"Skipped per-package agent guidance \u2014 no workspace packages could be discovered."}),[]}},ig=async()=>{let e=await ZR(),t=K.version;if(e===null)return{skipped:!0,root:null,version:t,written:[]};let r=[...await Jn(e,{version:t})];for(let n of await QR(e)){let o=await Xt(n);r.push(...await Gn(n,{repoRoot:e,version:t,declaredType:o}))}return{skipped:!1,root:e,version:t,written:r}};import pe from"node:fs";import sl from"node:os";import ge from"node:path";import il from"node:process";import ni from"node:fs/promises";import eS from"node:path";import tS from"node:process";var ag=` // "envManagement": { // required in layer 1; provider-tagged
177
177
  // "provider": "doppler",
178
178
  // "config": { "name": "my-doppler-project" }
179
179
  // },
@@ -285,13 +285,21 @@ ${l}`:l}).join(""),c=If.byteLength(a)>Nf;return{diffStat:r,...o?{lockfileDiffSta
285
285
  // "turbo": { "requiredTasks": ["build", "test"] }
286
286
  // }
287
287
  //
288
+ // // The <repo> label of the dev host \`<release>.<package>.<repo>.localhost\`, in place of the main
289
+ // // checkout's directory name. A DNS label: a-z, 0-9 and inner "-".
290
+ // //
291
+ // // PROJECT LAYER ONLY. REFUSED here and in the per-project override \u2014 the vite and Playwright
292
+ // // helpers read it from the committed infra-kit.json alone, so a per-machine copy would register a
293
+ // // dev host they never aim at.
294
+ // "aliasRepo": "trvl"
295
+ //
288
296
  // // Doppler SERVICE TOKENS are not a config key and never belong in this file. They live in
289
297
  // // tokens.json \u2014 a SIBLING of this file, at ~/.infra-kit/projects/<repo>/tokens.json (mode 0600) \u2014
290
298
  // // shaped { "envs": { "<env>": "dp.st\u2026" } }. Write it with \`infra-kit env-token-set <env>\` (which
291
299
  // // also fixes its modes), or by hand: both are supported, which is why the store carries no
292
300
  // // repo-identity field and no mandatory version. Pasting a token into an
293
301
  // // infra-kit.json (any layer) is REJECTED: the loader refuses to parse it and tells you to revoke
294
- // // the token first, because a config file can be committed, backed up by your editor, or shared.`,Yc=()=>`// infra-kit user-global config \u2014 ~/.infra-kit/infra-kit.json
302
+ // // the token first, because a config file can be committed, backed up by your editor, or shared.`,Xc=()=>`// infra-kit user-global config \u2014 ~/.infra-kit/infra-kit.json
295
303
  //
296
304
  // Merge chain (later layers override earlier ones at top-level keys):
297
305
  // 1. <repo>/infra-kit.json \u2014 committed project config (required)
@@ -301,7 +309,7 @@ ${l}`:l}).join(""),c=If.byteLength(a)>Nf;return{diffStat:r,...o?{lockfileDiffSta
301
309
  // Merge is shallow: setting a top-level key replaces that whole section from
302
310
  // layer 1. Arrays do not concatenate. Top-level keys recognized:
303
311
  // envManagement, ide, taskManager, worktrees, dev, devServersPresets,
304
- // protectedEnvs, mcp, vendorSource, audit (the last three project layer only). The schema is strict \u2014 an
312
+ // protectedEnvs, mcp, vendorSource, audit, aliasRepo (the last four project layer only). The schema is strict \u2014 an
305
313
  // unrecognized top-level key is a parse error, not a silently ignored one.
306
314
  //
307
315
  // This .example.jsonc is reference only \u2014 it is NOT loaded. Put real global
@@ -312,15 +320,15 @@ ${l}`:l}).join(""),c=If.byteLength(a)>Nf;return{diffStat:r,...o?{lockfileDiffSta
312
320
  // the committed project infra-kit.json (layer 1) and is usually NOT set in this
313
321
  // user-global layer \u2014 it is shown here only to document the full, valid config shape.
314
322
  {
315
- ${ng}
323
+ ${ag}
316
324
  }
317
- `,zc=e=>`// infra-kit user override for ${e} \u2014 ~/.infra-kit/projects/${e}/infra-kit.json
325
+ `,Zc=e=>`// infra-kit user override for ${e} \u2014 ~/.infra-kit/projects/${e}/infra-kit.json
318
326
  //
319
327
  // Layer 3 (highest precedence) of the config merge chain. Shallow-merged on top of
320
328
  // <repo>/infra-kit.json (layer 1) and ~/.infra-kit/infra-kit.json (layer 2) \u2014 a
321
329
  // top-level key set here replaces that whole section wholesale; arrays do not
322
330
  // concatenate. Top-level keys recognized: envManagement, ide, taskManager,
323
- // worktrees, dev, devServersPresets, protectedEnvs, mcp, vendorSource, audit (the last three project layer only \u2014
331
+ // worktrees, dev, devServersPresets, protectedEnvs, mcp, vendorSource, audit, aliasRepo (the last four project layer only \u2014
324
332
  // refused here). The schema is strict \u2014 an unrecognized top-level key is a parse
325
333
  // error, not a silently ignored one.
326
334
  //
@@ -331,9 +339,9 @@ ${ng}
331
339
  // the committed project infra-kit.json (layer 1) and is usually NOT set in this
332
340
  // override layer \u2014 it is shown here only to document the full, valid config shape.
333
341
  {
334
- ${ng}
342
+ ${ag}
335
343
  }
336
- `,Xc=()=>`// infra-kit factory registry \u2014 ~/.infra-kit/vendor.json
344
+ `,Qc=()=>`// infra-kit factory registry \u2014 ~/.infra-kit/vendor.json
337
345
  //
338
346
  // Machine-local registry the vendor commands (sync/manifest/diff) read to know
339
347
  // where your project repos live, which one is the source and which ones to stamp. This .example.jsonc is
@@ -345,92 +353,94 @@ ${ng}
345
353
  // "source": "starter-workspace", // string \u2014 the one repo \`vendor sync\` copies from (its infra-kit.json holds vendorSource)
346
354
  // "targets": ["my-repo-a", "my-repo-b"] // string[] (>=1) \u2014 repo dir names resolved under workspaceDir
347
355
  }
348
- `;var og=!1,YR=e=>e.replace(/\.json$/,".example.jsonc"),zR=async e=>{try{return await ti.readFile(e,"utf-8")}catch{return null}},Xr=async e=>{let t=e.userProject,r=YR(t);await ti.mkdir(HR.dirname(t),{recursive:!0});let n=!await Z(t);n&&await ti.writeFile(t,`{}
349
- `,"utf-8");let o=zc(e.projectName),s=await zR(r)!==o;return s&&await ti.writeFile(r,o,"utf-8"),n&&Tn(),{configPath:t,examplePath:r,createdConfig:n,refreshedExample:s}},Zr=e=>`Created ${v(e.configPath)} \u2014 see ${v(e.examplePath)} for the annotated reference.`,Zc=async()=>{if(qR.env.INFRA_KIT_NO_SEED||og)return;og=!0;let e;try{e=await H()}catch{return}if(await Z(e.main))try{let t=await Xr(e);t.createdConfig?u.info(Zr(t)):t.refreshedExample&&u.debug(`Refreshed ${v(t.examplePath)} to match the current schema.`)}catch(t){u.debug({err:t,msg:`Skipped seeding ${v(e.userProject)} (config bootstrap failed).`})}};import{spawn as XR}from"node:child_process";import ig from"node:fs";import Qr from"node:process";import{fileURLToPath as ag}from"node:url";var sg=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],Qc=e=>{let{argv:t,env:r,isTty:n,selfRealPath:o,cwd:s,realpath:i}=e;return sg.some(c=>{let l=r[c];return l!=null&&l!==""})?"opt-out":t.includes("--json")?"json":n?Xu(o,s,i)?"local-install":null:"not-a-tty"};var ZR=e=>{XR(Qr.execPath,[e,"--parent-pid",String(Qr.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},QR=()=>ag(new URL("./update-check.js",import.meta.url)),eS=()=>ig.realpathSync(ag(new URL("./cli.js",import.meta.url))),tS=/^[\w@./+ -]+$/i,rS=e=>tS.test(e),nS=(e,t,r)=>{!e?.latestVersion||!e.updateCommand||$n(e.latestVersion,t)&&e.updateCommand.every(rS)&&r(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${cs(e.updateCommand)}`)},el=(e,t={})=>{try{let r=t.argv??Qr.argv,n=t.env??Qr.env,o=t.isTty??!!Qr.stdout.isTTY,s=t.cwd??Qr.cwd(),i=t.nowMs??Date.now(),a=t.selfRealPath??eS(),c=t.readCache??An,l=t.spawnChild??ZR,d=t.fileExists??(y=>ig.existsSync(y)),p=t.notify??(y=>{u.info(y)});if(Qc({argv:r,env:n,isTty:o,selfRealPath:a,cwd:s,realpath:he})!==null)return;let m=c();if(nS(m,e,p),!Sa(m,i))return;let g=t.childPath??QR();if(!d(g))return;l(g)}catch{}};import et from"node:fs/promises";import Qe from"node:path";import{pathToFileURL as iS}from"node:url";import aS from"yaml";import{z as rn}from"zod";import oS from"node:fs/promises";import tl from"node:os";import rl from"node:path";import{z as sS}from"zod";import{z as po}from"zod";var cg="vendor.json",lg=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 en=()=>rl.join(tl.homedir(),Uu,cg),tn=e=>{if(e==="~")return tl.homedir();if(e.startsWith("~/"))return rl.join(tl.homedir(),e.slice(2));if(rl.isAbsolute(e))return e;throw new Error(`workspaceDir must be absolute or ~-prefixed, got: ${e}`)},ri=async()=>{let e=en(),t;try{t=await oS.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:
356
+ `;var cg=!1,rS=e=>e.replace(/\.json$/,".example.jsonc"),nS=async e=>{try{return await ni.readFile(e,"utf-8")}catch{return null}},en=async e=>{let t=e.userProject,r=rS(t);await ni.mkdir(eS.dirname(t),{recursive:!0});let n=!await Z(t);n&&await ni.writeFile(t,`{}
357
+ `,"utf-8");let o=Zc(e.projectName),s=await nS(r)!==o;return s&&await ni.writeFile(r,o,"utf-8"),n&&An(),{configPath:t,examplePath:r,createdConfig:n,refreshedExample:s}},tn=e=>`Created ${v(e.configPath)} \u2014 see ${v(e.examplePath)} for the annotated reference.`,el=async()=>{if(tS.env.INFRA_KIT_NO_SEED||cg)return;cg=!0;let e;try{e=await H()}catch{return}if(await Z(e.main))try{let t=await en(e);t.createdConfig?u.info(tn(t)):t.refreshedExample&&u.debug(`Refreshed ${v(t.examplePath)} to match the current schema.`)}catch(t){u.debug({err:t,msg:`Skipped seeding ${v(e.userProject)} (config bootstrap failed).`})}};import{spawn as oS}from"node:child_process";import dg from"node:fs";import rn from"node:process";import{fileURLToPath as ug}from"node:url";var lg=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],tl=e=>{let{argv:t,env:r,isTty:n,selfRealPath:o,cwd:s,realpath:i}=e;return lg.some(c=>{let l=r[c];return l!=null&&l!==""})?"opt-out":t.includes("--json")?"json":n?ep(o,s,i)?"local-install":null:"not-a-tty"};var sS=e=>{oS(rn.execPath,[e,"--parent-pid",String(rn.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},iS=()=>ug(new URL("./update-check.js",import.meta.url)),aS=()=>dg.realpathSync(ug(new URL("./cli.js",import.meta.url))),cS=/^[\w@./+ -]+$/i,lS=e=>cS.test(e),dS=(e,t,r)=>{!e?.latestVersion||!e.updateCommand||In(e.latestVersion,t)&&e.updateCommand.every(lS)&&r(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${ps(e.updateCommand)}`)},rl=(e,t={})=>{try{let r=t.argv??rn.argv,n=t.env??rn.env,o=t.isTty??!!rn.stdout.isTTY,s=t.cwd??rn.cwd(),i=t.nowMs??Date.now(),a=t.selfRealPath??aS(),c=t.readCache??Dn,l=t.spawnChild??sS,d=t.fileExists??(y=>dg.existsSync(y)),p=t.notify??(y=>{u.info(y)});if(tl({argv:r,env:n,isTty:o,selfRealPath:a,cwd:s,realpath:he})!==null)return;let m=c();if(dS(m,e,p),!Ea(m,i))return;let g=t.childPath??iS();if(!d(g))return;l(g)}catch{}};import nt from"node:fs/promises";import rt from"node:path";import{pathToFileURL as mS}from"node:url";import fS from"yaml";import{z as sn}from"zod";import uS from"node:fs/promises";import nl from"node:os";import ol from"node:path";import{z as pS}from"zod";import{z as go}from"zod";var pg="vendor.json",mg=go.object({workspaceDir:go.string().min(1),source:go.string().min(1),targets:go.array(go.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 nn=()=>ol.join(nl.homedir(),Ku,pg),on=e=>{if(e==="~")return nl.homedir();if(e.startsWith("~/"))return ol.join(nl.homedir(),e.slice(2));if(ol.isAbsolute(e))return e;throw new Error(`workspaceDir must be absolute or ~-prefixed, got: ${e}`)},oi=async()=>{let e=nn(),t;try{t=await uS.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:
350
358
 
351
359
  {
352
360
  "workspaceDir": "~/projects",
353
361
  "source": "my-starter",
354
362
  "targets": ["my-repo"]
355
363
  }
356
- `)}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=lg.safeParse(r);if(!n.success)throw new Error(`Invalid factory config at ${e}: ${sS.prettifyError(n.error)}`);return n.data};var dg=e=>e.replace(/\.json$/,".yml"),ug=async()=>{let e;try{e=await H()}catch{return}let t=[{label:"infra-kit.json",yml:dg(e.main),json:e.main,schema:_p},{label:"~/.infra-kit/infra-kit.json",yml:Qe.join(Qe.dirname(e.userGlobal),"config.yml"),json:e.userGlobal,schema:ka},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:dg(e.userProject),json:e.userProject,schema:ka}],r=0;for(let n of t){let[o,s]=await Promise.all([Z(n.yml),Z(n.json)]);if(o){if(s){u.info(`\u26A0 Skipped ${v(n.yml)} \u2014 ${v(n.json)} already exists (remove the stale .yml manually)`);continue}try{let i=await et.readFile(n.yml,"utf-8"),a=aS.parse(i)??{},c=n.schema.safeParse(a);if(!c.success){u.info(`\u26A0 Skipped ${v(n.yml)} \u2014 invalid config: ${rn.prettifyError(c.error)}`);continue}await et.mkdir(Qe.dirname(n.json),{recursive:!0}),await et.writeFile(n.json,`${JSON.stringify(c.data,null,2)}
357
- `,"utf-8"),await et.rm(n.yml,{force:!0}),u.info(`\u2713 Migrated ${v(n.yml)} \u2192 ${v(n.json)}`),r++}catch(i){u.info(`\u26A0 Skipped ${v(n.yml)} \u2014 ${i.message}`)}}}r>0&&vt()},pg=async()=>{let e;try{e=await H()}catch{return}let t=Qe.dirname(e.userGlobal),r=[{from:Qe.join(t,"config.json"),to:e.userGlobal},{from:Qe.join(t,"config.example.jsonc"),to:Qe.join(t,"infra-kit.example.jsonc")}],n=0;for(let{from:o,to:s}of r){let[i,a]=await Promise.all([Z(o),Z(s)]);if(i){if(a){u.info(`\u26A0 Skipped ${v(o)} \u2014 ${v(s)} already exists (remove the stale file manually)`);continue}try{await et.mkdir(Qe.dirname(s),{recursive:!0}),await et.rename(o,s),u.info(`\u2713 Renamed ${v(o)} \u2192 ${v(s)}`),n++}catch(c){u.info(`\u26A0 Skipped ${v(o)} \u2014 ${c.message}`)}}}n>0&&vt()},cS=rn.object({workspaceDir:rn.string().min(1),targets:rn.array(rn.string()).min(1)}).strict(),mg=async()=>{let e=en(),t=Qe.dirname(e),r=Qe.join(t,"vendor.config.ts"),[n,o]=await Promise.all([Z(r),Z(e)]);if(n){if(o){u.info(`\u26A0 Skipped ${v(r)} \u2014 ${v(e)} already exists (remove the stale vendor.config.ts manually)`);return}try{let s=await et.stat(r),c=(await import(`${iS(r).href}?mtime=${Number(s.mtimeMs)}`)).default,l=typeof c=="function",d=l?await c():c,p=cS.safeParse(d);if(!p.success){u.info(`\u26A0 Skipped ${v(r)} \u2014 invalid factory config: ${rn.prettifyError(p.error)}`);return}await et.mkdir(t,{recursive:!0}),await et.writeFile(e,`${JSON.stringify(p.data,null,2)}
358
- `,"utf-8"),await et.rm(r,{force:!0}),l?u.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.`):u.info(`\u2713 Migrated ${v(r)} \u2192 ${v(e)}`)}catch(s){u.info(`\u26A0 Skipped ${v(r)} \u2014 ${s.message}`)}}},fg=async()=>{let e=await lS(),t=0;for(let r of e)if(await Z(r))try{let n=await Op(r);if(!n.changed)continue;u.info(`\u2713 Migrated ${v(r)} (removed ${n.notes.join(" and ")})`),t++}catch(n){let o=n instanceof $p?"changed while migrating":n.message;u.info(`\u26A0 Skipped ${v(r)} \u2014 ${o}`)}t>0&&vt()},lS=async()=>{try{let e=await H();return[e.main,e.userGlobal,e.userProject]}catch{return[jp()]}};var or="# -- infra-kit:begin --",$t="# -- infra-kit:end --",dS=[["# region infra-kit","# endregion infra-kit"]],uS="# infra-kit shell functions",nn=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},on="Run `source ~/.zshrc` or open a new terminal to activate.",pS={step:"migrations",outcome:"unchanged",message:"Config migrations checked (legacy yml layers, user-global filename, ide structure, factory config, retired project cache)",level:"silent"},tt=async(e,t)=>{try{return await t()}catch(r){throw new nn(e,r)}},sl=async e=>{let t=[],r=(...s)=>{for(let i of s)t.push(i),e?.(i)};await tt("zshrc",()=>{r(mS())}),await tt("zshenv",()=>{r(fS())}),await tt("migrations",async()=>{await hS(),gS(),r(pS)}),await tt("user-config",()=>{r(vS())});let n=await tt("guidance",async()=>{let{entries:s,root:i}=await bS();return r(...s),i}),o=await tt("plugin-pointer",async()=>tg());return r(...PS(o,n)),await tt("worktrees",async()=>{r(...await $S(o))}),await tt("plugin-pointer",async()=>{await AS(o,r)}),await tt("mcp-proxies",async()=>{r(...await IS(o))}),await tt("project-config",async()=>{r(...await wS())}),r(...yS()),t};var mS=()=>{let e=fe.join(nl.homedir(),".zshrc"),t=ue.existsSync(e)?NS(ue.readFileSync(e,"utf-8")):"",r=$r({content:t,body:hg(),startMarker:or,endMarker:$t,placement:"append-end"});return ue.writeFileSync(e,r),{step:"zshrc",outcome:"written",message:`Added infra-kit shell functions to ${e}`,level:"info"}},fS=()=>{let e=fe.join(nl.homedir(),".zshenv"),t=ue.existsSync(e)?ue.readFileSync(e,"utf-8"):"",r=$r({content:t,body:il(),startMarker:or,endMarker:$t});return ue.writeFileSync(e,r),{step:"zshenv",outcome:"written",message:`Added infra-kit session-env block to ${e}`,level:"info"}},gS=()=>{ue.rmSync(fe.join(Hu(),"projects"),{recursive:!0,force:!0})},hS=async()=>{await ug(),await pg(),await fg(),await mg()},yS=()=>{let e=ol.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:on,level:"info"}),t},vS=()=>{let e=fe.join(nl.homedir(),".infra-kit"),t=fe.join(e,"infra-kit.json");return ue.mkdirSync(e,{recursive:!0}),ue.writeFileSync(fe.join(e,"infra-kit.example.jsonc"),Yc(),"utf-8"),ue.writeFileSync(fe.join(e,"vendor.example.jsonc"),Xc(),"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,`{}
359
- `,"utf-8"),{step:"user-config",outcome:"written",message:`Wrote user-global config to ${t} (see the sibling .example.jsonc files for reference)`,level:"info"})},wS=async()=>{if(ol.env.INFRA_KIT_NO_SEED)return[ni("skipped","INFRA_KIT_NO_SEED is set")];try{let e=await H();if(!ue.existsSync(e.main))return[ni("skipped",`no project config at ${e.main}`)];let t=await Xr(e);return t.createdConfig?[{step:"project-config",outcome:"written",message:Zr(t),level:"info"}]:[ni("unchanged","the user-project config was already present")]}catch(e){return u.debug({err:e,msg:"Skipped seeding the user-project config (init)."}),[ni("warned",e instanceof Error?e.message:String(e))]}},ni=(e,t)=>({step:"project-config",outcome:e,message:`Skipped seeding the user-project config \u2014 ${t}`,level:"silent"}),kS=(e,t,r)=>{let n=[];for(let s of r){if(s.action==="unchanged")continue;let i=s.type===void 0?"":` (${s.type})`;n.push({step:"guidance",outcome:s.action==="failed"?"warned":"written",message:` ${s.action.padEnd(9)} ${fe.relative(e,s.path)}${i}`,level:"info"})}n.push({step:"guidance",outcome:"written",message:`Agent-instruction files synced (infra-kit ${t})`,level:"info"});let o=r.filter(s=>s.action==="failed");return o.length===0||n.push({step:"guidance",outcome:"warned",message:`${o.length} package guidance files could not be written \u2014 run: infra-kit audit --fix --all`,level:"warn"}),n},bS=async()=>{let{skipped:e,root:t,version:r,written:n}=await rg();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:kS(t,r,n)}},RS=(e,t)=>{let r=fe.relative(e,t.path);return t.status==="created"?{step:"plugin-pointer",outcome:"written",message:` created ${r} (Claude Code plugin pointer)`,level:"info"}:t.status==="added"?{step:"plugin-pointer",outcome:"written",message:` updated ${r} \u2014 added ${t.added.join(", ")}`,level:"info"}:{step:"plugin-pointer",outcome:t.status==="unchanged"?"unchanged":"warned",message:`${r} \u2014 ${t.status}`,level:"silent"}},SS=(e,t)=>{let r=Ie;if(t.kind==="stale"||t.kind==="wrong-key"){let o=t.kind==="stale"?de: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 ${Ye} from ${fe.join(e,Ie)} \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 "${de}" key`:`no ${r}`})`,level:"info"}},PS=(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 ${q} plugin for that project. If that is not the repo you meant to set up, revert that file and uninstall the plugin.`,level:"warn"}],ES=()=>[mc,it].map(e=>({step:"plugin-pointer",outcome:"manual",message:e,level:"info"})),xS=e=>{let r={step:"plugin-pointer",outcome:"warned",message:`Claude Code plugin not updated \u2014 ${e.stale?`CLI ${K.version} is behind ${e.latestVersion}, update it first with the command below`:`CLI ${K.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:cs(e.updateCommand),level:"info"}]:[r]},TS=(e,t)=>e.status==="skipped-cli-stale"?xS(t):e.status==="updated"?[{step:"plugin-pointer",outcome:"unchanged",message:`Claude Code plugin ${q} 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: ${jr}`,level:"warn"}]:e.status==="installed"?[{step:"plugin-pointer",outcome:"written",message:`installed Claude Code plugin ${q} (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"},...ES()]:[{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: ${it}`,level:"warn"}],gg={stale:!1},CS=async()=>{let e=An(),t=e===null?await Pa(ol.env):e.latestVersion;return t===null||!Ea(t,K.version)?gg:{stale:!0,latestVersion:t,updateCommand:e?.updateCommand??zu(t)}},$S=async e=>{if(e===null)return[];let r=`${await Le(e)}${ge}`,n=Object.values(Sr).filter(o=>!ue.existsSync(fe.join(r,o)));for(let o of Object.values(Sr))ue.mkdirSync(fe.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"}]},AS=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(RS(e,fc(fe.join(e,".claude","settings.json"))));let n=Gt({projectPath:e}).kind==="installed"?await CS():gg;t(...TS(cc({projectRoot:e,cliIsStale:()=>n.stale}),n)),t(SS(e,Gn(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: ${it}`,level:"warn"})}},OS=(e,t)=>{let r=fe.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},IS=async e=>{if(e===null)return[];if(!ue.existsSync(fe.join(e,"infra-kit.json")))return[{step:"mcp-proxies",outcome:"skipped",message:"no infra-kit.json \u2014 no ik-mcp entries to derive",level:"silent"}];let t;try{t=(await M()).mcp}catch(r){let n=r instanceof Error?r.message:String(r);return[{step:"mcp-proxies",outcome:"warned",message:` ik-mcp entries not synced \u2014 infra-kit.json could not be loaded (${n.split(`
360
- `)[0]??n})`,level:"warn"}]}return!t||Object.keys(t).length===0?[]:OS(e,_s({projectRoot:e,proxies:t,write:!0}))},DS=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"),NS=e=>{let t=Pt(e,or,$t);if(t!==null)return t;for(let[a,c]of dS){let l=Pt(e,a,c);if(l!==null)return l}let r=e.indexOf(uS);if(r===-1)return e;let n=e.slice(0,r).replace(/\n+$/,""),o=e.slice(r).split(`
361
- `),s=0;for(;s<o.length&&DS(o[s]);)s++;let i=o.slice(s).join(`
364
+ `)}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=mg.safeParse(r);if(!n.success)throw new Error(`Invalid factory config at ${e}: ${pS.prettifyError(n.error)}`);return n.data};var fg=e=>e.replace(/\.json$/,".yml"),gg=async()=>{let e;try{e=await H()}catch{return}let t=[{label:"infra-kit.json",yml:fg(e.main),json:e.main,schema:Fp},{label:"~/.infra-kit/infra-kit.json",yml:rt.join(rt.dirname(e.userGlobal),"config.yml"),json:e.userGlobal,schema:Ra},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:fg(e.userProject),json:e.userProject,schema:Ra}],r=0;for(let n of t){let[o,s]=await Promise.all([Z(n.yml),Z(n.json)]);if(o){if(s){u.info(`\u26A0 Skipped ${v(n.yml)} \u2014 ${v(n.json)} already exists (remove the stale .yml manually)`);continue}try{let i=await nt.readFile(n.yml,"utf-8"),a=fS.parse(i)??{},c=n.schema.safeParse(a);if(!c.success){u.info(`\u26A0 Skipped ${v(n.yml)} \u2014 invalid config: ${sn.prettifyError(c.error)}`);continue}await nt.mkdir(rt.dirname(n.json),{recursive:!0}),await nt.writeFile(n.json,`${JSON.stringify(c.data,null,2)}
365
+ `,"utf-8"),await nt.rm(n.yml,{force:!0}),u.info(`\u2713 Migrated ${v(n.yml)} \u2192 ${v(n.json)}`),r++}catch(i){u.info(`\u26A0 Skipped ${v(n.yml)} \u2014 ${i.message}`)}}}r>0&&kt()},hg=async()=>{let e;try{e=await H()}catch{return}let t=rt.dirname(e.userGlobal),r=[{from:rt.join(t,"config.json"),to:e.userGlobal},{from:rt.join(t,"config.example.jsonc"),to:rt.join(t,"infra-kit.example.jsonc")}],n=0;for(let{from:o,to:s}of r){let[i,a]=await Promise.all([Z(o),Z(s)]);if(i){if(a){u.info(`\u26A0 Skipped ${v(o)} \u2014 ${v(s)} already exists (remove the stale file manually)`);continue}try{await nt.mkdir(rt.dirname(s),{recursive:!0}),await nt.rename(o,s),u.info(`\u2713 Renamed ${v(o)} \u2192 ${v(s)}`),n++}catch(c){u.info(`\u26A0 Skipped ${v(o)} \u2014 ${c.message}`)}}}n>0&&kt()},gS=sn.object({workspaceDir:sn.string().min(1),targets:sn.array(sn.string()).min(1)}).strict(),yg=async()=>{let e=nn(),t=rt.dirname(e),r=rt.join(t,"vendor.config.ts"),[n,o]=await Promise.all([Z(r),Z(e)]);if(n){if(o){u.info(`\u26A0 Skipped ${v(r)} \u2014 ${v(e)} already exists (remove the stale vendor.config.ts manually)`);return}try{let s=await nt.stat(r),c=(await import(`${mS(r).href}?mtime=${Number(s.mtimeMs)}`)).default,l=typeof c=="function",d=l?await c():c,p=gS.safeParse(d);if(!p.success){u.info(`\u26A0 Skipped ${v(r)} \u2014 invalid factory config: ${sn.prettifyError(p.error)}`);return}await nt.mkdir(t,{recursive:!0}),await nt.writeFile(e,`${JSON.stringify(p.data,null,2)}
366
+ `,"utf-8"),await nt.rm(r,{force:!0}),l?u.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.`):u.info(`\u2713 Migrated ${v(r)} \u2192 ${v(e)}`)}catch(s){u.info(`\u26A0 Skipped ${v(r)} \u2014 ${s.message}`)}}},vg=async()=>{let e=await hS(),t=0;for(let r of e)if(await Z(r))try{let n=await Np(r);if(!n.changed)continue;u.info(`\u2713 Migrated ${v(r)} (removed ${n.notes.join(" and ")})`),t++}catch(n){let o=n instanceof Ip?"changed while migrating":n.message;u.info(`\u26A0 Skipped ${v(r)} \u2014 ${o}`)}t>0&&kt()},hS=async()=>{try{let e=await H();return[e.main,e.userGlobal,e.userProject]}catch{return[Bp()]}};var sr="# -- infra-kit:begin --",It="# -- infra-kit:end --",yS=[["# region infra-kit","# endregion infra-kit"]],vS="# infra-kit shell functions",an=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},cn="Run `source ~/.zshrc` or open a new terminal to activate.",wS={step:"migrations",outcome:"unchanged",message:"Config migrations checked (legacy yml layers, user-global filename, ide structure, factory config, retired project cache)",level:"silent"},ot=async(e,t)=>{try{return await t()}catch(r){throw new an(e,r)}},al=async e=>{let t=[],r=(...s)=>{for(let i of s)t.push(i),e?.(i)};await ot("zshrc",()=>{r(kS())}),await ot("zshenv",()=>{r(bS())}),await ot("migrations",async()=>{await SS(),RS(),r(wS)}),await ot("user-config",()=>{r(ES())});let n=await ot("guidance",async()=>{let{entries:s,root:i}=await CS();return r(...s),i}),o=await ot("plugin-pointer",async()=>sg());return r(...OS(o,n)),await ot("worktrees",async()=>{r(...await MS(o))}),await ot("plugin-pointer",async()=>{await jS(o,r)}),await ot("mcp-proxies",async()=>{r(...await LS(o))}),await ot("project-config",async()=>{r(...await xS())}),r(...PS()),t};var kS=()=>{let e=ge.join(sl.homedir(),".zshrc"),t=pe.existsSync(e)?WS(pe.readFileSync(e,"utf-8")):"",r=Ir({content:t,body:kg(),startMarker:sr,endMarker:It,placement:"append-end"});return pe.writeFileSync(e,r),{step:"zshrc",outcome:"written",message:`Added infra-kit shell functions to ${e}`,level:"info"}},bS=()=>{let e=ge.join(sl.homedir(),".zshenv"),t=pe.existsSync(e)?pe.readFileSync(e,"utf-8"):"",r=Ir({content:t,body:cl(),startMarker:sr,endMarker:It});return pe.writeFileSync(e,r),{step:"zshenv",outcome:"written",message:`Added infra-kit session-env block to ${e}`,level:"info"}},RS=()=>{pe.rmSync(ge.join(zu(),"projects"),{recursive:!0,force:!0})},SS=async()=>{await gg(),await hg(),await vg(),await yg()},PS=()=>{let e=il.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:cn,level:"info"}),t},ES=()=>{let e=ge.join(sl.homedir(),".infra-kit"),t=ge.join(e,"infra-kit.json");return pe.mkdirSync(e,{recursive:!0}),pe.writeFileSync(ge.join(e,"infra-kit.example.jsonc"),Xc(),"utf-8"),pe.writeFileSync(ge.join(e,"vendor.example.jsonc"),Qc(),"utf-8"),pe.existsSync(t)?{step:"user-config",outcome:"unchanged",message:`User-global config already present at ${t} (refreshed reference examples)`,level:"info"}:(pe.writeFileSync(t,`{}
367
+ `,"utf-8"),{step:"user-config",outcome:"written",message:`Wrote user-global config to ${t} (see the sibling .example.jsonc files for reference)`,level:"info"})},xS=async()=>{if(il.env.INFRA_KIT_NO_SEED)return[si("skipped","INFRA_KIT_NO_SEED is set")];try{let e=await H();if(!pe.existsSync(e.main))return[si("skipped",`no project config at ${e.main}`)];let t=await en(e);return t.createdConfig?[{step:"project-config",outcome:"written",message:tn(t),level:"info"}]:[si("unchanged","the user-project config was already present")]}catch(e){return u.debug({err:e,msg:"Skipped seeding the user-project config (init)."}),[si("warned",e instanceof Error?e.message:String(e))]}},si=(e,t)=>({step:"project-config",outcome:e,message:`Skipped seeding the user-project config \u2014 ${t}`,level:"silent"}),TS=(e,t,r)=>{let n=[];for(let s of r){if(s.action==="unchanged")continue;let i=s.type===void 0?"":` (${s.type})`;n.push({step:"guidance",outcome:s.action==="failed"?"warned":"written",message:` ${s.action.padEnd(9)} ${ge.relative(e,s.path)}${i}`,level:"info"})}n.push({step:"guidance",outcome:"written",message:`Agent-instruction files synced (infra-kit ${t})`,level:"info"});let o=r.filter(s=>s.action==="failed");return o.length===0||n.push({step:"guidance",outcome:"warned",message:`${o.length} package guidance files could not be written \u2014 run: infra-kit audit --fix --all`,level:"warn"}),n},CS=async()=>{let{skipped:e,root:t,version:r,written:n}=await ig();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:TS(t,r,n)}},$S=(e,t)=>{let r=ge.relative(e,t.path);return t.status==="created"?{step:"plugin-pointer",outcome:"written",message:` created ${r} (Claude Code plugin pointer)`,level:"info"}:t.status==="added"?{step:"plugin-pointer",outcome:"written",message:` updated ${r} \u2014 added ${t.added.join(", ")}`,level:"info"}:{step:"plugin-pointer",outcome:t.status==="unchanged"?"unchanged":"warned",message:`${r} \u2014 ${t.status}`,level:"silent"}},AS=(e,t)=>{let r=Ne;if(t.kind==="stale"||t.kind==="wrong-key"){let o=t.kind==="stale"?ue:t.key;return{step:"mcp-server",outcome:"unchanged",message:` ${r} still registers the infra-kit MCP server under "${o}" \u2014 the plugin no longer serves one, so this entry only spawns a failed server row. Delete the "${o}" entry from ${r} by hand in a PR, keeping its siblings`,level:"info"}}return t.kind==="unparseable"?{step:"mcp-server",outcome:"warned",message:`Could not read ${Ze} from ${ge.join(e,Ne)} \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 "${ue}" key`:`no ${r}`})`,level:"info"}},OS=(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 ${q} plugin for that project. If that is not the repo you meant to set up, revert that file and uninstall the plugin.`,level:"warn"}],IS=()=>[gc,lt].map(e=>({step:"plugin-pointer",outcome:"manual",message:e,level:"info"})),DS=e=>{let r={step:"plugin-pointer",outcome:"warned",message:`Claude Code plugin not updated \u2014 ${e.stale?`CLI ${K.version} is behind ${e.latestVersion}, update it first with the command below`:`CLI ${K.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]},NS=(e,t)=>e.status==="skipped-cli-stale"?DS(t):e.status==="updated"?[{step:"plugin-pointer",outcome:"unchanged",message:`Claude Code plugin ${q} 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: ${Br}`,level:"warn"}]:e.status==="installed"?[{step:"plugin-pointer",outcome:"written",message:`installed Claude Code plugin ${q} (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"},...IS()]:[{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: ${lt}`,level:"warn"}],wg={stale:!1},_S=async()=>{let e=Dn(),t=e===null?await xa(il.env):e.latestVersion;return t===null||!Ta(t,K.version)?wg:{stale:!0,latestVersion:t,updateCommand:e?.updateCommand??Qu(t)}},MS=async e=>{if(e===null)return[];let r=`${await be(e)}${de}`,n=Object.values(Er).filter(o=>!pe.existsSync(ge.join(r,o)));for(let o of Object.values(Er))pe.mkdirSync(ge.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"}]},jS=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($S(e,hc(ge.join(e,".claude","settings.json"))));let n=Ht({projectPath:e}).kind==="installed"?await _S():wg;t(...NS(dc({projectRoot:e,cliIsStale:()=>n.stale}),n)),t(AS(e,qn(e)))}catch(r){let n=r instanceof Error?r.message:String(r);t({step:"plugin-pointer",outcome:"warned",message:`Could not finish the Claude Code plugin step for ${e} (${n}). Run by hand: ${lt}`,level:"warn"})}},FS=(e,t)=>{let r=ge.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},LS=async e=>{if(e===null)return[];if(!pe.existsSync(ge.join(e,"infra-kit.json")))return[{step:"mcp-proxies",outcome:"skipped",message:"no infra-kit.json \u2014 no ik-mcp entries to derive",level:"silent"}];let t;try{t=(await M()).mcp}catch(r){let n=r instanceof Error?r.message:String(r);return[{step:"mcp-proxies",outcome:"warned",message:` ik-mcp entries not synced \u2014 infra-kit.json could not be loaded (${n.split(`
368
+ `)[0]??n})`,level:"warn"}]}return!t||Object.keys(t).length===0?[]:FS(e,js({projectRoot:e,proxies:t,write:!0}))},BS=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"),WS=e=>{let t=Tt(e,sr,It);if(t!==null)return t;for(let[a,c]of yS){let l=Tt(e,a,c);if(l!==null)return l}let r=e.indexOf(vS);if(r===-1)return e;let n=e.slice(0,r).replace(/\n+$/,""),o=e.slice(r).split(`
369
+ `),s=0;for(;s<o.length&&BS(o[s]);)s++;let i=o.slice(s).join(`
362
370
  `);return n+(i?`
363
- ${i}`:"")},hg=()=>{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(`
364
- `)},yg=()=>`${or}
365
- ${hg()}
366
- ${$t}`,il=()=>["# 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(`
367
- `),al=()=>`${or}
368
- ${il()}
369
- ${$t}`;import _S from"node:fs/promises";var mo=async(e,t)=>{if(!t)return{hasOverrides:!1,overrideKeys:[],unreadable:!1};try{let r=await _S.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}}},fo=e=>e.unreadable?"(unreadable \u2014 invalid JSON)":e.overrideKeys.length===0?"(empty \u2014 no overrides)":`(${e.overrideKeys.length} override(s): ${e.overrideKeys.join(", ")})`;import jS from"node:fs";import FS from"node:os";import vg from"node:path";import LS from"node:process";import{$ as MS}from"zx";var sr=()=>MS({quiet:!0});var BS=()=>[vg.join(FS.homedir(),".local","bin"),"/opt/homebrew/bin","/usr/local/bin"],WS=async e=>{try{return(await sr()`command -v ${e}`).stdout.trim()||null}catch{return null}},go=()=>({runCommand:async e=>{let t=await sr()`${e}`;return{stdout:`${t.stdout}
370
- ${t.stderr}`}},resolveBinPath:async e=>{let t=await WS(e);return t!==null?t:BS().map(r=>vg.join(r,e)).find(r=>jS.existsSync(r))??null},realpath:he,platform:LS.platform});var At=(...e)=>({steps:e,needsSudo:!1,fetchesNetworkScript:!1}),sn=e=>/\d{1,10}\.\d{1,10}\.\d{1,10}/.exec(e)?.[0]??null,an=["darwin","linux"],ai=e=>t=>fa(t,e)?"homebrew":"unknown",ci=(e,t)=>r=>r===null?null:t(e(r),r),ll=e=>ci(ai(e.kegName),t=>t==="homebrew"?At(["brew","upgrade",e.brewFormula]):null),wg=e=>as(e,"Homebrew")||as(e,"homebrew")?"homebrew":"unknown",VS={id:"brew",binName:"brew",probeArgv:["brew","--version"],versionFrom:sn,platforms:an,prerequisites:[],bootstrapInstall:{steps:[["/bin/bash","-c","$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"]],needsSudo:!0,fetchesNetworkScript:!0},identify:wg,updateFor:ci(wg,e=>e==="homebrew"?At(["brew","update"]):null)},cl={brewFormula:"awscli",brewInstallSpec:"awscli",kegName:"awscli"},Rg="https://awscli.amazonaws.com/v2/install.sh",Sg={steps:[["/bin/bash","-c",`curl -fsSL ${Rg} | bash`]],needsSudo:!1,fetchesNetworkScript:!0},US="/usr/local/aws-cli",JS=e=>Sn(US,e,he)?{steps:[["sudo","/bin/bash","-c",`curl -fsSL ${Rg} | bash -s -- --system`]],needsSudo:!0,fetchesNetworkScript:!0}:Sg,kg=e=>fa(e,cl.kegName)?"homebrew":as(e,"aws-cli")?"script":"unknown",GS={id:"aws",binName:"aws",...cl,probeArgv:["aws","--version"],versionFrom:sn,platforms:an,prerequisites:[],bootstrapInstall:Sg,identify:kg,updateFor:ci(kg,(e,t)=>e==="homebrew"?At(["brew","upgrade",cl.brewFormula]):e==="script"?JS(t):null)},oi={brewFormula:"git",brewInstallSpec:"git",kegName:"git"},KS={id:"git",binName:"git",...oi,probeArgv:["git","--version"],versionFrom:sn,platforms:an,prerequisites:["brew"],bootstrapInstall:At(["brew","install",oi.brewInstallSpec]),identify:ai(oi.kegName),updateFor:ll(oi)},si={brewFormula:"gh",brewInstallSpec:"gh",kegName:"gh"},HS={id:"gh",binName:"gh",...si,probeArgv:["gh","--version"],versionFrom:sn,platforms:an,prerequisites:["brew"],bootstrapInstall:At(["brew","install",si.brewInstallSpec]),identify:ai(si.kegName),updateFor:ll(si)},ii={brewFormula:"doppler",brewInstallSpec:"dopplerhq/cli/doppler",kegName:"doppler"},qS={id:"doppler",binName:"doppler",...ii,probeArgv:["doppler","--version"],versionFrom:sn,platforms:an,prerequisites:["brew"],bootstrapInstall:At(["brew","install","gnupg"],["brew","install",ii.brewInstallSpec]),identify:ai(ii.kegName),updateFor:ll(ii)},ho="portless",bg=e=>Yu(e,ho)===null?"unknown":"npm",YS={id:"portless",binName:ho,npmPackage:ho,probeArgv:["portless","--version"],versionFrom:sn,platforms:[...an,"win32"],prerequisites:[],bootstrapInstall:At(["npm","install","-g",ho]),identify:bg,updateFor:ci(bg,e=>e==="npm"?At(["npm","install","-g",`${ho}@latest`]):null)},dl={brew:VS,git:KS,aws:GS,gh:HS,doppler:qS,portless:YS},ir=Object.keys(dl),Ne=e=>dl[e],ul=(e,t)=>e.platforms.includes(t),pl=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 Ne(o).prerequisites)n(i,[...s,o]);t.push(o)}};for(let o of e)n(o,[]);return t};var Pg=e=>({id:e,present:!1,onPath:!1,binRealPath:null,version:null,manager:"unknown"}),Eg=async(e,t)=>{try{return await e(t)}catch{return null}},zS=async(e,t)=>{try{let r=await e.resolveBinPath(t);return r==null?null:e.realpath(r)}catch{return null}},xg=async(e,t)=>{if(!ul(e,t.platform))return Pg(e.id);let r=await Eg(t.runCommand,e.probeArgv),n=await zS(t,e.binName);if(r==null&&n==null)return Pg(e.id);let o=r??(n==null?null:await Eg(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)}},yo=async(e,t)=>Promise.all(e.map(r=>xg(Ne(r),t)));import{$ as rP}from"zx";import{z as Tg}from"zod";var Cg=/^\d{4}-\d{2}-\d{2}$/,vo=e=>{if(!Cg.test(e))return!1;let[t,r,n]=e.split("-").map(Number),o=new Date(Date.UTC(t,r-1,n));return o.getUTCFullYear()===t&&o.getUTCMonth()===r-1&&o.getUTCDate()===n},$g=e=>`Release date "${e}" is not a calendar date in yyyy-mm-dd form.`,cn=class extends Error{constructor(t){super($g(t)),this.name="InvalidReleaseDateError"}},ar=e=>{let t=e.trim();if(!vo(t))throw new cn(t);return t},wo=e=>{let t=e.trim();return t===""||vo(t)?!0:$g(t)},ml=Tg.string().refine(vo,{message:"Expected a calendar date in yyyy-mm-dd form."}),fl=Tg.string().refine(e=>e===""||vo(e),{message:'Expected a calendar date in yyyy-mm-dd form, or "" to clear.'});var Ot=e=>e.slice(1).split(".").map(Number),ln=e=>[...e].sort((t,r)=>{let[n,o,s]=Ot(t),[i,a,c]=Ot(r);return n!==i?(n??0)-(i??0):o!==a?(o??0)-(a??0):(s??0)-(c??0)});var Og="next",XS=/^v?(\d+)\.(\d+)\.(\d+)$/,ZS=e=>e.replace(/^.*release\//,""),gl=e=>{let t=ZS(e.trim()),r=XS.exec(t);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null},Ag=e=>`${e[0]}.${e[1]}.${e[2]}`,hl=e=>{let t=[...e.remoteBranches??[],...e.jiraVersions??[]],r=[],n=new Set;for(let o of t){let s=gl(o);if(!s)continue;let i=Ag(s);n.has(i)||(n.add(i),r.push(s))}return ln(r.map(o=>Ag(o))).map(o=>Ot(`v${o}`))},cr=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},yl=(e,t)=>{if(e.length===0)throw new cr;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`},dn=(e,t)=>{try{return yl(e,t)}catch(r){if(r instanceof cr)return null;throw r}},vl=e=>e.trim().toLowerCase()===Og,di=e=>vl(e)||gl(e)!==null?{version:e}:{name:e},QS=e=>e==="regular"||e==="hotfix",Ig=e=>"name"in e,eP=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:ar(n)}},wl=e=>{let t=e.trim();if(t==="")throw new Error("Release spec is empty");let r=t.indexOf(":"),{token:n,releaseDate:o}=eP(r===-1?t:t.slice(0,r)),s="regular",i="";if(r!==-1){let a=t.slice(r+1),c=a.indexOf(":"),l=c===-1?a.trim():a.slice(0,c).trim();i=c===-1?"":a.slice(c+1).trim();let d=l.toLowerCase();if(!QS(d))throw new Error(`Invalid release type "${l}". Expected "regular" or "hotfix".`);s=d}return li({...di(n),type:s},{description:i,releaseDate:o})},kl=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},li=(e,t)=>{let{description:r,releaseDate:n}=t;return{...e,...r!==void 0&&r!==""?{description:r}:{},...n===void 0?{}:{releaseDate:n}}},tP=e=>{let t=e.name.trim();return ps(t),li({id:{kind:"name",name:t,raw:t},type:e.type},e)},bl=(e,t)=>{let r=[...t];return e.map(n=>{if(Ig(n))return tP(n);let o=n.version.trim();if(o==="")throw new Error("Release entry has an empty version");if(vl(o)){let a=yl(r,n.type);return r.push(Ot(`v${a}`)),li({id:pe(a),type:n.type},n)}let s=gl(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),li({id:pe(i),type:n.type},n)})},Rl=e=>e.some(t=>!Ig(t)&&vl(t.version));var nP=e=>e.split(`
371
- `).map(t=>{let r=t.indexOf(" ");return r===-1?null:G(t.slice(r+1))}).filter(t=>t!==null&&t.kind==="version").map(t=>t.raw),oP=async()=>{let e=await rP({quiet:!0})`git ls-remote --heads origin 'release/v*'`;return nP(e.stdout)},sP=async()=>{let e=await ct();return e?(await Kr(e)).map(r=>r.name):[]},ko=async()=>{let[e,t]=await Promise.allSettled([oP(),sP()]);return e.status==="rejected"&&u.warn({err:e.reason},"Failed to list remote release branches; continuing without them"),t.status==="rejected"&&u.warn({err:t.reason},"Failed to fetch Jira versions; continuing without them"),hl({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:t.status==="fulfilled"?t.value:[]})};import iP from"node:fs";import aP from"node:path";var Sl=[".claude/settings.json",".claude/settings.local.json"],cP=["infra-kit","ik","pnpm exec infra-kit","pnpm exec ik","pnpm infra-kit"],lP=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),dP=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},uP=(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(lP).join(".*")}$`,"s").test(t)||n===t||n.startsWith(`${t} `)},pP=e=>{let t=e.groupPath.join(" ");return t===e.cliName?[t]:[t,e.cliName]},mP=()=>lr.filter(e=>e.mutating),fP=e=>{let t=dP(e);return t===null?[]:mP().filter(r=>cP.some(n=>pP(r).some(o=>uP(t,`${n} ${o}`)))).map(r=>r.groupPath.join(" "))},gP=(e,t)=>{let r;try{r=iP.readFileSync(aP.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}},Dg=e=>{let t={present:[],unreadable:[],hits:[]};for(let r of Sl){let n=gP(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=fP(o);s.length>0&&t.hits.push({file:r,pattern:o,commands:s})}}}return t};var hP=e=>e.every(t=>t.status!=="fail"),yP=["brew","git","gh","doppler","aws"],vP=async e=>{let t=await yo(yP,e);return new Map(t.map(r=>[r.id,{manager:r.manager,version:r.version,present:r.present,onPath:r.onPath}]))},dt=async(e,t,r,n)=>{try{return await sr()`${t}`,{name:e,status:"pass",message:r}}catch{return{name:e,status:"fail",message:n}}},wP=async()=>{let e="orca installed",t=await xr();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)"}},Ug=(e,t,r,n)=>{let o=ce.join(xl.homedir(),t),s="Run: infra-kit setup --skip-tools";if(!Y.existsSync(o))return{name:e,status:"fail",message:`~/${t} not found. ${s}`};let i=Y.readFileSync(o,"utf-8"),a=i.indexOf(or),c=i.indexOf($t);return a===-1||c===-1||c<a?{name:e,status:"fail",message:`infra-kit ${r} block missing from ~/${t}. ${s}`}:i.slice(a,c+$t.length).trim()!==n.trim()?{name:e,status:"fail",message:`infra-kit ${r} block in ~/${t} is out of date. ${s}`}:{name:e,status:"pass",message:`infra-kit ${r} block in ~/${t} is up to date`}},kP=()=>Ug("zshrc init block",".zshrc","shell",yg()),bP=()=>Ug("zshenv session block",".zshenv","session-env",al()),RP=async()=>{let e="pnpm enableGlobalVirtualStore";try{let t=await T(),r=ce.join(t,"pnpm-workspace.yaml");if(!Y.existsSync(r))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${r}`};let n=Y.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}`}}},SP=async()=>{try{return vt(),{config:await M(),error:null}}catch(e){return{config:null,error:e}}},PP=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)"}},EP=384,Pl=448,xP=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(", "),TP=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}}})),CP=async(e,t={})=>{let r="env tokens configured",n=t.readStore??Be,o=t.resolveToken??em;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 TP(await Ps(),o);return{name:r,status:"pass",message:xP(s)}},$P=()=>We.env[Ht]||void 0,AP=async(e={})=>{let t="tokens.json present",r=e.readStore??Be,n=e.storePath??kt;if((e.readEnvToken??$P)())return{name:t,status:"skip",message:`${Ht} 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 ${Ht} instead.`}}return{name:t,status:"pass",message:`${s} holds ${a.length} token(s): ${a.join(", ")}`}},bo=(e,t)=>{let r=t(e);return r===null?null:r.mode&511},OP=async(e,t={})=>{let r="tokens.json perms",n=t.storePath??kt,o=t.statPath??IP,s=t.chmodPath??Y.chmodSync,i;try{i=await n()}catch{return{name:r,status:"skip",message:"the token store path could not be resolved"}}if(bo(i,o)===null)return{name:r,status:"skip",message:`No store to protect at ${v(i)} (see tokens.json present)`};let a=ce.dirname(i),c=ce.dirname(a),l=ce.dirname(c),p=[{target:l,expected:Pl,actual:bo(l,o)},{target:c,expected:Pl,actual:bo(c,o)},{target:a,expected:Pl,actual:bo(a,o)},{target:i,expected:EP,actual:bo(i,o)}].filter(g=>g.actual!==null&&g.actual!==g.expected);if(p.length===0)return{name:r,status:"pass",message:`${v(i)} is 0600 (0700 dirs)`};let m=p.map(g=>`${v(g.target)} is ${Ng(g.actual)}, expected ${Ng(g.expected)}`).join("; ");if(!e)return{name:r,status:"fail",message:`${m}. Fix: run \`infra-kit doctor --fix\`, or chmod them by hand.`};for(let g of p)s(g.target,g.expected);return{name:r,status:"pass",message:`Tightened ${p.length} path(s): ${m}`}},Ng=e=>`0${e.toString(8).padStart(3,"0")}`,IP=e=>{try{return Y.statSync(e)}catch{return null}},DP=async()=>{let e="user override path";try{let t=await H(),r=Y.existsSync(t.userProject),n=await mo(t.userProject,r),o=r?fo(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}}},NP=async()=>{let e="legacy user-global config",t;try{t=await H()}catch{return{name:e,status:"skip",message:"infra-kit config paths could not be resolved"}}let r=ce.join(ce.dirname(t.userGlobal),"config.json");return Y.existsSync(r)?Y.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"}},_P={cursor:{command:["cursor","--version"],label:"Cursor",failMsg:"Cursor is not installed. Install from: https://cursor.com/"}},MP=async e=>{let t=_P[e];try{return await sr()`${t.command}`,{ok:!0,label:t.label,failMsg:t.failMsg}}catch{return{ok:!1,label:t.label,failMsg:t.failMsg}}},jP=async e=>{let t="ide installed";if(!e.config)return{name:t,status:"skip",message:"infra-kit config could not be read (see config check)"};let r=yt(e.config).map(s=>s.provider);if(r.length===0)return{name:t,status:"pass",message:"No IDE configured (ide unset)"};let n=await Promise.all(r.map(s=>MP(s))),o=n.filter(s=>!s.ok);return o.length===0?{name:t,status:"pass",message:`Installed: ${n.map(s=>s.label).join(", ")}`}:{name:t,status:"fail",message:o.map(s=>s.failMsg).join("; ")}},_g=/^\d+\.\d+\.\d+$/,FP=(e,t)=>e===t||!_g.test(e)||!_g.test(t)?!1:ln([`v${e}`,`v${t}`])[0]===`v${e}`,LP=async(e,t)=>{let r;try{r=await Se(e)}catch{return[]}let n=[];for(let o of r){let s=Xt(Zt(ce.join(o,"CLAUDE.md")));s.state==="ok"&&s.version!==void 0&&FP(s.version,t)&&n.push(s.version)}return n},BP=async(e,t)=>{let r=await LP(e,t);if(r.length===0)return"";let n=ln(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`},WP=async()=>{let e=[{name:"CLAUDE.md block",status:"skip",message:"no infra-kit config in this repo"}],t;try{t=(await H()).main}catch{return e}if(!Y.existsSync(t))return e;let r=ce.dirname(t),n=ce.join(r,"CLAUDE.md"),o=Y.existsSync(n)?Y.readFileSync(n,"utf-8"):"",s=Ke(o,Oe,He),i=s?"CLAUDE.md block present":"infra-kit block missing from CLAUDE.md. Run: infra-kit setup --skip-tools",a=await BP(r,K.version);return[{name:"CLAUDE.md block",status:s?"pass":"fail",message:`${i}${a}`}]},VP=async()=>{try{let e=(await H()).main;return Y.existsSync(e)?ce.dirname(e):null}catch{return null}},UP=e=>{let t=Fp();return t===null||!$n(t,e)?"":` \u2014 plugin ${t} is fetched but not applied. Run: ${jr}`},JP=e=>{let t=e.kind==="installed"?ws(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 ${q} version ${t}${UP(t)}`}},Mg=3,jg=(e,t)=>he(e)===he(t),GP=e=>{if(e===void 0||e.gitRoot===null)return"";let t=v(e.gitRoot);if(e.projectDir!==null){if(jg(e.projectDir,e.gitRoot))return"";let r=Sn(e.gitRoot,he(e.projectDir),he)?"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 jg(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}`},KP=(e,t)=>{let r="plugin installed",n=GP(t);if(e.kind==="installed"){let{scope:c,projectPath:l}=e.installation,d=l===null?"":`, ${v(l)}`;return{name:r,status:"pass",message:`Plugin ${q} installed (${c??"unknown"} scope${d})${n}`}}if(e.kind==="absent")return{name:r,status:"fail",message:`Plugin ${q} is not installed. Run: ${it}${n}`};let o=e.installations.map(c=>c.projectPath===null?"(unnamed project)":v(c.projectPath)),s=o.length-Mg,i=s>0?` and ${s} more`:"",a=`${o.slice(0,Mg).join(", ")}${i}`;return{name:r,status:"fail",message:`Plugin ${q} is installed for ${a} only, not this project. Run: ${it}${n}`}},HP=()=>dt("claude CLI",["claude","--version"],"Installed: claude","claude CLI not found on PATH \u2014 `infra-kit setup` cannot install the plugin; install Claude Code first"),un="claude in chrome",qP="com.anthropic.claude_code_browser_extension",ui="run `/chrome` inside Claude Code to set up Claude in Chrome",YP={darwin:["Library","Application Support","Google","Chrome","NativeMessagingHosts"],linux:[".config","google-chrome","NativeMessagingHosts"]},zP=e=>{try{return Y.accessSync(e,Y.constants.X_OK),!0}catch{return!1}},XP=e=>{try{return JSON.parse(e)}catch{return null}},ZP=/^exec\s+(?<target>\S+)\s+--chrome-native-host\b/m,QP=(e={})=>{let t=e.platform??We.platform,r=e.home??xl.homedir(),n=e.readText??El,o=e.isExecutable??zP,s=YP[t];if(s===void 0)return{name:un,status:"skip",message:`no Chrome native host location known for ${t}`};let i=ce.join(r,...s,`${qP}.json`),a=n(i);if(a===null)return{name:un,status:"warn",message:`Chrome native host not registered \u2014 ${ui}`};let c=ae.object({path:ae.string().min(1)}).safeParse(XP(a));if(!c.success)return{name:un,status:"fail",message:`${v(i)} has no host path \u2014 ${ui} again`};let l=c.data.path;if(!o(l))return{name:un,status:"fail",message:`Chrome native host ${v(l)} is missing or not executable \u2014 ${ui} again`};let d=ZP.exec(n(l)??"")?.groups?.target;return d!==void 0&&!o(d)?{name:un,status:"fail",message:`Chrome native host runs ${v(d)}, which no longer exists \u2014 ${ui} again`}:{name:un,status:"pass",message:`Native host registered (${v(l)}); /infra-kit:doctor checks the live connection`}},eE=(e,...t)=>{try{return JSON.parse(Y.readFileSync(ce.join(e,...t),"utf-8"))}catch{return null}},tE=e=>{if(e.kind!=="installed")return{kind:"not-installed"};let t=ws(e.installation),{installPath:r}=e.installation;if(r===null)return{kind:"skills-only",version:t};let n=eE(r,Ie),o=n!==null&&typeof n=="object"?n[Ye]:void 0;return o==null||typeof o!="object"?{kind:"skills-only",version:t}:{kind:"stale-server",version:t,keys:Object.keys(o)}},Fg=e=>`Plugin ${q} ${e===null?"(version unreadable)":e}`,rE=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: ${it}`};if(e.kind==="stale-server"){let r=e.keys.length===0?"":` (under "${e.keys.join('", "')}")`;return{name:t,status:"pass",message:`${Fg(e.version)} still carries an MCP server in its ${Ie}${r} \u2014 a copy from before the plugin went skills-only. Update it: infra-kit setup (or ${jr}), then restart Claude Code`}}return{name:t,status:"pass",message:`${Fg(e.version)} is skills-only \u2014 no ${Ie}, as shipped; the /infra-kit:* skills drive the infra-kit CLI`}},nE=(e,t)=>{let r=Gt(e===null?{}:{projectPath:e}),n=Cn();return[{name:"marketplace registered",status:n?"pass":"fail",message:n?`Marketplace ${de} is known to Claude Code`:`Marketplace ${de} is not registered. Run: claude plugin marketplace add ${wt}`},KP(r,t),JP(r),rE(tE(r)),{name:"CLI version",status:"pass",message:`infra-kit CLI ${K.version}`}]},oE=({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(", ")},sE=e=>{let t="Agent mode",r=us(e),n=oE(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})`}},Lg=4,iE=e=>{let t=e.slice(0,Lg).join(", "),r=e.length-Lg;return r>0?`${t} +${r} more`:t},aE=e=>{let t="Agent allowlist",{present:r,unreadable:n,hits:o}=Dg(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"} (${iE(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 ${Sl.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`}},cE=(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`},lE=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 Jf(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} (${cE(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`}},Jg=e=>ga(["trust"],{bin:e}),dE=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),Bg="ERR_TLS_CERT_ALTNAME_INVALID",Gg=()=>`portless serving TLS on :${ht}`,uE=async(e,t,r)=>{let n=Gg();return await e(ht,!0)?{name:n,status:"pass",message:`portless is serving HTTPS on :${ht}`}:{name:n,status:"fail",message:`No portless daemon is serving HTTPS on :${ht}. Install it once (needs root): \`${ft(t,r)}\`.`}},pE=async(e,t,r,n,o)=>{let s="portless CA chain valid",i=["localhost",...t.slice(0,1).map(d=>d.name)],c=(await Promise.all(i.map(async d=>({servername:d,result:await e(ht,d)})))).filter(d=>!d.result.ok);if(c.length===0)return{name:s,status:"pass",message:`Served certificate chains to ${v(r)} (${i.join(", ")})`};let l=c.map(d=>d.result.ok?"":d.result.code);return l.includes(Bg)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${Bg} for servername(s) ${c.map(d=>d.servername).join(", ")} \u2014 doctor's probe is wrong, your trust store is not implicated. Please report this.`}:l.some(d=>dE.has(d))?{name:s,status:"fail",message:`The daemon is serving a certificate that does not chain to ${v(r)}. Its CA was regenerated \u2014 run \`${Jg(n)}\`, or reinstall: \`${ft(n,o)}\`.`}:{name:s,status:"fail",message:`TLS handshake failed (${l.join(", ")})`}},mE=(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: \`${Jg(r)}\` (no sudo needed).`}},fE=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 \`${ga(["alias","--remove","<name>"],{bin:r})}\`.`}},It="portless service target",So=e=>({name:It,status:"warn",message:e}),Kg=e=>e==="darwin"?rp:e==="linux"?np:null,gE=e=>e==="darwin"?`sudo launchctl kickstart -k system/${tp}`:`sudo systemctl restart ${op}`,hE="/bin/ps",yE=e=>{try{let t=Vg(hE,["-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}},El=e=>{try{return Y.readFileSync(e,"utf-8")}catch{return null}},vE=e=>{try{return Y.statSync(e).mtime}catch{return null}},wE=2e3,kE=e=>{try{let t=Vg(e,["-p","process.version"],{encoding:"utf-8",timeout:wE}),r=t.stdout?.trim()??"";return{version:r===""?null:r,status:t.status,signal:t.signal}}catch{return{version:null,status:null,signal:null}}},bE=(e,t)=>({platform:e.platform??We.platform,readServiceFile:e.readServiceFile??El,readFile:e.readFile??El,exists:e.exists??Y.existsSync,realpath:e.realpath??he,mtime:e.mtime??vE,execPath:e.execPath??We.execPath,home:e.home??xl.homedir(),cwd:e.cwd??We.cwd(),repoRoot:e.repoRoot??uo,stateDir:(e.stateDir??ip)(),processStartTime:e.processStartTime??yE,version:e.version??We.version,arch:e.arch??We.arch,nodeVersionOf:e.nodeVersionOf??kE,isGlobal:e.isGlobal??ds().node.isGlobal,nodeFs:e.nodeFs??Y,stableNode:null,stableNodeSidecar:null,bin:t}),Po="portless node",dr="~/.infra-kit/node",Ro=e=>({row:{name:Po,status:"fail",message:e},stableNode:null,sidecar:null}),Wg=(e,t)=>{try{return e(t,{throwIfNoEntry:!1})}catch{return}},RE=e=>e.signal!==null?`killed by ${e.signal}`:e.status===null?"did not start":e.status!==0?`exit ${e.status}`:`printed ${e.version??"nothing"}`,SE=(e,t)=>e.status===0&&e.signal===null&&e.version===t.version,PE=e=>{let t=up(e.home),r=Wg(e.nodeFs.lstatSync,t);if(r===void 0)return Ro(`${dr} is missing and could not be written \u2014 run \`infra-kit setup\` and see the debug log`);if(!r.isFile())return Ro(`${dr} is not a regular file; infra-kit will not replace it \u2014 move it away and run \`infra-kit setup\``);let n=pp(e.home,e.nodeFs);if(n===null)return Ro(`${dr} has no readable node.source.json and it could not be rewritten \u2014 run \`infra-kit setup\``);let o=Wg(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 Ro(`${dr} 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(!SE(c,e))return Ro(`${dr} does not run as Node ${e.version} (${RE(c)}). Re-run through the current Node: \`${ft(e.bin,{...e,stableNode:null})}\`, then \`infra-kit setup\``)}return{row:{name:Po,status:"pass",message:`${dr} is Node ${n.version} (${n.arch}, ${n.method} of ${v(n.source)})`},stableNode:t,sidecar:n}},EE=e=>{if(Kg(e.platform)===null)return{row:{name:Po,status:"skip",message:"no portless OS service on this platform"},stableNode:null,sidecar:null};let t=PE(e);return e.isGlobal()?t:{...t,row:{name:Po,status:"skip",message:`not a global install; the global infra-kit keeps ${dr} current`}}},Hg=(e,t)=>{let r=bE(e,t),n=EE(r);return{seams:{...r,stableNode:n.stableNode,stableNodeSidecar:n.sidecar},node:n.row}},xE=(e,t)=>{let r=t.readFile(ce.join(e,"package.json"));try{let n=r===null?null:ae.object({version:ae.string()}).safeParse(JSON.parse(r));return n?.success===!0?n.data.version:"?"}catch{return"?"}},TE=e=>{let t=Number.parseInt(e.readFile(ce.join(e.stateDir,"proxy.pid"))?.trim()??"",10);return!Number.isInteger(t)||t<=0?null:e.processStartTime(t)},CE=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?null:t},$E=(e,t,r)=>{let n=TE(r),o=a=>n!==null&&a!==null&&n.getTime()<a.getTime(),s=r.stableNodeSidecar,i=[...s!==null&&o(CE(s.versionChangedAt))?[`Node ${s.version}`]:[],...o(r.mtime(ce.join(e,"package.json")))?[`portless ${t}`]:[]];return i.length===0?null:i.join(" and ")},AE=async(e,t)=>{let r=t.realpath(t.cwd);return r===t.realpath(t.home)?!1:Sn(await t.repoRoot()??r,e,t.realpath)},ur=e=>({state:"drifted",row:e}),OE=async(e,t,r)=>{let n=ft(r.bin,r);if(!r.exists(e))return ur({name:It,status:"fail",message:`The service runs \`${e}\`, which no longer exists (Node was upgraded, or its package dir was re-created). Re-run: \`${n}\``});let o=ce.join(ha(r.home),"dist","cli.js");if(t!==o)return ur(So(`The service points at \`${t}\`, a version-specific location. Re-run once to switch it to the stable link: \`${n}\``));if(ls(r.home,r.exists)===null)return ur({name:It,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(ha(r.home));if(await AE(s,r))return ur({name:It,status:"fail",message:`The service runs portless from a project checkout (${s}). Re-run \`service install\` from the global install: \`${n}\``});let i=IE(e,n,r);if(i!==null)return i;let a=xE(s,r),c=$E(s,a,r);return c!==null?{state:"converged",row:So(`The running daemon predates ${c} that \`dev\` will talk to. Restart it: \`${gE(r.platform)}\` (or reboot).`)}:{state:"converged",row:{name:It,status:"pass",message:`service runs \`${e}\` (Node ${r.version}) + stable link \u2192 portless ${a}`}}},IE=(e,t,r)=>r.stableNode!==null?r.realpath(e)===r.realpath(r.stableNode)?null:ur(So(`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:ur(So(`The service runs \`${e}\`; infra-kit runs \`${r.execPath}\`. Works until the old Node is removed. Re-run when convenient: \`${t}\``)),qg=async e=>{let t=Kg(e.platform);if(t===null)return{state:"absent",row:{name:It,status:"skip",message:"no portless OS service file on this platform"}};let r=e.readServiceFile(t);if(r===null)return{state:"absent",row:{name:It,status:"skip",message:`the OS service is not installed (no ${t})`}};let[n,o]=pf(e.platform,r)??[];return n===void 0||o===void 0?ur(So(`could not parse ${t} \u2014 re-run \`${ft(e.bin,e)}\` to rewrite it.`)):OE(n,o,e)},Yg=async(e,t)=>{let{seams:r}=Hg(e,t);return{state:(await qg(r)).state,stableNode:r.stableNode}},DE=()=>[Po,It,Gg(),"portless CA chain valid","portless CA trusted","portless routes"],NE=async(e={})=>{let t=e.resolveBin??ep,r=e.isProxyServing??sp,n=e.handshake??lp,o=e.caTrusted??cp,s=e.routes??En,i=e.isListening??Pn,a=(e.caPath??ap)(),c=t();if(c===null)return[{name:"portless installed",status:"fail",message:"portless is not resolvable from node_modules \u2014 run `pnpm install`."},...DE().map(R=>({name:R,status:"skip",message:"portless not resolvable"}))];let l={name:"portless installed",status:"pass",message:"portless is resolvable from node_modules"},{seams:d,node:p}=Hg(e,c),m=s(),g=await uE(r,c,d),y=g.status==="fail"?{name:"portless CA chain valid",status:"skip",message:"no daemon to handshake with"}:await pE(n,m,a,c,d);return[l,p,(await qg(d)).row,g,y,mE(o(),a,c),await fE(m,i,c)]},_E=async(e={})=>{let t="portless routes",r=e.routes??En,n=e.isListening??Pn,o=e.devSessionRunning??af,s=r();if(s.length===0)return{name:t,status:"pass",message:"No portless routes registered"};let i=await Promise.all(s.map(async d=>({name:d.name,port:d.port,live:await n(d.port)}))),{prunable:a,withheld:c}=sf(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??dp().removeAlias;for(let d of a)await l(d);return{name:t,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},pi=async(e={})=>{let t=await SP(),r=vP(e.probeDeps??go()),n=async(m,g)=>{let[y,R]=await Promise.all([g,r]),w=R.get(m);return w===void 0?y:{...y,detail:w}},o=await Promise.all([n("brew",dt("brew installed",Ne("brew").probeArgv,"Homebrew is installed","Homebrew is not installed. Install from: https://brew.sh/")),n("git",dt("git installed",Ne("git").probeArgv,"git is installed","git is not installed. Install with: brew install git")),n("gh",dt("gh installed",Ne("gh").probeArgv,"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/")),dt("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),n("doppler",dt("doppler installed",Ne("doppler").probeArgv,"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli")),n("aws",dt("aws installed",Ne("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")),dt("package manager installed",["pnpm","--version"],"Installed: pnpm","pnpm is not installed. Install from: https://pnpm.io/installation"),dt("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"),wP(),Promise.resolve(kP()),Promise.resolve(bP()),RP(),Promise.resolve(PP(t)),AP(),CP(t),OP(e.fix??!1),DP(),NP(),jP(t)]),s=await NE(e.portlessDeps);if(e.fix){let m=await _E(),g=s.findIndex(y=>y.name===m.name);g>=0?s[g]=m:s.push(m)}let i=await VP(),a=await uo(),c={projectDir:We.env.CLAUDE_PROJECT_DIR||null,cwd:We.cwd(),gitRoot:a},l=[await HP(),...nE(i,c),QP(),sE({env:We.env,stdinIsTTY:We.stdin.isTTY===!0,flag:N.source==="flag"}),a===null?{name:"Agent allowlist",status:"skip",message:"no git root"}:aE(a)],d=[...o,await lE(a),...s,...await WP(),...l],p={checks:d.map(m=>({name:m.name,status:m.status,message:m.message,fixable:$c.has(m.name),detail:m.detail})),allPassed:hP(d),cliVersion:K.version};return{content:k(JSON.stringify(p,null,2)),structuredContent:p}},Tl=S({name:"doctor",description:"Check installation and authentication status of gh, doppler, and aws CLIs. Read-only: a row marked fixable is one `infra-kit doctor --fix` repairs, and that flag is not reachable from this boundary \u2014 report such a row to the human instead.",inputSchema:{},outputSchema:{checks:ae.array(ae.object({name:ae.string().describe("Name of the check"),status:ae.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:ae.string().describe("Details about the check result"),fixable:ae.boolean().describe("Whether `infra-kit doctor --fix` repairs this row"),detail:ae.object({manager:ae.string().describe("Which package manager owns this install, read from its resolved path"),version:ae.string().nullable().describe("The version the tool reported, or null"),present:ae.boolean().describe("The tool is installed somewhere findable \u2014 on PATH or not"),onPath:ae.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:ae.boolean().describe("Whether no check failed (warnings and skips do not count)"),cliVersion:ae.string().describe("Version of the infra-kit CLI that produced this report")},handler:()=>pi()});import{E2E_MODE_ENV as QE}from"@slip-stream-kit/config/internal";import{spawn as ex}from"node:child_process";import _l from"node:fs";import tx from"node:os";import Ml from"node:path";import jl from"node:process";import{z as E}from"zod";import{describeProxyRoutes as ME,loadDev as jE,readAppAliasName as FE,readCloudOrigin as LE,readLocalContext as Xg}from"@slip-stream-kit/config/internal";import zg from"node:fs";import pr from"node:path";import mi from"node:process";import{z as Cl}from"zod";var BE=async e=>{let t=pr.join(e,"apps"),r=zg.existsSync(t)?zg.readdirSync(t).toSorted():[],n=[];for(let o of r){let s=pr.join(t,o,"tests"),i=await Cr(s);i?.e2e&&n.push({app:o,testsDir:s,e2e:i.e2e})}return n},WE=(e,t)=>{let[r,n]=pr.relative(e,t).split(pr.sep);return r==="apps"&&n?n:void 0},VE=(e,t,r,n)=>{let o=c=>e.find(l=>l.app===c),s=o(t)??(t===void 0?o(WE(n,r)):void 0);if(s)return s;if(t===void 0&&e.length===1)return e[0];let i=e.map(c=>c.app);if(i.length===0)throw new f(void 0,{operation:"find an e2e package",remediation:"declare `e2e: { target }` in `apps/<app>/tests/infra-kit.config.ts` (see the `InfraKitE2e` type)",stderrExcerpt:`no apps/*/tests package under ${n} declares an e2e block`});let a="app";throw new x({status:"argument_required",argument:a,choices:Cl.toJSONSchema(Cl.object({app:Cl.enum(i)})),agentMode:N.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(", ")}`})},UE=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}})),JE=e=>zn(e).apps.find(t=>t.env!=="")?.env??null,$l=async(e,t={})=>{let r=t.cwd??mi.cwd(),n=t.projectRoot??await T(),o=(t.env??mi.env)[br]||null,s=t.healthProbe??Ta,i=VE(await BE(n),e,r,n),{target:a}=i.e2e,[c,l]=a.split("/"),d=pr.join(n,"apps",c,l),p=(await qt(d)).name,m=(await Cr(d))?.deployedUrlEnv??null;if(!p)throw new f(void 0,{operation:`resolve e2e target ${a}`,remediation:`check \`e2e.target\` in ${pr.join(i.testsDir,"infra-kit.config.ts")}`,stderrExcerpt:`${d} has no package.json name`});let g=um(d),y=FE(p,d),R=`${y}.localhost`,w=`https://${R}`,$=0;if(l==="ui")$=(t.listRoutes??En)().find(P=>P.name===R||P.name===y)?.port??0;else{let P=Xg(d).info.get(p);$=P?.port??0,w=P?.origin??w}let B=$>0&&await s({tag:a,port:$,kind:l})==="ok",I=B?JE(d):null;return{app:i.app,testsDir:i.testsDir,target:a,kind:l,targetDir:d,packageName:p,deployedUrlEnv:m,release:g,env:o,servedEnv:I,localUrl:w,served:B}},Zg=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}},Al=async(e,t={})=>{let r=t.healthProbe??Ta,n=Xg(e.targetDir),o=e.kind==="ui"?await jE(e.targetDir):void 0,s=o?.proxy?ME({proxy:o.proxy,localContext:n,env:e.env??void 0,cloud:LE(e.deployedUrlEnv??void 0,t.env??mi.env),getRelease:()=>e.release}):[],i=new Map([...n.info].map(([a,c])=>[a,c.port]));return{...Zg(e),mode:"local",baseUrl:e.localUrl,routes:await UE(s,i,r)}},Ol=(e,t={})=>{let{env:r,deployedUrlEnv:n,target:o}=e;if(!n)throw new f(void 0,{operation:`resolve the deployed app ${e.app}'s cloud e2e run targets`,remediation:`declare \`deployedUrlEnv: '<APP>_URL'\` in ${pr.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??mi.env)[n];if(!r||!s)throw new f(void 0,{operation:`resolve the deployed app ${e.app}'s cloud e2e run targets`,remediation:"load an environment (`infra-kit env-load -c <env>`), or drop --cloud to run against this worktree",stderrExcerpt:`a cloud run of ${o} needs ${n} and ${br}, and ${s?br:n} is not set`});return{...Zg(e),mode:"cloud",baseUrl:s,routes:[]}};import GE from"node:fs";import KE from"node:path";import{stripVTControlCharacters as HE}from"node:util";import{z as D}from"zod";var Qg=2e3,eh="--reporter=line,json",th=e=>({PLAYWRIGHT_JSON_OUTPUT_FILE:e,PLAYWRIGHT_JSON_OUTPUT_NAME:e}),rh=e=>e.some(t=>t==="--reporter"||t.startsWith("--reporter=")),Il=D.object({message:D.string().optional()}),qE=D.object({status:D.string(),retry:D.number(),error:Il.optional(),errors:D.array(Il).optional(),attachments:D.array(D.object({name:D.string(),path:D.string().optional()})).optional()}),YE=D.object({title:D.string(),file:D.string(),line:D.number().optional(),tests:D.array(D.object({projectName:D.string(),status:D.string(),results:D.array(qE)}))}),nh=D.lazy(()=>D.object({title:D.string(),specs:D.array(YE).optional(),suites:D.array(nh).optional()})),zE=D.object({config:D.object({rootDir:D.string().optional()}).optional(),suites:D.array(nh),errors:D.array(Il).optional(),stats:D.object({expected:D.number(),unexpected:D.number(),flaky:D.number(),skipped:D.number()})}),oh=e=>{let t=HE(e);return t.length>Qg?`${t.slice(0,Qg)}\u2026`:t},XE=e=>{let t=e.error?.message??e.errors?.[0]?.message;return t===void 0?null:oh(t)},ZE=e=>{let t=zE.safeParse(e);if(!t.success)return null;let{config:r,suites:n,errors:o,stats:s}=t.data,i=[],a=(c,l)=>{for(let d of c.specs??[])for(let p of d.tests){if(p.status!=="unexpected"&&p.status!=="flaky")continue;let m=p.results.findLast(g=>g.status!=="passed"&&g.status!=="skipped");i.push({title:[...l,d.title].join(" \u203A "),file:r?.rootDir?KE.resolve(r.rootDir,d.file):d.file,line:d.line??null,project:p.projectName,status:p.status,retry:m?.retry??0,error:m?XE(m):"Expected to fail, but passed.",tracePath:m?.attachments?.find(g=>g.name==="trace")?.path??null})}for(let d of c.suites??[])a(d,[...l,d.title])};for(let c of n)a(c,[]);return{summary:{expected:s.expected,unexpected:s.unexpected,flaky:s.flaky,skipped:s.skipped},failures:i,errors:(o??[]).flatMap(c=>c.message===void 0?[]:[oh(c.message)])}},sh=e=>{try{return ZE(JSON.parse(GE.readFileSync(e,"utf8")))}catch{return null}};var rx=["playwright.config.ts","playwright.config.mts","playwright.config.js","playwright.config.mjs"],nx=e=>rx.some(t=>{try{return _l.readFileSync(Ml.join(e,t),"utf8").includes("infraKitE2e")}catch{return!1}}),ih=e=>`infra-kit dev ${e.target.split("/")[0]} --no-watch --reuse`,ox=(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(`
372
- `)},sx=e=>{let t=e.routes.filter(n=>n.source==="local"&&n.live!==!0);if(t.length===0)return;let r=t.map(n=>`${n.path} (${n.packageName})`);throw new f(void 0,{operation:`run ${e.app} e2e against the local dev server`,remediation:"check the backend rows in `infra-kit dev-status`, fix or restart it, then re-run",stderrExcerpt:`routes held local but their backend is not responding: ${r.join(", ")}`})},ix=async(e,t)=>{if(e.env===null||!lm(e.env))return;let r=await(t.protectedEnvAccess??Je)();if(r.allowed)return;let n=`run ${e.app} e2e against "${e.env}"`;throw r.reason==="agent-blocked"?new x({status:"refused",env:e.env},2,{operation:n,remediation:'a human runs it from their own terminal \u2014 this project sets `protectedEnvs: "cli-only"`',stderrExcerpt:`"${e.env}" is withheld from agents in this project`}):new f(void 0,{operation:n,remediation:"load a non-protected env (`infra-kit env-load -c dev`), or set `protectedEnvs` in infra-kit.json",stderrExcerpt:`"${e.env}" is a protected environment`})},ax=e=>{if(!(e.servedEnv===null||e.servedEnv===e.env))throw new f(void 0,{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"}"`})},cx=async(e,t)=>{if(e.served){ax(e);let p=await Al(e,t);return sx(p),p}if(!nx(e.testsDir))throw new f(void 0,{operation:`run ${e.app} e2e locally`,remediation:`start it (\`${ih(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:d}=e;return{app:r,testsDir:n,target:o,packageName:s,deployedUrlEnv:i,release:a,env:c,servedEnv:l,localUrl:d,mode:"local",baseUrl:d,routes:[]}},lx=(e,t,r)=>new Promise((n,o)=>{let s=ex("pnpm",["exec","playwright","test",...t],{cwd:e.testsDir,env:{...jl.env,...r,[QE]:e.mode},stdio:["inherit",Jt.enabled||J()?2:"inherit","inherit"]});s.once("error",o),s.once("close",i=>{n(i??1)})}),fi=async(e,t={})=>{let r=await $l(e.app,t),n=e.cloud?Ol(r,t):await cx(r,t);u.info(ox(n,r.served)),n.mode==="cloud"&&await ix(n,t);let o={...n,served:r.served,devCommand:n.mode==="local"&&!r.served?ih(r):null,playwrightArgs:e.playwrightArgs??[]};if(e.dryRun)return Nl({...o,ran:!1,exitCode:null,...Dl});n.mode==="cloud"&&await V(e.yes,`Run ${n.app} e2e against ${n.baseUrl} ("${n.env}", shared)?`,{plan:o});let s=t.runPlaywright??lx;if(!J()||rh(o.playwrightArgs)){let c=await s(n,o.playwrightArgs,{});return c!==0&&(jl.exitCode=c),Nl({...o,ran:!0,exitCode:c,...Dl,report:J()?"caller-reporter":"off"})}let i=_l.mkdtempSync(Ml.join(tx.tmpdir(),"ik-e2e-report-")),a=Ml.join(i,"report.json");try{let c=await s(n,[eh,...o.playwrightArgs],th(a));c!==0&&(jl.exitCode=c);let l=sh(a);return Nl({...o,ran:!0,exitCode:c,...l?{report:"collected",...l}:{...Dl,report:"unavailable"}})}finally{_l.rmSync(i,{recursive:!0,force:!0})}},Dl={report:"off",summary:null,failures:[],errors:[]},Nl=e=>({content:k(JSON.stringify(e,null,2)),structuredContent:e}),dx={app:E.string(),testsDir:E.string(),target:E.string().describe("The package under test, `<app>/ui` or `<app>/api`."),packageName:E.string(),mode:E.enum(["local","cloud"]).describe("local (default): this worktree\u2019s dev server. cloud (--cloud): the deployed app at env."),baseUrl:E.string().describe("The URL the run was pointed at: the local alias, or the deployed URL."),deployedUrlEnv:E.string().nullable().describe("The target\u2019s variable holding its deployed URL; a cloud run reads it. Null when it declares none."),release:E.string().describe("This worktree\u2019s release slug \u2014 the first label of every local alias."),env:E.string().nullable().describe("INFRA_KIT_ENV of this process; the env a cloud run targets."),servedEnv:E.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:E.string().describe("This worktree\u2019s address for the target, whether or not anything serves it."),served:E.boolean().describe("Whether this worktree\u2019s dev server already served the target when the run began."),devCommand:E.string().nullable().describe("Local runs with nothing served: the dev command the Playwright config starts, and stops after."),routes:E.array(E.object({path:E.string(),packageName:E.string(),source:E.enum(["local","cloud"]),target:E.string().nullable(),live:E.boolean().nullable()})).describe("Served local UI runs only: the dev proxy\u2019s route-by-route local/cloud split, local backends probed."),playwrightArgs:E.array(E.string()),ran:E.boolean().describe("False for --dry-run."),exitCode:E.number().nullable().describe("Playwright\u2019s exit code; null when it did not run."),report:E.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."),summary:E.object({expected:E.number(),unexpected:E.number(),flaky:E.number(),skipped:E.number()}).nullable().describe("Test counts by outcome; null unless report is collected."),failures:E.array(E.object({title:E.string().describe("Describe path and test title, joined with \u203A."),file:E.string(),line:E.number().nullable(),project:E.string(),status:E.enum(["unexpected","flaky"]).describe("flaky: failed, then passed on a retry."),retry:E.number().describe("The retry index of the failed attempt reported here."),error:E.string().nullable().describe("The failure message, ANSI stripped, truncated to 2000 characters."),tracePath:E.string().nullable().describe("The failed attempt\u2019s trace.zip; open with `playwright show-trace`.")})).describe("Every test that failed or needed a retry; empty unless report is collected."),errors:E.array(E.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.")},Fl=S({name:"e2e",description:"Run an app\u2019s Playwright e2e suite against this worktree: the running dev server, or one the package\u2019s infraKitE2e() Playwright config starts and stops. cloud runs against the deployed app at INFRA_KIT_ENV instead, confirm-gated; a protected env (prod) follows protectedEnvs. dryRun reports the target without running.",requiresHumanConfirm:!0,inputSchema:{app:E.string().optional().describe("App folder with an apps/<app>/tests e2e package; inferred from cwd when omitted."),dryRun:E.boolean().optional(),yes:E.boolean().optional(),cloud:E.boolean().optional().describe("Run against the deployed app at INFRA_KIT_ENV instead of this worktree."),playwrightArgs:E.array(E.string()).optional().describe("Passed to `playwright test` verbatim \u2014 a spec path, `--grep <title>`, `--project=chromium`.")},outputSchema:dx,handler:e=>fi(e)});import gi from"node:fs";import Ll from"node:path";import{z as Eo}from"zod";var ux=e=>[...e.map(t=>`unset ${t}`),`unset ${br}`,`unset ${ns}`,`unset ${os}`,`unset ${Ju}`,`unset ${ss}`],hi=async()=>{let e=Rr(),t=Ll.join(e,kr);if(!gi.existsSync(t))throw new Error("No loaded environment found. Run `env-load` first.");let r=is(t),n=ux(r),o=Ll.resolve(e,ts);gi.mkdirSync(e,{recursive:!0,mode:448}),Rn(o,`${n.join(`
371
+ ${i}`:"")},kg=()=>{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(`
372
+ `)},bg=()=>`${sr}
373
+ ${kg()}
374
+ ${It}`,cl=()=>["# 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(`
375
+ `),ll=()=>`${sr}
376
+ ${cl()}
377
+ ${It}`;import VS from"node:fs/promises";var ho=async(e,t)=>{if(!t)return{hasOverrides:!1,overrideKeys:[],unreadable:!1};try{let r=await VS.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}}},yo=e=>e.unreadable?"(unreadable \u2014 invalid JSON)":e.overrideKeys.length===0?"(empty \u2014 no overrides)":`(${e.overrideKeys.length} override(s): ${e.overrideKeys.join(", ")})`;import JS from"node:fs";import GS from"node:os";import Rg from"node:path";import KS from"node:process";import{$ as US}from"zx";var ir=()=>US({quiet:!0});var HS=()=>[Rg.join(GS.homedir(),".local","bin"),"/opt/homebrew/bin","/usr/local/bin"],qS=async e=>{try{return(await ir()`command -v ${e}`).stdout.trim()||null}catch{return null}},vo=()=>({runCommand:async e=>{let t=await ir()`${e}`;return{stdout:`${t.stdout}
378
+ ${t.stderr}`}},resolveBinPath:async e=>{let t=await qS(e);return t!==null?t:HS().map(r=>Rg.join(r,e)).find(r=>JS.existsSync(r))??null},realpath:he,platform:KS.platform});var Dt=(...e)=>({steps:e,needsSudo:!1,fetchesNetworkScript:!1}),ln=e=>/\d{1,10}\.\d{1,10}\.\d{1,10}/.exec(e)?.[0]??null,dn=["darwin","linux"],li=e=>t=>ha(t,e)?"homebrew":"unknown",di=(e,t)=>r=>r===null?null:t(e(r),r),ul=e=>di(li(e.kegName),t=>t==="homebrew"?Dt(["brew","upgrade",e.brewFormula]):null),Sg=e=>us(e,"Homebrew")||us(e,"homebrew")?"homebrew":"unknown",YS={id:"brew",binName:"brew",probeArgv:["brew","--version"],versionFrom:ln,platforms:dn,prerequisites:[],bootstrapInstall:{steps:[["/bin/bash","-c","$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"]],needsSudo:!0,fetchesNetworkScript:!0},identify:Sg,updateFor:di(Sg,e=>e==="homebrew"?Dt(["brew","update"]):null)},dl={brewFormula:"awscli",brewInstallSpec:"awscli",kegName:"awscli"},xg="https://awscli.amazonaws.com/v2/install.sh",Tg={steps:[["/bin/bash","-c",`curl -fsSL ${xg} | bash`]],needsSudo:!1,fetchesNetworkScript:!0},zS="/usr/local/aws-cli",XS=e=>xn(zS,e,he)?{steps:[["sudo","/bin/bash","-c",`curl -fsSL ${xg} | bash -s -- --system`]],needsSudo:!0,fetchesNetworkScript:!0}:Tg,Pg=e=>ha(e,dl.kegName)?"homebrew":us(e,"aws-cli")?"script":"unknown",ZS={id:"aws",binName:"aws",...dl,probeArgv:["aws","--version"],versionFrom:ln,platforms:dn,prerequisites:[],bootstrapInstall:Tg,identify:Pg,updateFor:di(Pg,(e,t)=>e==="homebrew"?Dt(["brew","upgrade",dl.brewFormula]):e==="script"?XS(t):null)},ii={brewFormula:"git",brewInstallSpec:"git",kegName:"git"},QS={id:"git",binName:"git",...ii,probeArgv:["git","--version"],versionFrom:ln,platforms:dn,prerequisites:["brew"],bootstrapInstall:Dt(["brew","install",ii.brewInstallSpec]),identify:li(ii.kegName),updateFor:ul(ii)},ai={brewFormula:"gh",brewInstallSpec:"gh",kegName:"gh"},eP={id:"gh",binName:"gh",...ai,probeArgv:["gh","--version"],versionFrom:ln,platforms:dn,prerequisites:["brew"],bootstrapInstall:Dt(["brew","install",ai.brewInstallSpec]),identify:li(ai.kegName),updateFor:ul(ai)},ci={brewFormula:"doppler",brewInstallSpec:"dopplerhq/cli/doppler",kegName:"doppler"},tP={id:"doppler",binName:"doppler",...ci,probeArgv:["doppler","--version"],versionFrom:ln,platforms:dn,prerequisites:["brew"],bootstrapInstall:Dt(["brew","install","gnupg"],["brew","install",ci.brewInstallSpec]),identify:li(ci.kegName),updateFor:ul(ci)},wo="portless",Eg=e=>Zu(e,wo)===null?"unknown":"npm",rP={id:"portless",binName:wo,npmPackage:wo,probeArgv:["portless","--version"],versionFrom:ln,platforms:[...dn,"win32"],prerequisites:[],bootstrapInstall:Dt(["npm","install","-g",wo]),identify:Eg,updateFor:di(Eg,e=>e==="npm"?Dt(["npm","install","-g",`${wo}@latest`]):null)},pl={brew:YS,git:QS,aws:ZS,gh:eP,doppler:tP,portless:rP},ar=Object.keys(pl),Me=e=>pl[e],ml=(e,t)=>e.platforms.includes(t),fl=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 Me(o).prerequisites)n(i,[...s,o]);t.push(o)}};for(let o of e)n(o,[]);return t};var Cg=e=>({id:e,present:!1,onPath:!1,binRealPath:null,version:null,manager:"unknown"}),$g=async(e,t)=>{try{return await e(t)}catch{return null}},nP=async(e,t)=>{try{let r=await e.resolveBinPath(t);return r==null?null:e.realpath(r)}catch{return null}},Ag=async(e,t)=>{if(!ml(e,t.platform))return Cg(e.id);let r=await $g(t.runCommand,e.probeArgv),n=await nP(t,e.binName);if(r==null&&n==null)return Cg(e.id);let o=r??(n==null?null:await $g(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)}},ko=async(e,t)=>Promise.all(e.map(r=>Ag(Me(r),t)));import{$ as lP}from"zx";import{z as Og}from"zod";var Ig=/^\d{4}-\d{2}-\d{2}$/,bo=e=>{if(!Ig.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},Dg=e=>`Release date "${e}" is not a calendar date in yyyy-mm-dd form.`,un=class extends Error{constructor(t){super(Dg(t)),this.name="InvalidReleaseDateError"}},cr=e=>{let t=e.trim();if(!bo(t))throw new un(t);return t},Ro=e=>{let t=e.trim();return t===""||bo(t)?!0:Dg(t)},gl=Og.string().refine(bo,{message:"Expected a calendar date in yyyy-mm-dd form."}),hl=Og.string().refine(e=>e===""||bo(e),{message:'Expected a calendar date in yyyy-mm-dd form, or "" to clear.'});var Nt=e=>e.slice(1).split(".").map(Number),pn=e=>[...e].sort((t,r)=>{let[n,o,s]=Nt(t),[i,a,c]=Nt(r);return n!==i?(n??0)-(i??0):o!==a?(o??0)-(a??0):(s??0)-(c??0)});var _g="next",oP=/^v?(\d+)\.(\d+)\.(\d+)$/,sP=e=>e.replace(/^.*release\//,""),yl=e=>{let t=sP(e.trim()),r=oP.exec(t);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null},Ng=e=>`${e[0]}.${e[1]}.${e[2]}`,vl=e=>{let t=[...e.remoteBranches??[],...e.jiraVersions??[]],r=[],n=new Set;for(let o of t){let s=yl(o);if(!s)continue;let i=Ng(s);n.has(i)||(n.add(i),r.push(s))}return pn(r.map(o=>Ng(o))).map(o=>Nt(`v${o}`))},lr=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},wl=(e,t)=>{if(e.length===0)throw new lr;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`},mn=(e,t)=>{try{return wl(e,t)}catch(r){if(r instanceof lr)return null;throw r}},kl=e=>e.trim().toLowerCase()===_g,pi=e=>kl(e)||yl(e)!==null?{version:e}:{name:e},iP=e=>e==="regular"||e==="hotfix",Mg=e=>"name"in e,aP=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:cr(n)}},bl=e=>{let t=e.trim();if(t==="")throw new Error("Release spec is empty");let r=t.indexOf(":"),{token:n,releaseDate:o}=aP(r===-1?t:t.slice(0,r)),s="regular",i="";if(r!==-1){let a=t.slice(r+1),c=a.indexOf(":"),l=c===-1?a.trim():a.slice(0,c).trim();i=c===-1?"":a.slice(c+1).trim();let d=l.toLowerCase();if(!iP(d))throw new Error(`Invalid release type "${l}". Expected "regular" or "hotfix".`);s=d}return ui({...pi(n),type:s},{description:i,releaseDate:o})},Rl=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},ui=(e,t)=>{let{description:r,releaseDate:n}=t;return{...e,...r!==void 0&&r!==""?{description:r}:{},...n===void 0?{}:{releaseDate:n}}},cP=e=>{let t=e.name.trim();return hs(t),ui({id:{kind:"name",name:t,raw:t},type:e.type},e)},Sl=(e,t)=>{let r=[...t];return e.map(n=>{if(Mg(n))return cP(n);let o=n.version.trim();if(o==="")throw new Error("Release entry has an empty version");if(kl(o)){let a=wl(r,n.type);return r.push(Nt(`v${a}`)),ui({id:me(a),type:n.type},n)}let s=yl(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),ui({id:me(i),type:n.type},n)})},Pl=e=>e.some(t=>!Mg(t)&&kl(t.version));var dP=e=>e.split(`
379
+ `).map(t=>{let r=t.indexOf(" ");return r===-1?null:G(t.slice(r+1))}).filter(t=>t!==null&&t.kind==="version").map(t=>t.raw),uP=async()=>{let e=await lP({quiet:!0})`git ls-remote --heads origin 'release/v*'`;return dP(e.stdout)},pP=async()=>{let e=await ut();return e?(await Yr(e)).map(r=>r.name):[]},So=async()=>{let[e,t]=await Promise.allSettled([uP(),pP()]);return e.status==="rejected"&&u.warn({err:e.reason},"Failed to list remote release branches; continuing without them"),t.status==="rejected"&&u.warn({err:t.reason},"Failed to fetch Jira versions; continuing without them"),vl({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:t.status==="fulfilled"?t.value:[]})};import mP from"node:fs";import fP from"node:path";var El=[".claude/settings.json",".claude/settings.local.json"],gP=["infra-kit","ik","pnpm exec infra-kit","pnpm exec ik","pnpm infra-kit"],hP=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),yP=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},vP=(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(hP).join(".*")}$`,"s").test(t)||n===t||n.startsWith(`${t} `)},wP=e=>{let t=e.groupPath.join(" ");return t===e.cliName?[t]:[t,e.cliName]},kP=()=>dr.filter(e=>e.mutating),bP=e=>{let t=yP(e);return t===null?[]:kP().filter(r=>gP.some(n=>wP(r).some(o=>vP(t,`${n} ${o}`)))).map(r=>r.groupPath.join(" "))},RP=(e,t)=>{let r;try{r=mP.readFileSync(fP.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}},jg=e=>{let t={present:[],unreadable:[],hits:[]};for(let r of El){let n=RP(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=bP(o);s.length>0&&t.hits.push({file:r,pattern:o,commands:s})}}}return t};var SP=e=>e.every(t=>t.status!=="fail"),PP=["brew","git","gh","doppler","aws"],EP=async e=>{let t=await ko(PP,e);return new Map(t.map(r=>[r.id,{manager:r.manager,version:r.version,present:r.present,onPath:r.onPath}]))},ft=async(e,t,r,n)=>{try{return await ir()`${t}`,{name:e,status:"pass",message:r}}catch{return{name:e,status:"fail",message:n}}},xP=async()=>{let e="orca installed",t=await St();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)"}},Hg=(e,t,r,n)=>{let o=ce.join(Cl.homedir(),t),s="Run: infra-kit setup --skip-tools";if(!Y.existsSync(o))return{name:e,status:"fail",message:`~/${t} not found. ${s}`};let i=Y.readFileSync(o,"utf-8"),a=i.indexOf(sr),c=i.indexOf(It);return a===-1||c===-1||c<a?{name:e,status:"fail",message:`infra-kit ${r} block missing from ~/${t}. ${s}`}:i.slice(a,c+It.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`}},TP=()=>Hg("zshrc init block",".zshrc","shell",bg()),CP=()=>Hg("zshenv session block",".zshenv","session-env",ll()),$P=async()=>{let e="pnpm enableGlobalVirtualStore";try{let t=await T(),r=ce.join(t,"pnpm-workspace.yaml");if(!Y.existsSync(r))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${r}`};let n=Y.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}`}}},AP=async()=>{try{return kt(),{config:await M(),error:null}}catch(e){return{config:null,error:e}}},OP=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)"}},IP=384,xl=448,DP=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(", "),NP=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}}})),_P=async(e,t={})=>{let r="env tokens configured",n=t.readStore??Ve,o=t.resolveToken??nm;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 NP(await xs(),o);return{name:r,status:"pass",message:DP(s)}},MP=()=>Ue.env[Yt]||void 0,jP=async(e={})=>{let t="tokens.json present",r=e.readStore??Ve,n=e.storePath??Rt;if((e.readEnvToken??MP)())return{name:t,status:"skip",message:`${Yt} 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 ${Yt} instead.`}}return{name:t,status:"pass",message:`${s} holds ${a.length} token(s): ${a.join(", ")}`}},Po=(e,t)=>{let r=t(e);return r===null?null:r.mode&511},FP=async(e,t={})=>{let r="tokens.json perms",n=t.storePath??Rt,o=t.statPath??LP,s=t.chmodPath??Y.chmodSync,i;try{i=await n()}catch{return{name:r,status:"skip",message:"the token store path could not be resolved"}}if(Po(i,o)===null)return{name:r,status:"skip",message:`No store to protect at ${v(i)} (see tokens.json present)`};let a=ce.dirname(i),c=ce.dirname(a),l=ce.dirname(c),p=[{target:l,expected:xl,actual:Po(l,o)},{target:c,expected:xl,actual:Po(c,o)},{target:a,expected:xl,actual:Po(a,o)},{target:i,expected:IP,actual:Po(i,o)}].filter(g=>g.actual!==null&&g.actual!==g.expected);if(p.length===0)return{name:r,status:"pass",message:`${v(i)} is 0600 (0700 dirs)`};let m=p.map(g=>`${v(g.target)} is ${Fg(g.actual)}, expected ${Fg(g.expected)}`).join("; ");if(!e)return{name:r,status:"fail",message:`${m}. Fix: run \`infra-kit doctor --fix\`, or chmod them by hand.`};for(let g of p)s(g.target,g.expected);return{name:r,status:"pass",message:`Tightened ${p.length} path(s): ${m}`}},Fg=e=>`0${e.toString(8).padStart(3,"0")}`,LP=e=>{try{return Y.statSync(e)}catch{return null}},BP=async()=>{let e="user override path";try{let t=await H(),r=Y.existsSync(t.userProject),n=await ho(t.userProject,r),o=r?yo(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}}},WP=async()=>{let e="legacy user-global config",t;try{t=await H()}catch{return{name:e,status:"skip",message:"infra-kit config paths could not be resolved"}}let r=ce.join(ce.dirname(t.userGlobal),"config.json");return Y.existsSync(r)?Y.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"}},VP={cursor:{command:["cursor","--version"],label:"Cursor",failMsg:"Cursor is not installed. Install from: https://cursor.com/"}},UP=async e=>{let t=VP[e];try{return await ir()`${t.command}`,{ok:!0,label:t.label,failMsg:t.failMsg}}catch{return{ok:!1,label:t.label,failMsg:t.failMsg}}},JP=async e=>{let t="ide installed";if(!e.config)return{name:t,status:"skip",message:"infra-kit config could not be read (see config check)"};let r=wt(e.config).map(s=>s.provider);if(r.length===0)return{name:t,status:"pass",message:"No IDE configured (ide unset)"};let n=await Promise.all(r.map(s=>UP(s))),o=n.filter(s=>!s.ok);return o.length===0?{name:t,status:"pass",message:`Installed: ${n.map(s=>s.label).join(", ")}`}:{name:t,status:"fail",message:o.map(s=>s.failMsg).join("; ")}},Lg=/^\d+\.\d+\.\d+$/,GP=(e,t)=>e===t||!Lg.test(e)||!Lg.test(t)?!1:pn([`v${e}`,`v${t}`])[0]===`v${e}`,KP=async(e,t)=>{let r;try{r=await Pe(e)}catch{return[]}let n=[];for(let o of r){let s=Qt(er(ce.join(o,"CLAUDE.md")));s.state==="ok"&&s.version!==void 0&&GP(s.version,t)&&n.push(s.version)}return n},HP=async(e,t)=>{let r=await KP(e,t);if(r.length===0)return"";let n=pn(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`},qP=async()=>{let e=[{name:"CLAUDE.md block",status:"skip",message:"no infra-kit config in this repo"}],t;try{t=(await H()).main}catch{return e}if(!Y.existsSync(t))return e;let r=ce.dirname(t),n=ce.join(r,"CLAUDE.md"),o=Y.existsSync(n)?Y.readFileSync(n,"utf-8"):"",s=Ye(o,De,ze),i=s?"CLAUDE.md block present":"infra-kit block missing from CLAUDE.md. Run: infra-kit setup --skip-tools",a=await HP(r,K.version);return[{name:"CLAUDE.md block",status:s?"pass":"fail",message:`${i}${a}`}]},YP=async()=>{try{let e=(await H()).main;return Y.existsSync(e)?ce.dirname(e):null}catch{return null}},zP=e=>{let t=Wp();return t===null||!In(t,e)?"":` \u2014 plugin ${t} is fetched but not applied. Run: ${Br}`},XP=e=>{let t=e.kind==="installed"?Rs(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 ${q} version ${t}${zP(t)}`}},Bg=3,Wg=(e,t)=>he(e)===he(t),ZP=e=>{if(e===void 0||e.gitRoot===null)return"";let t=v(e.gitRoot);if(e.projectDir!==null){if(Wg(e.projectDir,e.gitRoot))return"";let r=xn(e.gitRoot,he(e.projectDir),he)?"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 Wg(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}`},QP=(e,t)=>{let r="plugin installed",n=ZP(t);if(e.kind==="installed"){let{scope:c,projectPath:l}=e.installation,d=l===null?"":`, ${v(l)}`;return{name:r,status:"pass",message:`Plugin ${q} installed (${c??"unknown"} scope${d})${n}`}}if(e.kind==="absent")return{name:r,status:"fail",message:`Plugin ${q} is not installed. Run: ${lt}${n}`};let o=e.installations.map(c=>c.projectPath===null?"(unnamed project)":v(c.projectPath)),s=o.length-Bg,i=s>0?` and ${s} more`:"",a=`${o.slice(0,Bg).join(", ")}${i}`;return{name:r,status:"fail",message:`Plugin ${q} is installed for ${a} only, not this project. Run: ${lt}${n}`}},eE=()=>ft("claude CLI",["claude","--version"],"Installed: claude","claude CLI not found on PATH \u2014 `infra-kit setup` cannot install the plugin; install Claude Code first"),fn="claude in chrome",tE="com.anthropic.claude_code_browser_extension",mi="run `/chrome` inside Claude Code to set up Claude in Chrome",rE={darwin:["Library","Application Support","Google","Chrome","NativeMessagingHosts"],linux:[".config","google-chrome","NativeMessagingHosts"]},nE=e=>{try{return Y.accessSync(e,Y.constants.X_OK),!0}catch{return!1}},oE=e=>{try{return JSON.parse(e)}catch{return null}},sE=/^exec\s+(?<target>\S+)\s+--chrome-native-host\b/m,iE=(e={})=>{let t=e.platform??Ue.platform,r=e.home??Cl.homedir(),n=e.readText??Tl,o=e.isExecutable??nE,s=rE[t];if(s===void 0)return{name:fn,status:"skip",message:`no Chrome native host location known for ${t}`};let i=ce.join(r,...s,`${tE}.json`),a=n(i);if(a===null)return{name:fn,status:"warn",message:`Chrome native host not registered \u2014 ${mi}`};let c=ae.object({path:ae.string().min(1)}).safeParse(oE(a));if(!c.success)return{name:fn,status:"fail",message:`${v(i)} has no host path \u2014 ${mi} again`};let l=c.data.path;if(!o(l))return{name:fn,status:"fail",message:`Chrome native host ${v(l)} is missing or not executable \u2014 ${mi} again`};let d=sE.exec(n(l)??"")?.groups?.target;return d!==void 0&&!o(d)?{name:fn,status:"fail",message:`Chrome native host runs ${v(d)}, which no longer exists \u2014 ${mi} again`}:{name:fn,status:"pass",message:`Native host registered (${v(l)}); /infra-kit:doctor checks the live connection`}},aE=(e,...t)=>{try{return JSON.parse(Y.readFileSync(ce.join(e,...t),"utf-8"))}catch{return null}},cE=e=>{if(e.kind!=="installed")return{kind:"not-installed"};let t=Rs(e.installation),{installPath:r}=e.installation;if(r===null)return{kind:"skills-only",version:t};let n=aE(r,Ne),o=n!==null&&typeof n=="object"?n[Ze]:void 0;return o==null||typeof o!="object"?{kind:"skills-only",version:t}:{kind:"stale-server",version:t,keys:Object.keys(o)}},Vg=e=>`Plugin ${q} ${e===null?"(version unreadable)":e}`,lE=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: ${lt}`};if(e.kind==="stale-server"){let r=e.keys.length===0?"":` (under "${e.keys.join('", "')}")`;return{name:t,status:"pass",message:`${Vg(e.version)} still carries an MCP server in its ${Ne}${r} \u2014 a copy from before the plugin went skills-only. Update it: infra-kit setup (or ${Br}), then restart Claude Code`}}return{name:t,status:"pass",message:`${Vg(e.version)} is skills-only \u2014 no ${Ne}, as shipped; the /infra-kit:* skills drive the infra-kit CLI`}},dE=(e,t)=>{let r=Ht(e===null?{}:{projectPath:e}),n=On();return[{name:"marketplace registered",status:n?"pass":"fail",message:n?`Marketplace ${ue} is known to Claude Code`:`Marketplace ${ue} is not registered. Run: claude plugin marketplace add ${bt}`},QP(r,t),XP(r),lE(cE(r)),{name:"CLI version",status:"pass",message:`infra-kit CLI ${K.version}`}]},uE=({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(", ")},pE=e=>{let t="Agent mode",r=gs(e),n=uE(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})`}},Ug=4,mE=e=>{let t=e.slice(0,Ug).join(", "),r=e.length-Ug;return r>0?`${t} +${r} more`:t},fE=e=>{let t="Agent allowlist",{present:r,unreadable:n,hits:o}=jg(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"} (${mE(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 ${El.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`}},gE=(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`},hE=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 qf(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} (${gE(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`}},qg=e=>ya(["trust"],{bin:e}),yE=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),Jg="ERR_TLS_CERT_ALTNAME_INVALID",Yg=()=>`portless serving TLS on :${vt}`,vE=async(e,t,r)=>{let n=Yg();return await e(vt,!0)?{name:n,status:"pass",message:`portless is serving HTTPS on :${vt}`}:{name:n,status:"fail",message:`No portless daemon is serving HTTPS on :${vt}. Install it once (needs root): \`${yt(t,r)}\`.`}},wE=async(e,t,r,n,o)=>{let s="portless CA chain valid",i=["localhost",...t.slice(0,1).map(d=>d.name)],c=(await Promise.all(i.map(async d=>({servername:d,result:await e(vt,d)})))).filter(d=>!d.result.ok);if(c.length===0)return{name:s,status:"pass",message:`Served certificate chains to ${v(r)} (${i.join(", ")})`};let l=c.map(d=>d.result.ok?"":d.result.code);return l.includes(Jg)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${Jg} for servername(s) ${c.map(d=>d.servername).join(", ")} \u2014 doctor's probe is wrong, your trust store is not implicated. Please report this.`}:l.some(d=>yE.has(d))?{name:s,status:"fail",message:`The daemon is serving a certificate that does not chain to ${v(r)}. Its CA was regenerated \u2014 run \`${qg(n)}\`, or reinstall: \`${yt(n,o)}\`.`}:{name:s,status:"fail",message:`TLS handshake failed (${l.join(", ")})`}},kE=(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: \`${qg(r)}\` (no sudo needed).`}},bE=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 \`${ya(["alias","--remove","<name>"],{bin:r})}\`.`}},_t="portless service target",xo=e=>({name:_t,status:"warn",message:e}),zg=e=>e==="darwin"?sp:e==="linux"?ip:null,RE=e=>e==="darwin"?`sudo launchctl kickstart -k system/${op}`:`sudo systemctl restart ${ap}`,SE="/bin/ps",PE=e=>{try{let t=Kg(SE,["-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}},Tl=e=>{try{return Y.readFileSync(e,"utf-8")}catch{return null}},EE=e=>{try{return Y.statSync(e).mtime}catch{return null}},xE=2e3,TE=e=>{try{let t=Kg(e,["-p","process.version"],{encoding:"utf-8",timeout:xE}),r=t.stdout?.trim()??"";return{version:r===""?null:r,status:t.status,signal:t.signal}}catch{return{version:null,status:null,signal:null}}},CE=(e,t)=>({platform:e.platform??Ue.platform,readServiceFile:e.readServiceFile??Tl,readFile:e.readFile??Tl,exists:e.exists??Y.existsSync,realpath:e.realpath??he,mtime:e.mtime??EE,execPath:e.execPath??Ue.execPath,home:e.home??Cl.homedir(),cwd:e.cwd??Ue.cwd(),repoRoot:e.repoRoot??fo,stateDir:(e.stateDir??lp)(),processStartTime:e.processStartTime??PE,version:e.version??Ue.version,arch:e.arch??Ue.arch,nodeVersionOf:e.nodeVersionOf??TE,isGlobal:e.isGlobal??fs().node.isGlobal,nodeFs:e.nodeFs??Y,stableNode:null,stableNodeSidecar:null,bin:t}),To="portless node",ur="~/.infra-kit/node",Eo=e=>({row:{name:To,status:"fail",message:e},stableNode:null,sidecar:null}),Gg=(e,t)=>{try{return e(t,{throwIfNoEntry:!1})}catch{return}},$E=e=>e.signal!==null?`killed by ${e.signal}`:e.status===null?"did not start":e.status!==0?`exit ${e.status}`:`printed ${e.version??"nothing"}`,AE=(e,t)=>e.status===0&&e.signal===null&&e.version===t.version,OE=e=>{let t=fp(e.home),r=Gg(e.nodeFs.lstatSync,t);if(r===void 0)return Eo(`${ur} is missing and could not be written \u2014 run \`infra-kit setup\` and see the debug log`);if(!r.isFile())return Eo(`${ur} 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 Eo(`${ur} has no readable node.source.json and it could not be rewritten \u2014 run \`infra-kit setup\``);let o=Gg(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 Eo(`${ur} 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(!AE(c,e))return Eo(`${ur} does not run as Node ${e.version} (${$E(c)}). Re-run through the current Node: \`${yt(e.bin,{...e,stableNode:null})}\`, then \`infra-kit setup\``)}return{row:{name:To,status:"pass",message:`${ur} is Node ${n.version} (${n.arch}, ${n.method} of ${v(n.source)})`},stableNode:t,sidecar:n}},IE=e=>{if(zg(e.platform)===null)return{row:{name:To,status:"skip",message:"no portless OS service on this platform"},stableNode:null,sidecar:null};let t=OE(e);return e.isGlobal()?t:{...t,row:{name:To,status:"skip",message:`not a global install; the global infra-kit keeps ${ur} current`}}},Xg=(e,t)=>{let r=CE(e,t),n=IE(r);return{seams:{...r,stableNode:n.stableNode,stableNodeSidecar:n.sidecar},node:n.row}},DE=(e,t)=>{let r=t.readFile(ce.join(e,"package.json"));try{let n=r===null?null:ae.object({version:ae.string()}).safeParse(JSON.parse(r));return n?.success===!0?n.data.version:"?"}catch{return"?"}},NE=e=>{let t=Number.parseInt(e.readFile(ce.join(e.stateDir,"proxy.pid"))?.trim()??"",10);return!Number.isInteger(t)||t<=0?null:e.processStartTime(t)},_E=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?null:t},ME=(e,t,r)=>{let n=NE(r),o=a=>n!==null&&a!==null&&n.getTime()<a.getTime(),s=r.stableNodeSidecar,i=[...s!==null&&o(_E(s.versionChangedAt))?[`Node ${s.version}`]:[],...o(r.mtime(ce.join(e,"package.json")))?[`portless ${t}`]:[]];return i.length===0?null:i.join(" and ")},jE=async(e,t)=>{let r=t.realpath(t.cwd);return r===t.realpath(t.home)?!1:xn(await t.repoRoot()??r,e,t.realpath)},pr=e=>({state:"drifted",row:e}),FE=async(e,t,r)=>{let n=yt(r.bin,r);if(!r.exists(e))return pr({name:_t,status:"fail",message:`The service runs \`${e}\`, which no longer exists (Node was upgraded, or its package dir was re-created). Re-run: \`${n}\``});let o=ce.join(va(r.home),"dist","cli.js");if(t!==o)return pr(xo(`The service points at \`${t}\`, a version-specific location. Re-run once to switch it to the stable link: \`${n}\``));if(ms(r.home,r.exists)===null)return pr({name:_t,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(va(r.home));if(await jE(s,r))return pr({name:_t,status:"fail",message:`The service runs portless from a project checkout (${s}). Re-run \`service install\` from the global install: \`${n}\``});let i=LE(e,n,r);if(i!==null)return i;let a=DE(s,r),c=ME(s,a,r);return c!==null?{state:"converged",row:xo(`The running daemon predates ${c} that \`dev\` will talk to. Restart it: \`${RE(r.platform)}\` (or reboot).`)}:{state:"converged",row:{name:_t,status:"pass",message:`service runs \`${e}\` (Node ${r.version}) + stable link \u2192 portless ${a}`}}},LE=(e,t,r)=>r.stableNode!==null?r.realpath(e)===r.realpath(r.stableNode)?null:pr(xo(`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:pr(xo(`The service runs \`${e}\`; infra-kit runs \`${r.execPath}\`. Works until the old Node is removed. Re-run when convenient: \`${t}\``)),Zg=async e=>{let t=zg(e.platform);if(t===null)return{state:"absent",row:{name:_t,status:"skip",message:"no portless OS service file on this platform"}};let r=e.readServiceFile(t);if(r===null)return{state:"absent",row:{name:_t,status:"skip",message:`the OS service is not installed (no ${t})`}};let[n,o]=hf(e.platform,r)??[];return n===void 0||o===void 0?pr(xo(`could not parse ${t} \u2014 re-run \`${yt(e.bin,e)}\` to rewrite it.`)):FE(n,o,e)},Qg=async(e,t)=>{let{seams:r}=Xg(e,t);return{state:(await Zg(r)).state,stableNode:r.stableNode}},BE=()=>[To,_t,Yg(),"portless CA chain valid","portless CA trusted","portless routes"],WE=async(e={})=>{let t=e.resolveBin??np,r=e.isProxyServing??cp,n=e.handshake??pp,o=e.caTrusted??up,s=e.routes??Cn,i=e.isListening??Tn,a=(e.caPath??dp)(),c=t();if(c===null)return[{name:"portless installed",status:"fail",message:"portless is not resolvable from node_modules \u2014 run `pnpm install`."},...BE().map(R=>({name:R,status:"skip",message:"portless not resolvable"}))];let l={name:"portless installed",status:"pass",message:"portless is resolvable from node_modules"},{seams:d,node:p}=Xg(e,c),m=s(),g=await vE(r,c,d),y=g.status==="fail"?{name:"portless CA chain valid",status:"skip",message:"no daemon to handshake with"}:await wE(n,m,a,c,d);return[l,p,(await Zg(d)).row,g,y,kE(o(),a,c),await bE(m,i,c)]},VE=async(e={})=>{let t="portless routes",r=e.routes??Cn,n=e.isListening??Tn,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 d=>({name:d.name,port:d.port,live:await n(d.port)}))),{prunable:a,withheld:c}=df(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??mp().removeAlias;for(let d of a)await l(d);return{name:t,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},fi=async(e={})=>{let t=await AP(),r=EP(e.probeDeps??vo()),n=async(m,g)=>{let[y,R]=await Promise.all([g,r]),w=R.get(m);return w===void 0?y:{...y,detail:w}},o=await Promise.all([n("brew",ft("brew installed",Me("brew").probeArgv,"Homebrew is installed","Homebrew is not installed. Install from: https://brew.sh/")),n("git",ft("git installed",Me("git").probeArgv,"git is installed","git is not installed. Install with: brew install git")),n("gh",ft("gh installed",Me("gh").probeArgv,"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/")),ft("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),n("doppler",ft("doppler installed",Me("doppler").probeArgv,"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli")),n("aws",ft("aws installed",Me("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")),ft("package manager installed",["pnpm","--version"],"Installed: pnpm","pnpm is not installed. Install from: https://pnpm.io/installation"),ft("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"),xP(),Promise.resolve(TP()),Promise.resolve(CP()),$P(),Promise.resolve(OP(t)),jP(),_P(t),FP(e.fix??!1),BP(),WP(),JP(t)]),s=await WE(e.portlessDeps);if(e.fix){let m=await VE(),g=s.findIndex(y=>y.name===m.name);g>=0?s[g]=m:s.push(m)}let i=await YP(),a=await fo(),c={projectDir:Ue.env.CLAUDE_PROJECT_DIR||null,cwd:Ue.cwd(),gitRoot:a},l=[await eE(),...dE(i,c),iE(),pE({env:Ue.env,stdinIsTTY:Ue.stdin.isTTY===!0,flag:N.source==="flag"}),a===null?{name:"Agent allowlist",status:"skip",message:"no git root"}:fE(a)],d=[...o,await hE(a),...s,...await qP(),...l],p={checks:d.map(m=>({name:m.name,status:m.status,message:m.message,fixable:Oc.has(m.name),detail:m.detail})),allPassed:SP(d),cliVersion:K.version};return{content:k(JSON.stringify(p,null,2)),structuredContent:p}},$l=S({name:"doctor",description:"Check installation and authentication status of gh, doppler, and aws CLIs. Read-only: a row marked fixable is one `infra-kit doctor --fix` repairs, and that flag is not reachable from this boundary \u2014 report such a row to the human instead.",inputSchema:{},outputSchema:{checks:ae.array(ae.object({name:ae.string().describe("Name of the check"),status:ae.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:ae.string().describe("Details about the check result"),fixable:ae.boolean().describe("Whether `infra-kit doctor --fix` repairs this row"),detail:ae.object({manager:ae.string().describe("Which package manager owns this install, read from its resolved path"),version:ae.string().nullable().describe("The version the tool reported, or null"),present:ae.boolean().describe("The tool is installed somewhere findable \u2014 on PATH or not"),onPath:ae.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:ae.boolean().describe("Whether no check failed (warnings and skips do not count)"),cliVersion:ae.string().describe("Version of the infra-kit CLI that produced this report")},handler:()=>fi()});import{E2E_MODE_ENV as ix}from"@slip-stream-kit/config/internal";import{spawn as ax}from"node:child_process";import jl from"node:fs";import cx from"node:os";import Fl from"node:path";import Ll from"node:process";import{z as E}from"zod";import{describeProxyRoutes as UE,loadDev as JE,readAppAliasName as GE,readCloudOrigin as KE,readLocalContext as th}from"@slip-stream-kit/config/internal";import eh from"node:fs";import mr from"node:path";import gi from"node:process";import{z as Al}from"zod";var HE=async e=>{let t=mr.join(e,"apps"),r=eh.existsSync(t)?eh.readdirSync(t).toSorted():[],n=[];for(let o of r){let s=mr.join(t,o,"tests"),i=await Or(s);i?.e2e&&n.push({app:o,testsDir:s,e2e:i.e2e})}return n},qE=(e,t)=>{let[r,n]=mr.relative(e,t).split(mr.sep);return r==="apps"&&n?n:void 0},YE=(e,t,r,n)=>{let o=c=>e.find(l=>l.app===c),s=o(t)??(t===void 0?o(qE(n,r)):void 0);if(s)return s;if(t===void 0&&e.length===1)return e[0];let i=e.map(c=>c.app);if(i.length===0)throw new f(void 0,{operation:"find an e2e package",remediation:"declare `e2e: { target }` in `apps/<app>/tests/infra-kit.config.ts` (see the `InfraKitE2e` type)",stderrExcerpt:`no apps/*/tests package under ${n} declares an e2e block`});let a="app";throw new C({status:"argument_required",argument:a,choices:Al.toJSONSchema(Al.object({app:Al.enum(i)})),agentMode:N.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(", ")}`})},zE=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}})),XE=e=>Qn(e).apps.find(t=>t.env!=="")?.env??null,Ol=async(e,t={})=>{let r=t.cwd??gi.cwd(),n=t.projectRoot??await T(),o=(t.env??gi.env)[Sr]||null,s=t.healthProbe??$a,i=YE(await HE(n),e,r,n),{target:a}=i.e2e,[c,l]=a.split("/"),d=mr.join(n,"apps",c,l),p=(await zt(d)).name,m=(await Or(d))?.deployedUrlEnv??null;if(!p)throw new f(void 0,{operation:`resolve e2e target ${a}`,remediation:`check \`e2e.target\` in ${mr.join(i.testsDir,"infra-kit.config.ts")}`,stderrExcerpt:`${d} has no package.json name`});let g=gm(d),y=GE(p,d),R=`${y}.localhost`,w=`https://${R}`,x=0;if(l==="ui")x=(t.listRoutes??Cn)().find(P=>P.name===R||P.name===y)?.port??0;else{let P=th(d).info.get(p);x=P?.port??0,w=P?.origin??w}let W=x>0&&await s({tag:a,port:x,kind:l})==="ok",I=W?XE(d):null;return{app:i.app,testsDir:i.testsDir,target:a,kind:l,targetDir:d,packageName:p,deployedUrlEnv:m,release:g,env:o,servedEnv:I,localUrl:w,served:W}},rh=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}},Il=async(e,t={})=>{let r=t.healthProbe??$a,n=th(e.targetDir),o=e.kind==="ui"?await JE(e.targetDir):void 0,s=o?.proxy?UE({proxy:o.proxy,localContext:n,env:e.env??void 0,cloud:KE(e.deployedUrlEnv??void 0,t.env??gi.env),getRelease:()=>e.release}):[],i=new Map([...n.info].map(([a,c])=>[a,c.port]));return{...rh(e),mode:"local",baseUrl:e.localUrl,routes:await zE(s,i,r)}},Dl=(e,t={})=>{let{env:r,deployedUrlEnv:n,target:o}=e;if(!n)throw new f(void 0,{operation:`resolve the deployed app ${e.app}'s cloud e2e run targets`,remediation:`declare \`deployedUrlEnv: '<APP>_URL'\` in ${mr.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??gi.env)[n];if(!r||!s)throw new f(void 0,{operation:`resolve the deployed app ${e.app}'s cloud e2e run targets`,remediation:"load an environment (`infra-kit env-load -c <env>`), or drop --cloud to run against this worktree",stderrExcerpt:`a cloud run of ${o} needs ${n} and ${Sr}, and ${s?Sr:n} is not set`});return{...rh(e),mode:"cloud",baseUrl:s,routes:[]}};import ZE from"node:fs";import QE from"node:path";import{stripVTControlCharacters as ex}from"node:util";import{z as D}from"zod";var nh=2e3,oh="--reporter=line,json",sh=e=>({PLAYWRIGHT_JSON_OUTPUT_FILE:e,PLAYWRIGHT_JSON_OUTPUT_NAME:e}),ih=e=>e.some(t=>t==="--reporter"||t.startsWith("--reporter=")),Nl=D.object({message:D.string().optional()}),tx=D.object({status:D.string(),retry:D.number(),error:Nl.optional(),errors:D.array(Nl).optional(),attachments:D.array(D.object({name:D.string(),path:D.string().optional()})).optional()}),rx=D.object({title:D.string(),file:D.string(),line:D.number().optional(),tests:D.array(D.object({projectName:D.string(),status:D.string(),results:D.array(tx)}))}),ah=D.lazy(()=>D.object({title:D.string(),specs:D.array(rx).optional(),suites:D.array(ah).optional()})),nx=D.object({config:D.object({rootDir:D.string().optional()}).optional(),suites:D.array(ah),errors:D.array(Nl).optional(),stats:D.object({expected:D.number(),unexpected:D.number(),flaky:D.number(),skipped:D.number()})}),ch=e=>{let t=ex(e);return t.length>nh?`${t.slice(0,nh)}\u2026`:t},ox=e=>{let t=e.error?.message??e.errors?.[0]?.message;return t===void 0?null:ch(t)},sx=e=>{let t=nx.safeParse(e);if(!t.success)return null;let{config:r,suites:n,errors:o,stats:s}=t.data,i=[],a=(c,l)=>{for(let d of c.specs??[])for(let p of d.tests){if(p.status!=="unexpected"&&p.status!=="flaky")continue;let m=p.results.findLast(g=>g.status!=="passed"&&g.status!=="skipped");i.push({title:[...l,d.title].join(" \u203A "),file:r?.rootDir?QE.resolve(r.rootDir,d.file):d.file,line:d.line??null,project:p.projectName,status:p.status,retry:m?.retry??0,error:m?ox(m):"Expected to fail, but passed.",tracePath:m?.attachments?.find(g=>g.name==="trace")?.path??null})}for(let d of c.suites??[])a(d,[...l,d.title])};for(let c of n)a(c,[]);return{summary:{expected:s.expected,unexpected:s.unexpected,flaky:s.flaky,skipped:s.skipped},failures:i,errors:(o??[]).flatMap(c=>c.message===void 0?[]:[ch(c.message)])}},lh=e=>{try{return sx(JSON.parse(ZE.readFileSync(e,"utf8")))}catch{return null}};var lx=["playwright.config.ts","playwright.config.mts","playwright.config.js","playwright.config.mjs"],dx=e=>lx.some(t=>{try{return jl.readFileSync(Fl.join(e,t),"utf8").includes("infraKitE2e")}catch{return!1}}),dh=e=>`infra-kit dev ${e.target.split("/")[0]} --no-watch --reuse`,ux=(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(`
380
+ `)},px=e=>{let t=e.routes.filter(n=>n.source==="local"&&n.live!==!0);if(t.length===0)return;let r=t.map(n=>`${n.path} (${n.packageName})`);throw new f(void 0,{operation:`run ${e.app} e2e against the local dev server`,remediation:"check the backend rows in `infra-kit dev-status`, fix or restart it, then re-run",stderrExcerpt:`routes held local but their backend is not responding: ${r.join(", ")}`})},mx=async(e,t)=>{if(e.env===null||!mm(e.env))return;let r=await(t.protectedEnvAccess??He)();if(r.allowed)return;let n=`run ${e.app} e2e against "${e.env}"`;throw r.reason==="agent-blocked"?new C({status:"refused",env:e.env},2,{operation:n,remediation:'a human runs it from their own terminal \u2014 this project sets `protectedEnvs: "cli-only"`',stderrExcerpt:`"${e.env}" is withheld from agents in this project`}):new f(void 0,{operation:n,remediation:"load a non-protected env (`infra-kit env-load -c dev`), or set `protectedEnvs` in infra-kit.json",stderrExcerpt:`"${e.env}" is a protected environment`})},fx=e=>{if(!(e.servedEnv===null||e.servedEnv===e.env))throw new f(void 0,{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"}"`})},gx=async(e,t)=>{if(e.served){fx(e);let p=await Il(e,t);return px(p),p}if(!dx(e.testsDir))throw new f(void 0,{operation:`run ${e.app} e2e locally`,remediation:`start it (\`${dh(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:d}=e;return{app:r,testsDir:n,target:o,packageName:s,deployedUrlEnv:i,release:a,env:c,servedEnv:l,localUrl:d,mode:"local",baseUrl:d,routes:[]}},hx=(e,t,r)=>new Promise((n,o)=>{let s=ax("pnpm",["exec","playwright","test",...t],{cwd:e.testsDir,env:{...Ll.env,...r,[ix]:e.mode},stdio:["inherit",Kt.enabled||J()?2:"inherit","inherit"]});s.once("error",o),s.once("close",i=>{n(i??1)})}),hi=async(e,t={})=>{let r=await Ol(e.app,t),n=e.cloud?Dl(r,t):await gx(r,t);u.info(ux(n,r.served)),n.mode==="cloud"&&await mx(n,t);let o={...n,served:r.served,devCommand:n.mode==="local"&&!r.served?dh(r):null,playwrightArgs:e.playwrightArgs??[]};if(e.dryRun)return Ml({...o,ran:!1,exitCode:null,..._l});n.mode==="cloud"&&await B(e.yes,`Run ${n.app} e2e against ${n.baseUrl} ("${n.env}", shared)?`,{plan:o});let s=t.runPlaywright??hx;if(!J()||ih(o.playwrightArgs)){let c=await s(n,o.playwrightArgs,{});return c!==0&&(Ll.exitCode=c),Ml({...o,ran:!0,exitCode:c,..._l,report:J()?"caller-reporter":"off"})}let i=jl.mkdtempSync(Fl.join(cx.tmpdir(),"ik-e2e-report-")),a=Fl.join(i,"report.json");try{let c=await s(n,[oh,...o.playwrightArgs],sh(a));c!==0&&(Ll.exitCode=c);let l=lh(a);return Ml({...o,ran:!0,exitCode:c,...l?{report:"collected",...l}:{..._l,report:"unavailable"}})}finally{jl.rmSync(i,{recursive:!0,force:!0})}},_l={report:"off",summary:null,failures:[],errors:[]},Ml=e=>({content:k(JSON.stringify(e,null,2)),structuredContent:e}),yx={app:E.string(),testsDir:E.string(),target:E.string().describe("The package under test, `<app>/ui` or `<app>/api`."),packageName:E.string(),mode:E.enum(["local","cloud"]).describe("local (default): this worktree\u2019s dev server. cloud (--cloud): the deployed app at env."),baseUrl:E.string().describe("The URL the run was pointed at: the local alias, or the deployed URL."),deployedUrlEnv:E.string().nullable().describe("The target\u2019s variable holding its deployed URL; a cloud run reads it. Null when it declares none."),release:E.string().describe("This worktree\u2019s release slug \u2014 the first label of every local alias."),env:E.string().nullable().describe("INFRA_KIT_ENV of this process; the env a cloud run targets."),servedEnv:E.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:E.string().describe("This worktree\u2019s address for the target, whether or not anything serves it."),served:E.boolean().describe("Whether this worktree\u2019s dev server already served the target when the run began."),devCommand:E.string().nullable().describe("Local runs with nothing served: the dev command the Playwright config starts, and stops after."),routes:E.array(E.object({path:E.string(),packageName:E.string(),source:E.enum(["local","cloud"]),target:E.string().nullable(),live:E.boolean().nullable()})).describe("Served local UI runs only: the dev proxy\u2019s route-by-route local/cloud split, local backends probed."),playwrightArgs:E.array(E.string()),ran:E.boolean().describe("False for --dry-run."),exitCode:E.number().nullable().describe("Playwright\u2019s exit code; null when it did not run."),report:E.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."),summary:E.object({expected:E.number(),unexpected:E.number(),flaky:E.number(),skipped:E.number()}).nullable().describe("Test counts by outcome; null unless report is collected."),failures:E.array(E.object({title:E.string().describe("Describe path and test title, joined with \u203A."),file:E.string(),line:E.number().nullable(),project:E.string(),status:E.enum(["unexpected","flaky"]).describe("flaky: failed, then passed on a retry."),retry:E.number().describe("The retry index of the failed attempt reported here."),error:E.string().nullable().describe("The failure message, ANSI stripped, truncated to 2000 characters."),tracePath:E.string().nullable().describe("The failed attempt\u2019s trace.zip; open with `playwright show-trace`.")})).describe("Every test that failed or needed a retry; empty unless report is collected."),errors:E.array(E.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.")},Bl=S({name:"e2e",description:"Run an app\u2019s Playwright e2e suite against this worktree: the running dev server, or one the package\u2019s infraKitE2e() Playwright config starts and stops. cloud runs against the deployed app at INFRA_KIT_ENV instead, confirm-gated; a protected env (prod) follows protectedEnvs. dryRun reports the target without running.",requiresHumanConfirm:!0,inputSchema:{app:E.string().optional().describe("App folder with an apps/<app>/tests e2e package; inferred from cwd when omitted."),dryRun:E.boolean().optional(),yes:E.boolean().optional(),cloud:E.boolean().optional().describe("Run against the deployed app at INFRA_KIT_ENV instead of this worktree."),playwrightArgs:E.array(E.string()).optional().describe("Passed to `playwright test` verbatim \u2014 a spec path, `--grep <title>`, `--project=chromium`.")},outputSchema:yx,handler:e=>hi(e)});import yi from"node:fs";import Wl from"node:path";import{z as Co}from"zod";var vx=e=>[...e.map(t=>`unset ${t}`),`unset ${Sr}`,`unset ${as}`,`unset ${cs}`,`unset ${Hu}`,`unset ${ls}`],vi=async()=>{let e=Pr(),t=Wl.join(e,Rr);if(!yi.existsSync(t))throw new Error("No loaded environment found. Run `env-load` first.");let r=ds(t),n=vx(r),o=Wl.resolve(e,ss);yi.mkdirSync(e,{recursive:!0,mode:448}),En(o,`${n.join(`
373
381
  `)}
374
- `,384),gi.rmSync(t,{force:!0}),gi.rmSync(Ll.join(e,rs),{force:!0});let s={filePath:o,variableCount:r.length,unsetStatements:n};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}},Bl=S({name:"env-clear",description:'Generate a shell script that unsets every env var previously loaded by env-load for this session, plus the infra-kit session metadata vars. Does NOT mutate the calling process \u2014 returns the path to a script that must be sourced ("source <filePath>") for the vars to go away. The infra-kit shell wrapper auto-sources; direct callers must handle sourcing themselves or surface filePath to the user. Errors if no env is currently loaded.',requiresHumanConfirm:!0,inputSchema:{confirm:Eo.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{filePath:Eo.string().describe("Path to the file that must be sourced to apply"),variableCount:Eo.number().describe("Number of variables cleared"),unsetStatements:Eo.array(Eo.string()).describe("Unset statements generated")},handler:()=>hi()});import px from"node:path";import xo from"node:process";import{z as pn}from"zod";var yi=async()=>{u.info("Environment session status:");let e=Rr(),t=xo.env[bn],r=px.join(e,kr),n=0,o=0,s=xo.env[ns]??null,i=xo.env[os]??null,a=xo.env[ss]??null;if(s){let l=is(r);l.length>0&&(o=l.length,n=l.filter(p=>p in xo.env).length);let d=a?.replace(/\.\d{3}Z$/,"")??null;if(u.info(` ${s}: ${n} of ${o} vars loaded (project: ${i}, loadedAt: ${d}, session: ${t})
382
+ `,384),yi.rmSync(t,{force:!0}),yi.rmSync(Wl.join(e,is),{force:!0});let s={filePath:o,variableCount:r.length,unsetStatements:n};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}},Vl=S({name:"env-clear",description:'Generate a shell script that unsets every env var previously loaded by env-load for this session, plus the infra-kit session metadata vars. Does NOT mutate the calling process \u2014 returns the path to a script that must be sourced ("source <filePath>") for the vars to go away. The infra-kit shell wrapper auto-sources; direct callers must handle sourcing themselves or surface filePath to the user. Errors if no env is currently loaded.',requiresHumanConfirm:!0,inputSchema:{confirm:Co.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{filePath:Co.string().describe("Path to the file that must be sourced to apply"),variableCount:Co.number().describe("Number of variables cleared"),unsetStatements:Co.array(Co.string()).describe("Unset statements generated")},handler:()=>vi()});import wx from"node:path";import $o from"node:process";import{z as gn}from"zod";var wi=async()=>{u.info("Environment session status:");let e=Pr(),t=$o.env[Pn],r=wx.join(e,Rr),n=0,o=0,s=$o.env[as]??null,i=$o.env[cs]??null,a=$o.env[ls]??null;if(s){let l=ds(r);l.length>0&&(o=l.length,n=l.filter(p=>p in $o.env).length);let d=a?.replace(/\.\d{3}Z$/,"")??null;if(u.info(` ${s}: ${n} of ${o} vars loaded (project: ${i}, loadedAt: ${d}, session: ${t})
375
383
  `),o>0&&n<o){let p=o-n;u.warn(` ${p} cached var(s) are not present in the current process \u2014 env-load needs to be re-sourced, or vars were unset manually.`)}}else u.info(` Session ${t}: no env loaded
376
- `);let c={sessionId:t,sessionLoadedCount:n,sessionTotalCount:o,sessionConfig:s,sessionProject:i,sessionLoadedAt:a};return{content:k(JSON.stringify(c,null,2)),structuredContent:c}},Wl=S({name:"env-status",description:"Report which Doppler project/config is currently loaded in the terminal session, when it was loaded, and how many variables are cached. Pure local introspection \u2014 makes NO Doppler call (use doctor for auth). Read-only \u2014 use env-load / env-clear to change the terminal session. Over MCP this reflects the session file as of this call \u2014 the server re-reads it before every tool.",inputSchema:{},outputSchema:{sessionId:pn.string().describe("Current terminal session ID"),sessionLoadedCount:pn.number().describe("Number of cached vars active in the current session"),sessionTotalCount:pn.number().describe("Total number of cached var names"),sessionConfig:pn.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:pn.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:pn.string().nullable().describe("ISO 8601 timestamp of when the env was loaded")},handler:yi});import mx from"node:process";import{z as Dt}from"zod";var ah="****",we=e=>typeof e!="string"||e.length<8?ah:`${ah}${e.slice(-4)}`;var ch=(e,t,r)=>e.map(n=>{let o=r||t[n];return o?{env:n,source:r?`env:${Ht}`:"store",redactedToken:we(o),present:!0}:{env:n,source:"-",redactedToken:"-",present:!1}}),fx=["ENV","SOURCE","TOKEN","PRESENT"],lh=(e,t)=>{let r=[...fx,...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())},vi=async({check:e}={})=>{let t=await Ps(),r=await Be(),n=mx.env[Ht],o=ch(t,r?.envs??{},n);if(e){let a=await Kt();for(let c of o){if(!c.present)continue;let l=n||r.envs[c.env],d=await Zp({childEnv:In(l),project:a,config:c.env});c.status=d.outcome}}for(let a of lh(o,!!e))u.info(a);let s=o.filter(a=>!a.present);s.length>0&&u.info(`
377
- 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}},Vl=S({name:"env-token-list",description:'List the Doppler service tokens configured for this repo: one row per environment declared in infra-kit.json, with its source (the local token store, or the INFRA_KIT_ENV_TOKEN env var) and a REDACTED token (last 4 chars at most \u2014 the raw value is never returned). With check=true, also asks Doppler whether each token is valid and correctly scoped (valid | revoked | mis-scoped | unreachable; "unreachable" means the probe could not tell, NOT that the token is bad). Read-only.',inputSchema:{check:Dt.boolean().optional().describe("Probe Doppler for each token\u2019s validity and scope (one cheap call per environment).")},outputSchema:{tokens:Dt.array(Dt.object({env:Dt.string().describe("Environment / Doppler config name"),source:Dt.string().describe('"store", "env:INFRA_KIT_ENV_TOKEN", or "-" when absent'),redactedToken:Dt.string().describe("Redacted token \u2014 last 4 chars at most, never the raw value"),present:Dt.boolean().describe("Whether a token is configured for this environment"),status:Dt.string().optional().describe("Only with check=true: valid | revoked | mis-scoped | unreachable")})).describe("One row per declared environment")},handler:vi});import{z as b}from"zod";import{$ as gx}from"zx";var hx=(e,t)=>({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0,dryRun:e,atomicPush:{attempted:!1,aborted:!1},results:[],skipped:t}),yx=e=>e.dualBase?"open PRs to both dev and main":e.titleMismatch?"title/base mismatch":e.type==="hotfix"?"hotfix (targets main)":null,vx=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(", ")},Jl=e=>({content:k(JSON.stringify(e,null,2)),structuredContent:e}),Ul=new Set(["up-to-date","fast-forward","merged"]),wx=(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=ve(pe(a))}catch(l){throw new f(l,{operation:`resolve release selector "${a}"`,remediation:`pass one of: ${t.join(", ")}`})}if(!o.has(c)){let l=s.get(c);throw new f(void 0,{operation:`select release branch for "${a}"`,stderrExcerpt:l?`${c} is skipped: ${l}`:`${c} is not an open regular release branch`,remediation:`pass one of: ${t.join(", ")}`})}i.add(c)}return t.filter(a=>i.has(a))},kx={"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"},uh=e=>{let t=kx[e.status];if(e.status==="conflict"){let r=e.conflictPaths?.length??0;return`${t}: ${r} file(s)`}return e.reason?`${t}: ${e.reason}`:t},bx=(e,t)=>{u.info(`
378
- \u{1F4CB} Merge plan:`);for(let r of e)u.info(` ${r.branch} \u2014 ${uh(r)}`);for(let r of t)u.info(` ${r.branch} \u2014 skipped: ${r.reason}`)},Rx=(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`},Sx=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=G(i.branch);return a?[[re(a),uh(i)]]:[]}));return Ct(ie({branches:r,descriptions:s}),{required:!0})},Px=async e=>{let{cwd:t,worktreePath:r,entries:n,selected:o,verify:s}=e,i=n.filter(y=>o.includes(y.branch)),a=y=>{for(let R of y)u.info(`\u2139\uFE0F ${R} was merged by someone else while we planned \u2014 dropping it from the push`)},c=await ao(t,Cf(i));a(c.nowUpToDate);let l=c.kept,d=new Map;if(s&&l.length>0){u.info(`
379
- \u{1F50E} Verifying ${l.length} merge(s) with: ${s}`);let y=await Af({worktreePath:r,refs:l,command:s});d=y.failed;for(let[w,$]of y.failed)u.info(`\u2717 ${w} failed verification \u2014 not pushing it. ${$.split(`
380
- `)[0]??""}`);let R=await ao(t,y.kept);a(R.nowUpToDate),l=R.kept}if(l.length===0)return{pushed:!1,pushAborted:!1,verifyFailed:d};u.info(`
381
- \u2B06\uFE0F Pushing atomically: ${l.map(y=>y.branch).join(", ")}`);let p=await hs(t,l);if(p.pushed)return{pushed:!0,pushAborted:!1,verifyFailed:d};let g=(await Promise.all(l.map(async y=>({branch:y.branch,landed:await Er(t,y.branch)===y.sha})))).filter(y=>y.landed);return g.length>0&&u.warn(`\u26A0\uFE0F The push reported failure, but origin already carries ${g.map(y=>y.branch).join(", ")} \u2014 re-run to reconcile.`),{pushed:!1,pushAborted:!0,abortedBy:p.stderr?.split(`
382
- `)[0],observedLanded:g.map(y=>y.branch)}},Ex=e=>{let t=["keepConflicts","continue","abort"].filter(n=>e[n]),r={keepConflicts:"--keep-conflicts",continue:"--continue",abort:"--abort"};if(t.length>1||t.length===1&&e.dryRun){let n=[...t.map(o=>r[o]),...e.dryRun?["--dry-run"]:[]];throw new f(void 0,{operation:"choose the merge-dev mode",stderrExcerpt:`${n.join(" and ")} cannot be combined`,remediation:"pass at most one of --keep-conflicts, --continue, --abort; --dry-run only on a plain run"})}if(e.tree!==void 0&&!e.continue)throw new f(void 0,{operation:"choose the merge-dev mode",stderrExcerpt:"--tree belongs to --continue",remediation:"run the rerun a --continue preview printed, unchanged"})},dh=e=>{let{results:t,atomicPush:r,declined:n}=e;for(let i of t){let a=i.reason?.split(`
383
- `)[0];u.info(a?` ${i.branch} \u2014 ${i.status}: ${a}`:` ${i.branch} \u2014 ${i.status}`)}let o=n?[]:t.filter(i=>i.status!=="aborted"),s=o.filter(i=>!Ul.has(i.status));return Jl({successfulMerges:o.length-s.length,failedMerges:s.length,failedBranches:s.map(i=>i.branch),totalBranches:t.length,dryRun:!1,atomicPush:r,results:t,skipped:[]})},xx=async e=>{let{all:t,versions:r,verify:n,confirmedCommand:o}=e,s=await Le();if(e.abort)return dh(await eg({cwd:s,versions:r,all:t,confirmedCommand:o}));let i=typeof n=="string"&&n.length>0?n:void 0;return dh(await Zf({cwd:s,versions:r,all:t,verify:i,trees:Qf(e.tree),confirmedCommand:o}))},wi=async e=>{let{all:t,versions:r,dryRun:n=!1,verify:o,keepConflicts:s=!1,confirmedCommand:i}=e;Ex(e);let a=o===!0?$f:o||void 0;if(await Oc({operation:"merge dev into release branches"}),e.continue||e.abort)return xx(e);let c=[],l=[];for(let te of await F()){let Ut=yx(te);Ut?l.push({branch:te.branch,reason:Ut}):c.push(te.branch)}if(c.length===0)return u.info(l.length===0?"\u2139\uFE0F No open release branches found":`\u2139\uFE0F No open regular release branches \u2014 ${l.length} skipped (${vx(l)})`),h.print(),Jl(hx(n,l));let d=await Le();try{await gx({cwd:d,quiet:!0})`git fetch origin --prune`}catch(te){throw new f(te,{operation:"fetch origin before planning the merges",remediation:"check network access and that `origin` is reachable"})}let p=r===void 0?c:wx(r,c,l),m=await Cp({cwd:d},async te=>{let Ut=qs(te.remove);try{return await Tx({cwd:d,worktree:te,toPlan:p,candidates:c,skipped:l,all:t,versions:r,dryRun:n,verify:a,keepConflicts:s,confirmedCommand:i})}finally{Ut()}}),{entries:g,selected:y,pushed:R,pushAborted:w,abortedBy:$,declined:B,verifyFailed:I,handOffs:P}=m,le=await gt(d).catch(()=>[]);return Ax({entries:g,selected:y,pushed:R,pushAborted:w,abortedBy:$,declined:B,verifyFailed:I,handOffs:P,dryRun:n,worktrees:le,skipped:l})},Tx=async e=>{let{cwd:t,worktree:r,toPlan:n,candidates:o,skipped:s,all:i,versions:a,dryRun:c,verify:l,keepConflicts:d,confirmedCommand:p}=e,m=d?await $e(t,"origin/dev"):null,g=await Tf({cwd:t,worktreePath:r.path,branches:n}),y={entries:g,pushed:!1,pushAborted:!1,declined:!1};if(bx(g,s),c)return{...y,selected:n};let R=await Sx({entries:g,toPlan:n,all:i,explicit:a!==void 0});R.length===o.length?h.addOption("--all",!0):h.addOption("--versions",R);let w=g.filter(P=>R.includes(P.branch)&&P.mergeSha).length;w>0&&u.info(`
384
- \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 V(p,`Are you sure you want to merge dev into these branches: ${R.join(", ")}?`,{throwOnDecline:!0,plan:Cx(g,R,s)})}catch(P){if(!ot(P))throw P;return{...y,selected:R,declined:!0}}p||h.addOption("--yes",!0);let $=await Px({cwd:t,worktreePath:r.path,entries:g,selected:R,verify:l}),B=g.filter(P=>R.includes(P.branch)&&P.status==="conflict").map(P=>P.branch),I=d&&m&&B.length>0?await Yf({cwd:t,branches:B,devSha:m}):void 0;return{entries:g,selected:R,declined:!1,...$,handOffs:I}},Cx=(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:Kc(n.conflictPaths)}:{},...n.reason?{reason:n.reason}:{}})),skipped:r}),$x=(e,t)=>e.resolution?`# ${e.branch} \u2014 ${e.status}, left to resolve in ${e.resolution.worktreePath} (then --continue)
384
+ `);let c={sessionId:t,sessionLoadedCount:n,sessionTotalCount:o,sessionConfig:s,sessionProject:i,sessionLoadedAt:a};return{content:k(JSON.stringify(c,null,2)),structuredContent:c}},Ul=S({name:"env-status",description:"Report which Doppler project/config is currently loaded in the terminal session, when it was loaded, and how many variables are cached. Pure local introspection \u2014 makes NO Doppler call (use doctor for auth). Read-only \u2014 use env-load / env-clear to change the terminal session. Over MCP this reflects the session file as of this call \u2014 the server re-reads it before every tool.",inputSchema:{},outputSchema:{sessionId:gn.string().describe("Current terminal session ID"),sessionLoadedCount:gn.number().describe("Number of cached vars active in the current session"),sessionTotalCount:gn.number().describe("Total number of cached var names"),sessionConfig:gn.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:gn.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:gn.string().nullable().describe("ISO 8601 timestamp of when the env was loaded")},handler:wi});import kx from"node:process";import{z as Mt}from"zod";var uh="****",we=e=>typeof e!="string"||e.length<8?uh:`${uh}${e.slice(-4)}`;var ph=(e,t,r)=>e.map(n=>{let o=r||t[n];return o?{env:n,source:r?`env:${Yt}`:"store",redactedToken:we(o),present:!0}:{env:n,source:"-",redactedToken:"-",present:!1}}),bx=["ENV","SOURCE","TOKEN","PRESENT"],mh=(e,t)=>{let r=[...bx,...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())},ki=async({check:e}={})=>{let t=await xs(),r=await Ve(),n=kx.env[Yt],o=ph(t,r?.envs??{},n);if(e){let a=await qt();for(let c of o){if(!c.present)continue;let l=n||r.envs[c.env],d=await tm({childEnv:_n(l),project:a,config:c.env});c.status=d.outcome}}for(let a of mh(o,!!e))u.info(a);let s=o.filter(a=>!a.present);s.length>0&&u.info(`
385
+ 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}},Jl=S({name:"env-token-list",description:'List the Doppler service tokens configured for this repo: one row per environment declared in infra-kit.json, with its source (the local token store, or the INFRA_KIT_ENV_TOKEN env var) and a REDACTED token (last 4 chars at most \u2014 the raw value is never returned). With check=true, also asks Doppler whether each token is valid and correctly scoped (valid | revoked | mis-scoped | unreachable; "unreachable" means the probe could not tell, NOT that the token is bad). Read-only.',inputSchema:{check:Mt.boolean().optional().describe("Probe Doppler for each token\u2019s validity and scope (one cheap call per environment).")},outputSchema:{tokens:Mt.array(Mt.object({env:Mt.string().describe("Environment / Doppler config name"),source:Mt.string().describe('"store", "env:INFRA_KIT_ENV_TOKEN", or "-" when absent'),redactedToken:Mt.string().describe("Redacted token \u2014 last 4 chars at most, never the raw value"),present:Mt.boolean().describe("Whether a token is configured for this environment"),status:Mt.string().optional().describe("Only with check=true: valid | revoked | mis-scoped | unreachable")})).describe("One row per declared environment")},handler:ki});import{z as b}from"zod";import{$ as Rx}from"zx";var Sx=(e,t)=>({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0,dryRun:e,atomicPush:{attempted:!1,aborted:!1},results:[],skipped:t}),Px=e=>e.dualBase?"open PRs to both dev and main":e.titleMismatch?"title/base mismatch":e.type==="hotfix"?"hotfix (targets main)":null,Ex=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(", ")},Kl=e=>({content:k(JSON.stringify(e,null,2)),structuredContent:e}),Gl=new Set(["up-to-date","fast-forward","merged"]),xx=(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=ve(me(a))}catch(l){throw new f(l,{operation:`resolve release selector "${a}"`,remediation:`pass one of: ${t.join(", ")}`})}if(!o.has(c)){let l=s.get(c);throw new f(void 0,{operation:`select release branch for "${a}"`,stderrExcerpt:l?`${c} is skipped: ${l}`:`${c} is not an open regular release branch`,remediation:`pass one of: ${t.join(", ")}`})}i.add(c)}return t.filter(a=>i.has(a))},Tx={"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"},gh=e=>{let t=Tx[e.status];if(e.status==="conflict"){let r=e.conflictPaths?.length??0;return`${t}: ${r} file(s)`}return e.reason?`${t}: ${e.reason}`:t},Cx=(e,t)=>{u.info(`
386
+ \u{1F4CB} Merge plan:`);for(let r of e)u.info(` ${r.branch} \u2014 ${gh(r)}`);for(let r of t)u.info(` ${r.branch} \u2014 skipped: ${r.reason}`)},$x=(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`},Ax=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=G(i.branch);return a?[[re(a),gh(i)]]:[]}));return Ot(ie({branches:r,descriptions:s}),{required:!0})},Ox=async e=>{let{cwd:t,worktreePath:r,entries:n,selected:o,verify:s}=e,i=n.filter(y=>o.includes(y.branch)),a=y=>{for(let R of y)u.info(`\u2139\uFE0F ${R} was merged by someone else while we planned \u2014 dropping it from the push`)},c=await uo(t,If(i));a(c.nowUpToDate);let l=c.kept,d=new Map;if(s&&l.length>0){u.info(`
387
+ \u{1F50E} Verifying ${l.length} merge(s) with: ${s}`);let y=await Nf({worktreePath:r,refs:l,command:s});d=y.failed;for(let[w,x]of y.failed)u.info(`\u2717 ${w} failed verification \u2014 not pushing it. ${x.split(`
388
+ `)[0]??""}`);let R=await uo(t,y.kept);a(R.nowUpToDate),l=R.kept}if(l.length===0)return{pushed:!1,pushAborted:!1,verifyFailed:d};u.info(`
389
+ \u2B06\uFE0F Pushing atomically: ${l.map(y=>y.branch).join(", ")}`);let p=await ws(t,l);if(p.pushed)return{pushed:!0,pushAborted:!1,verifyFailed:d};let g=(await Promise.all(l.map(async y=>({branch:y.branch,landed:await Cr(t,y.branch)===y.sha})))).filter(y=>y.landed);return g.length>0&&u.warn(`\u26A0\uFE0F The push reported failure, but origin already carries ${g.map(y=>y.branch).join(", ")} \u2014 re-run to reconcile.`),{pushed:!1,pushAborted:!0,abortedBy:p.stderr?.split(`
390
+ `)[0],observedLanded:g.map(y=>y.branch)}},Ix=e=>{let t=["keepConflicts","continue","abort"].filter(n=>e[n]),r={keepConflicts:"--keep-conflicts",continue:"--continue",abort:"--abort"};if(t.length>1||t.length===1&&e.dryRun){let n=[...t.map(o=>r[o]),...e.dryRun?["--dry-run"]:[]];throw new f(void 0,{operation:"choose the merge-dev mode",stderrExcerpt:`${n.join(" and ")} cannot be combined`,remediation:"pass at most one of --keep-conflicts, --continue, --abort; --dry-run only on a plain run"})}if(e.tree!==void 0&&!e.continue)throw new f(void 0,{operation:"choose the merge-dev mode",stderrExcerpt:"--tree belongs to --continue",remediation:"run the rerun a --continue preview printed, unchanged"})},fh=e=>{let{results:t,atomicPush:r,declined:n}=e;for(let i of t){let a=i.reason?.split(`
391
+ `)[0];u.info(a?` ${i.branch} \u2014 ${i.status}: ${a}`:` ${i.branch} \u2014 ${i.status}`)}let o=n?[]:t.filter(i=>i.status!=="aborted"),s=o.filter(i=>!Gl.has(i.status));return Kl({successfulMerges:o.length-s.length,failedMerges:s.length,failedBranches:s.map(i=>i.branch),totalBranches:t.length,dryRun:!1,atomicPush:r,results:t,skipped:[]})},Dx=async e=>{let{all:t,versions:r,verify:n,confirmedCommand:o}=e,s=await be();if(e.abort)return fh(await og({cwd:s,versions:r,all:t,confirmedCommand:o}));let i=typeof n=="string"&&n.length>0?n:void 0;return fh(await rg({cwd:s,versions:r,all:t,verify:i,trees:ng(e.tree),confirmedCommand:o}))},bi=async e=>{let{all:t,versions:r,dryRun:n=!1,verify:o,keepConflicts:s=!1,confirmedCommand:i}=e;Ix(e);let a=o===!0?Df:o||void 0;if(await Dc({operation:"merge dev into release branches"}),e.continue||e.abort)return Dx(e);let c=[],l=[];for(let te of await F()){let Gt=Px(te);Gt?l.push({branch:te.branch,reason:Gt}):c.push(te.branch)}if(c.length===0)return u.info(l.length===0?"\u2139\uFE0F No open release branches found":`\u2139\uFE0F No open regular release branches \u2014 ${l.length} skipped (${Ex(l)})`),h.print(),Kl(Sx(n,l));let d=await be();try{await Rx({cwd:d,quiet:!0})`git fetch origin --prune`}catch(te){throw new f(te,{operation:"fetch origin before planning the merges",remediation:"check network access and that `origin` is reachable"})}let p=r===void 0?c:xx(r,c,l),m=await Op({cwd:d},async te=>{let Gt=zs(te.remove);try{return await Nx({cwd:d,worktree:te,toPlan:p,candidates:c,skipped:l,all:t,versions:r,dryRun:n,verify:a,keepConflicts:s,confirmedCommand:i})}finally{Gt()}}),{entries:g,selected:y,pushed:R,pushAborted:w,abortedBy:x,declined:W,verifyFailed:I,handOffs:P}=m,le=await Ke(d).catch(()=>[]);return jx({entries:g,selected:y,pushed:R,pushAborted:w,abortedBy:x,declined:W,verifyFailed:I,handOffs:P,dryRun:n,worktrees:le,skipped:l})},Nx=async e=>{let{cwd:t,worktree:r,toPlan:n,candidates:o,skipped:s,all:i,versions:a,dryRun:c,verify:l,keepConflicts:d,confirmedCommand:p}=e,m=d?await Oe(t,"origin/dev"):null,g=await Of({cwd:t,worktreePath:r.path,branches:n}),y={entries:g,pushed:!1,pushAborted:!1,declined:!1};if(Cx(g,s),c)return{...y,selected:n};let R=await Ax({entries:g,toPlan:n,all:i,explicit:a!==void 0});R.length===o.length?h.addOption("--all",!0):h.addOption("--versions",R);let w=g.filter(P=>R.includes(P.branch)&&P.mergeSha).length;w>0&&u.info(`
392
+ \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 B(p,`Are you sure you want to merge dev into these branches: ${R.join(", ")}?`,{throwOnDecline:!0,plan:_x(g,R,s)})}catch(P){if(!at(P))throw P;return{...y,selected:R,declined:!0}}p||h.addOption("--yes",!0);let x=await Ox({cwd:t,worktreePath:r.path,entries:g,selected:R,verify:l}),W=g.filter(P=>R.includes(P.branch)&&P.status==="conflict").map(P=>P.branch),I=d&&m&&W.length>0?await Qf({cwd:t,branches:W,devSha:m}):void 0;return{entries:g,selected:R,declined:!1,...x,handOffs:I}},_x=(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:qc(n.conflictPaths)}:{},...n.reason?{reason:n.reason}:{}})),skipped:r}),Mx=(e,t)=>e.resolution?`# ${e.branch} \u2014 ${e.status}, left to resolve in ${e.resolution.worktreePath} (then --continue)
385
393
  `:`# ${e.branch} \u2014 ${e.status}
386
- ${Rx(e.branch,t)}
387
- `,Ax=e=>{let{entries:t,selected:r,pushed:n,pushAborted:o,abortedBy:s,declined:i,dryRun:a,worktrees:c,verifyFailed:l,handOffs:d,skipped:p}=e,m=new Set(n?t.filter(w=>r.includes(w.branch)&&w.mergeSha&&!l?.has(w.branch)).map(w=>w.branch):[]),g=t.filter(w=>r.includes(w.branch)).map(w=>{let $=!!w.mergeSha,B=e.verifyFailed?.get(w.branch),I=o&&$?"push-aborted":w.status,P=B?"verify-failed":I,le=d?.get(w.branch);return{branch:w.branch,status:P,mergeSha:w.mergeSha,conflictPaths:w.conflictPaths,pushed:m.has(w.branch),reason:B??le?.reason??w.reason,...le?.resolution?{resolution:le.resolution}:{}}}),y=g.filter(w=>!Ul.has(w.status));for(let w of g){let $=t.find(B=>B.branch===w.branch);u.info({branch:w.branch,status:w.status,mergeSha:w.mergeSha,conflictCount:w.conflictPaths?.length??0,durationMs:$?.durationMs,pushed:w.pushed,msg:"merge-dev branch result"})}if(i||a)u.info(i?`
394
+ ${$x(e.branch,t)}
395
+ `,jx=e=>{let{entries:t,selected:r,pushed:n,pushAborted:o,abortedBy:s,declined:i,dryRun:a,worktrees:c,verifyFailed:l,handOffs:d,skipped:p}=e,m=new Set(n?t.filter(w=>r.includes(w.branch)&&w.mergeSha&&!l?.has(w.branch)).map(w=>w.branch):[]),g=t.filter(w=>r.includes(w.branch)).map(w=>{let x=!!w.mergeSha,W=e.verifyFailed?.get(w.branch),I=o&&x?"push-aborted":w.status,P=W?"verify-failed":I,le=d?.get(w.branch);return{branch:w.branch,status:P,mergeSha:w.mergeSha,conflictPaths:w.conflictPaths,pushed:m.has(w.branch),reason:W??le?.reason??w.reason,...le?.resolution?{resolution:le.resolution}:{}}}),y=g.filter(w=>!Gl.has(w.status));for(let w of g){let x=t.find(W=>W.branch===w.branch);u.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)u.info(i?`
388
396
  Operation cancelled \u2014 nothing was pushed.
389
397
  `:`
390
398
  \u{1F50D} Dry run \u2014 nothing was pushed.
391
399
  `);else if(y.length>0){u.info(`
392
400
  \u26A0\uFE0F ${y.length} branch(es) did not merge.
393
- `);for(let w of y)u.info($x(w,c))}else u.info(`\u2705 All merges completed successfully!
394
- `);h.print();let R=a||i;return Jl({successfulMerges:R?0:g.filter(w=>Ul.has(w.status)).length,failedMerges:R?0:y.length,failedBranches:R?[]:y.map(w=>w.branch),totalBranches:g.length,dryRun:a,atomicPush:{attempted:!a&&!i,aborted:o,abortedBy:s},results:g.map(w=>R?{...w,pushed:!1}:w),skipped:p})},Gl=S({name:"gh-merge-dev",description:"Merge origin/dev into open regular release branches and push them in one atomic push. A release PR is classified by its base branch, not its title: a PR to main is a hotfix and is skipped, as is any row whose title disagrees with its base or whose head has open PRs to both dev and main \u2014 every skipped row is reported in `skipped` with its reason. Merges happen in a disposable scratch worktree, so no existing checkout is touched and the branches may be checked out elsewhere. When invoked via MCP, pass all=true or an explicit versions list \u2014 the branch picker is unreachable without a TTY, and the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. Irreversible once pushed.",requiresHumanConfirm:!0,inputSchema:{all:b.boolean().optional().describe("Target every open regular release branch. Must be true for MCP calls unless `versions` is supplied (the interactive picker is unavailable without a TTY)."),versions:b.union([b.string(),b.array(b.string())]).optional().describe('Target a subset of the open regular release branches. Each entry may be a version label ("1.2.5") or a raw branch name ("release/v1.2.5"). A selector that is not an open regular release is an error; one that names a skipped row (hotfix, title/base mismatch, dual-base) quotes that reason. Takes precedence over `all`.'),dryRun:b.boolean().optional().describe("Compute and print the merge plan without pushing anything."),verify:b.union([b.boolean(),b.string()]).optional().describe("Check each merge before pushing it. `true` runs `pnpm install --frozen-lockfile` \u2014 which catches the characteristic dev\u2192release failure, a pnpm-lock.yaml whose text merge is clean but whose result is broken. A string runs that command instead. A branch that fails verification is dropped from the push; nothing is ever rolled back, because verification runs pre-push. Under `continue`, a string runs after the mandatory `pnpm install --frozen-lockfile --ignore-scripts`."),keepConflicts:b.boolean().optional().describe("On the confirmed run, after the clean branches are pushed, leave each conflicted branch mid-merge in a detached worktree under `<root>-worktrees/merge-dev/` for resolution. Excludes `continue`, `abort` and `dryRun`."),continue:b.boolean().optional().describe("Check the selected resolutions (only conflicted paths edited, no markers, install passes), preview them, and on confirmation commit exactly the previewed tree and push atomically. Excludes `keepConflicts`, `abort` and `dryRun`."),abort:b.boolean().optional().describe("Discard the selected resolution worktrees and their state. Excludes `keepConflicts`, `continue` and `dryRun`."),tree:b.union([b.string(),b.array(b.string())]).optional().describe("With `continue` and confirmation: `<branch>=<treeSha>`, comma-separated or repeated \u2014 the trees the human approved in the `continue` preview. Pass the preview `rerun` unchanged; a branch whose resolved tree differs is reported `tree-changed` and not committed."),confirm:b.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{successfulMerges:b.number().describe("Number of branches that reached their desired state"),failedMerges:b.number().describe("Number of branches that did not"),failedBranches:b.array(b.string()).describe("List of branches that did not merge"),totalBranches:b.number().describe("Total number of branches processed"),dryRun:b.boolean().describe("True when nothing was pushed because this was a plan-only run"),atomicPush:b.object({attempted:b.boolean(),aborted:b.boolean(),abortedBy:b.string().optional()}).describe("Outcome of the single all-or-nothing push"),results:b.array(b.object({branch:b.string(),status:b.string(),mergeSha:b.string().optional(),conflictPaths:b.array(b.string()).optional(),pushed:b.boolean(),reason:b.string().optional(),resolution:b.object({worktreePath:b.string(),baseSha:b.string(),devSha:b.string(),conflictPaths:b.array(b.string()),lockfileOnly:b.boolean(),rererePreResolved:b.array(b.string()),state:b.enum(["needs-agent","lockfile-only","exists"])}).optional().describe("The `keepConflicts` hand-off for a conflicted branch"),blocked:b.object({code:b.enum(["unmerged-paths","markers-remaining","out-of-scope-edit","verify-failed","verify-mutated-tree","parents-mismatch","git-too-old","tree-changed"]),paths:b.array(b.string()).optional(),detail:b.string()}).optional().describe("Why a `continue` run did not commit this resolution")})).describe("Per-branch terminal state"),skipped:b.array(b.object({branch:b.string(),reason:b.enum(["hotfix (targets main)","title/base mismatch","open PRs to both dev and main"])})).describe("Every discovered release PR that was not a merge candidate, with why. Empty only when nothing was discovered.")},handler:wi});import{z as Ao}from"zod";import{$ as _e}from"zx";var ph=(e,t)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-t).trim()},Nt=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=ph(t.stderr,500);o&&(r.stderr=o);let s=ph(t.stdout,200);return s&&(r.stdout=s),r};var To=e=>{let{removed:t,failed:r}=e;if(t.length>0){u.info("\u274C Removed worktrees:");for(let n of t)u.info(n);u.info("")}if(r.length>0){u.warn("\u26A0\uFE0F Not removed:");for(let{branch:n,reason:o}of r)u.warn(`${n} \u2014 ${o}`);u.warn("")}t.length===0&&r.length===0&&u.info("\u2139\uFE0F No worktrees to remove")};var Co=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 ye()?new x({status:"partial_failure",...n},1,s):new f(void 0,s)};import bi from"node:fs/promises";import{$ as hh}from"zx";var Ox=new Set([".omc",".DS_Store"]),Ix=new Set(["state","sessions"]),Dx=2e3,Nx="check 'git worktree list' for the path; uncommitted changes block removal",_x=e=>new Promise(t=>{setTimeout(t,e)}),Kl=e=>typeof e=="object"&&e!==null?e.code:void 0,mh=e=>{let t=e.length;for(;t>1&&e[t-1]==="/";)t-=1;return e.slice(0,t)},fh=async e=>{try{return mh(await bi.realpath(e))}catch{return mh(e)}},Mx=async e=>{let{projectRoot:t,worktreePath:r}=e;try{let n=await gt(t),o=await fh(r);for(let s of n)if(await fh(s.path)===o)return!0;return!1}catch{return!0}},jx=async e=>{let t;try{t=await bi.readdir(e)}catch(n){return{kind:Kl(n)==="ENOENT"?"gone":"not-sweepable",entries:[]}}if(!t.every(n=>Ox.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=>Ix.has(s))?"sweepable":"not-sweepable",entries:t}}catch(n){return{kind:Kl(n)==="ENOENT"?"sweepable":"not-sweepable",entries:t}}},gh=async e=>{try{return await bi.rm(e,{recursive:!0,force:!0}),"removed"}catch(t){return Kl(t)==="ENOTEMPTY"?"busy":"failed"}},Fx=async e=>{let{worktreePath:t,sleep:r}=e,n=await gh(t);return n!=="busy"?n==="removed":(await r(Dx),await gh(t)==="removed")},ki=(e,t,r)=>{let n=new f(t,{operation:`remove worktree for ${e}`,remediation:r});return u.error({error:t,branch:e,msg:n.message}),{branch:e,status:"failed",reason:n.message}},Lx=async e=>{let{branch:t,worktreePath:r,projectRoot:n,error:o,sleep:s}=e;if(await Mx({projectRoot:n,worktreePath:r}))return ki(t,o,Nx);let i=await jx(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 Fx({worktreePath:r,sleep:s})?ki(t,o,a):(u.warn(`\u26A0\uFE0F swept leftover ${i.entries.join(", ")} from ${r}: a post-exit hook (e.g. oh-my-claudecode SessionEnd) wrote into the worktree while git was deleting it; set OMC_STATE_DIR to keep tool state out of worktrees`),{branch:t,status:"removed"})},Bx=async e=>{let{branch:t,worktreeDir:r,projectRoot:n,orcaProbe:o,sleep:s}=e,i=`${r}/${t}`,a=await rm(i,o);if(!a.closed&&"error"in a)return ki(t,a.error,"close the Orca terminals of this worktree manually (orca terminal close --terminal <handle>) and re-run");try{return await hh`git worktree remove ${i}`,{branch:t,status:"removed"}}catch(c){return Lx({branch:t,worktreePath:i,projectRoot:n,error:c,sleep:s})}},mr=async e=>{let{branches:t,worktreeDir:r,projectRoot:n,pruneFolder:o=!1,sleep:s=_x}=e,i=t.length>0?await xr():"unreachable",a=await Promise.all(t.map(l=>Bx({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 hh`git worktree prune`,c};var $o=async(e,t)=>{if(!(await me("release")).includes(e))return[];let n=await T(),o=`${n}${ge}`,{removed:s,failed:i}=await mr({branches:[e],worktreeDir:o,projectRoot:n});if(!s.includes(e)){let a=i.find(c=>c.branch===e);throw new f(void 0,{...t,stderrExcerpt:a?.reason})}return s};var mn=async(e,t,r)=>{try{return await r()}catch(n){throw u.debug({err:Nt(n)},`Failed to ${e}`),new f(n,{operation:e,remediation:t})}},Wx=async e=>{let t=ya(e),r=await _e`gh pr list --head dev --base main --state merged --json number,state,title,baseRefName,headRefName --limit 20`;return JSON.parse(r.stdout).find(s=>s.title===t)??null},yh=async()=>{let e=await _e`gh pr list --head dev --base main --state open --json number,state,title,baseRefName,headRefName --limit 5`;return JSON.parse(e.stdout)[0]??null},Vx=async e=>{let t=lt(e),r=await Nc(t);if(r.length>1){let s=r.map(i=>`#${i.number} \u2192 ${i.baseRefName}`).join(", ");throw new f(void 0,{operation:`deliver release ${t}`,remediation:`the branch has open PRs to both dev and main (${s}); close the one that should not be delivered`})}let n=r[0]??await Ur(t);if(!n)throw u.error(`\u274C No PR found for branch ${t}.`),new f(void 0,{operation:`deliver release ${t}`,remediation:`confirm a PR exists ('gh pr list --head ${t} --state all')`});let o=to(n.baseRefName);if(!o)throw new f(void 0,{operation:`deliver release ${t}`,remediation:`PR #${n.number} targets '${n.baseRefName}', which is neither dev nor main; retarget it ('gh pr edit ${n.number} --base <dev|main>')`});return{selectedReleaseBranch:t,releaseType:o,prNumber:n.number}},Ux=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 se(),o=await Tt(ie({branches:t,descriptions:n,types:r})),s=e.find(i=>i.branch===o);if(!s)throw u.error(`\u274C Release branch ${o} not found in open PRs.`),new f(void 0,{operation:`deliver release ${o}`,remediation:`confirm an open PR exists for ${o} ('gh pr list')`});if(s.dualBase)throw new f(void 0,{operation:`deliver release ${o}`,remediation:"the branch has open PRs to both dev and main; close the one that should not be delivered"});return{selectedReleaseBranch:o,releaseType:s.type,prNumber:s.number}},Jx=async e=>{let{selectedReleaseBranch:t,releaseType:r,prNumber:n}=e,o=Xe(r),s=await _c(n);if(s.state==="MERGED"){u.info(`\u2713 Release PR ${t} already merged \u2014 skipping`);return}if(s.state==="CLOSED")throw new f(void 0,{operation:`merge release PR ${t} into ${o}`,remediation:"the PR is closed without merge; reopen it or create a new release"});if(s.baseRefName!==o||s.headRefName!==t)throw new f(void 0,{operation:`merge release PR #${n} ${t} into ${o}`,remediation:`PR #${n} now reads ${s.headRefName} \u2192 ${s.baseRefName}; it changed since it was resolved \u2014 re-run the command`});await mn(`merge release PR #${n} ${t} into ${o}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await _e`gh pr merge ${n} --squash --admin --delete-branch`})},Gx=async e=>{let t=X(e),r=ya(e),n=await yh();if(n){let s=n.number;return n.title!==r&&(u.info(`Adopting open dev \u2192 main PR #${s} ("${n.title}") and retitling for ${t}`),await mn(`retitle dev \u2192 main PR #${s} to "${r}"`,`update manually: gh pr edit ${s} --title "${r}"`,async()=>{await _e`gh pr edit ${s} --title ${r}`})),s}await mn(`create RC PR (dev \u2192 main) for ${t}`,"run 'gh pr create --base main --head dev' manually to surface the underlying error (e.g. no commits between dev and main)",async()=>{await _e`gh pr create --base main --head dev --title ${r} --body ""`});let o=await yh();if(!o)throw new f(void 0,{operation:`look up RC PR for ${t}`,remediation:"verify the RC PR was created ('gh pr list --head dev --base main')"});return o.number},Kx=async e=>{let t=X(e);if(await Wx(e)){u.info(`\u2713 RC PR for ${t} already merged into main \u2014 skipping`);return}let n=await Gx(e);await mn(`merge RC PR #${n} (dev \u2192 main) for ${t}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await _e`gh pr merge ${n} --squash --admin`})},Hx=async()=>{_e.quiet=!1,await mn("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await _e`gh workflow run deploy-all.yml --ref main -f environment=prod`}),_e.quiet=!0},qx=async()=>{await mn("sync main back into dev","run manually: git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push",async()=>{await _e`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},Yx=async e=>{try{await fs(e)}catch(t){u.warn({err:Nt(t)},`Failed to delete local branch ${e} (non-blocking)`)}try{await gs(e)}catch(t){u.warn({err:Nt(t)},`Failed to delete remote branch ${e} (non-blocking)`)}},zx=async e=>{let t=await ct();if(!t){u.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let r=re(e);await jc({versionName:r},t)}catch(r){let n=no(r)&&r.kind==="auth"?" \u2014 reissue the Atlassian API token and update JIRA_TOKEN":"";u.error({err:Nt(r)},`Failed to deliver Jira release (non-blocking)${n}`)}},Ri=async e=>{let{version:t,confirmedCommand:r}=e;await Pe({operation:"deliver release"});let{selectedReleaseBranch:n,releaseType:o,prNumber:s}=t?await Vx(t):await Ux(),i=G(n);if(!i)throw new f(void 0,{operation:`deliver release ${n}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let a=X(i);if(h.addOption("--version",a),u.info(`Delivering ${i.kind==="name"?"named release":"version"} ${n}`),ye())throw new x({status:"refused",agentMode:N.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 V(r,`Are you sure you want to deliver version ${n} to production?`),h.addOption("--yes",!0),_e.quiet=!0;let l=`${await T()}${ge}`;await $o(n,{operation:`remove worktree for ${n} before merge`,remediation:`run manually: git worktree remove ${l}/${n} (use --force if uncommitted changes)`}),await Jx({selectedReleaseBranch:n,releaseType:o,prNumber:s}),o!=="hotfix"&&await Kx(i),await Hx(),await qx(),await Yx(n),_e.quiet=!1,await zx(i),u.info(`Successfully delivered ${n} to production!`),h.print();let d={releaseBranch:n,version:a,type:o,success:!0};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}},Hl=S({name:"gh-release-deliver",description:'Deliver a release to production. For hotfixes: squash-merges the release branch to main and dispatches the deploy-all workflow. For regular releases: squash-merges to dev, opens an RC PR, merges dev into main, dispatches the deploy-all workflow, then syncs main back to dev. Also releases the matching Jira fix version if Jira is configured. Dispatches the deploy workflow fire-and-forget \u2014 the tool returns once the workflow is accepted by GitHub, not when the deployment finishes. PR-merge steps are idempotent: re-running after a partial failure skips PRs that are already merged. Irreversible production operation: the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. "version" is required when invoked via MCP (the picker is unreachable without a TTY).',requiresHumanConfirm:!0,inputSchema:{version:Ao.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:Ao.string().describe("The release branch that was delivered"),version:Ao.string().describe("The version that was delivered"),type:Ao.enum(["regular","hotfix"]).describe("Release type"),success:Ao.boolean().describe("Whether the delivery was successful")},handler:Ri});import{z as ut}from"zod";import{$ as nd}from"zx";import{z as Do}from"zod";import vh from"node:fs/promises";import ql from"node:path";var wh=".github/workflows",Xx=/script_name:\s*(?<service>[a-z0-9-]+)/,Zx=/uses:\s*\.\/\.github\/workflows\/_deploy-(?<service>[a-z0-9-]+)-jobs\.ya?ml/,Qx=/inputs\.environment\s*==\s*'(?<env>[a-z0-9-]+)'/g,Yl=async e=>{let t=ql.resolve(e,wh),r;try{r=await vh.readdir(t)}catch{return new Map}return kh(t,r.filter(n=>n.endsWith(".yml")||n.endsWith(".yaml")))},Oo=async(e,t)=>kh(ql.resolve(e,wh),[t]),kh=async(e,t)=>{let r=new Map;for(let n of t){let o;try{o=await vh.readFile(ql.resolve(e,n),"utf-8")}catch{continue}eT(o,r)}return r},eT=(e,t)=>{for(let r of e.split(/\n(?= {2}[\w-]+:)/i)){let n=Xx.exec(r)?.groups?.service??Zx.exec(r)?.groups?.service;if(n===void 0||r.trimStart().startsWith("#"))continue;let o=[...r.matchAll(Qx)].map(s=>s.groups?.env??"");o.length!==0&&t.set(n,[...new Set([...t.get(n)??[],...o])])}},zl=(e,t)=>e===null?t??null:t===void 0?e:e.filter(r=>t.includes(r));import tT from"node:fs/promises";import rT from"node:path";import nT from"yaml";var oT=".github/workflows",sT="skip_terraform_deploy",Io=async(e,t)=>{let r=rT.resolve(e,oT,t),n;try{n=nT.parse(await tT.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!==sT).map(([i])=>i)};var bh="dev",Xl=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Rh=(e,t)=>e[t]===void 0,Sh=(e,t)=>{let r=e[t];return typeof r=="string"&&r.length>0?r:void 0},Zl=async e=>{try{return await e}catch{return[]}},iT=async()=>{let e=await F();return rr(e.map(t=>t.branch))},aT=(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},fr=e=>{let{workflowFile:t,fields:r,toolName:n}=e,o=c=>(u.info({msg:`Tool execution form options empty (${t}): ${n}`,emptyList:c}),null),s=async c=>{let l=await Zl(iT());if(l.length===0)return null;let d=Sh(c,"version");return Do.enum([...new Set([...l,bh])]).optional().describe(`Which release to deploy from. "${bh}" deploys from the dev branch instead of a release branch. ${d===void 0?"Leaving it blank sends no version, and the tool will refuse rather than guess one.":`Leave it blank to keep the caller's "${d}".`}`)},i=async c=>{let l=bt(await Zl(Rt(t)),await Je());if(l.length===0)return null;let d=l.filter(On),p=l.filter(g=>!On(g)),m=Sh(c,"env");return Do.enum(l).optional().describe(`Target environment. Shared with the whole team: ${d.length>0?d.join(", "):"none"}. Personal accounts: ${p.length>0?p.join(", "):"none"}. This list is read from .github/workflows/${t} in the WORKING TREE, not from the branch being deployed or from GitHub. ${m===void 0?"Leaving it blank sends no environment at all.":`Leave it blank to keep the caller's "${m}" \u2014 including when this tree does not declare it.`}`)},a=async()=>{let c=await T(),l=await Zl(Io(c,t));if(l.length===0)return null;let d=await Oo(c,t);return Do.array(Do.enum(l)).optional().describe(`Services to deploy. Environment gates declared by ${t} \u2014 ${aT(l,d)} A service the chosen environment gates out is REFUSED before dispatch, not skipped in silence. Selecting none discards the form and falls back to the caller's arguments.`)};return{message:`Choose the arguments for ${n}. Anything left blank keeps what the caller sent.`,isFormable:c=>Xl(c)?r.some(l=>Rh(c,l)):!1,buildRequestedSchema:async c=>{let l=Xl(c)?c:{},d={};if(r.includes("version")){let p=await s(l);if(p===null)return o("releases");d.version=p}if(r.includes("env")){let p=await i(l);if(p===null)return o("envs");d.env=p}if(r.includes("services")&&Rh(l,"services")){let p=await a();if(p===null)return o("services");d.services=p}return Object.keys(d).length===0?o("fields"):Do.object(d)},toArgs:(c,l)=>{let d={...Xl(l)?l:{}};for(let p of r){let m=c[p];if(m!==void 0){if(p==="services"&&(!Array.isArray(m)||m.length===0))return null;d[p]=m}}return d}}};import cT from"@inquirer/select";var fn=async(e,t)=>{if(e.length===0)throw new f(void 0,{operation:t,remediation:"pass --env <name> explicitly",stderrExcerpt:"the workflow declares no `environment` choices to pick from"});return O(r=>cT({message:"\u{1F9EA} Select environment",choices:e.map(n=>({name:n,value:n}))},r),{whenHeadless:"refuse"})};import lT from"@inquirer/confirm";var No=async e=>{let{confirmedCommand:t,branch:r,env:n}=e;if(t)return!0;let o=`Deploy ${r} \u2192 ${n} via GitHub Actions?`;J()&&ks(o,{branch:r,env:n}),h.setInteractive();let s=await O(i=>lT({message:o,default:!1},i),{whenHeadless:"refuse"});return s&&h.addOption("--yes",!0),s};import dT from"@inquirer/select";import uT from"node:process";var Ql=()=>!J()&&uT.stdin.isTTY===!0,pT={ci:"Dispatch the GitHub workflow for a release ref",local:"Run devops/scripts/deploy-*.sh here, against your current checkout"},ed=async()=>O(e=>dT({message:"\u{1F680} Where should this deploy run?",choices:_t.filter(t=>t!=="local").map(t=>({name:t,value:t,description:pT[t]}))},e),{whenHeadless:"refuse"});var _t=["ci","local"],mT={ci:["--version","--skip-terraform"],local:["--dry-run","--print-env"]},Ph=e=>{if(!e){let r={operation:"resolve the deploy source",remediation:`pass --from with one of: ${_t.join(", ")}`,stderrExcerpt:"--from is required \u2014 it decides whether this deploy runs in CI or on this machine"};throw J()?new x({status:"argument_required",argument:"from",agentMode:N.source},2,r):new f(void 0,r)}let t=_t.find(r=>r===e);if(!t)throw new f(void 0,{operation:"resolve the deploy source",remediation:`use one of: ${_t.join(", ")}`,stderrExcerpt:`unknown --from value "${e}"`});return t},td=(e,t)=>{let n=mT[e==="ci"?"local":"ci"].filter(o=>{let s=t[o];return s!==void 0&&s!==!1});if(n.length!==0)throw new f(void 0,{operation:`deploy --from ${e}`,remediation:e==="ci"?"drop the flag, or use --from local to deploy from this machine":"drop the flag, or use --from ci to dispatch the release workflow",stderrExcerpt:`${n.join(", ")} ${n.length===1?"is":"are"} not valid with --from ${e}`})},rd=async e=>e||!Ql()?Ph(e):ed();var _o=async e=>{if(e)return e==="dev"?"dev":lt(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 se();return Tt([{value:"dev",label:"dev"},...ie({branches:r,descriptions:o,types:n})])};var Eh="deploy-all.yml",xh=fr({workflowFile:Eh,fields:["version","env"],toolName:"gh-release-deploy-all"}),Si=async e=>{let{version:t,env:r,skipTerraform:n,confirmedCommand:o}=e;await Ge({provider:xh,params:e,operation:"launch deploy-all workflow",argument:p=>p[0]??"version"});let s=await _o(t),i=io(s);h.addOption("--version",i);let a=await Je(),c=bt(await Rt(Eh),a),l="";r?l=r:(h.setInteractive(),l=await fn(c,"launch deploy-all workflow")),h.addOption("--env",l),Tr(l,"launch deploy-all workflow",a),Ss({env:l,branch:s});let d=n??!1;if(d&&h.addOption("--skip-terraform",!0),!await No({confirmedCommand:o,branch:s,env:l})){u.info("Deployment cancelled");let p={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:d,success:!1};return{content:k(JSON.stringify(p,null,2)),structuredContent:p}}try{nd.quiet=!0,await nd`gh workflow run deploy-all.yml --ref ${s} -f environment=${l} ${d?["-f","skip_terraform_deploy=true"]:[]}`,nd.quiet=!1,u.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${s} and environment: ${l}`),h.print();let m={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:d,success:!0};return{content:k(JSON.stringify(m,null,2)),structuredContent:m}}catch(p){throw u.error({error:p},"\u274C Error launching workflow"),new f(p,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},od=S({name:"gh-release-deploy-all",formProvider:xh,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:ut.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:ut.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:ut.boolean().optional().describe("Skip the terraform deployment stage."),confirm:ut.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:ut.string().describe("The release branch that was deployed"),version:ut.string().describe("The version that was deployed"),environment:ut.string().describe("The environment deployed to"),skipTerraformDeploy:ut.boolean().describe("Whether terraform deployment was skipped"),success:ut.boolean().describe("Whether the deployment was successful")},handler:Si});import fT from"@inquirer/checkbox";import{z as xe}from"zod";import{$ as sd}from"zx";var gr="deploy-selected-services.yml",Th=fr({workflowFile:gr,fields:["version","env","services"],toolName:"gh-release-deploy-selected"}),Pi=async e=>{let{version:t,env:r,services:n,skipTerraform:o,confirmedCommand:s}=e;await Ge({provider:Th,params:e,operation:"launch deploy-selected workflow",argument:I=>I[0]??"version"});let i=await _o(t),a=io(i);h.addOption("--version",a);let c=await Je(),l=bt(await Rt(gr),c),d="";r?d=r:(h.setInteractive(),d=await fn(l,"launch deploy-selected workflow")),h.addOption("--env",d),Tr(d,"launch deploy-selected workflow",c),Ss({env:d,branch:i});let p=await T(),m=await Io(p,gr);if(m.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${gr}`,stderrExcerpt:`no services found in .github/workflows/${gr}`});let g=[];if(n&&n.length>0?g=n:(h.setInteractive(),g=await O(I=>fT({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:m.map(P=>({name:P,value:P}))},I),{whenHeadless:"refuse"})),h.addOption("--services",g),g.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${m.join(", ")}`,stderrExcerpt:"no services selected"});let y=g.filter(I=>!m.includes(I));if(y.length>0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${m.join(", ")}`,stderrExcerpt:`invalid services: ${y.join(", ")}`});let R=await Oo(p,gr),w=g.filter(I=>{let P=R.get(I);return P!==void 0&&!P.includes(d)});if(w.length>0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:w.map(I=>`${I} deploys only to: ${(R.get(I)??[]).join(", ")}`).join("; "),stderrExcerpt:`${gr} gates these services out of ${d}: ${w.join(", ")}`});let $=o??!1;$&&h.addOption("--skip-terraform",!0);let B=I=>{let P={releaseBranch:i,version:a,environment:d,services:g,skipTerraformDeploy:$,success:I};return{content:k(JSON.stringify(P,null,2)),structuredContent:P}};if(!await No({confirmedCommand:s,branch:i,env:d}))return u.info("Deployment cancelled"),B(!1);try{sd.quiet=!0;let I=g.flatMap(le=>["-f",`${le}=true`]);return await sd`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${d} ${I} ${$?["-f","skip_terraform_deploy=true"]:[]}`,sd.quiet=!1,u.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${d}, services: ${g.join(", ")}`),h.print(),B(!0)}catch(I){throw u.error({error:I},"\u274C Error launching workflow"),new f(I,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},id=S({name:"gh-release-deploy-selected",requiresHumanConfirm:!0,formProvider:Th,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:xe.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:xe.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:xe.array(xe.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:xe.boolean().optional().describe("Skip the terraform deployment stage."),confirm:xe.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:xe.string().describe("The release branch that was deployed"),version:xe.string().describe("The version that was deployed"),environment:xe.string().describe("The environment deployed to"),services:xe.array(xe.string()).describe("The services that were deployed"),skipTerraformDeploy:xe.boolean().describe("Whether terraform deployment was skipped"),success:xe.boolean().describe("Whether the deployment was successful")},handler:Pi});import{z as Mt}from"zod";var Ei=async()=>{let t=(await F()).flatMap(i=>{let a=G(i.branch);return a?[{version:X(a),jiraKey:re(a),type:i.type,titleMismatch:i.titleMismatch}]:[]}),r=await Gs(),n=Math.max(...t.map(i=>i.version.length)),o=t.map(i=>{let a=so(i.version,i.type,n),c=r.get(i.jiraKey),l=c?.description?` ${c.description}`:"",d=c?.releaseDate?` \xB7 ships ${c.releaseDate}`:"",p=i.titleMismatch?" \u26A0 title/base mismatch":"";return`${a}${l}${d}${p}`});u.info(`All release branches:
401
+ `);for(let w of y)u.info(Mx(w,c))}else u.info(`\u2705 All merges completed successfully!
402
+ `);h.print();let R=a||i;return Kl({successfulMerges:R?0:g.filter(w=>Gl.has(w.status)).length,failedMerges:R?0:y.length,failedBranches:R?[]:y.map(w=>w.branch),totalBranches:g.length,dryRun:a,atomicPush:{attempted:!a&&!i,aborted:o,abortedBy:s},results:g.map(w=>R?{...w,pushed:!1}:w),skipped:p})},Hl=S({name:"gh-merge-dev",description:"Merge origin/dev into open regular release branches and push them in one atomic push. A release PR is classified by its base branch, not its title: a PR to main is a hotfix and is skipped, as is any row whose title disagrees with its base or whose head has open PRs to both dev and main \u2014 every skipped row is reported in `skipped` with its reason. Merges happen in a disposable scratch worktree, so no existing checkout is touched and the branches may be checked out elsewhere. When invoked via MCP, pass all=true or an explicit versions list \u2014 the branch picker is unreachable without a TTY, and the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. Irreversible once pushed.",requiresHumanConfirm:!0,inputSchema:{all:b.boolean().optional().describe("Target every open regular release branch. Must be true for MCP calls unless `versions` is supplied (the interactive picker is unavailable without a TTY)."),versions:b.union([b.string(),b.array(b.string())]).optional().describe('Target a subset of the open regular release branches. Each entry may be a version label ("1.2.5") or a raw branch name ("release/v1.2.5"). A selector that is not an open regular release is an error; one that names a skipped row (hotfix, title/base mismatch, dual-base) quotes that reason. Takes precedence over `all`.'),dryRun:b.boolean().optional().describe("Compute and print the merge plan without pushing anything."),verify:b.union([b.boolean(),b.string()]).optional().describe("Check each merge before pushing it. `true` runs `pnpm install --frozen-lockfile` \u2014 which catches the characteristic dev\u2192release failure, a pnpm-lock.yaml whose text merge is clean but whose result is broken. A string runs that command instead. A branch that fails verification is dropped from the push; nothing is ever rolled back, because verification runs pre-push. Under `continue`, a string runs after the mandatory `pnpm install --frozen-lockfile --ignore-scripts`."),keepConflicts:b.boolean().optional().describe("On the confirmed run, after the clean branches are pushed, leave each conflicted branch mid-merge in a detached worktree under `<root>-worktrees/merge-dev/` for resolution. Excludes `continue`, `abort` and `dryRun`."),continue:b.boolean().optional().describe("Check the selected resolutions (only conflicted paths edited, no markers, install passes), preview them, and on confirmation commit exactly the previewed tree and push atomically. Excludes `keepConflicts`, `abort` and `dryRun`."),abort:b.boolean().optional().describe("Discard the selected resolution worktrees and their state. Excludes `keepConflicts`, `continue` and `dryRun`."),tree:b.union([b.string(),b.array(b.string())]).optional().describe("With `continue` and confirmation: `<branch>=<treeSha>`, comma-separated or repeated \u2014 the trees the human approved in the `continue` preview. Pass the preview `rerun` unchanged; a branch whose resolved tree differs is reported `tree-changed` and not committed."),confirm:b.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{successfulMerges:b.number().describe("Number of branches that reached their desired state"),failedMerges:b.number().describe("Number of branches that did not"),failedBranches:b.array(b.string()).describe("List of branches that did not merge"),totalBranches:b.number().describe("Total number of branches processed"),dryRun:b.boolean().describe("True when nothing was pushed because this was a plan-only run"),atomicPush:b.object({attempted:b.boolean(),aborted:b.boolean(),abortedBy:b.string().optional()}).describe("Outcome of the single all-or-nothing push"),results:b.array(b.object({branch:b.string(),status:b.string(),mergeSha:b.string().optional(),conflictPaths:b.array(b.string()).optional(),pushed:b.boolean(),reason:b.string().optional(),resolution:b.object({worktreePath:b.string(),baseSha:b.string(),devSha:b.string(),conflictPaths:b.array(b.string()),lockfileOnly:b.boolean(),rererePreResolved:b.array(b.string()),state:b.enum(["needs-agent","lockfile-only","exists"])}).optional().describe("The `keepConflicts` hand-off for a conflicted branch"),blocked:b.object({code:b.enum(["unmerged-paths","markers-remaining","out-of-scope-edit","verify-failed","verify-mutated-tree","parents-mismatch","git-too-old","tree-changed"]),paths:b.array(b.string()).optional(),detail:b.string()}).optional().describe("Why a `continue` run did not commit this resolution")})).describe("Per-branch terminal state"),skipped:b.array(b.object({branch:b.string(),reason:b.enum(["hotfix (targets main)","title/base mismatch","open PRs to both dev and main"])})).describe("Every discovered release PR that was not a merge candidate, with why. Empty only when nothing was discovered.")},handler:bi});import{z as No}from"zod";import{$ as je}from"zx";var hh=(e,t)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-t).trim()},jt=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=hh(t.stderr,500);o&&(r.stderr=o);let s=hh(t.stdout,200);return s&&(r.stdout=s),r};var Ao=e=>{let{removed:t,failed:r}=e;if(t.length>0){u.info("\u274C Removed worktrees:");for(let n of t)u.info(n);u.info("")}if(r.length>0){u.warn("\u26A0\uFE0F Not removed:");for(let{branch:n,reason:o}of r)u.warn(`${n} \u2014 ${o}`);u.warn("")}t.length===0&&r.length===0&&u.info("\u2139\uFE0F No worktrees to remove")};var Oo=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 ye()?new C({status:"partial_failure",...n},1,s):new f(void 0,s)};import Ri from"node:fs/promises";import{$ as Yl}from"zx";var Fx=new Set([".omc",".DS_Store"]),Lx=new Set(["state","sessions"]),Bx=2e3,kh="check 'git worktree list' for the path; uncommitted changes block removal",Wx=e=>new Promise(t=>{setTimeout(t,e)}),ql=e=>typeof e=="object"&&e!==null?e.code:void 0,yh=e=>{let t=e.length;for(;t>1&&e[t-1]==="/";)t-=1;return e.slice(0,t)},vh=async e=>{try{return yh(await Ri.realpath(e))}catch{return yh(e)}},Vx=async e=>{let{projectRoot:t,worktreePath:r}=e;try{let n=await Ke(t),o=await vh(r);for(let s of n)if(await vh(s.path)===o)return!0;return!1}catch{return!0}},Ux=async e=>{let t;try{t=await Ri.readdir(e)}catch(n){return{kind:ql(n)==="ENOENT"?"gone":"not-sweepable",entries:[]}}if(!t.every(n=>Fx.has(n)))return{kind:"not-sweepable",entries:t};if(!t.includes(".omc"))return{kind:"sweepable",entries:t};try{return{kind:(await Ri.readdir(`${e}/.omc`)).every(s=>Lx.has(s))?"sweepable":"not-sweepable",entries:t}}catch(n){return{kind:ql(n)==="ENOENT"?"sweepable":"not-sweepable",entries:t}}},wh=async e=>{try{return await Ri.rm(e,{recursive:!0,force:!0}),"removed"}catch(t){return ql(t)==="ENOTEMPTY"?"busy":"failed"}},Jx=async e=>{let{worktreePath:t,sleep:r}=e,n=await wh(t);return n!=="busy"?n==="removed":(await r(Bx),await wh(t)==="removed")},Io=(e,t,r)=>{let n=new f(t,{operation:`remove worktree for ${e}`,remediation:r});return u.error({error:t,branch:e,msg:n.message}),{branch:e,status:"failed",reason:n.message}},Gx=async e=>{let{branch:t,worktreePath:r,projectRoot:n,error:o,sleep:s}=e;if(await Vx({projectRoot:n,worktreePath:r}))return Io(t,o,kh);let i=await Ux(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 Jx({worktreePath:r,sleep:s})?Io(t,o,a):(u.warn(`\u26A0\uFE0F swept leftover ${i.entries.join(", ")} from ${r}: a post-exit hook (e.g. oh-my-claudecode SessionEnd) wrote into the worktree while git was deleting it; set OMC_STATE_DIR to keep tool state out of worktrees`),{branch:t,status:"removed"})},Kx=async e=>{try{return(await Yl`git -C ${e} status --porcelain`).stdout.split(`
403
+ `).filter(r=>r.trim().length>0)}catch{return[]}},Hx=async e=>{let{branch:t,worktreeDir:r,projectRoot:n,orcaProbe:o,sleep:s}=e,i=`${r}/${t}`,a=await Kx(i);if(a.length>0)return Io(t,new Error(`uncommitted changes in ${i}: ${a.slice(0,5).join(", ")}`),kh);let c=await im(i,o);if(!c.closed&&"error"in c)return Io(t,c.error,"close the Orca terminals of this worktree manually (orca terminal close --terminal <handle>) and re-run");try{return await Yl`git worktree remove ${i}`,{branch:t,status:"removed"}}catch(l){return Gx({branch:t,worktreePath:i,projectRoot:n,error:l,sleep:s})}},fr=async e=>{let{branches:t,worktreeDir:r,projectRoot:n,pruneFolder:o=!1,sleep:s=Wx}=e,i=t.length>0?await St():"unreachable",a=await Promise.all(t.map(l=>Hx({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 Yl`git worktree prune`,c};var Do=async(e,t)=>{if(!(await fe("release")).includes(e))return[];let n=await T(),o=`${n}${de}`,{removed:s,failed:i}=await fr({branches:[e],worktreeDir:o,projectRoot:n});if(!s.includes(e)){let a=i.find(c=>c.branch===e);throw new f(void 0,{...t,stderrExcerpt:a?.reason})}return s};var hn=async(e,t,r)=>{try{return await r()}catch(n){throw u.debug({err:jt(n)},`Failed to ${e}`),new f(n,{operation:e,remediation:t})}},qx=async e=>{let t=wa(e),r=await je`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},bh=async()=>{let e=await je`gh pr list --head dev --base main --state open --json number,state,title,baseRefName,headRefName --limit 5`;return JSON.parse(e.stdout)[0]??null},Yx=async e=>{let t=pt(e),r=await Mc(t);if(r.length>1){let s=r.map(i=>`#${i.number} \u2192 ${i.baseRefName}`).join(", ");throw new f(void 0,{operation:`deliver release ${t}`,remediation:`the branch has open PRs to both dev and main (${s}); close the one that should not be delivered`})}let n=r[0]??await Kr(t);if(!n)throw u.error(`\u274C No PR found for branch ${t}.`),new f(void 0,{operation:`deliver release ${t}`,remediation:`confirm a PR exists ('gh pr list --head ${t} --state all')`});let o=oo(n.baseRefName);if(!o)throw new f(void 0,{operation:`deliver release ${t}`,remediation:`PR #${n.number} targets '${n.baseRefName}', which is neither dev nor main; retarget it ('gh pr edit ${n.number} --base <dev|main>')`});return{selectedReleaseBranch:t,releaseType:o,prNumber:n.number}},zx=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 se(),o=await At(ie({branches:t,descriptions:n,types:r})),s=e.find(i=>i.branch===o);if(!s)throw u.error(`\u274C Release branch ${o} not found in open PRs.`),new f(void 0,{operation:`deliver release ${o}`,remediation:`confirm an open PR exists for ${o} ('gh pr list')`});if(s.dualBase)throw new f(void 0,{operation:`deliver release ${o}`,remediation:"the branch has open PRs to both dev and main; close the one that should not be delivered"});return{selectedReleaseBranch:o,releaseType:s.type,prNumber:s.number}},Xx=async e=>{let{selectedReleaseBranch:t,releaseType:r,prNumber:n}=e,o=et(r),s=await jc(n);if(s.state==="MERGED"){u.info(`\u2713 Release PR ${t} already merged \u2014 skipping`);return}if(s.state==="CLOSED")throw new f(void 0,{operation:`merge release PR ${t} into ${o}`,remediation:"the PR is closed without merge; reopen it or create a new release"});if(s.baseRefName!==o||s.headRefName!==t)throw new f(void 0,{operation:`merge release PR #${n} ${t} into ${o}`,remediation:`PR #${n} now reads ${s.headRefName} \u2192 ${s.baseRefName}; it changed since it was resolved \u2014 re-run the command`});await hn(`merge release PR #${n} ${t} into ${o}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await je`gh pr merge ${n} --squash --admin --delete-branch`})},Zx=async e=>{let t=X(e),r=wa(e),n=await bh();if(n){let s=n.number;return n.title!==r&&(u.info(`Adopting open dev \u2192 main PR #${s} ("${n.title}") and retitling for ${t}`),await hn(`retitle dev \u2192 main PR #${s} to "${r}"`,`update manually: gh pr edit ${s} --title "${r}"`,async()=>{await je`gh pr edit ${s} --title ${r}`})),s}await hn(`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 je`gh pr create --base main --head dev --title ${r} --body ""`});let o=await bh();if(!o)throw new f(void 0,{operation:`look up RC PR for ${t}`,remediation:"verify the RC PR was created ('gh pr list --head dev --base main')"});return o.number},Qx=async e=>{let t=X(e);if(await qx(e)){u.info(`\u2713 RC PR for ${t} already merged into main \u2014 skipping`);return}let n=await Zx(e);await hn(`merge RC PR #${n} (dev \u2192 main) for ${t}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await je`gh pr merge ${n} --squash --admin`})},eT=async()=>{je.quiet=!1,await hn("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await je`gh workflow run deploy-all.yml --ref main -f environment=prod`}),je.quiet=!0},tT=async()=>{await hn("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 je`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},rT=async e=>{try{await ys(e)}catch(t){u.warn({err:jt(t)},`Failed to delete local branch ${e} (non-blocking)`)}try{await vs(e)}catch(t){u.warn({err:jt(t)},`Failed to delete remote branch ${e} (non-blocking)`)}},nT=async e=>{let t=await ut();if(!t){u.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let r=re(e);await Lc({versionName:r},t)}catch(r){let n=io(r)&&r.kind==="auth"?" \u2014 reissue the Atlassian API token and update JIRA_TOKEN":"";u.error({err:jt(r)},`Failed to deliver Jira release (non-blocking)${n}`)}},Si=async e=>{let{version:t,confirmedCommand:r}=e;await Ee({operation:"deliver release"});let{selectedReleaseBranch:n,releaseType:o,prNumber:s}=t?await Yx(t):await zx(),i=G(n);if(!i)throw new f(void 0,{operation:`deliver release ${n}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let a=X(i);if(h.addOption("--version",a),u.info(`Delivering ${i.kind==="name"?"named release":"version"} ${n}`),ye())throw new C({status:"refused",agentMode:N.source},2,{operation:`deliver release ${n}`,remediation:"ask a human to run `infra-kit release deliver` from their own shell \u2014 delivery is never confirmed by an agent",stderrExcerpt:"release deliver is CLI-only: refused in agent mode regardless of --yes"});await B(r,`Are you sure you want to deliver version ${n} to production?`),h.addOption("--yes",!0),je.quiet=!0;let l=`${await T()}${de}`;await Do(n,{operation:`remove worktree for ${n} before merge`,remediation:`run manually: git worktree remove ${l}/${n} (use --force if uncommitted changes)`}),await Xx({selectedReleaseBranch:n,releaseType:o,prNumber:s}),o!=="hotfix"&&await Qx(i),await eT(),await tT(),await rT(n),je.quiet=!1,await nT(i),u.info(`Successfully delivered ${n} to production!`),h.print();let d={releaseBranch:n,version:a,type:o,success:!0};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}},zl=S({name:"gh-release-deliver",description:'Deliver a release to production. For hotfixes: squash-merges the release branch to main and dispatches the deploy-all workflow. For regular releases: squash-merges to dev, opens an RC PR, merges dev into main, dispatches the deploy-all workflow, then syncs main back to dev. Also releases the matching Jira fix version if Jira is configured. Dispatches the deploy workflow fire-and-forget \u2014 the tool returns once the workflow is accepted by GitHub, not when the deployment finishes. PR-merge steps are idempotent: re-running after a partial failure skips PRs that are already merged. Irreversible production operation: the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. "version" is required when invoked via MCP (the picker is unreachable without a TTY).',requiresHumanConfirm:!0,inputSchema:{version:No.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:No.string().describe("The release branch that was delivered"),version:No.string().describe("The version that was delivered"),type:No.enum(["regular","hotfix"]).describe("Release type"),success:No.boolean().describe("Whether the delivery was successful")},handler:Si});import{z as gt}from"zod";import{$ as id}from"zx";import{z as jo}from"zod";import Rh from"node:fs/promises";import Xl from"node:path";var Sh=".github/workflows",oT=/script_name:\s*(?<service>[a-z0-9-]+)/,sT=/uses:\s*\.\/\.github\/workflows\/_deploy-(?<service>[a-z0-9-]+)-jobs\.ya?ml/,iT=/inputs\.environment\s*==\s*'(?<env>[a-z0-9-]+)'/g,Zl=async e=>{let t=Xl.resolve(e,Sh),r;try{r=await Rh.readdir(t)}catch{return new Map}return Ph(t,r.filter(n=>n.endsWith(".yml")||n.endsWith(".yaml")))},_o=async(e,t)=>Ph(Xl.resolve(e,Sh),[t]),Ph=async(e,t)=>{let r=new Map;for(let n of t){let o;try{o=await Rh.readFile(Xl.resolve(e,n),"utf-8")}catch{continue}aT(o,r)}return r},aT=(e,t)=>{for(let r of e.split(/\n(?= {2}[\w-]+:)/i)){let n=oT.exec(r)?.groups?.service??sT.exec(r)?.groups?.service;if(n===void 0||r.trimStart().startsWith("#"))continue;let o=[...r.matchAll(iT)].map(s=>s.groups?.env??"");o.length!==0&&t.set(n,[...new Set([...t.get(n)??[],...o])])}},Ql=(e,t)=>e===null?t??null:t===void 0?e:e.filter(r=>t.includes(r));import cT from"node:fs/promises";import lT from"node:path";import dT from"yaml";var uT=".github/workflows",pT="skip_terraform_deploy",Mo=async(e,t)=>{let r=lT.resolve(e,uT,t),n;try{n=dT.parse(await cT.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!==pT).map(([i])=>i)};var Eh="dev",ed=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),xh=(e,t)=>e[t]===void 0,Th=(e,t)=>{let r=e[t];return typeof r=="string"&&r.length>0?r:void 0},td=async e=>{try{return await e}catch{return[]}},mT=async()=>{let e=await F();return mt(e.map(t=>t.branch))},fT=(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},gr=e=>{let{workflowFile:t,fields:r,toolName:n}=e,o=c=>(u.info({msg:`Tool execution form options empty (${t}): ${n}`,emptyList:c}),null),s=async c=>{let l=await td(mT());if(l.length===0)return null;let d=Th(c,"version");return jo.enum([...new Set([...l,Eh])]).optional().describe(`Which release to deploy from. "${Eh}" deploys from the dev branch instead of a release branch. ${d===void 0?"Leaving it blank sends no version, and the tool will refuse rather than guess one.":`Leave it blank to keep the caller's "${d}".`}`)},i=async c=>{let l=Pt(await td(Et(t)),await He());if(l.length===0)return null;let d=l.filter(Nn),p=l.filter(g=>!Nn(g)),m=Th(c,"env");return jo.enum(l).optional().describe(`Target environment. Shared with the whole team: ${d.length>0?d.join(", "):"none"}. Personal accounts: ${p.length>0?p.join(", "):"none"}. This list is read from .github/workflows/${t} in the WORKING TREE, not from the branch being deployed or from GitHub. ${m===void 0?"Leaving it blank sends no environment at all.":`Leave it blank to keep the caller's "${m}" \u2014 including when this tree does not declare it.`}`)},a=async()=>{let c=await T(),l=await td(Mo(c,t));if(l.length===0)return null;let d=await _o(c,t);return jo.array(jo.enum(l)).optional().describe(`Services to deploy. Environment gates declared by ${t} \u2014 ${fT(l,d)} A service the chosen environment gates out is REFUSED before dispatch, not skipped in silence. Selecting none discards the form and falls back to the caller's arguments.`)};return{message:`Choose the arguments for ${n}. Anything left blank keeps what the caller sent.`,isFormable:c=>ed(c)?r.some(l=>xh(c,l)):!1,buildRequestedSchema:async c=>{let l=ed(c)?c:{},d={};if(r.includes("version")){let p=await s(l);if(p===null)return o("releases");d.version=p}if(r.includes("env")){let p=await i(l);if(p===null)return o("envs");d.env=p}if(r.includes("services")&&xh(l,"services")){let p=await a();if(p===null)return o("services");d.services=p}return Object.keys(d).length===0?o("fields"):jo.object(d)},toArgs:(c,l)=>{let d={...ed(l)?l:{}};for(let p of r){let m=c[p];if(m!==void 0){if(p==="services"&&(!Array.isArray(m)||m.length===0))return null;d[p]=m}}return d}}};import gT from"@inquirer/select";var yn=async(e,t)=>{if(e.length===0)throw new f(void 0,{operation:t,remediation:"pass --env <name> explicitly",stderrExcerpt:"the workflow declares no `environment` choices to pick from"});return O(r=>gT({message:"\u{1F9EA} Select environment",choices:e.map(n=>({name:n,value:n}))},r),{whenHeadless:"refuse"})};import hT from"@inquirer/confirm";var Fo=async e=>{let{confirmedCommand:t,branch:r,env:n}=e;if(t)return!0;let o=`Deploy ${r} \u2192 ${n} via GitHub Actions?`;J()&&Ss(o,{branch:r,env:n}),h.setInteractive();let s=await O(i=>hT({message:o,default:!1},i),{whenHeadless:"refuse"});return s&&h.addOption("--yes",!0),s};import yT from"@inquirer/select";import vT from"node:process";var rd=()=>!J()&&vT.stdin.isTTY===!0,wT={ci:"Dispatch the GitHub workflow for a release ref",local:"Run devops/scripts/deploy-*.sh here, against your current checkout"},nd=async()=>O(e=>yT({message:"\u{1F680} Where should this deploy run?",choices:Ft.filter(t=>t!=="local").map(t=>({name:t,value:t,description:wT[t]}))},e),{whenHeadless:"refuse"});var Ft=["ci","local"],kT={ci:["--version","--skip-terraform"],local:["--dry-run","--print-env"]},Ch=e=>{if(!e){let r={operation:"resolve the deploy source",remediation:`pass --from with one of: ${Ft.join(", ")}`,stderrExcerpt:"--from is required \u2014 it decides whether this deploy runs in CI or on this machine"};throw J()?new C({status:"argument_required",argument:"from",agentMode:N.source},2,r):new f(void 0,r)}let t=Ft.find(r=>r===e);if(!t)throw new f(void 0,{operation:"resolve the deploy source",remediation:`use one of: ${Ft.join(", ")}`,stderrExcerpt:`unknown --from value "${e}"`});return t},od=(e,t)=>{let n=kT[e==="ci"?"local":"ci"].filter(o=>{let s=t[o];return s!==void 0&&s!==!1});if(n.length!==0)throw new f(void 0,{operation:`deploy --from ${e}`,remediation:e==="ci"?"drop the flag, or use --from local to deploy from this machine":"drop the flag, or use --from ci to dispatch the release workflow",stderrExcerpt:`${n.join(", ")} ${n.length===1?"is":"are"} not valid with --from ${e}`})},sd=async e=>e||!rd()?Ch(e):nd();var Lo=async e=>{if(e)return e==="dev"?"dev":pt(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 se();return At([{value:"dev",label:"dev"},...ie({branches:r,descriptions:o,types:n})])};var $h="deploy-all.yml",Ah=gr({workflowFile:$h,fields:["version","env"],toolName:"gh-release-deploy-all"}),Pi=async e=>{let{version:t,env:r,skipTerraform:n,confirmedCommand:o}=e;await qe({provider:Ah,params:e,operation:"launch deploy-all workflow",argument:p=>p[0]??"version"});let s=await Lo(t),i=lo(s);h.addOption("--version",i);let a=await He(),c=Pt(await Et($h),a),l="";r?l=r:(h.setInteractive(),l=await yn(c,"launch deploy-all workflow")),h.addOption("--env",l),Ar(l,"launch deploy-all workflow",a),Es({env:l,branch:s});let d=n??!1;if(d&&h.addOption("--skip-terraform",!0),!await Fo({confirmedCommand:o,branch:s,env:l})){u.info("Deployment cancelled");let p={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:d,success:!1};return{content:k(JSON.stringify(p,null,2)),structuredContent:p}}try{id.quiet=!0,await id`gh workflow run deploy-all.yml --ref ${s} -f environment=${l} ${d?["-f","skip_terraform_deploy=true"]:[]}`,id.quiet=!1,u.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${s} and environment: ${l}`),h.print();let m={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:d,success:!0};return{content:k(JSON.stringify(m,null,2)),structuredContent:m}}catch(p){throw u.error({error:p},"\u274C Error launching workflow"),new f(p,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},ad=S({name:"gh-release-deploy-all",formProvider:Ah,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:gt.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:gt.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:gt.boolean().optional().describe("Skip the terraform deployment stage."),confirm:gt.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:gt.string().describe("The release branch that was deployed"),version:gt.string().describe("The version that was deployed"),environment:gt.string().describe("The environment deployed to"),skipTerraformDeploy:gt.boolean().describe("Whether terraform deployment was skipped"),success:gt.boolean().describe("Whether the deployment was successful")},handler:Pi});import bT from"@inquirer/checkbox";import{z as Te}from"zod";import{$ as cd}from"zx";var hr="deploy-selected-services.yml",Oh=gr({workflowFile:hr,fields:["version","env","services"],toolName:"gh-release-deploy-selected"}),Ei=async e=>{let{version:t,env:r,services:n,skipTerraform:o,confirmedCommand:s}=e;await qe({provider:Oh,params:e,operation:"launch deploy-selected workflow",argument:I=>I[0]??"version"});let i=await Lo(t),a=lo(i);h.addOption("--version",a);let c=await He(),l=Pt(await Et(hr),c),d="";r?d=r:(h.setInteractive(),d=await yn(l,"launch deploy-selected workflow")),h.addOption("--env",d),Ar(d,"launch deploy-selected workflow",c),Es({env:d,branch:i});let p=await T(),m=await Mo(p,hr);if(m.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${hr}`,stderrExcerpt:`no services found in .github/workflows/${hr}`});let g=[];if(n&&n.length>0?g=n:(h.setInteractive(),g=await O(I=>bT({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:m.map(P=>({name:P,value:P}))},I),{whenHeadless:"refuse"})),h.addOption("--services",g),g.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${m.join(", ")}`,stderrExcerpt:"no services selected"});let y=g.filter(I=>!m.includes(I));if(y.length>0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${m.join(", ")}`,stderrExcerpt:`invalid services: ${y.join(", ")}`});let R=await _o(p,hr),w=g.filter(I=>{let P=R.get(I);return P!==void 0&&!P.includes(d)});if(w.length>0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:w.map(I=>`${I} deploys only to: ${(R.get(I)??[]).join(", ")}`).join("; "),stderrExcerpt:`${hr} gates these services out of ${d}: ${w.join(", ")}`});let x=o??!1;x&&h.addOption("--skip-terraform",!0);let W=I=>{let P={releaseBranch:i,version:a,environment:d,services:g,skipTerraformDeploy:x,success:I};return{content:k(JSON.stringify(P,null,2)),structuredContent:P}};if(!await Fo({confirmedCommand:s,branch:i,env:d}))return u.info("Deployment cancelled"),W(!1);try{cd.quiet=!0;let I=g.flatMap(le=>["-f",`${le}=true`]);return await cd`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${d} ${I} ${x?["-f","skip_terraform_deploy=true"]:[]}`,cd.quiet=!1,u.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${d}, services: ${g.join(", ")}`),h.print(),W(!0)}catch(I){throw u.error({error:I},"\u274C Error launching workflow"),new f(I,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},ld=S({name:"gh-release-deploy-selected",requiresHumanConfirm:!0,formProvider:Oh,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:Te.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:Te.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:Te.array(Te.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:Te.boolean().optional().describe("Skip the terraform deployment stage."),confirm:Te.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:Te.string().describe("The release branch that was deployed"),version:Te.string().describe("The version that was deployed"),environment:Te.string().describe("The environment deployed to"),services:Te.array(Te.string()).describe("The services that were deployed"),skipTerraformDeploy:Te.boolean().describe("Whether terraform deployment was skipped"),success:Te.boolean().describe("Whether the deployment was successful")},handler:Ei});import{z as Lt}from"zod";var xi=async()=>{let t=(await F()).flatMap(i=>{let a=G(i.branch);return a?[{version:X(a),jiraKey:re(a),type:i.type,titleMismatch:i.titleMismatch}]:[]}),r=await Hs(),n=Math.max(...t.map(i=>i.version.length)),o=t.map(i=>{let a=co(i.version,i.type,n),c=r.get(i.jiraKey),l=c?.description?` ${c.description}`:"",d=c?.releaseDate?` \xB7 ships ${c.releaseDate}`:"",p=i.titleMismatch?" \u26A0 title/base mismatch":"";return`${a}${l}${d}${p}`});u.info(`All release branches:
395
404
  `),u.info(`
396
405
  ${o.join(`
397
406
  `)}
398
- `);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}},ad=S({name:"gh-release-list",description:"List every open release PR with its version, type (regular / hotfix), and the associated Jira fix version\u2019s description and planned release date. Read-only; sourced from GitHub and Jira.",inputSchema:{},outputSchema:{releases:Mt.array(Mt.object({version:Mt.string().describe("Release version"),type:Mt.enum(["regular","hotfix"]).describe("Release type"),description:Mt.string().nullable().describe("Jira version description"),releaseDate:Mt.string().nullable().describe("Planned release date of the Jira version (yyyy-mm-dd)"),titleMismatch:Mt.boolean().describe("The PR title names a different release type than its base branch")})).describe("List of all release branches"),count:Mt.number().describe("Number of release branches")},handler:Ei});import gT from"node:process";var cd=e=>({...e}),ld=e=>{let{env:t,branch:r,sha:n,isClean:o,ambient:s=gT.env}=e,i={VITE_DOMAIN_ENV:t,VITE_BRANCH_NAME:r,VITE_COMMIT_HASH:o?n:`${n}-dirty`},a={},c=[];for(let[l,d]of Object.entries(s)){if(l.startsWith("VITE_")){c.push(l);continue}a[l]=d}return c.sort(),{childEnv:{...a,...i,DEPLOY_ENV:t,DEPLOY_BRANCH:r,DEPLOY_SHA:n,DEPLOY_SHA_LABEL:i.VITE_COMMIT_HASH,TURBO_TELEMETRY_DISABLED:"1"},contract:i,stripped:c}},xi=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(`
399
- `)};import $T from"@inquirer/checkbox";import AT from"@inquirer/confirm";import OT from"@inquirer/select";import{spawn as IT}from"node:child_process";import DT from"node:process";import{z}from"zod";import{$ as jo}from"zx";import{$ as Mo}from"zx";var hT=async e=>{let t=Mo.quiet;Mo.quiet=!0;try{let r=`/${e}/environment`,n=await Mo`aws sts get-caller-identity --query Account --output text`,o=await Mo`aws ssm get-parameter --name ${r} --query Parameter.Value --output text`;return{accountId:n.stdout.trim(),stage:o.stdout.trim()}}catch(r){throw new f(r,{operation:"resolve the AWS account for this deploy",remediation:`check that credentials are loaded and that \`/${e}/environment\` exists in the account they point at \u2014 run \`aws sts get-caller-identity\` to see which account that is`})}finally{Mo.quiet=t}},Ch=(e,t)=>{if(t.stage!==e)throw new f(void 0,{operation:"verify the target environment",remediation:"switch AWS_PROFILE to the account for this environment, or pass the env this account is",stderrExcerpt:`you asked for "${e}", but AWS account ${t.accountId} reports "${t.stage}" \u2014 refusing to deploy to an environment you did not name`})},$h=e=>{let{env:t,isShared:r,isClean:n}=e;if(!(!r||n))throw new f(void 0,{operation:`deploy to shared environment "${t}"`,remediation:"commit, or `git stash -u` (plain stash leaves untracked files), or deploy to a personal environment",stderrExcerpt:"the working tree has uncommitted or untracked changes and this environment is shared"})},Ah=(e,t)=>{if(t.includes(e))throw new f(void 0,{operation:`deploy to "${e}"`,remediation:"wait for the CI run to finish, or watch it with `gh run watch`",stderrExcerpt:`a CI deploy to "${e}" is already in flight \u2014 running both would interleave`})},dd=async e=>{let{env:t,project:r,isShared:n,isClean:o,runningEnvs:s,protectedEnvAccess:i}=e;Tr(t,`deploy to "${t}"`,i),Ah(t,s),$h({env:t,isShared:n,isClean:o});let a=await hT(r);return Ch(t,a),{identity:a}};import Oh from"node:fs/promises";import Ti from"node:path";var yT="devops/scripts",vT=/^deploy-(?<service>[a-z0-9-]+)\.sh$/,wT=/skip_unless_env_enabled\s+"[^"]*"\s+"[^"]*"\s+"(?<envs>[^"]*)"/,kT=/aws\s+ssm\s+get-parameter\s+--name[=\s]+(?<arg>[^\s)]+)/,bT=/aws\s+ssm\s+get-parameter\s+--name[=\s]+["']?\/(?<prefix>[\w.-]+)\/environment["']?(?![\w./-])/,ud=async e=>{let t=Ti.resolve(e,yT),r;try{r=await Oh.readdir(t)}catch{return[]}let n=await Yl(e);return(await Promise.all(r.map(s=>({entry:s,match:vT.exec(s)})).filter(s=>s.match!==null).map(async({entry:s,match:i})=>{let a=Ti.resolve(t,s),c=i?.groups?.service??"",l=ST(await RT(a));return{name:c,scriptPath:a,allowedEnvs:zl(PT(l),n.get(c)),ssmPrefix:xT(l)}}))).sort((s,i)=>s.name.localeCompare(i.name))},RT=async e=>{try{return await Oh.readFile(e,"utf-8")}catch{return""}},ST=e=>e.split(`
400
- `).map((t,r)=>({line:r+1,text:t})).filter(({text:t})=>!t.trimStart().startsWith("#")),PT=e=>{let t=e.reduce((n,{text:o})=>n??wT.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},ET=e=>{let t=e.replaceAll(/["']/g,"");return t.includes("$")&&(t.includes("/environment")||t.startsWith("$"))},xT=e=>{for(let{line:t,text:r}of e){let n=bT.exec(r)?.groups?.prefix;if(n!==void 0)return n;let o=kT.exec(r)?.groups?.arg;if(o!==void 0&&ET(o))return{unparseable:{line:t,text:r.trim()}}}return null},TT=e=>{let t=new Map;for(let r of e)typeof r.ssmPrefix=="string"&&t.set(r.ssmPrefix,[...t.get(r.ssmPrefix)??[],Ti.basename(r.scriptPath)]);return t},CT=e=>{let t=e.flatMap(r=>{if(r.ssmPrefix===null||typeof r.ssmPrefix=="string")return[];let{line:n,text:o}=r.ssmPrefix.unparseable;return[`${Ti.basename(r.scriptPath)}:${n}: ${o}`]});if(t.length!==0)throw new f(void 0,{operation:"resolve the SSM project prefix",remediation:"write the parameter name as a literal `/<project>/environment` so infra-kit can preflight it",stderrExcerpt:t.join("; ")})},Ih=e=>{CT(e);let t=TT(e),[r,...n]=t.keys();if(r===void 0)throw new f(void 0,{operation:"resolve the SSM project prefix",remediation:'add `aws ssm get-parameter --name "/<project>/environment"` to at least one devops/scripts/deploy-*.sh',stderrExcerpt:`none of ${e.length} deploy scripts reads /<project>/environment`});if(n.length>0){let o=[...t.entries()].sort(([,s],[,i])=>s.length-i.length).map(([s,i])=>`${s}: ${i.join(", ")}`).join("; ");throw new f(void 0,{operation:"resolve the SSM project prefix",remediation:"make every deploy script read the same /<project>/environment parameter",stderrExcerpt:`${t.size} different prefixes across ${e.length} deploy scripts \u2014 ${o}`})}return r},Ci=(e,t)=>e.allowedEnvs===null||e.allowedEnvs.includes(t),pd=(e,t)=>e.filter(r=>Ci(r,t));var fd="deploy-all.yml",Nh="/bin/sh",NT=async()=>{let e=jo.quiet;jo.quiet=!0;try{let t=await jo`gh run list --workflow=${fd} --status=in_progress --json displayTitle`;return JSON.parse(t.stdout).flatMap(n=>/\[(?<env>[a-z0-9-]+)\]/.exec(n.displayTitle??"")?.groups?.env??[])}catch{return[]}finally{jo.quiet=e}},_T=async(e,t)=>{let r=e.map(o=>({name:o.name,value:o.name})),n=await O(o=>$T({message:`Deploy which services to ${t}?`,choices:r,pageSize:20},o),{whenHeadless:{refuse:"service"}});if(n.length===0)throw new f(void 0,{operation:"select services",remediation:"pick at least one service, or use `local deploy-all`",stderrExcerpt:"no services selected"});return n},MT=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 J()&&ks(i,{env:t,services:n,accountId:o,shared:r}),r?O(a=>OT({message:i,choices:[{name:"No, cancel",value:!1},{name:`Yes, deploy to ${t}`,value:!0}]},a),{whenHeadless:"refuse"}):O(a=>AT({message:i,default:!1},a),{whenHeadless:"refuse"})},jT=(e,t,r)=>new Promise((n,o)=>{let s=IT(Nh,[e.scriptPath],{cwd:r,env:t,stdio:"inherit"});s.on("error",o),s.on("close",i=>{n(i??1)})}),FT=async e=>{let{chosen:t,childEnv:r,cwd:n,env:o}=e,s=[],i=[];for(let a of t){u.info(`\u2192 ${a.name} \u2192 ${o}`);let c=await jT(a,r,n);if(c!==0){i.push(a.name),u.error(`\u2717 ${a.name} failed (exit ${c})`);break}s.push(a.name),u.info(`\u2713 ${a.name}`)}return{deployed:s,failed:i}},LT=e=>{let{names:t,services:r,env:n}=e,o=new Map(r.map(a=>[a.name,a])),s=t.filter(a=>!o.has(a));if(s.length>0)throw new f(void 0,{operation:"resolve the requested services",remediation:`known services: ${r.map(a=>a.name).join(", ")}`,stderrExcerpt:`no deploy script for: ${s.join(", ")}`});let i=t.filter(a=>{let c=o.get(a);return c!==void 0&&!Ci(c,n)});if(i.length>0)throw new f(void 0,{operation:`deploy to "${n}"`,remediation:"drop those services, or deploy them to an environment they allow",stderrExcerpt:`not enabled for "${n}": ${i.join(", ")} (the scripts would skip them)`});return t.map(a=>o.get(a))},md=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:cd(o.contract),strippedVars:o.stripped,dryRun:a,success:c};return{content:k(JSON.stringify(l,null,2)),structuredContent:l}},BT=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(),_T(r,o))},_h=async(e,t)=>{let{env:r,service:n,confirmedCommand:o,dryRun:s,printEnv:i}=e,a=await T(),c=await ud(a);if(c.length===0)throw new f(void 0,{operation:"discover deployable services",remediation:"run this from a repo that has devops/scripts/deploy-*.sh",stderrExcerpt:`no deploy scripts found under ${a}/devops/scripts`});let l=Ih(c);await Ge({provider:gd[t],params:e,operation:"deploy locally",argument:"env"});let d=await Je(),p=bt(await Rt(fd),d),m=r??"";m||(h.setInteractive(),m=await fn(p,"deploy locally")),h.addOption("--env",m);let g=pd(c,m);if(g.length===0)throw new f(void 0,{operation:`deploy to "${m}"`,remediation:"pick an environment these services allow",stderrExcerpt:`no service on disk is enabled for "${m}"`});let y=await BT({selection:t,eligible:g,service:n,env:m}),R=LT({names:y,services:c,env:m});if(t==="selected")for(let ma of y)h.addOption("--service",ma);let w=On(m),$=await Pr(),B=(await jo`git rev-parse HEAD`.quiet()).stdout.trim(),I=await Rp(),P=ld({env:m,branch:$,sha:B,isClean:I});i&&u.info(`Deploy contract for ${m}:
401
- ${xi(P)}`);let te=(await dd({env:m,project:l,isShared:w,isClean:I,runningEnvs:await NT(),protectedEnvAccess:d})).identity.accountId;if(s)return u.info([`Would deploy to "${m}" (AWS account ${te}) from this machine`,`Preflight parameter: /${l}/environment`,xi(P),"Commands:",...R.map(ma=>` ${Nh} ${ma.scriptPath}`),"","Dry run: preflight and contract only \u2014 says nothing about whether the deploy would succeed."].join(`
402
- `)),md({env:m,accountId:te,names:y,built:P,deployed:[],failed:[],dryRun:!0,success:!0});if(!o&&!await MT({env:m,isShared:w,names:y,accountId:te}))return u.info("Deployment cancelled"),md({env:m,accountId:te,names:y,built:P,deployed:[],failed:[],dryRun:!1,success:!1});P.stripped.length>0&&u.info(`Stripped ambient VITE_* from the build env: ${P.stripped.join(", ")}`);let{deployed:Ut,failed:es}=await FT({chosen:R,childEnv:P.childEnv,cwd:a,env:m});return es.length>0&&(u.error(`Partial deploy to "${m}": succeeded [${Ut.join(", ")||"none"}], failed [${es.join(", ")}]. There is no rollback \u2014 redeploy the previous commit to restore it.`),DT.exitCode=1),h.print(),md({env:m,accountId:te,names:y,built:P,deployed:Ut,failed:es,dryRun:!1,success:es.length===0})},Mh=async e=>_h(e,"all"),jh=async e=>_h(e,"selected"),Fh='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.',Lh={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.")},Bh={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")},Dh=e=>fr({workflowFile:fd,fields:["env"],toolName:e}),gd={all:Dh("local-deploy-all"),selected:Dh("local-deploy-selected")},hd=S({name:"local-deploy-all",description:`Deploy EVERY service enabled for an environment, from this machine. ${Fh}`,requiresHumanConfirm:!0,formProvider:gd.all,inputSchema:Lh,outputSchema:Bh,handler:Mh}),yd=S({name:"local-deploy-selected",description:`Deploy a NAMED SUBSET of services from this machine. ${Fh}`,requiresHumanConfirm:!0,formProvider:gd.selected,inputSchema:{...Lh,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:Bh,handler:jh});import UT from"@inquirer/confirm";import $i from"@inquirer/input";import Jh from"@inquirer/select";import wd from"node:process";import{z as U}from"zod";import{z as Fo}from"zod";var gn=async(e,t)=>new Promise(r=>{let n=setTimeout(()=>{r(null)},t);e.then(o=>{clearTimeout(n),r(o)},()=>{clearTimeout(n),r(null)})});var Uh=2500,Wh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Vh=e=>typeof e=="string"&&e.trim()!==""?e.trim():void 0,WT=async()=>{let e=await ko();return{regular:dn(e,"regular"),hotfix:dn(e,"hotfix")}},VT=(e,t)=>e===null?(u.info({msg:"Tool execution form hint unavailable (timeout): release-create"}),`The "next" hint could not be computed within ${t/1e3} s \u2014 "next" still works and is resolved at execution.`):e.regular===null&&e.hotfix===null?(u.info({msg:"Tool execution form hint unavailable (no prior versions): release-create"}),'No prior version is known from origin release/v* branches or Jira, so "next" will be REFUSED \u2014 pass an explicit semver.'):`"next" resolves to ${e.regular} for a regular release or ${e.hotfix} for a hotfix (computed now from origin release/v* branches and Jira fix versions; recomputed at execution).`,vd=(e={})=>{let t=e.hintBudgetMs??Uh;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=>Wh(r)&&(r.releases===void 0||Array.isArray(r.releases)&&r.releases.length===0),buildRequestedSchema:async()=>{let r=await gn(WT(),t);return Fo.object({type:Fo.enum(["regular","hotfix"]).describe('Release type. "regular" branches off dev and bumps the minor; "hotfix" branches off main and bumps the patch.'),release:Fo.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. ${VT(r,t)}`),description:Fo.string().optional().describe("Optional. Becomes the Jira fix version description and feeds the PR body. Blank means none."),releaseDate:Fo.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=Vh(r.description),a=Vh(r.releaseDate),c=di(o);return{...Wh(n)?n:{},releases:[{...c,type:s,...i===void 0?{}:{description:i},...a===void 0?{}:{releaseDate:a}}]}}}};var JT='"1.2.5" or "next"',kd=(e,t)=>{try{return bl(e,t)}catch(r){throw r instanceof cr?new f(r,{operation:"resolve release version",remediation:'pass an explicit version (e.g. "1.2.5") instead of "next" when there are no prior versions'}):r instanceof vp?new f(r,{operation:"validate release name",remediation:'use a kebab-case name like "checkout-redesign" (lowercase, digits, single hyphens, not a reserved word)'}):r}},GT=async(e,t)=>{let r=dn(e,t),n=r?` [${r}]`:"",o=(await O(i=>$i({message:` Version (e.g. ${JT})${n}: `},i),{whenHeadless:"refuse"})).trim(),s=o===""?r??"":o;return s===""&&(u.error("No version provided. Exiting..."),wd.exit(1)),s},KT=async()=>{let e=(await O(t=>$i({message:' Name (kebab-case, e.g. "checkout-redesign"): '},t),{whenHeadless:"refuse"})).trim();e===""&&(u.error("No name provided. Exiting..."),wd.exit(1));try{ps(e)}catch(t){let r=t instanceof Error?t.message:String(t);u.error(`${r} Exiting...`),wd.exit(1)}return e},HT=async()=>(await O(e=>$i({message:" Release date (yyyy-mm-dd, optional, press Enter to skip): ",validate:wo},e),{whenHeadless:"refuse"})).trim(),qT=async e=>{h.setInteractive();let t=null,r=[],n=async()=>(t===null&&(t=await e(),r.push(...t)),r),o=[],s=!0;for(;s;){let i=o.length+1,a=await O(m=>Jh({message:`Release #${i} \u2014 version or name?`,choices:[{name:"version (semver / next)",value:"version"},{name:"name (free-form)",value:"name"}],default:"version"},m),{whenHeadless:"refuse"}),c=await O(m=>Jh({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 KT();l=kd([{name:m,type:c}],[])[0]}else{let m=await GT(await n(),c);l=kd([{version:m,type:c}],r)[0],l.id.kind==="version"&&r.push(Ot(`v${l.id.raw}`))}let d=(await O(m=>$i({message:" Description (optional, press Enter to skip): "},m),{whenHeadless:"refuse"})).trim(),p=await HT();o.push({...l,...d!==""?{description:d}:{},...p!==""?{releaseDate:p}:{}}),s=await O(m=>UT({message:"Add another release?",default:!1},m),{whenHeadless:"refuse"})}return o},YT=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 ")},Gh=e=>{for(let t of e)h.addOption("--release",kl(t))},zT=async(e,t)=>{if(e&&e.length>0){let n=Rl(e)?await t():[],o=kd(e,n);return Gh(o),o}if(ye())throw new x({status:"argument_required",argument:"release",agentMode:N.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 qT(t);return Gh(r),r},XT=e=>{if(new Set(e.map(r=>r.type)).size>1)throw new f(void 0,{operation:"create release",remediation:"create regular and hotfix releases in separate invocations",stderrExcerpt:"mixed regular and hotfix releases in one batch are not supported"})},ZT=async(e,t)=>{let r=e.map(YT).join(`
403
- - `);await V(t,`Create the following ${e.length} release(s)?
407
+ `);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}},dd=S({name:"gh-release-list",description:"List every open release PR with its version, type (regular / hotfix), and the associated Jira fix version\u2019s description and planned release date. Read-only; sourced from GitHub and Jira.",inputSchema:{},outputSchema:{releases:Lt.array(Lt.object({version:Lt.string().describe("Release version"),type:Lt.enum(["regular","hotfix"]).describe("Release type"),description:Lt.string().nullable().describe("Jira version description"),releaseDate:Lt.string().nullable().describe("Planned release date of the Jira version (yyyy-mm-dd)"),titleMismatch:Lt.boolean().describe("The PR title names a different release type than its base branch")})).describe("List of all release branches"),count:Lt.number().describe("Number of release branches")},handler:xi});import RT from"node:process";var ud=e=>({...e}),pd=e=>{let{env:t,branch:r,sha:n,isClean:o,ambient:s=RT.env}=e,i={VITE_DOMAIN_ENV:t,VITE_BRANCH_NAME:r,VITE_COMMIT_HASH:o?n:`${n}-dirty`},a={},c=[];for(let[l,d]of Object.entries(s)){if(l.startsWith("VITE_")){c.push(l);continue}a[l]=d}return c.sort(),{childEnv:{...a,...i,DEPLOY_ENV:t,DEPLOY_BRANCH:r,DEPLOY_SHA:n,DEPLOY_SHA_LABEL:i.VITE_COMMIT_HASH,TURBO_TELEMETRY_DISABLED:"1"},contract:i,stripped:c}},Ti=e=>{let t=Object.entries(e.contract).map(([r,n])=>` ${r.padEnd(17)}= ${n}`);return e.stripped.length>0&&t.push(` stripped from shell: ${e.stripped.join(", ")}`),t.join(`
408
+ `)};import MT from"@inquirer/checkbox";import jT from"@inquirer/confirm";import FT from"@inquirer/select";import{spawn as LT}from"node:child_process";import BT from"node:process";import{z}from"zod";import{$ as Wo}from"zx";import{$ as Bo}from"zx";var ST=async e=>{let t=Bo.quiet;Bo.quiet=!0;try{let r=`/${e}/environment`,n=await Bo`aws sts get-caller-identity --query Account --output text`,o=await Bo`aws ssm get-parameter --name ${r} --query Parameter.Value --output text`;return{accountId:n.stdout.trim(),stage:o.stdout.trim()}}catch(r){throw new f(r,{operation:"resolve the AWS account for this deploy",remediation:`check that credentials are loaded and that \`/${e}/environment\` exists in the account they point at \u2014 run \`aws sts get-caller-identity\` to see which account that is`})}finally{Bo.quiet=t}},Ih=(e,t)=>{if(t.stage!==e)throw new f(void 0,{operation:"verify the target environment",remediation:"switch AWS_PROFILE to the account for this environment, or pass the env this account is",stderrExcerpt:`you asked for "${e}", but AWS account ${t.accountId} reports "${t.stage}" \u2014 refusing to deploy to an environment you did not name`})},Dh=e=>{let{env:t,isShared:r,isClean:n}=e;if(!(!r||n))throw new f(void 0,{operation:`deploy to shared environment "${t}"`,remediation:"commit, or `git stash -u` (plain stash leaves untracked files), or deploy to a personal environment",stderrExcerpt:"the working tree has uncommitted or untracked changes and this environment is shared"})},Nh=(e,t)=>{if(t.includes(e))throw new f(void 0,{operation:`deploy to "${e}"`,remediation:"wait for the CI run to finish, or watch it with `gh run watch`",stderrExcerpt:`a CI deploy to "${e}" is already in flight \u2014 running both would interleave`})},md=async e=>{let{env:t,project:r,isShared:n,isClean:o,runningEnvs:s,protectedEnvAccess:i}=e;Ar(t,`deploy to "${t}"`,i),Nh(t,s),Dh({env:t,isShared:n,isClean:o});let a=await ST(r);return Ih(t,a),{identity:a}};import _h from"node:fs/promises";import Ci from"node:path";var PT="devops/scripts",ET=/^deploy-(?<service>[a-z0-9-]+)\.sh$/,xT=/skip_unless_env_enabled\s+"[^"]*"\s+"[^"]*"\s+"(?<envs>[^"]*)"/,TT=/aws\s+ssm\s+get-parameter\s+--name[=\s]+(?<arg>[^\s)]+)/,CT=/aws\s+ssm\s+get-parameter\s+--name[=\s]+["']?\/(?<prefix>[\w.-]+)\/environment["']?(?![\w./-])/,fd=async e=>{let t=Ci.resolve(e,PT),r;try{r=await _h.readdir(t)}catch{return[]}let n=await Zl(e);return(await Promise.all(r.map(s=>({entry:s,match:ET.exec(s)})).filter(s=>s.match!==null).map(async({entry:s,match:i})=>{let a=Ci.resolve(t,s),c=i?.groups?.service??"",l=AT(await $T(a));return{name:c,scriptPath:a,allowedEnvs:Ql(OT(l),n.get(c)),ssmPrefix:DT(l)}}))).sort((s,i)=>s.name.localeCompare(i.name))},$T=async e=>{try{return await _h.readFile(e,"utf-8")}catch{return""}},AT=e=>e.split(`
409
+ `).map((t,r)=>({line:r+1,text:t})).filter(({text:t})=>!t.trimStart().startsWith("#")),OT=e=>{let t=e.reduce((n,{text:o})=>n??xT.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},IT=e=>{let t=e.replaceAll(/["']/g,"");return t.includes("$")&&(t.includes("/environment")||t.startsWith("$"))},DT=e=>{for(let{line:t,text:r}of e){let n=CT.exec(r)?.groups?.prefix;if(n!==void 0)return n;let o=TT.exec(r)?.groups?.arg;if(o!==void 0&&IT(o))return{unparseable:{line:t,text:r.trim()}}}return null},NT=e=>{let t=new Map;for(let r of e)typeof r.ssmPrefix=="string"&&t.set(r.ssmPrefix,[...t.get(r.ssmPrefix)??[],Ci.basename(r.scriptPath)]);return t},_T=e=>{let t=e.flatMap(r=>{if(r.ssmPrefix===null||typeof r.ssmPrefix=="string")return[];let{line:n,text:o}=r.ssmPrefix.unparseable;return[`${Ci.basename(r.scriptPath)}:${n}: ${o}`]});if(t.length!==0)throw new f(void 0,{operation:"resolve the SSM project prefix",remediation:"write the parameter name as a literal `/<project>/environment` so infra-kit can preflight it",stderrExcerpt:t.join("; ")})},Mh=e=>{_T(e);let t=NT(e),[r,...n]=t.keys();if(r===void 0)throw new f(void 0,{operation:"resolve the SSM project prefix",remediation:'add `aws ssm get-parameter --name "/<project>/environment"` to at least one devops/scripts/deploy-*.sh',stderrExcerpt:`none of ${e.length} deploy scripts reads /<project>/environment`});if(n.length>0){let o=[...t.entries()].sort(([,s],[,i])=>s.length-i.length).map(([s,i])=>`${s}: ${i.join(", ")}`).join("; ");throw new f(void 0,{operation:"resolve the SSM project prefix",remediation:"make every deploy script read the same /<project>/environment parameter",stderrExcerpt:`${t.size} different prefixes across ${e.length} deploy scripts \u2014 ${o}`})}return r},$i=(e,t)=>e.allowedEnvs===null||e.allowedEnvs.includes(t),gd=(e,t)=>e.filter(r=>$i(r,t));var yd="deploy-all.yml",Fh="/bin/sh",WT=async()=>{let e=Wo.quiet;Wo.quiet=!0;try{let t=await Wo`gh run list --workflow=${yd} --status=in_progress --json displayTitle`;return JSON.parse(t.stdout).flatMap(n=>/\[(?<env>[a-z0-9-]+)\]/.exec(n.displayTitle??"")?.groups?.env??[])}catch{return[]}finally{Wo.quiet=e}},VT=async(e,t)=>{let r=e.map(o=>({name:o.name,value:o.name})),n=await O(o=>MT({message:`Deploy which services to ${t}?`,choices:r,pageSize:20},o),{whenHeadless:{refuse:"service"}});if(n.length===0)throw new f(void 0,{operation:"select services",remediation:"pick at least one service, or use `local deploy-all`",stderrExcerpt:"no services selected"});return n},UT=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 J()&&Ss(i,{env:t,services:n,accountId:o,shared:r}),r?O(a=>FT({message:i,choices:[{name:"No, cancel",value:!1},{name:`Yes, deploy to ${t}`,value:!0}]},a),{whenHeadless:"refuse"}):O(a=>jT({message:i,default:!1},a),{whenHeadless:"refuse"})},JT=(e,t,r)=>new Promise((n,o)=>{let s=LT(Fh,[e.scriptPath],{cwd:r,env:t,stdio:"inherit"});s.on("error",o),s.on("close",i=>{n(i??1)})}),GT=async e=>{let{chosen:t,childEnv:r,cwd:n,env:o}=e,s=[],i=[];for(let a of t){u.info(`\u2192 ${a.name} \u2192 ${o}`);let c=await JT(a,r,n);if(c!==0){i.push(a.name),u.error(`\u2717 ${a.name} failed (exit ${c})`);break}s.push(a.name),u.info(`\u2713 ${a.name}`)}return{deployed:s,failed:i}},KT=e=>{let{names:t,services:r,env:n}=e,o=new Map(r.map(a=>[a.name,a])),s=t.filter(a=>!o.has(a));if(s.length>0)throw new f(void 0,{operation:"resolve the requested services",remediation:`known services: ${r.map(a=>a.name).join(", ")}`,stderrExcerpt:`no deploy script for: ${s.join(", ")}`});let i=t.filter(a=>{let c=o.get(a);return c!==void 0&&!$i(c,n)});if(i.length>0)throw new f(void 0,{operation:`deploy to "${n}"`,remediation:"drop those services, or deploy them to an environment they allow",stderrExcerpt:`not enabled for "${n}": ${i.join(", ")} (the scripts would skip them)`});return t.map(a=>o.get(a))},hd=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:ud(o.contract),strippedVars:o.stripped,dryRun:a,success:c};return{content:k(JSON.stringify(l,null,2)),structuredContent:l}},HT=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(),VT(r,o))},Lh=async(e,t)=>{let{env:r,service:n,confirmedCommand:o,dryRun:s,printEnv:i}=e,a=await T(),c=await fd(a);if(c.length===0)throw new f(void 0,{operation:"discover deployable services",remediation:"run this from a repo that has devops/scripts/deploy-*.sh",stderrExcerpt:`no deploy scripts found under ${a}/devops/scripts`});let l=Mh(c);await qe({provider:vd[t],params:e,operation:"deploy locally",argument:"env"});let d=await He(),p=Pt(await Et(yd),d),m=r??"";m||(h.setInteractive(),m=await yn(p,"deploy locally")),h.addOption("--env",m);let g=gd(c,m);if(g.length===0)throw new f(void 0,{operation:`deploy to "${m}"`,remediation:"pick an environment these services allow",stderrExcerpt:`no service on disk is enabled for "${m}"`});let y=await HT({selection:t,eligible:g,service:n,env:m}),R=KT({names:y,services:c,env:m});if(t==="selected")for(let ga of y)h.addOption("--service",ga);let w=Nn(m),x=await Tr(),W=(await Wo`git rev-parse HEAD`.quiet()).stdout.trim(),I=await Ep(),P=pd({env:m,branch:x,sha:W,isClean:I});i&&u.info(`Deploy contract for ${m}:
410
+ ${Ti(P)}`);let te=(await md({env:m,project:l,isShared:w,isClean:I,runningEnvs:await WT(),protectedEnvAccess:d})).identity.accountId;if(s)return u.info([`Would deploy to "${m}" (AWS account ${te}) from this machine`,`Preflight parameter: /${l}/environment`,Ti(P),"Commands:",...R.map(ga=>` ${Fh} ${ga.scriptPath}`),"","Dry run: preflight and contract only \u2014 says nothing about whether the deploy would succeed."].join(`
411
+ `)),hd({env:m,accountId:te,names:y,built:P,deployed:[],failed:[],dryRun:!0,success:!0});if(!o&&!await UT({env:m,isShared:w,names:y,accountId:te}))return u.info("Deployment cancelled"),hd({env:m,accountId:te,names:y,built:P,deployed:[],failed:[],dryRun:!1,success:!1});P.stripped.length>0&&u.info(`Stripped ambient VITE_* from the build env: ${P.stripped.join(", ")}`);let{deployed:Gt,failed:os}=await GT({chosen:R,childEnv:P.childEnv,cwd:a,env:m});return os.length>0&&(u.error(`Partial deploy to "${m}": succeeded [${Gt.join(", ")||"none"}], failed [${os.join(", ")}]. There is no rollback \u2014 redeploy the previous commit to restore it.`),BT.exitCode=1),h.print(),hd({env:m,accountId:te,names:y,built:P,deployed:Gt,failed:os,dryRun:!1,success:os.length===0})},Bh=async e=>Lh(e,"all"),Wh=async e=>Lh(e,"selected"),Vh='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.',Uh={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.")},Jh={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")},jh=e=>gr({workflowFile:yd,fields:["env"],toolName:e}),vd={all:jh("local-deploy-all"),selected:jh("local-deploy-selected")},wd=S({name:"local-deploy-all",description:`Deploy EVERY service enabled for an environment, from this machine. ${Vh}`,requiresHumanConfirm:!0,formProvider:vd.all,inputSchema:Uh,outputSchema:Jh,handler:Bh}),kd=S({name:"local-deploy-selected",description:`Deploy a NAMED SUBSET of services from this machine. ${Vh}`,requiresHumanConfirm:!0,formProvider:vd.selected,inputSchema:{...Uh,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:Jh,handler:Wh});import zT from"@inquirer/confirm";import Ai from"@inquirer/input";import qh from"@inquirer/select";import Rd from"node:process";import{z as U}from"zod";import{z as Vo}from"zod";var vn=async(e,t)=>new Promise(r=>{let n=setTimeout(()=>{r(null)},t);e.then(o=>{clearTimeout(n),r(o)},()=>{clearTimeout(n),r(null)})});var Hh=2500,Gh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Kh=e=>typeof e=="string"&&e.trim()!==""?e.trim():void 0,qT=async()=>{let e=await So();return{regular:mn(e,"regular"),hotfix:mn(e,"hotfix")}},YT=(e,t)=>e===null?(u.info({msg:"Tool execution form hint unavailable (timeout): release-create"}),`The "next" hint could not be computed within ${t/1e3} s \u2014 "next" still works and is resolved at execution.`):e.regular===null&&e.hotfix===null?(u.info({msg:"Tool execution form hint unavailable (no prior versions): release-create"}),'No prior version is known from origin release/v* branches or Jira, so "next" will be REFUSED \u2014 pass an explicit semver.'):`"next" resolves to ${e.regular} for a regular release or ${e.hotfix} for a hotfix (computed now from origin release/v* branches and Jira fix versions; recomputed at execution).`,bd=(e={})=>{let t=e.hintBudgetMs??Hh;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=>Gh(r)&&(r.releases===void 0||Array.isArray(r.releases)&&r.releases.length===0),buildRequestedSchema:async()=>{let r=await vn(qT(),t);return Vo.object({type:Vo.enum(["regular","hotfix"]).describe('Release type. "regular" branches off dev and bumps the minor; "hotfix" branches off main and bumps the patch.'),release:Vo.string().describe(`A semver such as "1.64.0", the literal "next", or a kebab-case name such as "checkout-redesign" \u2014 no "@" here, the date has its own field. ${YT(r,t)}`),description:Vo.string().optional().describe("Optional. Becomes the Jira fix version description and feeds the PR body. Blank means none."),releaseDate:Vo.string().optional().describe("Optional. Planned production date, yyyy-mm-dd. Becomes the Jira fix version's release date; delivery overwrites it with the actual date. On the re-run it is passed as <token>@yyyy-mm-dd inside -r.")})},toArgs:(r,n)=>{let o=typeof r.release=="string"?r.release.trim():"";if(o==="")return null;let s=r.type==="hotfix"?"hotfix":"regular",i=Kh(r.description),a=Kh(r.releaseDate),c=pi(o);return{...Gh(n)?n:{},releases:[{...c,type:s,...i===void 0?{}:{description:i},...a===void 0?{}:{releaseDate:a}}]}}}};var XT='"1.2.5" or "next"',Sd=(e,t)=>{try{return Sl(e,t)}catch(r){throw r instanceof lr?new f(r,{operation:"resolve release version",remediation:'pass an explicit version (e.g. "1.2.5") instead of "next" when there are no prior versions'}):r instanceof bp?new f(r,{operation:"validate release name",remediation:'use a kebab-case name like "checkout-redesign" (lowercase, digits, single hyphens, not a reserved word)'}):r}},ZT=async(e,t)=>{let r=mn(e,t),n=r?` [${r}]`:"",o=(await O(i=>Ai({message:` Version (e.g. ${XT})${n}: `},i),{whenHeadless:"refuse"})).trim(),s=o===""?r??"":o;return s===""&&(u.error("No version provided. Exiting..."),Rd.exit(1)),s},QT=async()=>{let e=(await O(t=>Ai({message:' Name (kebab-case, e.g. "checkout-redesign"): '},t),{whenHeadless:"refuse"})).trim();e===""&&(u.error("No name provided. Exiting..."),Rd.exit(1));try{hs(e)}catch(t){let r=t instanceof Error?t.message:String(t);u.error(`${r} Exiting...`),Rd.exit(1)}return e},eC=async()=>(await O(e=>Ai({message:" Release date (yyyy-mm-dd, optional, press Enter to skip): ",validate:Ro},e),{whenHeadless:"refuse"})).trim(),tC=async e=>{h.setInteractive();let t=null,r=[],n=async()=>(t===null&&(t=await e(),r.push(...t)),r),o=[],s=!0;for(;s;){let i=o.length+1,a=await O(m=>qh({message:`Release #${i} \u2014 version or name?`,choices:[{name:"version (semver / next)",value:"version"},{name:"name (free-form)",value:"name"}],default:"version"},m),{whenHeadless:"refuse"}),c=await O(m=>qh({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 QT();l=Sd([{name:m,type:c}],[])[0]}else{let m=await ZT(await n(),c);l=Sd([{version:m,type:c}],r)[0],l.id.kind==="version"&&r.push(Nt(`v${l.id.raw}`))}let d=(await O(m=>Ai({message:" Description (optional, press Enter to skip): "},m),{whenHeadless:"refuse"})).trim(),p=await eC();o.push({...l,...d!==""?{description:d}:{},...p!==""?{releaseDate:p}:{}}),s=await O(m=>zT({message:"Add another release?",default:!1},m),{whenHeadless:"refuse"})}return o},rC=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 ")},Yh=e=>{for(let t of e)h.addOption("--release",Rl(t))},nC=async(e,t)=>{if(e&&e.length>0){let n=Pl(e)?await t():[],o=Sd(e,n);return Yh(o),o}if(ye())throw new C({status:"argument_required",argument:"release",agentMode:N.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 tC(t);return Yh(r),r},oC=e=>{if(new Set(e.map(r=>r.type)).size>1)throw new f(void 0,{operation:"create release",remediation:"create regular and hotfix releases in separate invocations",stderrExcerpt:"mixed regular and hotfix releases in one batch are not supported"})},sC=async(e,t)=>{let r=e.map(rC).join(`
412
+ - `);await B(t,`Create the following ${e.length} release(s)?
404
413
  - ${r}
405
- `),h.addOption("--yes",!0)},QT=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 Wr({operation:`create release ${o}`});let s=await Lc(t.type),i=await Bc({id:t.id,jiraConfig:r,description:t.description,...t.releaseDate===void 0?{}:{releaseDate:t.releaseDate},type:t.type,baseSha:s});return u.info(`\u2705 Successfully created release: ${o} (${t.type})`),u.info(`\u{1F517} GitHub PR: ${i.prUrl}`),u.info(`\u{1F517} Jira Version: ${i.jiraVersionUrl}
406
- `),{result:i}}catch(s){let i=no(s)?s:void 0,a=new f(s,{operation:`create release ${o} (${t.type})`,remediation:i?.kind==="auth"?"reissue the Atlassian API token and update JIRA_TOKEN":"verify the version or name is unique and the base branch is clean",stderrExcerpt:i?.message});return u.error(`\u274C ${a.message}
407
- `),{failure:{version:n,error:a.message}}}},eC=(e,t,r)=>{t===e?u.info(`\u2705 All ${e} release branch(es) were created successfully.`):t>0?(u.warn(`\u26A0\uFE0F ${t} of ${e} release branches were created successfully.`),u.warn(`\u274C ${r} release(s) failed.`)):u.error(`\u274C All ${e} release branch(es) failed to create.`)},Kh=vd(),Ai=async e=>{let{releases:t,confirmedCommand:r}=e;await Pe({operation:"create release"}),await Ge({provider:Kh,params:e,operation:"create release",argument:"release"});let n=await qr(),o=null,i=await zT(t,async()=>(o===null&&(o=await ko()),o));if(i.length===0)throw new f(void 0,{operation:"create release",remediation:'pass at least one entry in "releases" (e.g. [{ version: "1.2.5", type: "regular" }])',stderrExcerpt:"no releases provided"});XT(i),await Zn({operation:"create release",base:Xe(i[0].type)}),await ZT(i,!!r);let a=[],c=[];for(let d of i){let{result:p,failure:m}=await QT({entry:d,jiraConfig:n});p&&a.push(p),m&&c.push(m)}eC(i.length,a.length,c.length),h.print();let l={createdBranches:a.map(d=>d.branchName),successCount:a.length,failureCount:c.length,releases:a,failedReleases:c};return{content:k(JSON.stringify(l,null,2)),structuredContent:l}},bd=S({name:"release-create",requiresHumanConfirm:!0,formProvider:Kh,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:U.array(U.object({version:U.string().optional().describe('Version to create (e.g., "1.2.5") or the literal token "next" for auto-increment. Mutually exclusive with "name".'),name:U.string().optional().describe('Free-form kebab-case release name (e.g., "checkout-redesign"). Mutually exclusive with "version". Named releases never auto-bump.'),type:U.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" (branches off dev) or "hotfix" (branches off main).'),description:U.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:U.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{createdBranches:U.array(U.string()).describe("List of created release branch names"),successCount:U.number().describe("Number of releases created successfully"),failureCount:U.number().describe("Number of releases that failed"),releases:U.array(U.object({version:U.string().describe("Version number"),type:U.enum(["regular","hotfix"]).describe("Release type"),branchName:U.string().describe("Release branch name"),prUrl:U.string().describe("GitHub PR URL"),jiraVersionUrl:U.string().describe("Jira version URL"),releaseDate:U.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:U.array(U.object({version:U.string().describe("Version number that failed"),error:U.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:Ai});import Hh from"@inquirer/input";import{z as Me}from"zod";var qh=["description","releaseDate"],tC=async()=>{let e=await F(),t=e.map(s=>s.branch),r=new Map(e.map(s=>[s.branch,s.type])),n=await se(),o=await Tt(ie({branches:t,descriptions:n,types:r}));return{branch:o,type:r.get(o)||"regular"}},rC=async e=>{let r=(await F()).find(n=>n.branch===e);if(!r)throw new f(void 0,{operation:`edit release ${e}`,remediation:`confirm an open PR exists for ${e} ('gh pr list')`});return r.type},nC=async e=>{let t=e===""?"(no current description)":`current: "${e}"`,n=(await O(o=>Hh({message:` New description ${t} (press Enter to keep current): `},o),{whenHeadless:{refuse:"description"}})).trim();return n===""?e:n},oC=async e=>{let t=e===null?"(no current date)":`current: ${e}`,n=(await O(o=>Hh({message:` Release date yyyy-mm-dd ${t} (press Enter to keep current): `,validate:wo},o),{whenHeadless:{refuse:"releaseDate"}})).trim();return n===""?e:ar(n)},sC=e=>{if(e!==void 0)return e===""?null:e},iC=async e=>(h.setInteractive(),{description:await nC(e.description),releaseDate:await oC(e.releaseDate)}),Rd=e=>e??"(none)",aC=(e,t,r)=>e==="description"?` description: "${t.description}" \u2192 "${r.description}"`:` release date: ${Rd(t.releaseDate)} \u2192 ${Rd(r.releaseDate)}`,Oi=async e=>{let{version:t,description:r,releaseDate:n,confirmedCommand:o}=e,s=sC(n),i=await qr(),a;t?(a=lt(t),await rC(a)):(h.setInteractive(),a=(await tC()).branch);let c=G(a);if(!c)throw new f(void 0,{operation:`edit release ${a}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let l=X(c);h.addOption("--version",l);let d=re(c),p=await at(d,i);if(!p)throw new f(void 0,{operation:`edit release ${d}`,remediation:`create the Jira fix version "${d}" first or pick a different release`});let m={description:p.description??"",releaseDate:p.releaseDate||null},g=r!==void 0||s!==void 0;if(!g&&J())throw new x({status:"argument_required",argument:"description",agentMode:N.source},2,{operation:"edit release",remediation:"pass --description and/or --release-date on the re-run",stderrExcerpt:"no field to edit and no human to ask"});let y=g?{description:r??m.description,releaseDate:s===void 0?m.releaseDate:s}:await iC(m),R=qh.filter(le=>y[le]!==m[le]),w=R.includes("description"),$=R.includes("releaseDate"),B=tr(i,p),I=le=>{let te={version:l,branch:a,jiraVersionUrl:B,previousDescription:m.description,newDescription:y.description,previousReleaseDate:m.releaseDate,newReleaseDate:y.releaseDate,changedFields:R,changed:le};return{content:k(JSON.stringify(te,null,2)),structuredContent:te}};if(R.length===0)return u.info(`No change \u2014 ${d} already has description "${m.description}" and release date ${Rd(m.releaseDate)}`),h.print(),I(!1);w&&h.addOption("--description",y.description),$&&h.addOption("--release-date",y.releaseDate??"");let P=R.map(le=>aC(le,m,y));return await V(o,`Update ${d}?
414
+ `),h.addOption("--yes",!0)},iC=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 Jr({operation:`create release ${o}`});let s=await Wc(t.type),i=await Vc({id:t.id,jiraConfig:r,description:t.description,...t.releaseDate===void 0?{}:{releaseDate:t.releaseDate},type:t.type,baseSha:s});return u.info(`\u2705 Successfully created release: ${o} (${t.type})`),u.info(`\u{1F517} GitHub PR: ${i.prUrl}`),u.info(`\u{1F517} Jira Version: ${i.jiraVersionUrl}
415
+ `),{result:i}}catch(s){let i=io(s)?s:void 0,a=new f(s,{operation:`create release ${o} (${t.type})`,remediation:i?.kind==="auth"?"reissue the Atlassian API token and update JIRA_TOKEN":"verify the version or name is unique and the base branch is clean",stderrExcerpt:i?.message});return u.error(`\u274C ${a.message}
416
+ `),{failure:{version:n,error:a.message}}}},aC=(e,t,r)=>{t===e?u.info(`\u2705 All ${e} release branch(es) were created successfully.`):t>0?(u.warn(`\u26A0\uFE0F ${t} of ${e} release branches were created successfully.`),u.warn(`\u274C ${r} release(s) failed.`)):u.error(`\u274C All ${e} release branch(es) failed to create.`)},zh=bd(),Oi=async e=>{let{releases:t,confirmedCommand:r}=e;await Ee({operation:"create release"}),await qe({provider:zh,params:e,operation:"create release",argument:"release"});let n=await Xr(),o=null,i=await nC(t,async()=>(o===null&&(o=await So()),o));if(i.length===0)throw new f(void 0,{operation:"create release",remediation:'pass at least one entry in "releases" (e.g. [{ version: "1.2.5", type: "regular" }])',stderrExcerpt:"no releases provided"});oC(i),await to({operation:"create release",base:et(i[0].type)}),await sC(i,!!r);let a=[],c=[];for(let d of i){let{result:p,failure:m}=await iC({entry:d,jiraConfig:n});p&&a.push(p),m&&c.push(m)}aC(i.length,a.length,c.length),h.print();let l={createdBranches:a.map(d=>d.branchName),successCount:a.length,failureCount:c.length,releases:a,failedReleases:c};return{content:k(JSON.stringify(l,null,2)),structuredContent:l}},Pd=S({name:"release-create",requiresHumanConfirm:!0,formProvider:zh,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:U.array(U.object({version:U.string().optional().describe('Version to create (e.g., "1.2.5") or the literal token "next" for auto-increment. Mutually exclusive with "name".'),name:U.string().optional().describe('Free-form kebab-case release name (e.g., "checkout-redesign"). Mutually exclusive with "version". Named releases never auto-bump.'),type:U.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" (branches off dev) or "hotfix" (branches off main).'),description:U.string().optional().describe("Optional description for the Jira version."),releaseDate:gl.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:U.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{createdBranches:U.array(U.string()).describe("List of created release branch names"),successCount:U.number().describe("Number of releases created successfully"),failureCount:U.number().describe("Number of releases that failed"),releases:U.array(U.object({version:U.string().describe("Version number"),type:U.enum(["regular","hotfix"]).describe("Release type"),branchName:U.string().describe("Release branch name"),prUrl:U.string().describe("GitHub PR URL"),jiraVersionUrl:U.string().describe("Jira version URL"),releaseDate:U.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:U.array(U.object({version:U.string().describe("Version number that failed"),error:U.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:Oi});import Xh from"@inquirer/input";import{z as Fe}from"zod";var Zh=["description","releaseDate"],cC=async()=>{let e=await F(),t=e.map(s=>s.branch),r=new Map(e.map(s=>[s.branch,s.type])),n=await se(),o=await At(ie({branches:t,descriptions:n,types:r}));return{branch:o,type:r.get(o)||"regular"}},lC=async e=>{let r=(await F()).find(n=>n.branch===e);if(!r)throw new f(void 0,{operation:`edit release ${e}`,remediation:`confirm an open PR exists for ${e} ('gh pr list')`});return r.type},dC=async e=>{let t=e===""?"(no current description)":`current: "${e}"`,n=(await O(o=>Xh({message:` New description ${t} (press Enter to keep current): `},o),{whenHeadless:{refuse:"description"}})).trim();return n===""?e:n},uC=async e=>{let t=e===null?"(no current date)":`current: ${e}`,n=(await O(o=>Xh({message:` Release date yyyy-mm-dd ${t} (press Enter to keep current): `,validate:Ro},o),{whenHeadless:{refuse:"releaseDate"}})).trim();return n===""?e:cr(n)},pC=e=>{if(e!==void 0)return e===""?null:e},mC=async e=>(h.setInteractive(),{description:await dC(e.description),releaseDate:await uC(e.releaseDate)}),Ed=e=>e??"(none)",fC=(e,t,r)=>e==="description"?` description: "${t.description}" \u2192 "${r.description}"`:` release date: ${Ed(t.releaseDate)} \u2192 ${Ed(r.releaseDate)}`,Ii=async e=>{let{version:t,description:r,releaseDate:n,confirmedCommand:o}=e,s=pC(n),i=await Xr(),a;t?(a=pt(t),await lC(a)):(h.setInteractive(),a=(await cC()).branch);let c=G(a);if(!c)throw new f(void 0,{operation:`edit release ${a}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let l=X(c);h.addOption("--version",l);let d=re(c),p=await dt(d,i);if(!p)throw new f(void 0,{operation:`edit release ${d}`,remediation:`create the Jira fix version "${d}" first or pick a different release`});let m={description:p.description??"",releaseDate:p.releaseDate||null},g=r!==void 0||s!==void 0;if(!g&&J())throw new C({status:"argument_required",argument:"description",agentMode:N.source},2,{operation:"edit release",remediation:"pass --description and/or --release-date on the re-run",stderrExcerpt:"no field to edit and no human to ask"});let y=g?{description:r??m.description,releaseDate:s===void 0?m.releaseDate:s}:await mC(m),R=Zh.filter(le=>y[le]!==m[le]),w=R.includes("description"),x=R.includes("releaseDate"),W=nr(i,p),I=le=>{let te={version:l,branch:a,jiraVersionUrl:W,previousDescription:m.description,newDescription:y.description,previousReleaseDate:m.releaseDate,newReleaseDate:y.releaseDate,changedFields:R,changed:le};return{content:k(JSON.stringify(te,null,2)),structuredContent:te}};if(R.length===0)return u.info(`No change \u2014 ${d} already has description "${m.description}" and release date ${Ed(m.releaseDate)}`),h.print(),I(!1);w&&h.addOption("--description",y.description),x&&h.addOption("--release-date",y.releaseDate??"");let P=R.map(le=>fC(le,m,y));return await B(o,`Update ${d}?
408
417
  ${P.join(`
409
418
  `)}
410
- `),h.addOption("--yes",!0),await Hr({versionId:p.id,...w?{description:y.description}:{},...$?{releaseDate:y.releaseDate}:{}},i),w&&await Vs({branch:a,body:ro(B,y.description)}),u.info(`\u2705 Updated ${R.join(" and ")} for ${d}`),u.info(`\u{1F517} Jira Version: ${B}`),u.info(`\u{1F517} PR branch: ${a}
411
- `),h.print(),I(!0)},Sd=S({name:"release-edit",description:"Edit a release's description and/or planned release date in Jira; a changed description is mirrored into the GitHub release PR body. Accepts a release version or a release name: targets the Jira fix version named `v<version>` (versioned) or `<name>` (named) and the open PR on branch `release/v<version>` or `release/<name>`. The PR body is rewritten canonically to `<jiraVersionUrl>\\n\\n<description>` \u2014 any prior manual edits to the body are overwritten. `version` and at least one of `description`/`releaseDate` are required for MCP calls (the picker and prompts are unreachable without a TTY). Empty string clears a field. Confirmation is auto-skipped for MCP, so the caller is responsible for gating.",inputSchema:{version:Me.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:Me.string().optional().describe("New description. Empty string clears the description."),releaseDate:fl.optional().describe("New planned release date (yyyy-mm-dd). Empty string clears the date.")},outputSchema:{version:Me.string().describe("Release version"),branch:Me.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:Me.string().describe("Jira fix version URL"),previousDescription:Me.string().describe("The description before the update"),newDescription:Me.string().describe("The description after the update"),previousReleaseDate:Me.string().nullable().describe("The planned release date before the update, or null"),newReleaseDate:Me.string().nullable().describe("The planned release date after the update, or null"),changedFields:Me.array(Me.enum(qh)).describe("The fields whose value actually changed"),changed:Me.boolean().describe("Whether anything actually changed")},handler:Oi});import{z as L}from"zod";import{$ as $d}from"zx";import Yh from"node:fs/promises";import Ii from"node:path";var Pd=async e=>{let{workspacePath:t,folderPaths:r}=e,n=Ii.dirname(t),o;try{o=await Yh.readFile(t,"utf-8")}catch(d){throw new Error(`Cursor workspace file not found at ${t}: ${d.message}`)}let s;try{s=JSON.parse(o)}catch(d){throw new Error(`Failed to parse ${t} as JSON. Comments (JSONC) are not supported. ${d.message}`)}let i=s.folders??[],a=new Set(i.map(d=>Ii.resolve(n,d.path))),c=[],l=[];for(let d of r){let p=Ii.resolve(d);if(a.has(p)){l.push(d);continue}let m=Ii.relative(n,p);i.push({path:m}),a.add(p),c.push(d)}return s.folders=i,await Yh.writeFile(t,`${JSON.stringify(s,null,2)}
412
- `,"utf-8"),{added:c,skipped:l}};import{$ as cC}from"zx";var Ed=async e=>{await cC`cursor ${e}`};import zh from"node:fs/promises";import Di from"node:path";var xd=async e=>{let{workspacePath:t,folderPaths:r}=e,n=Di.dirname(t),o;try{o=await zh.readFile(t,"utf-8")}catch(m){throw new Error(`Cursor workspace file not found at ${t}: ${m.message}`)}let s;try{s=JSON.parse(o)}catch(m){throw new Error(`Failed to parse ${t} as JSON. Comments (JSONC) are not supported. ${m.message}`)}let i=s.folders??[],a=new Set(r.map(m=>Di.resolve(m))),c=new Set,l=i.filter(m=>{let g=Di.resolve(n,m.path);return a.has(g)?(c.add(g),!1):!0});s.folders=l,await zh.writeFile(t,`${JSON.stringify(s,null,2)}
413
- `,"utf-8");let d=[],p=[];for(let m of r){let g=Di.resolve(m);c.has(g)?d.push(m):p.push(m)}return{removed:d,notFound:p}};import Xh from"node:path";var Lo=(e,t)=>Xh.isAbsolute(e)?e:Xh.resolve(t,e);var Td=async e=>{let{projectRoot:t,worktreeDir:r,branches:n}=e,o=await M(),s=yt(o),i=n.map(c=>`${r}/${c}`),a=[];for(let c of s)a.push(await lC({ide:c,projectRoot:t,folderPaths:i}));return a},lC=async e=>{let{ide:t,projectRoot:r,folderPaths:n}=e;if(!t.config.workspaceConfigPath)return u.warn("\u26A0\uFE0F Skipping Cursor: ide.config.workspaceConfigPath is not set in infra-kit config"),{ran:!1,provider:"cursor",added:0,skipped:0};let o=Lo(t.config.workspaceConfigPath,r),{added:s,skipped:i}=await Pd({workspacePath:o,folderPaths:n}),a=i.length>0?` (${i.length} already present)`:"";return u.info(`\u2705 Added ${s.length} folder(s) to ${o}${a}`),await Ed(o),{ran:!0,provider:"cursor",added:s.length,skipped:i.length}};var hr=async e=>{let{projectRoot:t,worktreeDir:r,removedWorktrees:n}=e;if(n.length===0)return[];let o=await M(),s=yt(o),i=n.map(c=>`${r}/${c}`),a=[];for(let c of s)a.push(await dC({ide:c,projectRoot:t,folderPaths:i}));return a},dC=async e=>{let{ide:t,projectRoot:r,folderPaths:n}=e;if(!t.config.workspaceConfigPath)return{provider:"cursor",supported:!0,removed:[]};let o=Lo(t.config.workspaceConfigPath,r);try{let{removed:s}=await xd({workspacePath:o,folderPaths:n});return s.length>0&&u.info(`\u2705 Removed ${s.length} folder(s) from ${o}`),{provider:"cursor",supported:!0,removed:s}}catch(s){return u.warn({error:s},`\u26A0\uFE0F Failed to update Cursor workspace at ${o}`),{provider:"cursor",supported:!0,removed:[]}}};var yr=["workspace","none"];import{z as Zh}from"zod";var ty=2500,Ni="release-remove",Qh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),uC=e=>e.version===void 0||e.version==="",pC=async()=>{try{return{outcome:"listed",prs:await F()}}catch(e){return e instanceof f&&e.operation===eo?{outcome:"empty"}:{outcome:"failed"}}},ey=(e,t)=>(e===null?u.info({msg:`Tool execution form enumeration timed out (gh pr list, ${t/1e3} s): ${Ni}`}):e.outcome==="failed"?u.info({msg:`Tool execution form enumeration failed (gh pr list): ${Ni}`}):u.info({msg:`Tool execution form options empty (open release PRs): ${Ni}`}),null),mC=(e,t)=>{let r=new Map(e.map(n=>[n.branch,n.type]));return Ks(e.map(n=>n.branch)).map(({branch:n,id:o,label:s})=>{let i=t?.get(re(o)),a=i===void 0?"":` \u2014 ${i}`;return{label:s,prose:`${s} [${r.get(n)??"regular"}]${a}`}})},fC=(e,t,r)=>{let n=e.map(o=>o.prose).join("; ");return t!==null?`Open release PRs right now: ${n}. `:(u.info({msg:`Tool execution form descriptions unavailable (timeout): ${Ni}`}),`Open release PRs right now: ${n}. Jira descriptions could not be fetched within ${r/1e3} s. `)},Cd=(e={})=>{let t=e.fetchBudgetMs??ty;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=>Qh(r)&&uC(r),buildRequestedSchema:async()=>{let[r,n]=await Promise.all([gn(pC(),t),gn(se(),t)]);if(r===null||r.outcome!=="listed")return ey(r,t);let o=mC(r.prs,n);return o.length===0?ey({outcome:"empty"},t):Zh.object({version:Zh.enum(o.map(s=>s.label)).describe(`The ONE release to tear down. ${fC(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:{...Qh(n)?n:{},version:r.version}}};var ry=["worktree","ide-folders","pr","local-branch","remote-branch","jira"],Mi={worktree:"remove the worktree","ide-folders":"strip the worktree from configured editors",pr:"close the PR","local-branch":"delete the local branch","remote-branch":"delete the remote branch",jira:"remove the Jira fix version"},vr="remove a release",Ve=e=>{throw u.warn({operation:e.operation},`\u26D4 ${e.stderrExcerpt??e.operation}`),new f(void 0,e)},ny=(e,t)=>{throw u.warn({operation:t.operation},`\u26D4 ${t.stderrExcerpt??t.operation}`),new x({...e,agentMode:N.source},2,t)},gC=e=>{ye()&&(e.version||ny({status:"argument_required",argument:"version"},{operation:vr,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&&ny({status:"refused"},{operation:vr,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"}))},sy=e=>{e.pr?.state==="MERGED"&&Ve({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`})},hC=(e,t)=>{if(t.skipJira||(e.jiraConfig||Ve({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)&&Ve({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||Ve({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)`}))},yC=e=>{if(e.worktreePresent||e.pr!==null||e.localTipSha!==null||e.remoteTipSha!==null||e.jira)return;Ve({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"})},vC=e=>{!e.worktreeDirty||e.worktreeDirty.length===0||Ve({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(", ")}`})},wC=async e=>(await $d`git -C ${e} status --porcelain`).stdout.split(`
414
- `).map(r=>r.trimEnd()).filter(r=>r.length>0),kC=async e=>{try{let{terminals:t}=await tm(e);return t.filter(r=>r.connected).length}catch(t){return u.debug({error:t,worktreePath:e},"release remove: orca terminal probe failed"),0}},bC=async e=>{let t=await Rs([e]);if(t!==null)throw u.warn({operation:vr},`\u26D4 this command runs inside an Orca terminal of ${t}`),new x({status:"refused",reason:"orca_caller_inside_target",agentMode:N.source},2,{operation:vr,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`})},RC=async(e,t)=>{let r={jiraConfig:null,jira:null,moveIssuesTo:null};if(t.skipJira)return r;let n=await ct();if(!n)return r;let o=await at(re(e),n),s=t.moveIssuesTo?await SC(t.moveIssuesTo,n):null;if(!o)return{jiraConfig:n,jira:null,moveIssuesTo:s};let i=await Js(o.id,n);return{jiraConfig:n,moveIssuesTo:s,jira:{version:o,fixCount:i.issuesFixedCount,affectsCount:i.issuesAffectedCount,url:tr(n,o)}}},SC=async(e,t)=>{let r=await at(e,t);return r||Ve({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}"`})},PC=async(e,t)=>{let r=G(e);r||Ve({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 T(),o=`${n}${ge}`,s=`${o}/${e}`,[i,a,c,l]=await Promise.all([me("release"),Ur(e),$e(n,`refs/heads/${e}`),Er(n,e)]),d=i.includes(e);return d&&await bC(s),{...await RC(r,t),branch:e,id:r,label:X(r),baseBranch:a?.baseRefName??Xe("regular"),projectRoot:n,worktreeDir:o,worktreePath:s,worktreePresent:d,orcaTerminalCount:d?await kC(s):0,worktreeDirty:d?await wC(s):null,localTipSha:c,remoteTipSha:l,pr:a}},oy=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}),EC=(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}`},xC=(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: ${EC(e,t)}`];return e.orcaTerminalCount>0&&n.push(` \u2022 ${e.orcaTerminalCount} Orca terminal(s) in ${e.worktreePath} will be closed`),n.join(`
415
- `)},_i=class extends Error{constructor(r,n){super(`step ${r} failed`,{cause:n});this.step=r;this.reason=n;this.name="StepFailure"}step;reason},TC=e=>typeof e=="string"?e:e.outcome;async function Bo(e,t,r){try{let n=await r(),o=TC(n);return t.push({step:e}),u.info({step:e,outcome:o},`\u2705 ${Mi[e]} \u2014 ${o}`),n}catch(n){throw new _i(e,n)}}var CC=async(e,t,r)=>{try{await r(),t.push({step:e})}catch(n){t.push({step:e,detail:"attempted"}),u.warn({err:Nt(n),step:e},`\u26A0\uFE0F ${Mi[e]} failed (non-blocking)`)}},$C=(e,t)=>t.step==="local-branch"&&e.localTipSha?`local-branch (was ${e.localTipSha.slice(0,7)})`:t.detail?`${t.step} (${t.detail})`:t.step,AC=e=>{let{plan:t,step:r,done:n,cause:o}=e,s=n.map(p=>$C(t,p)).join(", ")||"nothing",i=t.jira?`The Jira fix version ${t.jira.version.name} was NOT removed. `:"",a=t.localTipSha?`Restore the branch with \`git branch ${t.branch} ${t.localTipSha}\`. `:"",c=`Re-run \`infra-kit release remove --version ${t.label}\` to finish; completed steps are skipped.`,l=`completed: ${s}. ${i}${a}${c}`,d=o instanceof f?o.remediation:void 0;return new f(o,{operation:`remove release ${t.label} \u2014 step ${ry.indexOf(r)+1} of ${ry.length} (${Mi[r]})`,remediation:d?`${d} \u2014 ${l}`:l})},OC=async e=>{let t=await $o(e.branch,{operation:`remove the worktree for ${e.branch}`,remediation:`commit or discard the changes inside ${e.worktreePath} (\`git -C ${e.worktreePath} stash -u\`), then re-run`});return{outcome:t.includes(e.branch)?"removed":"absent",removedBranches:t}},IC=e=>{let t=e.map(s=>({provider:s.provider,outcome:DC(s),removed:s.removed})),r=t.some(s=>s.outcome==="verified"),o=t.some(s=>s.outcome==="attempted")?"attempted":"skipped";return{outcome:r?"verified":o,providers:t}},DC=e=>e.removed.length>0?"verified":"attempted",NC=async(e,t,r)=>{let n={outcome:"attempted",providers:[]};return await CC("ide-folders",r,async()=>{let o=await hr({projectRoot:e.projectRoot,worktreeDir:e.worktreeDir,removedWorktrees:t});n=IC(o)}),u.info({outcome:n.outcome,step:"ide-folders"},`\u2705 ${Mi["ide-folders"]} \u2014 ${n.outcome}`),n},_C=async e=>{let t=await Ur(e.branch);if(sy({...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 $d`gh pr close ${String(t.number)} --comment ${r}`,{outcome:"closed",number:t.number}},MC=async e=>(await Pr()===e.branch&&await $d`git switch ${e.baseBranch}`,await fs(e.branch),await Pp(e.branch)?Ve({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"),jC=async e=>(await gs(e.branch),e.remoteTipSha?"deleted":"absent"),FC=async(e,t,r)=>{let n=await Js(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}\``;Ve({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}`})},LC=async(e,t)=>t.skipJira?"skipped":!e.jira||!e.jiraConfig?"absent":(await FC(e,e.jira,e.jiraConfig),u.info({jiraVersionId:e.jira.version.id,jiraVersionName:e.jira.version.name},"\u{1F5D1}\uFE0F removing Jira fix version"),await Fc({versionId:e.jira.version.id,moveFixIssuesTo:e.moveIssuesTo?.id,moveAffectedIssuesTo:e.moveIssuesTo?.id},e.jiraConfig),"removed"),BC=(e,t)=>({branch:e.branch,version:e.label,baseBranch:e.baseBranch,worktree:t.worktree.outcome,ideFolders:t.ideFolders,pr:t.pr.outcome,prNumber:t.pr.number,localBranch:t.localBranch,localTipSha:e.localTipSha,remoteBranch:t.remoteBranch,remoteTipSha:e.remoteTipSha,jira:t.jira,jiraVersion:e.jira?{id:e.jira.version.id,name:e.jira.version.name,url:e.jira.url}:null}),WC=async(e,t,r)=>{let n=await Bo("worktree",r,()=>OC(e)),o=await NC(e,n.removedBranches,r),s=await Bo("pr",r,()=>_C(e));u.info({branch:e.branch,localTipSha:e.localTipSha,remoteTipSha:e.remoteTipSha},"\u{1F516} branch tips before deletion");let i=await Bo("local-branch",r,()=>MC(e)),a=await Bo("remote-branch",r,()=>jC(e)),c=await Bo("jira",r,()=>LC(e,t));return{worktree:n,ideFolders:o,pr:s,localBranch:i,remoteBranch:a,jira:c}},VC=async(e,t)=>{let r=[];try{return BC(e,await WC(e,t,r))}catch(n){throw n instanceof _i?AC({plan:e,step:n.step,done:r,cause:n.reason}):n}},UC=async e=>{if(e)return lt(e);h.setInteractive();let[t,r]=await Promise.all([se(),F()]),n=r.map(s=>s.branch);n.length===0&&Ve({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 Tt(ie({branches:n,descriptions:t,types:o}))}catch(s){throw be(s)?s:new f(s,{operation:"select a release to remove",remediation:"pass `--version <ref>` (e.g. `--version 1.2.5`); the picker needs an interactive terminal"})}},iy=Cd(),ji=async e=>{let{confirmedCommand:t,version:r,moveIssuesTo:n,skipJira:o}=e;await Pe({operation:vr}),await M(),await Ge({provider:iy,params:e,operation:vr,argument:"version"}),gC(e);try{let s=await PC(await UC(r),e);u.debug({plan:oy(s)},"release remove: resolved plan"),sy(s),hC(s,e),yC(s),await Zn({operation:`remove release ${s.label}`,base:s.baseBranch}),vC(s),h.addOption("--version",s.label),n&&h.addOption("--move-issues-to",n),o&&h.addOption("--skip-jira",!0),await V(t,xC(s,!!o),{throwOnDecline:!0,plan:{...oy(s),skipJira:!!o}}),t||h.addOption("--yes",!0);let i=await VC(s,e);return h.print(),{content:k(JSON.stringify(i,null,2)),structuredContent:i}}catch(s){throw be(s)||ot(s)||s instanceof f?s:(u.error({err:Nt(s)},"\u274C Error removing release"),new f(s,{operation:vr,remediation:"check `gh auth status`, `git worktree list` and the Jira credentials, then re-run"}))}},Ad=S({name:"release-remove",description:'Tear down ONE release created by release-create: removes its git worktree (closing every Orca terminal open in it first \u2014 a call made from an Orca terminal inside that worktree is refused as orca_caller_inside_target before anything is touched), strips the worktree from the Cursor workspace, closes its pull request with a comment, deletes the release branch locally and on origin, and REMOVES ITS JIRA FIX VERSION \u2014 the one irreversible step (new id, new URL, lost issue links), which is why every call is gated behind human confirmation. Omit "version" and this server offers the human a form listing the open release PRs; the accepted choice feeds the confirm gate. A client that cannot render a form gets a gate with no version \u2014 confirming it is refused, never guessed. Pass "version" when the human already named the release. One release per call \u2014 repeat the call for another; there is no "versions" field. Refuses before any mutation when the PR is MERGED (the release has shipped), when the fix version is released/archived, when the fix version still carries issues (pass "moveIssuesTo" to reassign them), or when nothing named that version exists. skipJira is CLI-only and has no field here: it would leave a live fix version behind with nothing in the result pointing at it. Resumable: every step is a verified no-op when its artefact is already gone, so a re-run finishes a partial teardown. What is lost with the worktree directory: gitignored contents including a hydrated .env of Doppler secrets (re-fetch with env-load) and node_modules/dist.',requiresHumanConfirm:!0,formProvider:iy,inputSchema:{version:L.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:L.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:L.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{branch:L.string().describe("The release branch that was targeted"),version:L.string().describe('The release label (e.g. "1.2.5")'),baseBranch:L.string().describe("The branch HEAD was moved to before the local delete"),worktree:L.enum(["removed","absent"]).describe("Whether a git worktree was removed or none existed"),ideFolders:L.object({outcome:L.enum(["verified","attempted","skipped"]).describe('"verified" only when an editor reported a real diff; "skipped" when no editor is configured'),providers:L.array(L.object({provider:L.string(),outcome:L.enum(["verified","attempted","skipped"]),removed:L.array(L.string()).describe("Folder paths confirmed removed")}))}).describe("Per-editor outcome of stripping the worktree folder"),pr:L.enum(["closed","already-closed","absent"]).describe("What happened to the release pull request"),prNumber:L.number().nullable().describe("The pull request number, or null when none exists"),localBranch:L.enum(["deleted","absent"]).describe("Whether a local branch was deleted or none existed"),localTipSha:L.string().nullable().describe("The local tip before deletion \u2014 the handle that restores the branch"),remoteBranch:L.enum(["deleted","absent"]).describe("Whether the origin branch was deleted or none existed"),remoteTipSha:L.string().nullable().describe("The origin tip before deletion"),jira:L.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:L.object({id:L.string(),name:L.string(),url:L.string()}).nullable().describe("The fix version this release owned, captured before removal \u2014 the id is the only handle that survives it")},handler:ji});import{spawnSync as HC}from"node:child_process";import{homedir as qC}from"node:os";import YC from"node:process";var JC=e=>{let t=new Set(e.steps.map(r=>r[0]));return t.has("brew")?"homebrew":t.has("npm")?"npm":null},GC=e=>{let t=[];return e.needsSudo&&t.push("needs-sudo"),e.fetchesNetworkScript&&t.push("fetches-network-script"),t},KC=(e,t)=>{let r=JC(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},Wo=(e,t)=>{let r=[...GC(e),...KC(e,t)];return r.length===0?{executable:!0}:{executable:!1,reasons:r}},Vo=e=>e.steps.map(mt);var zC=["NONINTERACTIVE","CI","INTERACTIVE","HAVE_SUDO_ACCESS","SUDO_ASKPASS"],XC=e=>{let t={...Qu(e)};for(let r of zC)delete t[r];return t},Od=(e,t,r={})=>{let n=r.spawnSync??HC,o=r.env??YC.env,s=(r.agentMode??ye)(),i=Vo(e),a=Wo(e,t);return a.executable?s?{ran:!1,commands:i,refusedBecause:["agent-mode"]}:e$({recipe:e,spawn:n,env:o,commands:i,notify:r.notify??ZC}):{ran:!1,commands:i,refusedBecause:a.reasons}},ZC=e=>{u.info(e)},cy=64,QC=cy*1024*1024,e$=({recipe:e,spawn:t,env:r,commands:n,notify:o})=>{let s=XC(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:QC,cwd:qC(),env:s}),l=i$(c);if(l!==null)return{ran:!0,ok:!1,commands:n,failedStep:n[i],detail:l}}return{ran:!0,ok:!0,commands:n}},t$=5,r$=/^(?:error|fatal|warning: failed|[a-z-]{0,20} ERR!)[:\s]/i,ay=e=>e==null?[]:String(e).split(`
416
- `).map(t=>t.trim()).filter(t=>t.length>0),n$=e=>{let t=ay(e.stderr),r=ay(e.stdout),n=[...t,...r].filter(s=>r$.test(s)),o=t.length>0?t:r;return(n.length>0?n:o).slice(-t$).join(" / ")},o$="ENOBUFS",s$=e=>e.error?.code===o$,i$=e=>{if(s$(e))return`terminated after exceeding the ${cy} 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=n$(e),r=t===""?"":`: ${t}`;return`exited ${e.status??"unknown"}${r}`};var a$=e=>{let t=[];return e.some(n=>n.id==="brew"&&n.present)&&t.push("homebrew"),t.push("npm"),t},c$=e=>{let t=Ne(e.id);return e.present?t.updateFor(e.binRealPath):t.bootstrapInstall},l$=(e,t)=>{let r=c$(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=Wo(r,n);return{state:e,action:e.present?"update":"install",recipe:r,executable:o.executable,refusedBecause:o.executable?[]:o.reasons,commands:Vo(r),context:n}},Fi=async(e=ir,t=go())=>{let r=await yo(ir,t),n={owner:null,present:a$(r)},o=pl(e),s=new Map(r.map(a=>[a.id,a]));return{plans:o.filter(a=>e.includes(a)).map(a=>l$(s.get(a),n)),context:n}};var Id=(e,t)=>({...Uo(e),action:"skipped",commands:e.commands,detail:t}),Uo=e=>({id:e.state.id,before:{present:e.state.present,onPath:e.state.onPath,version:e.state.version,manager:e.state.manager}}),ly=(e,t)=>e.action==="none"?Id(e,`nothing to do: ${e.state.manager} installs are not managed from here`):t==="update"&&e.action==="install"?Id(e,"not installed, and --update only updates \u2014 drop the flag to install it"):e.executable?null:{...Uo(e),action:"refused",commands:e.commands,detail:`refused (${e.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},d$=(e,t)=>t.ran?t.ok?{...Uo(e),action:e.action==="install"?"installed":"updated",commands:t.commands,detail:e.action==="install"?"installed":"updated"}:{...Uo(e),action:"failed",commands:t.commands,detail:`${t.failedStep??"a step"} ${t.detail??"failed"}`}:{...Uo(e),action:"refused",commands:t.commands,detail:`refused (${t.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},Dd=async e=>{let t=e.run??Od,{plans:r}=await Fi(e.ids,e.probeDeps),n=[];for(let o of r){let s=ly(o,e.mode);if(s!==null){n.push(s);continue}n.push(d$(o,t(o.recipe,o.context)))}return n},Nd=async(e,t)=>{let{plans:r}=await Fi(e,t);return r.map(n=>ly(n,"converge")??Id(n,`would ${n.action} \u2014 nothing was run (--skip-tools)`))};import x$ from"node:process";import{z as C}from"zod";var _d={zshrc:0,zshenv:1,migrations:2,"user-config":3,guidance:4,worktrees:5,"plugin-pointer":6,"mcp-server":7,"mcp-proxies":8,"project-config":9,shell:10},u$=Object.keys(_d).sort((e,t)=>_d[e]-_d[t]),dy={skipped:0,ok:1,changed:2,manual:3,warn:4,fail:5},uy=new Set(["manual","warn","fail"]),Md=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 Ae(e)}},p$=e=>e.reduce((t,r)=>dy[r]>dy[t]?r:t,"skipped"),my=e=>e.message.trim(),m$=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 "),py=e=>e.message===on,f$=(e,t)=>{let[r]=e;return e.length===1&&r!==void 0?my(r):e.length>1?m$(e):t?"activate with the last line below":"see below"},g$=(e,t)=>{if(t.length===0)return{name:e,status:"skipped",message:"did not run"};let r=t.map(i=>Md(i.outcome)),n=t.filter(i=>uy.has(Md(i.outcome))).map(my),o=t.filter(i=>!uy.has(Md(i.outcome))&&!py(i)),s={name:e,status:p$(r),message:f$(o,t.some(py))};return n.length>0?{...s,notes:n}:s},h$=e=>({label:"Local setup",rows:u$.map(t=>g$(t,e.filter(r=>r.step===t)))}),y$=(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 Ae(e.action)}},v$=(e,t)=>{let r=y$(e,t),n={name:e.id,status:r,message:e.detail};return r==="manual"&&e.commands.length>0?{...n,notes:[...e.commands]}:n},w$=(e,t)=>({label:t.skipTools?"Tools (probe: nothing installed)":"Tools",rows:e.map(r=>v$(r,t))}),k$=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 Ae(e)}},b$=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 Ae(e)}},R$=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 Ae(e)}},S$=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 Ae(e.outcome)}},P$=(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 Ae(e)}},E$=e=>({label:"Portless service",rows:[{name:"link",status:k$(e.link),message:R$(e.link)},{name:"node",status:b$(e.node.outcome),message:S$(e.node)},P$(e.service,e.command)]}),fy=(e,t)=>[h$(e.init),w$(e.tools,t),E$(e.portless)],gy=e=>e.some(t=>t.rows.some(r=>r.status==="fail"));var T$=()=>{let{link:e,node:t}=ds();return{link:e,node:t,target:{home:e.home,isGlobal:e.isGlobal,processStartTime:()=>null}}},C$=async e=>{let t=fp(e.link).outcome,r=mp(e.node),n=ls(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 Yg(e.target,n);if(o==="converged")return{link:t,node:r,service:o,command:null};let i=ft(n,{home:e.link.home,exists:e.target.exists,execPath:e.target.execPath,stableNode:s});return{link:t,node:r,service:o,command:i}},yy="--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.",$$=e=>{let t=Array.isArray(e.update)?e.update:void 0,r=e.update===!0||t!==void 0,n=e.skipTools===!0;if(n&&(e.tools!==void 0||r))throw new Error(yy);return{ids:e.tools??t??ir,mode:r?"update":"converge",skipTools:n}},hy=(e,t)=>e instanceof nn?e.step:t.at(-1)?.step??"zshrc",A$=async()=>{let e=[];try{await sl(t=>{e.push(t)})}catch(t){e.push({step:hy(t,e),outcome:"failed",message:`The ${hy(t,e)} step failed: ${t instanceof Error?t.message:String(t)}`,level:"warn"})}return e},O$=(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}`}))},I$=async(e,t)=>{try{return e.skipTools?await Nd(e.ids,t.probeDeps):await Dd({ids:e.ids,mode:e.mode,probeDeps:t.probeDeps,run:t.run})}catch(r){return O$(e.ids,r)}},D$=e=>({step:e.step,outcome:e.outcome,message:e.message}),Li=async(e={})=>{let t=$$(e),r=await A$(),n=await I$(t,e),o=await C$(e.portlessDeps??T$()),s=fy({init:r,tools:n,portless:o},{skipTools:t.skipTools});ze({title:"infra-kit setup",sections:s},{ascii:e.ascii}),u.info(on),gy(s)&&(x$.exitCode=1);let i={init:r.map(D$),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}},N$=C.object({step:C.enum(["zshrc","zshenv","migrations","user-config","guidance","worktrees","plugin-pointer","mcp-server","mcp-proxies","project-config","shell"]).describe("Which init step this reports on"),outcome:C.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:C.string().describe("The same line a human running this would have read")}),_$=C.object({id:C.string().describe("Dependency id"),action:C.enum(["installed","updated","skipped","refused","failed"]).describe("What happened"),before:C.object({present:C.boolean(),onPath:C.boolean(),version:C.string().nullable(),manager:C.string()}).describe("The tool\u2019s state before this run"),commands:C.array(C.string()).describe("The exact commands, one per step \u2014 printed even when refused"),detail:C.string().describe("Why, in one line")}),M$=C.object({link:C.enum(["created","repointed","unchanged","skipped-local","skipped-unresolved","failed"]).describe("What the ~/.infra-kit/portless link step did"),node:C.enum(["created","refreshed","unchanged","skipped-local","skipped-platform","failed"]).describe("What the ~/.infra-kit/node step did"),service:C.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:C.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")}),j$={init:C.array(N$).describe("One entry per init step, in the order they ran"),tools:C.array(_$).describe("One result per requested dependency"),portlessService:M$.describe("The portless link, node, and system-service step \u2014 run on every setup, never gated on the tool options"),converged:C.boolean().describe("Whether the dependency step could act at all (false under skipTools)"),changed:C.boolean().describe("Whether anything was installed or updated"),report:C.array(C.object({label:C.string().describe("Section heading"),rows:C.array(C.object({name:C.string().describe("Init step, tool id, or portless part"),status:C.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:C.string().describe("The row message, as printed"),notes:C.array(C.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:C.boolean().describe("Whether no tool failed (a refusal is not a failure)")},F$={tools:C.array(C.enum(ir)).optional().describe("Which tools to act on. Omit for all six."),mode:C.enum(["converge","update"]).optional().describe("converge (default): install what is missing and update the rest. update: never install."),skipTools:C.boolean().optional().describe("Read-only: run the init half, then REPORT what each tool needs without installing anything.")},jd=S({name:"setup",description:'Set this machine up in one call: inject the shell integration into .zshrc and the session-env block into .zshenv, run the config migrations, seed the user-global config, refresh the agent-instruction files, register the Claude Code plugin pointer and install or update the skills plugin (the `/infra-kit:*` skills drive the infra-kit CLI on PATH; a leftover .mcp.json entry is reported, never written), then bring brew, git, aws, gh, doppler and portless to a working state \u2014 installing what is missing and updating what is present. Pass mode:"update" to update only and never install, or skipTools:true to do the local setup and then REPORT what each tool needs without installing anything. Recipes that need sudo or pipe a script fetched over the network \u2014 the Homebrew bootstrap and the first AWS CLI install \u2014 are never run; they are reported with the exact commands for you to run yourself. Use `doctor` first to see the state of this machine without changing it.',inputSchema:F$,outputSchema:j$,requiresHumanConfirm:!0,handler:e=>Li({tools:e.tools,update:e.mode==="update",skipTools:e.skipTools})});import{existsSync as wy}from"node:fs";import ky from"node:path";import Y$ from"node:process";import{z as pt}from"zod";import{createHash as L$}from"node:crypto";import{readFileSync as B$}from"node:fs";var wr=e=>L$("sha256").update(B$(e)).digest("hex");import{readFileSync as K$,writeFileSync as H$}from"node:fs";import Ui from"node:path";import{z as rt}from"zod";var Q="vendor",W$=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack"]),V$=new Set([".sync-manifest.json",".eslintcache","log.txt","routeTree.gen.ts"]),U$=[".tsbuildinfo"],Fd=e=>W$.has(e),Ld=e=>V$.has(e)?!0:U$.some(t=>e.endsWith(t)),Bi=e=>{let t=e.split("/"),r=t.pop()??"";return t.some(o=>Fd(o))||Ld(r)};import{readdirSync as J$}from"node:fs";import Bd from"node:path";var G$=e=>e.split(Bd.sep).join("/"),Wi=e=>{let t=[],r=n=>{for(let o of J$(n,{withFileTypes:!0})){let s=Bd.join(n,o.name);if(o.isDirectory()){if(Fd(o.name))continue;r(s);continue}Ld(o.name)||t.push(G$(Bd.relative(e,s)))}};return r(e),t.sort()};var je=".sync-manifest.json",Vi=1,q$=rt.object({schemaVersion:rt.number().optional(),source:rt.string(),commit:rt.string(),syncedAt:rt.string(),fileCount:rt.number(),files:rt.record(rt.string(),rt.string())}),Wd=e=>(e.schemaVersion??Vi)>Vi,vy=(e,t)=>{let r={},n=t?[...new Set(t)].sort():Wi(e);for(let o of n)try{r[o]=wr(Ui.join(e,o))}catch(s){let i=s instanceof Error?s.message:String(s);throw new Error(`Cannot hash vendor file "${o}" (broken symlink or unreadable file): ${i}`)}return r},Jo=e=>{let t=Ui.join(e,je),r;try{r=K$(t,"utf8")}catch{throw new Error(`Missing ${je} at ${t}`)}let n=q$.safeParse(JSON.parse(r));if(!n.success)throw new Error(`Invalid ${je} at ${t}: ${rt.prettifyError(n.error)}`);return n.data},Vd=(e,t,r)=>{let n=vy(e,r),o={schemaVersion:Vi,source:t.source,commit:t.commit,syncedAt:new Date().toISOString(),fileCount:Object.keys(n).length,files:n};return H$(Ui.join(e,je),`${JSON.stringify(o,null,2)}
417
- `),o},Ud=(e,t)=>{let r=Object.fromEntries(Object.entries(t.files).filter(([c])=>!Bi(c))),n=Wi(e),o=[],s=[];for(let c of n){if(!(c in r)){s.push(c);continue}wr(Ui.join(e,c))!==r[c]&&o.push(c)}let i=new Set(n),a=Object.keys(r).filter(c=>!i.has(c));return{modified:o,added:s,removed:a}};var Jd=30,Gd=(e,t)=>{if(t.length!==0){u.info(`
418
- ${e} (${t.length}):`);for(let r of t.slice(0,Jd))u.info(` ${r}`);t.length>Jd&&u.info(` \u2026and ${t.length-Jd} more`)}},Ji=async(e={})=>{let t=e.cwd??await T(),r=ky.join(t,Q),n={modified:[],added:[],removed:[],fileCount:0};if(!wy(r)){u.info(`\u2139\uFE0F No ${Q}/ folder found \u2014 nothing to check.`);let d={status:"skipped",ok:!0,...n};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}}if(!wy(ky.join(r,je))){u.error(`\u274C Missing ${Q}/${je}. Re-run the vendor sync to generate it.`);let d={status:"missing-manifest",ok:!1,...n};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}}let o=Jo(r);if(Wd(o)){u.error(`\u274C ${Q}/${je} has a newer schemaVersion (${String(o.schemaVersion)}) than this CLI supports. Upgrade infra-kit.`);let d={status:"unknown-schema",ok:!1,...n};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}}let{modified:s,added:i,removed:a}=Ud(r,o),c=s.length>0||i.length>0||a.length>0;c?(u.error(`\u274C ${Q}/ has drifted from ${Q}/${je}.`),u.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),Gd("Modified",s),Gd("Added (not in manifest)",i),Gd("Removed (in manifest, now missing)",a)):u.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}},z$={status:pt.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:pt.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:pt.number(),modified:pt.array(pt.string()),added:pt.array(pt.string()),removed:pt.array(pt.string())},Kd=S({name:"vendor-check",description:"Verify that files under vendor/ match the checksums in vendor/.sync-manifest.json. Self-contained (no source repo or config needed). Returns ok=false on drift, missing manifest, or an unknown future schemaVersion; ok=true when clean or when no vendor/ folder exists.",inputSchema:{},outputSchema:z$,handler:()=>Ji({cwd:Y$.cwd()})});import by from"node:process";import{z as Go}from"zod";var Ry=async e=>{try{return await e()}catch{return null}},Gi=async()=>{let e=K.version;u.info(e);let t=await Ry(T),r=t===null?null:await Ry(()=>Le(t)),n={version:e,cwd:by.cwd(),repoRoot:t,mainRepoRoot:r,projectDir:by.env.CLAUDE_PROJECT_DIR||null};return{content:k(JSON.stringify(n,null,2)),structuredContent:n}},Hd=S({name:"version",description:"Print the installed infra-kit CLI version and where this process runs (cwd, repo root, main repo root, CLAUDE_PROJECT_DIR)",inputSchema:{},outputSchema:{version:Go.string().describe("Installed infra-kit CLI version (from package.json)"),cwd:Go.string().describe("The working directory of this process"),repoRoot:Go.string().nullable().describe("git toplevel of cwd \u2014 the worktree itself in a linked worktree; null when git cannot answer"),mainRepoRoot:Go.string().nullable().describe("The main checkout a linked worktree belongs to (equals repoRoot outside worktrees); null with repoRoot"),projectDir:Go.string().nullable().describe("CLAUDE_PROJECT_DIR as Claude Code set it for this process, or null")},handler:Gi});import _y from"@inquirer/confirm";import rA from"node:path";import{z as _}from"zod";import{$ as Ho}from"zx";import X$ from"@inquirer/input";import Py from"@inquirer/select";import{$ as jt}from"zx";var Ko="dev",Z$="main",qd="feature/",Ey=["new","local","remote"],Ki=e=>{let t=e.trim().replace(/^feature\//,"").toLowerCase().replaceAll(/\s+/g,"-");return`${qd}${t}`},xy=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},Q$=2,Yd=async()=>{let e=await jt({nothrow:!0,quiet:!0})`git ls-remote --exit-code origin refs/heads/${Ko}`;if(e.exitCode===0)return Ko;if(e.exitCode!==Q$)throw new f(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 ${Ko} exists`});return await xy()??Ko},Ty=async e=>{let t=e?.trim();return t?t===Ko||t===Z$||t===await xy()?t:ve(pe(t)):Yd()},Cy=async()=>O(e=>Py({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"}}),$y=async()=>O(e=>X$({message:"Feature name (becomes feature/<name>):",required:!0,validate:t=>Ki(t)===qd?"Enter a name":!0},e),{whenHeadless:{refuse:"feature"}}),Ay=async(e,t)=>e.length===0?t:O(r=>Py({message:"Base branch:",default:t,choices:[t,...e].map(n=>({name:n,value:n}))},r),{whenHeadless:{value:t}}),eA=async e=>{let t=await jt({nothrow:!0,quiet:!0})`git check-ref-format --branch ${e}`;if(e===qd||t.exitCode!==0)throw new f(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`})},Sy=async e=>(await jt({nothrow:!0,quiet:!0})`git fetch origin ${e}`).exitCode===0,tA=async e=>(await jt({nothrow:!0,quiet:!0})`git show-ref --verify --quiet refs/heads/${e}`).exitCode===0,Oy=async e=>{let{names:t,base:r}=e,n=[...new Set(t.map(Ki))];for(let s of n)await eA(s);if(!await Sy(r))throw new f(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 tA(s)?o.push({branch:s,base:r,source:"local"}):await Sy(s)?o.push({branch:s,base:r,source:"remote"}):o.push({branch:s,base:r,source:"new"});return o},Iy=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}`},Dy=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 qo="create worktrees",nA=["already_open","orca_unreachable","orca_absent","orca_worktree_not_selectable","orca_error"],zd=()=>({orcaOpened:[],orcaSkipped:[],orcaHidden:[]}),Hi=async e=>{let{confirmedCommand:t,githubDesktop:r,orca:n}=e,o=e.ide??e.cursor;await Pe({operation:qo}),oA(e);try{let s=await T(),i=`${s}${ge}`;await Ny(`${i}/${Sr.release}`),await Ny(`${i}/${Sr.feature}`);let a=await sA(e),c=a==="feature"?await aA(e):await iA(e);if(c===null){u.info("\u2139\uFE0F No open release branches found"),h.print();let P={kind:a,createdWorktrees:[],count:0,features:[],...zd()};return{content:k(JSON.stringify(P,null,2)),structuredContent:P}}let l=await M(),d=o??(yt(l).length>0?"workspace":"none");h.addOption("--ide",d);let p=await cA(r,l),m=await lA(n,l),g=await Le(s),y=rA.basename(g),R=m?await dA({explicit:n!==void 0,mainRepoRoot:g}):null;await V(t,uA(R,y,c.previewLines)),t||h.addOption("--yes",!0);let w=R?await pA(R,g):null,$=await yA(c.targets,i);if(vA($),d==="workspace"&&await Td({projectRoot:s,worktreeDir:i,branches:$}),p)for(let P of $)await Ho`github ${i}/${P}`,await Ho`sleep 5`;let B=w?await fA({registration:w,createdWorktrees:$,worktreeDir:i,mainRepoRoot:g,repoName:y,config:l}):zd();gA(B),h.print();let I={kind:a,createdWorktrees:$,count:$.length,features:c.features.filter(P=>$.includes(P.branch)),...B};return{content:k(JSON.stringify(I,null,2)),structuredContent:I}}catch(s){throw be(s)||s instanceof x?s:(u.debug({err:s},"Error managing worktrees"),new f(s,{operation:qo,remediation:s instanceof f&&s.remediation||"verify branches don't already exist as worktrees: 'git worktree list'"}))}},oA=e=>{let t=e.all||e.versions!==void 0,r=e.feature!==void 0||e.base!==void 0;if(t&&r)throw new f(void 0,{operation:qo,remediation:"pass either --versions/--all (release worktrees) or --feature [--base] (feature worktrees)",stderrExcerpt:"--feature/--base cannot be combined with --versions/--all"})},sA=async e=>e.feature!==void 0||e.base!==void 0?"feature":e.all||e.versions!==void 0?"release":(h.setInteractive(),Cy()),iA=async e=>{let{all:t,versions:r}=e,n=await me("release"),o=[];if(r)o=r.split(",").map(a=>ve(pe(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])),d=await se();o=await Ct(ie({branches:c,descriptions:d,types:l}),{required:!0})}}t?h.addOption("--all",!0):h.addOption("--versions",rr(o));let{branchesToCreate:s}=hA({selectedReleaseBranches:o,currentWorktrees:n});return{targets:s.map(a=>({branch:a,add:c=>Ho`git worktree add ${c} ${a}`})),features:[],previewLines:[]}},aA=async e=>{let r=e.feature?.split(",").filter(l=>l.trim()!=="")??[],n=e.base;if(r.length===0&&(h.setInteractive(),r=[await $y()],n===void 0)){let l=(await F()).map(d=>d.branch);n=await Ay(l,await Yd())}let o=await Ty(n),s=await Oy({names:r,base:o});h.addOption("--feature",s.map(l=>l.branch.replace(/^feature\//,"")).join(",")),h.addOption("--base",o);let i=await me("feature"),a=s.filter(l=>i.includes(l.branch)?(u.info(`\u2139\uFE0F ${l.branch} is already checked out in a worktree`),!1):!0);return{targets:a.map(l=>({branch:l.branch,add:d=>Iy(l,d)})),features:a,previewLines:a.map(Dy)}},cA=async(e,t)=>{let r=t.worktrees?.openInGithubDesktop,n=e??r??await O(o=>_y({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},lA=async(e,t)=>{let r=t.worktrees?.openInOrca,n=e??r??await O(o=>_y({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},My=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"},dA=async e=>{let{explicit:t,mainRepoRoot:r}=e,n=await xr();if(n!=="ready"){let{reason:s,text:i}=My(n);if(t)throw u.warn({operation:qo},`\u26D4 --orca was passed but ${i}`),new x({status:"refused",reason:s,agentMode:N.source},2,{operation:qo,remediation:n==="absent"?"install Orca (brew install --cask stablyai/orca/orca) and register its CLI from Settings \u2192 Experimental \u2192 CLI, or re-run with --no-orca":"open Orca (`orca open`) and re-run, or re-run with --no-orca",stderrExcerpt:`--orca was passed but ${i}; no worktree was created`});return u.warn(`\u26A0\uFE0F ${i} \u2014 worktrees will be created but not opened in Orca`),{probe:n,registered:!1,visibility:void 0}}let o=await nm(r);return{probe:n,registered:o.registered,visibility:o.visibility}},uA=(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(`
419
- `)},pA=async(e,t)=>{if(e.probe!=="ready")return{kind:"skip",reason:My(e.probe).reason};if(e.registered)return{kind:"ready",visibility:e.visibility};try{let{visibility:r}=await om(t);return{kind:"ready",visibility:r}}catch(r){return u.warn({error:r},"\u26A0\uFE0F orca repo add failed \u2014 worktrees will be created but not opened in Orca"),{kind:"skip",reason:"orca_error",code:r instanceof bs?r.code:void 0}}},mA=e=>`Orca \u2192 ${e} \u2192 "hidden worktrees" card \u2192 Show, or Settings \u2192 General \u2192 Workspace \u2192 external-worktree sources`,fA=async e=>{let{registration:t,createdWorktrees:r,worktreeDir:n,mainRepoRoot:o,repoName:s,config:i}=e,a=zd();if(t.kind==="skip"){for(let p of r)a.orcaSkipped.push({branch:p,reason:t.reason,code:t.code});return a}let c=Mp(i),l=r.length===1&&t.visibility!=="hide",d=im();for(let p of r){let m=`${n}/${p}`;try{let{layout:g}=await am({cwd:m,title:cm({branch:p}),focus:l,layout:"full",panes:c,poll:d});await sm(o,m)?a.orcaOpened.push({branch:p,layout:g}):a.orcaHidden.push({branch:p,path:m,fix:mA(s)})}catch(g){u.warn({error:g,branch:p},`\u26A0\uFE0F Failed to open Orca terminals for ${p}`),g instanceof bs&&g.code==="orca_worktree_not_selectable"?a.orcaSkipped.push({branch:p,reason:"orca_worktree_not_selectable"}):a.orcaSkipped.push({branch:p,reason:"orca_error",code:g instanceof bs?g.code:void 0})}}return a},gA=e=>{for(let t of e.orcaOpened)u.info(`\u{1FA9F} Opened ${t.branch} in Orca (${t.layout})`);for(let t of e.orcaHidden)u.info(`\u{1F648} ${t.branch} opened in Orca but its row is hidden (${t.path}) \u2014 ${t.fix}`);for(let t of e.orcaSkipped){let r=t.code?` (${t.code})`:"";u.info(`\u21A9\uFE0F ${t.branch} not opened in Orca: ${t.reason}${r}`)}},Ny=async e=>{await Ho`mkdir -p ${e}`},hA=e=>{let{selectedReleaseBranches:t,currentWorktrees:r}=e,n=r.filter(s=>ms(s));return{branchesToCreate:t.filter(s=>!n.includes(s))}},yA=async(e,t)=>{let r=await Promise.allSettled(e.map(async o=>{let s=`${t}/${o.branch}`;return await o.add(s),await Ho({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 f(s.reason,{operation:`git worktree add for ${i}`,remediation:"check the branch name and that the parent dir is writable"});u.error({error:s.reason,msg:a.message})}return n},vA=e=>{if(e.length>0){u.info("\u2705 Created git worktrees:");for(let t of e)u.info(t);u.info("")}else u.info("\u2139\uFE0F No new git worktrees to create")},Xd=S({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:_.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:_.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:_.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:_.string().optional().describe('Comma-separated release versions or names to target (e.g. "1.2.5, 1.2.6" or "checkout-redesign, 1.2.5"). Either "versions" or all=true must be provided for MCP calls. Overrides "all" when set.'),ide:_.enum(yr).optional().describe('Editor open mode for created worktrees, applied to the configured editor (Cursor, per the "ide" config). "workspace" (the only attach style) adds each worktree to the Cursor workspace and opens it. "none" skips the editor. Resolution order: this flag \u2192 "workspace" when an "ide" is configured \u2192 "none" otherwise.'),cursor:_.enum(yr).optional().describe('Deprecated alias for "ide". Prefer "ide". Ignored when "ide" is provided.'),githubDesktop:_.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:_.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:_.enum(["release","feature"]).describe("Which kind of worktree the run created"),features:_.array(_.object({branch:_.string(),base:_.string(),source:_.enum(Ey)})).describe('Created feature worktrees: source "new" = cut from origin/<base>; "local" / "remote" = an existing branch checked out as-is (base not applied)'),createdWorktrees:_.array(_.string()).describe("List of created git worktree branches"),count:_.number().describe("Number of git worktrees created"),orcaOpened:_.array(_.object({branch:_.string(),layout:_.enum(["full","single-pane"])})).describe("Created worktrees that got an Orca terminal tab on a row the sidebar shows, with the layout applied"),orcaSkipped:_.array(_.object({branch:_.string(),reason:_.enum(nA),code:_.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:_.array(_.object({branch:_.string(),path:_.string(),fix:_.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:Hi});import{z as Ft}from"zod";var qi=async()=>{await M();let[e,t]=await Promise.all([me("release"),me("feature")]);if(e.length===0&&t.length===0){u.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 wA(e):[],n=[];r.length>0&&n.push(`\u{1F33F} Active worktrees:
420
-
421
- ${kA(r).join(`
419
+ `),h.addOption("--yes",!0),await zr({versionId:p.id,...w?{description:y.description}:{},...x?{releaseDate:y.releaseDate}:{}},i),w&&await Js({branch:a,body:so(W,y.description)}),u.info(`\u2705 Updated ${R.join(" and ")} for ${d}`),u.info(`\u{1F517} Jira Version: ${W}`),u.info(`\u{1F517} PR branch: ${a}
420
+ `),h.print(),I(!0)},xd=S({name:"release-edit",description:"Edit a release's description and/or planned release date in Jira; a changed description is mirrored into the GitHub release PR body. Accepts a release version or a release name: targets the Jira fix version named `v<version>` (versioned) or `<name>` (named) and the open PR on branch `release/v<version>` or `release/<name>`. The PR body is rewritten canonically to `<jiraVersionUrl>\\n\\n<description>` \u2014 any prior manual edits to the body are overwritten. `version` and at least one of `description`/`releaseDate` are required for MCP calls (the picker and prompts are unreachable without a TTY). Empty string clears a field. Confirmation is auto-skipped for MCP, so the caller is responsible for gating.",inputSchema:{version:Fe.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:Fe.string().optional().describe("New description. Empty string clears the description."),releaseDate:hl.optional().describe("New planned release date (yyyy-mm-dd). Empty string clears the date.")},outputSchema:{version:Fe.string().describe("Release version"),branch:Fe.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:Fe.string().describe("Jira fix version URL"),previousDescription:Fe.string().describe("The description before the update"),newDescription:Fe.string().describe("The description after the update"),previousReleaseDate:Fe.string().nullable().describe("The planned release date before the update, or null"),newReleaseDate:Fe.string().nullable().describe("The planned release date after the update, or null"),changedFields:Fe.array(Fe.enum(Zh)).describe("The fields whose value actually changed"),changed:Fe.boolean().describe("Whether anything actually changed")},handler:Ii});import{z as L}from"zod";import{$ as Id}from"zx";import Qh from"node:fs/promises";import Di from"node:path";var Td=async e=>{let{workspacePath:t,folderPaths:r}=e,n=Di.dirname(t),o;try{o=await Qh.readFile(t,"utf-8")}catch(d){throw new Error(`Cursor workspace file not found at ${t}: ${d.message}`)}let s;try{s=JSON.parse(o)}catch(d){throw new Error(`Failed to parse ${t} as JSON. Comments (JSONC) are not supported. ${d.message}`)}let i=s.folders??[],a=new Set(i.map(d=>Di.resolve(n,d.path))),c=[],l=[];for(let d of r){let p=Di.resolve(d);if(a.has(p)){l.push(d);continue}let m=Di.relative(n,p);i.push({path:m}),a.add(p),c.push(d)}return s.folders=i,await Qh.writeFile(t,`${JSON.stringify(s,null,2)}
421
+ `,"utf-8"),{added:c,skipped:l}};import{$ as gC}from"zx";var Cd=async e=>{await gC`cursor ${e}`};import ey from"node:fs/promises";import Ni from"node:path";var $d=async e=>{let{workspacePath:t,folderPaths:r}=e,n=Ni.dirname(t),o;try{o=await ey.readFile(t,"utf-8")}catch(m){throw new Error(`Cursor workspace file not found at ${t}: ${m.message}`)}let s;try{s=JSON.parse(o)}catch(m){throw new Error(`Failed to parse ${t} as JSON. Comments (JSONC) are not supported. ${m.message}`)}let i=s.folders??[],a=new Set(r.map(m=>Ni.resolve(m))),c=new Set,l=i.filter(m=>{let g=Ni.resolve(n,m.path);return a.has(g)?(c.add(g),!1):!0});s.folders=l,await ey.writeFile(t,`${JSON.stringify(s,null,2)}
422
+ `,"utf-8");let d=[],p=[];for(let m of r){let g=Ni.resolve(m);c.has(g)?d.push(m):p.push(m)}return{removed:d,notFound:p}};import ty from"node:path";var Uo=(e,t)=>ty.isAbsolute(e)?e:ty.resolve(t,e);var Ad=async e=>{let{projectRoot:t,worktreeDir:r,branches:n}=e,o=await M(),s=wt(o),i=n.map(c=>`${r}/${c}`),a=[];for(let c of s)a.push(await hC({ide:c,projectRoot:t,folderPaths:i}));return a},hC=async e=>{let{ide:t,projectRoot:r,folderPaths:n}=e;if(!t.config.workspaceConfigPath)return u.warn("\u26A0\uFE0F Skipping Cursor: ide.config.workspaceConfigPath is not set in infra-kit config"),{ran:!1,provider:"cursor",added:0,skipped:0};let o=Uo(t.config.workspaceConfigPath,r),{added:s,skipped:i}=await Td({workspacePath:o,folderPaths:n}),a=i.length>0?` (${i.length} already present)`:"";return u.info(`\u2705 Added ${s.length} folder(s) to ${o}${a}`),await Cd(o),{ran:!0,provider:"cursor",added:s.length,skipped:i.length}};var yr=async e=>{let{projectRoot:t,worktreeDir:r,removedWorktrees:n}=e;if(n.length===0)return[];let o=await M(),s=wt(o),i=n.map(c=>`${r}/${c}`),a=[];for(let c of s)a.push(await yC({ide:c,projectRoot:t,folderPaths:i}));return a},yC=async e=>{let{ide:t,projectRoot:r,folderPaths:n}=e;if(!t.config.workspaceConfigPath)return{provider:"cursor",supported:!0,removed:[]};let o=Uo(t.config.workspaceConfigPath,r);try{let{removed:s}=await $d({workspacePath:o,folderPaths:n});return s.length>0&&u.info(`\u2705 Removed ${s.length} folder(s) from ${o}`),{provider:"cursor",supported:!0,removed:s}}catch(s){return u.warn({error:s},`\u26A0\uFE0F Failed to update Cursor workspace at ${o}`),{provider:"cursor",supported:!0,removed:[]}}};var vr=["workspace","none"];import{z as ry}from"zod";var sy=2500,_i="release-remove",ny=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),vC=e=>e.version===void 0||e.version==="",wC=async()=>{try{return{outcome:"listed",prs:await F()}}catch(e){return e instanceof f&&e.operation===no?{outcome:"empty"}:{outcome:"failed"}}},oy=(e,t)=>(e===null?u.info({msg:`Tool execution form enumeration timed out (gh pr list, ${t/1e3} s): ${_i}`}):e.outcome==="failed"?u.info({msg:`Tool execution form enumeration failed (gh pr list): ${_i}`}):u.info({msg:`Tool execution form options empty (open release PRs): ${_i}`}),null),kC=(e,t)=>{let r=new Map(e.map(n=>[n.branch,n.type]));return qs(e.map(n=>n.branch)).map(({branch:n,id:o,label:s})=>{let i=t?.get(re(o)),a=i===void 0?"":` \u2014 ${i}`;return{label:s,prose:`${s} [${r.get(n)??"regular"}]${a}`}})},bC=(e,t,r)=>{let n=e.map(o=>o.prose).join("; ");return t!==null?`Open release PRs right now: ${n}. `:(u.info({msg:`Tool execution form descriptions unavailable (timeout): ${_i}`}),`Open release PRs right now: ${n}. Jira descriptions could not be fetched within ${r/1e3} s. `)},Od=(e={})=>{let t=e.fetchBudgetMs??sy;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=>ny(r)&&vC(r),buildRequestedSchema:async()=>{let[r,n]=await Promise.all([vn(wC(),t),vn(se(),t)]);if(r===null||r.outcome!=="listed")return oy(r,t);let o=kC(r.prs,n);return o.length===0?oy({outcome:"empty"},t):ry.object({version:ry.enum(o.map(s=>s.label)).describe(`The ONE release to tear down. ${bC(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:{...ny(n)?n:{},version:r.version}}};var iy=["worktree","ide-folders","pr","local-branch","remote-branch","jira"],ji={worktree:"remove the worktree","ide-folders":"strip the worktree from configured editors",pr:"close the PR","local-branch":"delete the local branch","remote-branch":"delete the remote branch",jira:"remove the Jira fix version"},wr="remove a release",Je=e=>{throw u.warn({operation:e.operation},`\u26D4 ${e.stderrExcerpt??e.operation}`),new f(void 0,e)},ay=(e,t)=>{throw u.warn({operation:t.operation},`\u26D4 ${t.stderrExcerpt??t.operation}`),new C({...e,agentMode:N.source},2,t)},RC=e=>{ye()&&(e.version||ay({status:"argument_required",argument:"version"},{operation:wr,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&&ay({status:"refused"},{operation:wr,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"}))},ly=e=>{e.pr?.state==="MERGED"&&Je({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`})},SC=(e,t)=>{if(t.skipJira||(e.jiraConfig||Je({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)&&Je({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||Je({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)`}))},PC=e=>{if(e.worktreePresent||e.pr!==null||e.localTipSha!==null||e.remoteTipSha!==null||e.jira)return;Je({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"})},EC=e=>{!e.worktreeDirty||e.worktreeDirty.length===0||Je({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(", ")}`})},xC=async e=>(await Id`git -C ${e} status --porcelain`).stdout.split(`
423
+ `).map(r=>r.trimEnd()).filter(r=>r.length>0),TC=async e=>{try{let{terminals:t}=await sm(e);return t.filter(r=>r.connected).length}catch(t){return u.debug({error:t,worktreePath:e},"release remove: orca terminal probe failed"),0}},CC=async e=>{let t=await Ps([e]);if(t!==null)throw u.warn({operation:wr},`\u26D4 this command runs inside an Orca terminal of ${t}`),new C({status:"refused",reason:"orca_caller_inside_target",agentMode:N.source},2,{operation:wr,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`})},$C=async(e,t)=>{let r={jiraConfig:null,jira:null,moveIssuesTo:null};if(t.skipJira)return r;let n=await ut();if(!n)return r;let o=await dt(re(e),n),s=t.moveIssuesTo?await AC(t.moveIssuesTo,n):null;if(!o)return{jiraConfig:n,jira:null,moveIssuesTo:s};let i=await Ks(o.id,n);return{jiraConfig:n,moveIssuesTo:s,jira:{version:o,fixCount:i.issuesFixedCount,affectsCount:i.issuesAffectedCount,url:nr(n,o)}}},AC=async(e,t)=>{let r=await dt(e,t);return r||Je({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}"`})},OC=async(e,t)=>{let r=G(e);r||Je({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 T(),o=`${n}${de}`,s=`${o}/${e}`,[i,a,c,l]=await Promise.all([fe("release"),Kr(e),Oe(n,`refs/heads/${e}`),Cr(n,e)]),d=i.includes(e);return d&&await CC(s),{...await $C(r,t),branch:e,id:r,label:X(r),baseBranch:a?.baseRefName??et("regular"),projectRoot:n,worktreeDir:o,worktreePath:s,worktreePresent:d,orcaTerminalCount:d?await TC(s):0,worktreeDirty:d?await xC(s):null,localTipSha:c,remoteTipSha:l,pr:a}},cy=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}),IC=(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}`},DC=(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: ${IC(e,t)}`];return e.orcaTerminalCount>0&&n.push(` \u2022 ${e.orcaTerminalCount} Orca terminal(s) in ${e.worktreePath} will be closed`),n.join(`
424
+ `)},Mi=class extends Error{constructor(r,n){super(`step ${r} failed`,{cause:n});this.step=r;this.reason=n;this.name="StepFailure"}step;reason},NC=e=>typeof e=="string"?e:e.outcome;async function Jo(e,t,r){try{let n=await r(),o=NC(n);return t.push({step:e}),u.info({step:e,outcome:o},`\u2705 ${ji[e]} \u2014 ${o}`),n}catch(n){throw new Mi(e,n)}}var _C=async(e,t,r)=>{try{await r(),t.push({step:e})}catch(n){t.push({step:e,detail:"attempted"}),u.warn({err:jt(n),step:e},`\u26A0\uFE0F ${ji[e]} failed (non-blocking)`)}},MC=(e,t)=>t.step==="local-branch"&&e.localTipSha?`local-branch (was ${e.localTipSha.slice(0,7)})`:t.detail?`${t.step} (${t.detail})`:t.step,jC=e=>{let{plan:t,step:r,done:n,cause:o}=e,s=n.map(p=>MC(t,p)).join(", ")||"nothing",i=t.jira?`The Jira fix version ${t.jira.version.name} was NOT removed. `:"",a=t.localTipSha?`Restore the branch with \`git branch ${t.branch} ${t.localTipSha}\`. `:"",c=`Re-run \`infra-kit release remove --version ${t.label}\` to finish; completed steps are skipped.`,l=`completed: ${s}. ${i}${a}${c}`,d=o instanceof f?o.remediation:void 0;return new f(o,{operation:`remove release ${t.label} \u2014 step ${iy.indexOf(r)+1} of ${iy.length} (${ji[r]})`,remediation:d?`${d} \u2014 ${l}`:l})},FC=async e=>{let t=await Do(e.branch,{operation:`remove the worktree for ${e.branch}`,remediation:`commit or discard the changes inside ${e.worktreePath} (\`git -C ${e.worktreePath} stash -u\`), then re-run`});return{outcome:t.includes(e.branch)?"removed":"absent",removedBranches:t}},LC=e=>{let t=e.map(s=>({provider:s.provider,outcome:BC(s),removed:s.removed})),r=t.some(s=>s.outcome==="verified"),o=t.some(s=>s.outcome==="attempted")?"attempted":"skipped";return{outcome:r?"verified":o,providers:t}},BC=e=>e.removed.length>0?"verified":"attempted",WC=async(e,t,r)=>{let n={outcome:"attempted",providers:[]};return await _C("ide-folders",r,async()=>{let o=await yr({projectRoot:e.projectRoot,worktreeDir:e.worktreeDir,removedWorktrees:t});n=LC(o)}),u.info({outcome:n.outcome,step:"ide-folders"},`\u2705 ${ji["ide-folders"]} \u2014 ${n.outcome}`),n},VC=async e=>{let t=await Kr(e.branch);if(ly({...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 Id`gh pr close ${String(t.number)} --comment ${r}`,{outcome:"closed",number:t.number}},UC=async e=>(await Tr()===e.branch&&await Id`git switch ${e.baseBranch}`,await ys(e.branch),await Tp(e.branch)?Je({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"),JC=async e=>(await vs(e.branch),e.remoteTipSha?"deleted":"absent"),GC=async(e,t,r)=>{let n=await Ks(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}\``;Je({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}`})},KC=async(e,t)=>t.skipJira?"skipped":!e.jira||!e.jiraConfig?"absent":(await GC(e,e.jira,e.jiraConfig),u.info({jiraVersionId:e.jira.version.id,jiraVersionName:e.jira.version.name},"\u{1F5D1}\uFE0F removing Jira fix version"),await Bc({versionId:e.jira.version.id,moveFixIssuesTo:e.moveIssuesTo?.id,moveAffectedIssuesTo:e.moveIssuesTo?.id},e.jiraConfig),"removed"),HC=(e,t)=>({branch:e.branch,version:e.label,baseBranch:e.baseBranch,worktree:t.worktree.outcome,ideFolders:t.ideFolders,pr:t.pr.outcome,prNumber:t.pr.number,localBranch:t.localBranch,localTipSha:e.localTipSha,remoteBranch:t.remoteBranch,remoteTipSha:e.remoteTipSha,jira:t.jira,jiraVersion:e.jira?{id:e.jira.version.id,name:e.jira.version.name,url:e.jira.url}:null}),qC=async(e,t,r)=>{let n=await Jo("worktree",r,()=>FC(e)),o=await WC(e,n.removedBranches,r),s=await Jo("pr",r,()=>VC(e));u.info({branch:e.branch,localTipSha:e.localTipSha,remoteTipSha:e.remoteTipSha},"\u{1F516} branch tips before deletion");let i=await Jo("local-branch",r,()=>UC(e)),a=await Jo("remote-branch",r,()=>JC(e)),c=await Jo("jira",r,()=>KC(e,t));return{worktree:n,ideFolders:o,pr:s,localBranch:i,remoteBranch:a,jira:c}},YC=async(e,t)=>{let r=[];try{return HC(e,await qC(e,t,r))}catch(n){throw n instanceof Mi?jC({plan:e,step:n.step,done:r,cause:n.reason}):n}},zC=async e=>{if(e)return pt(e);h.setInteractive();let[t,r]=await Promise.all([se(),F()]),n=r.map(s=>s.branch);n.length===0&&Je({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 At(ie({branches:n,descriptions:t,types:o}))}catch(s){throw Re(s)?s:new f(s,{operation:"select a release to remove",remediation:"pass `--version <ref>` (e.g. `--version 1.2.5`); the picker needs an interactive terminal"})}},dy=Od(),Fi=async e=>{let{confirmedCommand:t,version:r,moveIssuesTo:n,skipJira:o}=e;await Ee({operation:wr}),await M(),await qe({provider:dy,params:e,operation:wr,argument:"version"}),RC(e);try{let s=await OC(await zC(r),e);u.debug({plan:cy(s)},"release remove: resolved plan"),ly(s),SC(s,e),PC(s),await to({operation:`remove release ${s.label}`,base:s.baseBranch}),EC(s),h.addOption("--version",s.label),n&&h.addOption("--move-issues-to",n),o&&h.addOption("--skip-jira",!0),await B(t,DC(s,!!o),{throwOnDecline:!0,plan:{...cy(s),skipJira:!!o}}),t||h.addOption("--yes",!0);let i=await YC(s,e);return h.print(),{content:k(JSON.stringify(i,null,2)),structuredContent:i}}catch(s){throw Re(s)||at(s)||s instanceof f?s:(u.error({err:jt(s)},"\u274C Error removing release"),new f(s,{operation:wr,remediation:"check `gh auth status`, `git worktree list` and the Jira credentials, then re-run"}))}},Dd=S({name:"release-remove",description:'Tear down ONE release created by release-create: removes its git worktree (closing every Orca terminal open in it first \u2014 a call made from an Orca terminal inside that worktree is refused as orca_caller_inside_target before anything is touched), strips the worktree from the Cursor workspace, closes its pull request with a comment, deletes the release branch locally and on origin, and REMOVES ITS JIRA FIX VERSION \u2014 the one irreversible step (new id, new URL, lost issue links), which is why every call is gated behind human confirmation. Omit "version" and this server offers the human a form listing the open release PRs; the accepted choice feeds the confirm gate. A client that cannot render a form gets a gate with no version \u2014 confirming it is refused, never guessed. Pass "version" when the human already named the release. One release per call \u2014 repeat the call for another; there is no "versions" field. Refuses before any mutation when the PR is MERGED (the release has shipped), when the fix version is released/archived, when the fix version still carries issues (pass "moveIssuesTo" to reassign them), or when nothing named that version exists. skipJira is CLI-only and has no field here: it would leave a live fix version behind with nothing in the result pointing at it. Resumable: every step is a verified no-op when its artefact is already gone, so a re-run finishes a partial teardown. What is lost with the worktree directory: gitignored contents including a hydrated .env of Doppler secrets (re-fetch with env-load) and node_modules/dist.',requiresHumanConfirm:!0,formProvider:dy,inputSchema:{version:L.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:L.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:L.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{branch:L.string().describe("The release branch that was targeted"),version:L.string().describe('The release label (e.g. "1.2.5")'),baseBranch:L.string().describe("The branch HEAD was moved to before the local delete"),worktree:L.enum(["removed","absent"]).describe("Whether a git worktree was removed or none existed"),ideFolders:L.object({outcome:L.enum(["verified","attempted","skipped"]).describe('"verified" only when an editor reported a real diff; "skipped" when no editor is configured'),providers:L.array(L.object({provider:L.string(),outcome:L.enum(["verified","attempted","skipped"]),removed:L.array(L.string()).describe("Folder paths confirmed removed")}))}).describe("Per-editor outcome of stripping the worktree folder"),pr:L.enum(["closed","already-closed","absent"]).describe("What happened to the release pull request"),prNumber:L.number().nullable().describe("The pull request number, or null when none exists"),localBranch:L.enum(["deleted","absent"]).describe("Whether a local branch was deleted or none existed"),localTipSha:L.string().nullable().describe("The local tip before deletion \u2014 the handle that restores the branch"),remoteBranch:L.enum(["deleted","absent"]).describe("Whether the origin branch was deleted or none existed"),remoteTipSha:L.string().nullable().describe("The origin tip before deletion"),jira:L.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:L.object({id:L.string(),name:L.string(),url:L.string()}).nullable().describe("The fix version this release owned, captured before removal \u2014 the id is the only handle that survives it")},handler:Fi});import{spawnSync as e$}from"node:child_process";import{homedir as t$}from"node:os";import r$ from"node:process";var XC=e=>{let t=new Set(e.steps.map(r=>r[0]));return t.has("brew")?"homebrew":t.has("npm")?"npm":null},ZC=e=>{let t=[];return e.needsSudo&&t.push("needs-sudo"),e.fetchesNetworkScript&&t.push("fetches-network-script"),t},QC=(e,t)=>{let r=XC(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},Go=(e,t)=>{let r=[...ZC(e),...QC(e,t)];return r.length===0?{executable:!0}:{executable:!1,reasons:r}},Ko=e=>e.steps.map(Ae);var n$=["NONINTERACTIVE","CI","INTERACTIVE","HAVE_SUDO_ACCESS","SUDO_ASKPASS"],o$=e=>{let t={...rp(e)};for(let r of n$)delete t[r];return t},Nd=(e,t,r={})=>{let n=r.spawnSync??e$,o=r.env??r$.env,s=(r.agentMode??ye)(),i=Ko(e),a=Go(e,t);return a.executable?s?{ran:!1,commands:i,refusedBecause:["agent-mode"]}:a$({recipe:e,spawn:n,env:o,commands:i,notify:r.notify??s$}):{ran:!1,commands:i,refusedBecause:a.reasons}},s$=e=>{u.info(e)},py=64,i$=py*1024*1024,a$=({recipe:e,spawn:t,env:r,commands:n,notify:o})=>{let s=o$(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:i$,cwd:t$(),env:s}),l=m$(c);if(l!==null)return{ran:!0,ok:!1,commands:n,failedStep:n[i],detail:l}}return{ran:!0,ok:!0,commands:n}},c$=5,l$=/^(?:error|fatal|warning: failed|[a-z-]{0,20} ERR!)[:\s]/i,uy=e=>e==null?[]:String(e).split(`
425
+ `).map(t=>t.trim()).filter(t=>t.length>0),d$=e=>{let t=uy(e.stderr),r=uy(e.stdout),n=[...t,...r].filter(s=>l$.test(s)),o=t.length>0?t:r;return(n.length>0?n:o).slice(-c$).join(" / ")},u$="ENOBUFS",p$=e=>e.error?.code===u$,m$=e=>{if(p$(e))return`terminated after exceeding the ${py} 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=d$(e),r=t===""?"":`: ${t}`;return`exited ${e.status??"unknown"}${r}`};var f$=e=>{let t=[];return e.some(n=>n.id==="brew"&&n.present)&&t.push("homebrew"),t.push("npm"),t},g$=e=>{let t=Me(e.id);return e.present?t.updateFor(e.binRealPath):t.bootstrapInstall},h$=(e,t)=>{let r=g$(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=Go(r,n);return{state:e,action:e.present?"update":"install",recipe:r,executable:o.executable,refusedBecause:o.executable?[]:o.reasons,commands:Ko(r),context:n}},Li=async(e=ar,t=vo())=>{let r=await ko(ar,t),n={owner:null,present:f$(r)},o=fl(e),s=new Map(r.map(a=>[a.id,a]));return{plans:o.filter(a=>e.includes(a)).map(a=>h$(s.get(a),n)),context:n}};var _d=(e,t)=>({...Ho(e),action:"skipped",commands:e.commands,detail:t}),Ho=e=>({id:e.state.id,before:{present:e.state.present,onPath:e.state.onPath,version:e.state.version,manager:e.state.manager}}),my=(e,t)=>e.action==="none"?_d(e,`nothing to do: ${e.state.manager} installs are not managed from here`):t==="update"&&e.action==="install"?_d(e,"not installed, and --update only updates \u2014 drop the flag to install it"):e.executable?null:{...Ho(e),action:"refused",commands:e.commands,detail:`refused (${e.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},y$=(e,t)=>t.ran?t.ok?{...Ho(e),action:e.action==="install"?"installed":"updated",commands:t.commands,detail:e.action==="install"?"installed":"updated"}:{...Ho(e),action:"failed",commands:t.commands,detail:`${t.failedStep??"a step"} ${t.detail??"failed"}`}:{...Ho(e),action:"refused",commands:t.commands,detail:`refused (${t.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},Md=async e=>{let t=e.run??Nd,{plans:r}=await Li(e.ids,e.probeDeps),n=[];for(let o of r){let s=my(o,e.mode);if(s!==null){n.push(s);continue}n.push(y$(o,t(o.recipe,o.context)))}return n},jd=async(e,t)=>{let{plans:r}=await Li(e,t);return r.map(n=>my(n,"converge")??_d(n,`would ${n.action} \u2014 nothing was run (--skip-tools)`))};import D$ from"node:process";import{z as $}from"zod";var Fd={zshrc:0,zshenv:1,migrations:2,"user-config":3,guidance:4,worktrees:5,"plugin-pointer":6,"mcp-server":7,"mcp-proxies":8,"project-config":9,shell:10},v$=Object.keys(Fd).sort((e,t)=>Fd[e]-Fd[t]),fy={skipped:0,ok:1,changed:2,manual:3,warn:4,fail:5},gy=new Set(["manual","warn","fail"]),Ld=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 Ie(e)}},w$=e=>e.reduce((t,r)=>fy[r]>fy[t]?r:t,"skipped"),yy=e=>e.message.trim(),k$=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 "),hy=e=>e.message===cn,b$=(e,t)=>{let[r]=e;return e.length===1&&r!==void 0?yy(r):e.length>1?k$(e):t?"activate with the last line below":"see below"},R$=(e,t)=>{if(t.length===0)return{name:e,status:"skipped",message:"did not run"};let r=t.map(i=>Ld(i.outcome)),n=t.filter(i=>gy.has(Ld(i.outcome))).map(yy),o=t.filter(i=>!gy.has(Ld(i.outcome))&&!hy(i)),s={name:e,status:w$(r),message:b$(o,t.some(hy))};return n.length>0?{...s,notes:n}:s},S$=e=>({label:"Local setup",rows:v$.map(t=>R$(t,e.filter(r=>r.step===t)))}),P$=(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 Ie(e.action)}},E$=(e,t)=>{let r=P$(e,t),n={name:e.id,status:r,message:e.detail};return r==="manual"&&e.commands.length>0?{...n,notes:[...e.commands]}:n},x$=(e,t)=>({label:t.skipTools?"Tools (probe: nothing installed)":"Tools",rows:e.map(r=>E$(r,t))}),T$=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 Ie(e)}},C$=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 Ie(e)}},$$=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 Ie(e)}},A$=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 Ie(e.outcome)}},O$=(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 Ie(e)}},I$=e=>({label:"Portless service",rows:[{name:"link",status:T$(e.link),message:$$(e.link)},{name:"node",status:C$(e.node.outcome),message:A$(e.node)},O$(e.service,e.command)]}),vy=(e,t)=>[S$(e.init),x$(e.tools,t),I$(e.portless)],wy=e=>e.some(t=>t.rows.some(r=>r.status==="fail"));var N$=()=>{let{link:e,node:t}=fs();return{link:e,node:t,target:{home:e.home,isGlobal:e.isGlobal,processStartTime:()=>null}}},_$=async e=>{let t=yp(e.link).outcome,r=hp(e.node),n=ms(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 Qg(e.target,n);if(o==="converged")return{link:t,node:r,service:o,command:null};let i=yt(n,{home:e.link.home,exists:e.target.exists,execPath:e.target.execPath,stableNode:s});return{link:t,node:r,service:o,command:i}},by="--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.",M$=e=>{let t=Array.isArray(e.update)?e.update:void 0,r=e.update===!0||t!==void 0,n=e.skipTools===!0;if(n&&(e.tools!==void 0||r))throw new Error(by);return{ids:e.tools??t??ar,mode:r?"update":"converge",skipTools:n}},ky=(e,t)=>e instanceof an?e.step:t.at(-1)?.step??"zshrc",j$=async()=>{let e=[];try{await al(t=>{e.push(t)})}catch(t){e.push({step:ky(t,e),outcome:"failed",message:`The ${ky(t,e)} step failed: ${t instanceof Error?t.message:String(t)}`,level:"warn"})}return e},F$=(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}`}))},L$=async(e,t)=>{try{return e.skipTools?await jd(e.ids,t.probeDeps):await Md({ids:e.ids,mode:e.mode,probeDeps:t.probeDeps,run:t.run})}catch(r){return F$(e.ids,r)}},B$=e=>({step:e.step,outcome:e.outcome,message:e.message}),Bi=async(e={})=>{let t=M$(e),r=await j$(),n=await L$(t,e),o=await _$(e.portlessDeps??N$()),s=vy({init:r,tools:n,portless:o},{skipTools:t.skipTools});Qe({title:"infra-kit setup",sections:s},{ascii:e.ascii}),u.info(cn),wy(s)&&(D$.exitCode=1);let i={init:r.map(B$),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}},W$=$.object({step:$.enum(["zshrc","zshenv","migrations","user-config","guidance","worktrees","plugin-pointer","mcp-server","mcp-proxies","project-config","shell"]).describe("Which init step this reports on"),outcome:$.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:$.string().describe("The same line a human running this would have read")}),V$=$.object({id:$.string().describe("Dependency id"),action:$.enum(["installed","updated","skipped","refused","failed"]).describe("What happened"),before:$.object({present:$.boolean(),onPath:$.boolean(),version:$.string().nullable(),manager:$.string()}).describe("The tool\u2019s state before this run"),commands:$.array($.string()).describe("The exact commands, one per step \u2014 printed even when refused"),detail:$.string().describe("Why, in one line")}),U$=$.object({link:$.enum(["created","repointed","unchanged","skipped-local","skipped-unresolved","failed"]).describe("What the ~/.infra-kit/portless link step did"),node:$.enum(["created","refreshed","unchanged","skipped-local","skipped-platform","failed"]).describe("What the ~/.infra-kit/node step did"),service:$.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:$.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")}),J$={init:$.array(W$).describe("One entry per init step, in the order they ran"),tools:$.array(V$).describe("One result per requested dependency"),portlessService:U$.describe("The portless link, node, and system-service step \u2014 run on every setup, never gated on the tool options"),converged:$.boolean().describe("Whether the dependency step could act at all (false under skipTools)"),changed:$.boolean().describe("Whether anything was installed or updated"),report:$.array($.object({label:$.string().describe("Section heading"),rows:$.array($.object({name:$.string().describe("Init step, tool id, or portless part"),status:$.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:$.string().describe("The row message, as printed"),notes:$.array($.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:$.boolean().describe("Whether no tool failed (a refusal is not a failure)")},G$={tools:$.array($.enum(ar)).optional().describe("Which tools to act on. Omit for all six."),mode:$.enum(["converge","update"]).optional().describe("converge (default): install what is missing and update the rest. update: never install."),skipTools:$.boolean().optional().describe("Read-only: run the init half, then REPORT what each tool needs without installing anything.")},Bd=S({name:"setup",description:'Set this machine up in one call: inject the shell integration into .zshrc and the session-env block into .zshenv, run the config migrations, seed the user-global config, refresh the agent-instruction files, register the Claude Code plugin pointer and install or update the skills plugin (the `/infra-kit:*` skills drive the infra-kit CLI on PATH; a leftover .mcp.json entry is reported, never written), then bring brew, git, aws, gh, doppler and portless to a working state \u2014 installing what is missing and updating what is present. Pass mode:"update" to update only and never install, or skipTools:true to do the local setup and then REPORT what each tool needs without installing anything. Recipes that need sudo or pipe a script fetched over the network \u2014 the Homebrew bootstrap and the first AWS CLI install \u2014 are never run; they are reported with the exact commands for you to run yourself. Use `doctor` first to see the state of this machine without changing it.',inputSchema:G$,outputSchema:J$,requiresHumanConfirm:!0,handler:e=>Bi({tools:e.tools,update:e.mode==="update",skipTools:e.skipTools})});import{existsSync as Sy}from"node:fs";import Py from"node:path";import rA from"node:process";import{z as ht}from"zod";import{createHash as K$}from"node:crypto";import{readFileSync as H$}from"node:fs";var kr=e=>K$("sha256").update(H$(e)).digest("hex");import{readFileSync as Q$,writeFileSync as eA}from"node:fs";import Ji from"node:path";import{z as st}from"zod";var Q="vendor",q$=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack"]),Y$=new Set([".sync-manifest.json",".eslintcache","log.txt","routeTree.gen.ts"]),z$=[".tsbuildinfo"],Wd=e=>q$.has(e),Vd=e=>Y$.has(e)?!0:z$.some(t=>e.endsWith(t)),Wi=e=>{let t=e.split("/"),r=t.pop()??"";return t.some(o=>Wd(o))||Vd(r)};import{readdirSync as X$}from"node:fs";import Ud from"node:path";var Z$=e=>e.split(Ud.sep).join("/"),Vi=e=>{let t=[],r=n=>{for(let o of X$(n,{withFileTypes:!0})){let s=Ud.join(n,o.name);if(o.isDirectory()){if(Wd(o.name))continue;r(s);continue}Vd(o.name)||t.push(Z$(Ud.relative(e,s)))}};return r(e),t.sort()};var Le=".sync-manifest.json",Ui=1,tA=st.object({schemaVersion:st.number().optional(),source:st.string(),commit:st.string(),syncedAt:st.string(),fileCount:st.number(),files:st.record(st.string(),st.string())}),Jd=e=>(e.schemaVersion??Ui)>Ui,Ry=(e,t)=>{let r={},n=t?[...new Set(t)].sort():Vi(e);for(let o of n)try{r[o]=kr(Ji.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},qo=e=>{let t=Ji.join(e,Le),r;try{r=Q$(t,"utf8")}catch{throw new Error(`Missing ${Le} at ${t}`)}let n=tA.safeParse(JSON.parse(r));if(!n.success)throw new Error(`Invalid ${Le} at ${t}: ${st.prettifyError(n.error)}`);return n.data},Gd=(e,t,r)=>{let n=Ry(e,r),o={schemaVersion:Ui,source:t.source,commit:t.commit,syncedAt:new Date().toISOString(),fileCount:Object.keys(n).length,files:n};return eA(Ji.join(e,Le),`${JSON.stringify(o,null,2)}
426
+ `),o},Kd=(e,t)=>{let r=Object.fromEntries(Object.entries(t.files).filter(([c])=>!Wi(c))),n=Vi(e),o=[],s=[];for(let c of n){if(!(c in r)){s.push(c);continue}kr(Ji.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 Hd=30,qd=(e,t)=>{if(t.length!==0){u.info(`
427
+ ${e} (${t.length}):`);for(let r of t.slice(0,Hd))u.info(` ${r}`);t.length>Hd&&u.info(` \u2026and ${t.length-Hd} more`)}},Gi=async(e={})=>{let t=e.cwd??await T(),r=Py.join(t,Q),n={modified:[],added:[],removed:[],fileCount:0};if(!Sy(r)){u.info(`\u2139\uFE0F No ${Q}/ folder found \u2014 nothing to check.`);let d={status:"skipped",ok:!0,...n};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}}if(!Sy(Py.join(r,Le))){u.error(`\u274C Missing ${Q}/${Le}. Re-run the vendor sync to generate it.`);let d={status:"missing-manifest",ok:!1,...n};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}}let o=qo(r);if(Jd(o)){u.error(`\u274C ${Q}/${Le} has a newer schemaVersion (${String(o.schemaVersion)}) than this CLI supports. Upgrade infra-kit.`);let d={status:"unknown-schema",ok:!1,...n};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}}let{modified:s,added:i,removed:a}=Kd(r,o),c=s.length>0||i.length>0||a.length>0;c?(u.error(`\u274C ${Q}/ has drifted from ${Q}/${Le}.`),u.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),qd("Modified",s),qd("Added (not in manifest)",i),qd("Removed (in manifest, now missing)",a)):u.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}},nA={status:ht.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:ht.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:ht.number(),modified:ht.array(ht.string()),added:ht.array(ht.string()),removed:ht.array(ht.string())},Yd=S({name:"vendor-check",description:"Verify that files under vendor/ match the checksums in vendor/.sync-manifest.json. Self-contained (no source repo or config needed). Returns ok=false on drift, missing manifest, or an unknown future schemaVersion; ok=true when clean or when no vendor/ folder exists.",inputSchema:{},outputSchema:nA,handler:()=>Gi({cwd:rA.cwd()})});import Ey from"node:process";import{z as Yo}from"zod";var xy=async e=>{try{return await e()}catch{return null}},Ki=async()=>{let e=K.version;u.info(e);let t=await xy(T),r=t===null?null:await xy(()=>be(t)),n={version:e,cwd:Ey.cwd(),repoRoot:t,mainRepoRoot:r,projectDir:Ey.env.CLAUDE_PROJECT_DIR||null};return{content:k(JSON.stringify(n,null,2)),structuredContent:n}},zd=S({name:"version",description:"Print the installed infra-kit CLI version and where this process runs (cwd, repo root, main repo root, CLAUDE_PROJECT_DIR)",inputSchema:{},outputSchema:{version:Yo.string().describe("Installed infra-kit CLI version (from package.json)"),cwd:Yo.string().describe("The working directory of this process"),repoRoot:Yo.string().nullable().describe("git toplevel of cwd \u2014 the worktree itself in a linked worktree; null when git cannot answer"),mainRepoRoot:Yo.string().nullable().describe("The main checkout a linked worktree belongs to (equals repoRoot outside worktrees); null with repoRoot"),projectDir:Yo.string().nullable().describe("CLAUDE_PROJECT_DIR as Claude Code set it for this process, or null")},handler:Ki});import Ly from"@inquirer/confirm";import lA from"node:path";import{z as _}from"zod";import{$ as Xo}from"zx";import oA from"@inquirer/input";import Cy from"@inquirer/select";import{$ as Bt}from"zx";var zo="dev",sA="main",Xd="feature/",$y=["new","local","remote"],Hi=e=>{let t=e.trim().replace(/^feature\//,"").toLowerCase().replaceAll(/\s+/g,"-");return`${Xd}${t}`},Ay=async()=>{let e=await Bt({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},iA=2,Zd=async()=>{let e=await Bt({nothrow:!0,quiet:!0})`git ls-remote --exit-code origin refs/heads/${zo}`;if(e.exitCode===0)return zo;if(e.exitCode!==iA)throw new f(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 ${zo} exists`});return await Ay()??zo},Oy=async e=>{let t=e?.trim();return t?t===zo||t===sA||t===await Ay()?t:ve(me(t)):Zd()},Iy=async()=>O(e=>Cy({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"}}),Dy=async()=>O(e=>oA({message:"Feature name (becomes feature/<name>):",required:!0,validate:t=>Hi(t)===Xd?"Enter a name":!0},e),{whenHeadless:{refuse:"feature"}}),Ny=async(e,t)=>e.length===0?t:O(r=>Cy({message:"Base branch:",default:t,choices:[t,...e].map(n=>({name:n,value:n}))},r),{whenHeadless:{value:t}}),aA=async e=>{let t=await Bt({nothrow:!0,quiet:!0})`git check-ref-format --branch ${e}`;if(e===Xd||t.exitCode!==0)throw new f(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`})},Ty=async e=>(await Bt({nothrow:!0,quiet:!0})`git fetch origin ${e}`).exitCode===0,cA=async e=>(await Bt({nothrow:!0,quiet:!0})`git show-ref --verify --quiet refs/heads/${e}`).exitCode===0,_y=async e=>{let{names:t,base:r}=e,n=[...new Set(t.map(Hi))];for(let s of n)await aA(s);if(!await Ty(r))throw new f(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 cA(s)?o.push({branch:s,base:r,source:"local"}):await Ty(s)?o.push({branch:s,base:r,source:"remote"}):o.push({branch:s,base:r,source:"new"});return o},My=async(e,t)=>{let{branch:r,base:n,source:o}=e;o==="local"?await Bt`git worktree add ${t} ${r}`:o==="remote"?await Bt`git worktree add --track -b ${r} ${t} origin/${r}`:await Bt`git worktree add --no-track -b ${r} ${t} origin/${n}`},jy=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 Zo="create worktrees",dA=["already_open","orca_unreachable","orca_absent","orca_worktree_not_selectable","orca_error"],Qd=()=>({orcaOpened:[],orcaSkipped:[],orcaHidden:[]}),qi=async e=>{let{confirmedCommand:t,githubDesktop:r,orca:n}=e,o=e.ide??e.cursor;await Ee({operation:Zo}),uA(e);try{let s=await T(),i=`${s}${de}`;await Fy(`${i}/${Er.release}`),await Fy(`${i}/${Er.feature}`);let a=await pA(e),c=a==="feature"?await fA(e):await mA(e);if(c===null){u.info("\u2139\uFE0F No open release branches found"),h.print();let P={kind:a,createdWorktrees:[],count:0,features:[],...Qd()};return{content:k(JSON.stringify(P,null,2)),structuredContent:P}}let l=await M(),d=o??(wt(l).length>0?"workspace":"none");h.addOption("--ide",d);let p=await gA(r,l),m=await hA(n,l),g=await be(s),y=lA.basename(g),R=m?await yA({explicit:n!==void 0,mainRepoRoot:g}):null;await B(t,vA(R,y,c.previewLines)),t||h.addOption("--yes",!0);let w=R?await wA(R,g):null,x=await PA(c.targets,i);if(EA(x),d==="workspace"&&await Ad({projectRoot:s,worktreeDir:i,branches:x}),p)for(let P of x)await Xo`github ${i}/${P}`,await Xo`sleep 5`;let W=w?await bA({registration:w,createdWorktrees:x,worktreeDir:i,mainRepoRoot:g,repoName:y,config:l}):Qd();RA(W),h.print();let I={kind:a,createdWorktrees:x,count:x.length,features:c.features.filter(P=>x.includes(P.branch)),...W};return{content:k(JSON.stringify(I,null,2)),structuredContent:I}}catch(s){throw Re(s)||s instanceof C?s:(u.debug({err:s},"Error managing worktrees"),new f(s,{operation:Zo,remediation:s instanceof f&&s.remediation||"verify branches don't already exist as worktrees: 'git worktree list'"}))}},uA=e=>{let t=e.all||e.versions!==void 0,r=e.feature!==void 0||e.base!==void 0;if(t&&r)throw new f(void 0,{operation:Zo,remediation:"pass either --versions/--all (release worktrees) or --feature [--base] (feature worktrees)",stderrExcerpt:"--feature/--base cannot be combined with --versions/--all"})},pA=async e=>e.feature!==void 0||e.base!==void 0?"feature":e.all||e.versions!==void 0?"release":(h.setInteractive(),Iy()),mA=async e=>{let{all:t,versions:r}=e,n=await fe("release"),o=[];if(r)o=r.split(",").map(a=>ve(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])),d=await se();o=await Ot(ie({branches:c,descriptions:d,types:l}),{required:!0})}}t?h.addOption("--all",!0):h.addOption("--versions",mt(o));let{branchesToCreate:s}=SA({selectedReleaseBranches:o,currentWorktrees:n});return{targets:s.map(a=>({branch:a,add:c=>Xo`git worktree add ${c} ${a}`})),features:[],previewLines:[]}},fA=async e=>{let r=e.feature?.split(",").filter(l=>l.trim()!=="")??[],n=e.base;if(r.length===0&&(h.setInteractive(),r=[await Dy()],n===void 0)){let l=(await F()).map(d=>d.branch);n=await Ny(l,await Zd())}let o=await Oy(n),s=await _y({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)?(u.info(`\u2139\uFE0F ${l.branch} is already checked out in a worktree`),!1):!0);return{targets:a.map(l=>({branch:l.branch,add:d=>My(l,d)})),features:a,previewLines:a.map(jy)}},gA=async(e,t)=>{let r=t.worktrees?.openInGithubDesktop,n=e??r??await O(o=>Ly({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},hA=async(e,t)=>{let r=t.worktrees?.openInOrca,n=e??r??await O(o=>Ly({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},By=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"},yA=async e=>{let{explicit:t,mainRepoRoot:r}=e,n=await St();if(n!=="ready"){let{reason:s,text:i}=By(n);if(t)throw u.warn({operation:Zo},`\u26D4 --orca was passed but ${i}`),new C({status:"refused",reason:s,agentMode:N.source},2,{operation:Zo,remediation:n==="absent"?"install Orca (brew install --cask stablyai/orca/orca) and register its CLI from Settings \u2192 Experimental \u2192 CLI, or re-run with --no-orca":"open Orca (`orca open`) and re-run, or re-run with --no-orca",stderrExcerpt:`--orca was passed but ${i}; no worktree was created`});return u.warn(`\u26A0\uFE0F ${i} \u2014 worktrees will be created but not opened in Orca`),{probe:n,registered:!1,visibility:void 0}}let o=await am(r);return{probe:n,registered:o.registered,visibility:o.visibility}},vA=(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(`
428
+ `)},wA=async(e,t)=>{if(e.probe!=="ready")return{kind:"skip",reason:By(e.probe).reason};if(e.registered)return{kind:"ready",visibility:e.visibility};try{let{visibility:r}=await cm(t);return{kind:"ready",visibility:r}}catch(r){return u.warn({error:r},"\u26A0\uFE0F orca repo add failed \u2014 worktrees will be created but not opened in Orca"),{kind:"skip",reason:"orca_error",code:r instanceof $r?r.code:void 0}}},kA=e=>`Orca \u2192 ${e} \u2192 "hidden worktrees" card \u2192 Show, or Settings \u2192 General \u2192 Workspace \u2192 external-worktree sources`,bA=async e=>{let{registration:t,createdWorktrees:r,worktreeDir:n,mainRepoRoot:o,repoName:s,config:i}=e,a=Qd();if(t.kind==="skip"){for(let p of r)a.orcaSkipped.push({branch:p,reason:t.reason,code:t.code});return a}let c=Lp(i),l=r.length===1&&t.visibility!=="hide",d=dm();for(let p of r){let m=`${n}/${p}`;try{let{layout:g}=await um({cwd:m,title:pm({branch:p}),focus:l,layout:"full",panes:c,poll:d});await lm(o,m)?a.orcaOpened.push({branch:p,layout:g}):a.orcaHidden.push({branch:p,path:m,fix:kA(s)})}catch(g){u.warn({error:g,branch:p},`\u26A0\uFE0F Failed to open Orca terminals for ${p}`),g instanceof $r&&g.code==="orca_worktree_not_selectable"?a.orcaSkipped.push({branch:p,reason:"orca_worktree_not_selectable"}):a.orcaSkipped.push({branch:p,reason:"orca_error",code:g instanceof $r?g.code:void 0})}}return a},RA=e=>{for(let t of e.orcaOpened)u.info(`\u{1FA9F} Opened ${t.branch} in Orca (${t.layout})`);for(let t of e.orcaHidden)u.info(`\u{1F648} ${t.branch} opened in Orca but its row is hidden (${t.path}) \u2014 ${t.fix}`);for(let t of e.orcaSkipped){let r=t.code?` (${t.code})`:"";u.info(`\u21A9\uFE0F ${t.branch} not opened in Orca: ${t.reason}${r}`)}},Fy=async e=>{await Xo`mkdir -p ${e}`},SA=e=>{let{selectedReleaseBranches:t,currentWorktrees:r}=e,n=r.filter(s=>xr(s));return{branchesToCreate:t.filter(s=>!n.includes(s))}},PA=async(e,t)=>{let r=await Promise.allSettled(e.map(async o=>{let s=`${t}/${o.branch}`;return await o.add(s),await Xo({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 f(s.reason,{operation:`git worktree add for ${i}`,remediation:"check the branch name and that the parent dir is writable"});u.error({error:s.reason,msg:a.message})}return n},EA=e=>{if(e.length>0){u.info("\u2705 Created git worktrees:");for(let t of e)u.info(t);u.info("")}else u.info("\u2139\uFE0F No new git worktrees to create")},eu=S({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:_.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:_.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:_.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:_.string().optional().describe('Comma-separated release versions or names to target (e.g. "1.2.5, 1.2.6" or "checkout-redesign, 1.2.5"). Either "versions" or all=true must be provided for MCP calls. Overrides "all" when set.'),ide:_.enum(vr).optional().describe('Editor open mode for created worktrees, applied to the configured editor (Cursor, per the "ide" config). "workspace" (the only attach style) adds each worktree to the Cursor workspace and opens it. "none" skips the editor. Resolution order: this flag \u2192 "workspace" when an "ide" is configured \u2192 "none" otherwise.'),cursor:_.enum(vr).optional().describe('Deprecated alias for "ide". Prefer "ide". Ignored when "ide" is provided.'),githubDesktop:_.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:_.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:_.enum(["release","feature"]).describe("Which kind of worktree the run created"),features:_.array(_.object({branch:_.string(),base:_.string(),source:_.enum($y)})).describe('Created feature worktrees: source "new" = cut from origin/<base>; "local" / "remote" = an existing branch checked out as-is (base not applied)'),createdWorktrees:_.array(_.string()).describe("List of created git worktree branches"),count:_.number().describe("Number of git worktrees created"),orcaOpened:_.array(_.object({branch:_.string(),layout:_.enum(["full","single-pane"])})).describe("Created worktrees that got an Orca terminal tab on a row the sidebar shows, with the layout applied"),orcaSkipped:_.array(_.object({branch:_.string(),reason:_.enum(dA),code:_.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:_.array(_.object({branch:_.string(),path:_.string(),fix:_.string()})).describe("Created worktrees whose Orca terminals opened on a row the sidebar HIDES (the repo hides external worktrees); fix names the in-app steps to reveal it")},handler:qi});import{z as Wt}from"zod";var Yi=async()=>{await M();let[e,t]=await Promise.all([fe("release"),fe("feature")]);if(e.length===0&&t.length===0){u.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 xA(e):[],n=[];r.length>0&&n.push(`\u{1F33F} Active worktrees:
429
+
430
+ ${TA(r).join(`
422
431
  `)}`),t.length>0&&n.push(`\u{1F9EA} Feature worktrees:
423
432
 
424
433
  ${t.join(`
425
434
  `)}`),u.info(n.join(`
426
435
 
427
- `));let o={worktrees:r,count:r.length,features:t};return{content:k(JSON.stringify(o,null,2)),structuredContent:o}},wA=async e=>{let[t,r]=await Promise.all([F(),se()]),n=new Map(t.map(o=>[o.branch,o.type]));return e.flatMap(o=>{let s=G(o);if(!s)return[];let i=X(s),a=n.get(o)||"regular",c=r.get(re(s))||null;return[{version:i,type:a,description:c}]})},kA=e=>{let t=Math.max(...e.map(r=>r.version.length));return e.map(r=>{let n=so(r.version,r.type,t);return r.description?`${n} ${r.description}`:n})},Zd=S({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:Ft.array(Ft.object({version:Ft.string().describe("Release version"),type:Ft.enum(["regular","hotfix"]).describe("Release type"),description:Ft.string().nullable().describe("Jira version description")})).describe("Release worktrees with details"),count:Ft.number().describe("Number of release worktrees"),features:Ft.array(Ft.string()).describe("Branches of feature worktrees (feature/<name>)")},handler:qi});import{z as Lt}from"zod";var bA=e=>{if(ye()){if(e.all)throw new x({status:"refused",agentMode:N.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 x({status:"argument_required",argument:"versions",agentMode:N.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"})}},RA=(e,t)=>{let r=e.filter(n=>!t.includes(n));if(r.length>0)throw new f(void 0,{operation:"remove worktrees",remediation:`no active worktree for: ${r.join(", ")}. Run 'infra-kit worktrees list' to see current worktrees`,stderrExcerpt:`unmatched worktree target(s): ${r.join(", ")}`})},SA=async(e,t)=>{let r=await Rs(t.map(n=>`${e}/${n}`));if(r!==null)throw new x({status:"refused",reason:"orca_caller_inside_target",agentMode:N.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`})},PA=e=>e?e.split(",").map(t=>ve(pe(t.trim()))):[],EA=e=>e?e.split(",").filter(t=>t.trim()!=="").map(Ki):[],xA=e=>{let t=e.filter(n=>n.startsWith("feature/")),r=e.filter(n=>!t.includes(n));r.length>0&&h.addOption("--versions",rr(r)),t.length>0&&h.addOption("--feature",t.map(n=>n.replace(/^feature\//,"")).join(","))},Yi=async e=>{let{confirmedCommand:t,all:r,versions:n,feature:o}=e;await Pe({operation:"remove worktrees"}),await M(),bA({all:r,versions:n,feature:o});try{let[s,i]=await Promise.all([me("release"),me("feature")]),a=[...s,...i];if(a.length===0){u.info("\u2139\uFE0F No active worktrees to remove"),h.print();let g={removedWorktrees:[],failedWorktrees:[],count:0};return{content:k(JSON.stringify(g,null,2)),structuredContent:g}}let c=await T(),l=`${c}${ge}`,d=[];if(r)d=a;else if(n||o)d=[...PA(n),...EA(o)];else{h.setInteractive();let[g,y]=await Promise.all([se(),F()]),R=new Map(y.map(w=>[w.branch,w.type]));d=await Ct([...ie({branches:s,descriptions:g,types:R}),...i.map(w=>({value:w,label:w,type:"feature"}))],{required:!0})}RA(d,a);let p=d.length===a.length;p?h.addOption("--all",!0):xA(d),await SA(l,d),await V(t,"Are you sure you want to proceed with these worktree changes?"),t||h.addOption("--yes",!0);let m=await mr({branches:d,worktreeDir:l,projectRoot:c,pruneFolder:p});return await hr({projectRoot:c,worktreeDir:l,removedWorktrees:m.removed}),To(m),h.print(),Co({result:m,operation:"remove worktrees"})}catch(s){throw be(s)||s instanceof f?s:(u.error({error:s},"\u274C Error managing worktrees"),new f(s,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"}))}},Qd=S({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:Lt.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:Lt.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:Lt.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{removedWorktrees:Lt.array(Lt.string()).describe("List of removed git worktree branches"),failedWorktrees:Lt.array(Lt.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:Lt.number().describe("Number of git worktrees removed")},handler:Yi});import{z as Yo}from"zod";var zi=async e=>{let{confirmedCommand:t}=e;await Pe({operation:"sync worktrees"}),await M();try{let r=await me("release"),n=await T(),o=`${n}${ge}`,s=await Ws();await V(t,"Are you sure you want to proceed with these worktree changes?"),t||h.addOption("--yes",!0);let{branchesToRemove:i}=TA({releasePRsList:s,currentWorktrees:r}),a=await mr({branches:i,worktreeDir:o,projectRoot:n});return await hr({projectRoot:n,worktreeDir:o,removedWorktrees:a.removed}),To(a),h.print(),Co({result:a,operation:"sync worktrees"})}catch(r){throw be(r)||r instanceof f?r:(u.error({error:r},"\u274C Error managing worktrees"),new f(r,{operation:"sync worktrees with remote",remediation:"ensure 'gh auth status' is ok and you can reach origin"}))}},TA=e=>{let{releasePRsList:t,currentWorktrees:r}=e;return{branchesToRemove:r.filter(s=>ms(s)).filter(s=>!t.includes(s))}},eu=S({name:"worktrees-sync",description:"Remove worktrees whose release PR is no longer open (stale cleanup). Only removes \u2014 never creates; use worktrees-add to create worktrees for new releases. The CLI confirmation is auto-skipped for MCP calls, so the caller is responsible for gating. A branch git refuses to remove is listed in failedWorktrees and the result carries isError; a leftover that git already unregistered and that holds only tool state (.omc/state, .omc/sessions, .DS_Store) is swept automatically.",inputSchema:{},outputSchema:{removedWorktrees:Yo.array(Yo.string()).describe("List of removed worktree branches"),failedWorktrees:Yo.array(Yo.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:Yo.number().describe("Number of worktrees removed during sync")},handler:zi});var tu=[{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"}],lr=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["dev"],longRunning:!0},{cliName:"dev-status",menuGroup:"develop",mcpTool:Sc,mcpExposed:!0,mutating:!1,groupPath:["dev-status"]},{cliName:"e2e",menuGroup:"develop",mcpTool:Fl,mcpExposed:!1,mutating:!0,groupPath:["e2e"]},{cliName:"merge-dev",menuGroup:"release",mcpTool:Gl,mcpExposed:!0,mutating:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:ad,mcpExposed:!0,mutating:!1,groupPath:["release","list"]},{cliName:"release-create",menuGroup:"release",mcpTool:bd,mcpExposed:!0,mutating:!0,groupPath:["release","create"]},{cliName:"release-edit",menuGroup:"release",mcpTool:Sd,mcpExposed:!0,mutating:!0,groupPath:["release","edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:od,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:id,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:Hl,mcpExposed:!1,mutating:!0,humanOnly:!0,groupPath:["release","deliver"]},{cliName:"release-remove",menuGroup:"release",mcpTool:Ad,mcpExposed:!0,mutating:!0,groupPath:["release","remove"]},{cliName:"local-deploy-all",menuGroup:null,mcpTool:hd,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-all"]},{cliName:"local-deploy-selected",menuGroup:null,mcpTool:yd,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-selected"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:Xd,mcpExposed:!0,mutating:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:Zd,mcpExposed:!0,mutating:!1,groupPath:["worktrees","list"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:Qd,mcpExposed:!0,mutating:!0,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:eu,mcpExposed:!0,mutating:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:Wl,mcpExposed:!0,mutating:!1,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:mm,mcpExposed:!0,mutating:!1,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:Oa,mcpExposed:!0,mutating:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:Bl,mcpExposed:!0,mutating:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:Vl,mcpExposed:!0,mutating:!1,groupPath:["env-token-list"]},{cliName:"config-get",menuGroup:"configuration",mcpTool:bc,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:Kd,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:"setup",menuGroup:"setup",mcpTool:jd,mcpExposed:!0,mutating:!0,groupPath:["setup"]},{cliName:"doctor",menuGroup:"setup",mcpTool:Tl,mcpExposed:!0,mutating:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:vc,mcpExposed:!0,mutating:!1,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:Hd,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 ru=e=>lr.filter(t=>t.menuGroup===e),nu=e=>lr.some(t=>t.longRunning===!0&&t.groupPath.join(" ")===e);var CA=(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},jy=e=>tu.flatMap(({key:t,label:r})=>ru(t).flatMap(n=>{let o=CA(e,n.groupPath);return o?[{name:n.groupPath.join(" "),description:o.description(),group:r}]:[]}));import ou from"node:process";var $A="MODULE_TYPELESS_PACKAGE_JSON",AA=(e,t)=>typeof e=="object"&&e!==null?e.code:t,Fy=!1,su=()=>{if(Fy)return;Fy=!0;let e=ou.emitWarning.bind(ou);ou.emitWarning=((t,...r)=>{AA(r[0],r[1])!==$A&&e(t,...r)})};import{Command as cI,InvalidArgumentError as lI}from"commander";import{resolve as dI}from"node:path";import Fe from"node:process";import{cd as uI}from"zx";import Ly from"node:process";import{$ as OA}from"zx";var iu=async()=>{let e=await H(),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 mo(e.userProject,r),o=r?fo(n):"";u.info(`Project name: ${e.projectName}
436
+ `));let o={worktrees:r,count:r.length,features:t};return{content:k(JSON.stringify(o,null,2)),structuredContent:o}},xA=async e=>{let[t,r]=await Promise.all([F(),se()]),n=new Map(t.map(o=>[o.branch,o.type]));return e.flatMap(o=>{let s=G(o);if(!s)return[];let i=X(s),a=n.get(o)||"regular",c=r.get(re(s))||null;return[{version:i,type:a,description:c}]})},TA=e=>{let t=Math.max(...e.map(r=>r.version.length));return e.map(r=>{let n=co(r.version,r.type,t);return r.description?`${n} ${r.description}`:n})},tu=S({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:Wt.array(Wt.object({version:Wt.string().describe("Release version"),type:Wt.enum(["regular","hotfix"]).describe("Release type"),description:Wt.string().nullable().describe("Jira version description")})).describe("Release worktrees with details"),count:Wt.number().describe("Number of release worktrees"),features:Wt.array(Wt.string()).describe("Branches of feature worktrees (feature/<name>)")},handler:Yi});import{z as Be}from"zod";import CA from"node:fs/promises";import{$ as $A}from"zx";var Vy="remove this worktree",AA=2,OA=3,zi=async e=>{try{return await CA.realpath(e)}catch{return e}},br=(e,t)=>{throw new f(void 0,{operation:Vy,remediation:e,stderrExcerpt:t})},IA=e=>{if(e.startsWith("feature/"))return["--feature",e.slice(8)];let[t]=mt([e]);return xr(e)&&t?["--versions",t]:br("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`)},DA=async()=>{let e=await zi(await T()),t=await zi(await be(e));e===t&&br("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 Ke(t))await zi(o.path)===e&&(r=o.branch);if(!r)return br("check out a branch in this worktree first",`no branch is checked out at ${e}`);let n=await zi(`${t}${de}/${r}`);return n!==e&&br("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:IA(r)}},Wy=async e=>(await $A({quiet:!0})`git -C ${e} status --porcelain`).stdout.split(`
437
+ `).filter(r=>r.trim().length>0),NA=async e=>{let[t,r]=await Promise.all([Wy(e.worktreePath),Wy(e.mainRoot)]);t.length>0&&br("commit or stash your changes (`git stash -u`), then retry",`uncommitted changes: ${t.join(", ")}`),r.length>0&&br(`commit or stash the changes in the main checkout ${e.mainRoot}, then retry`,`the main checkout has uncommitted changes: ${r.join(", ")}`);let n=await St();n!=="ready"&&br(`run \`infra-kit worktrees remove ${Ae(e.targetArgs)}\` from the main checkout ${e.mainRoot}`,`--self hands the removal to an Orca terminal, and Orca is ${n}`)},_A=async e=>{let t=Ae(["infra-kit","worktrees","remove",...e.targetArgs,"--yes"]),r=`sleep ${AA}; ${t} && { sleep ${OA}; 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 $r?new f(n,{operation:Vy,remediation:`run \`infra-kit worktrees remove ${Ae(e.targetArgs)}\` from the main checkout ${e.mainRoot}`,stderrExcerpt:n.message}):n}},Uy=async e=>{let t=await DA();await NA(t),h.addOption("--self",!0),await B(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 _A(t);u.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 MA=e=>{if(ye()){if(e.all)throw new C({status:"refused",agentMode:N.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:N.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"})}},jA=(e,t)=>{let r=e.filter(n=>!t.includes(n));if(r.length>0)throw new f(void 0,{operation:"remove worktrees",remediation:`no active worktree for: ${r.join(", ")}. Run 'infra-kit worktrees list' to see current worktrees`,stderrExcerpt:`unmatched worktree target(s): ${r.join(", ")}`})},FA=async(e,t)=>{let r=await Ps(t.map(n=>`${e}/${n}`));if(r!==null)throw new C({status:"refused",reason:"orca_caller_inside_target",agentMode:N.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`})},LA=e=>e?e.split(",").map(t=>ve(me(t.trim()))):[],BA=e=>e?e.split(",").filter(t=>t.trim()!=="").map(Hi):[],WA=e=>{let t=e.filter(n=>n.startsWith("feature/")),r=e.filter(n=>!t.includes(n));r.length>0&&h.addOption("--versions",mt(r)),t.length>0&&h.addOption("--feature",t.map(n=>n.replace(/^feature\//,"")).join(","))},Xi=async e=>{let{confirmedCommand:t,all:r,versions:n,feature:o,self:s}=e;if(s){if(r||n||o)throw new f(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 Uy(t)}await Ee({operation:"remove worktrees"}),await M(),MA({all:r,versions:n,feature:o});try{let[i,a]=await Promise.all([fe("release"),fe("feature")]),c=[...i,...a];if(c.length===0){u.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 T(),d=`${l}${de}`,p=[];if(r)p=c;else if(n||o)p=[...LA(n),...BA(o)];else{h.setInteractive();let[y,R]=await Promise.all([se(),F()]),w=new Map(R.map(x=>[x.branch,x.type]));p=await Ot([...ie({branches:i,descriptions:y,types:w}),...a.map(x=>({value:x,label:x,type:"feature"}))],{required:!0})}jA(p,c);let m=p.length===c.length;m?h.addOption("--all",!0):WA(p),await FA(d,p),await B(t,"Are you sure you want to proceed with these worktree changes?"),t||h.addOption("--yes",!0);let g=await fr({branches:p,worktreeDir:d,projectRoot:l,pruneFolder:m});return await yr({projectRoot:l,worktreeDir:d,removedWorktrees:g.removed}),Ao(g),h.print(),Oo({result:g,operation:"remove worktrees"})}catch(i){throw Re(i)||i instanceof f?i:(u.error({error:i},"\u274C Error managing worktrees"),new f(i,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"}))}},ru=S({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:Be.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:Be.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:Be.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{removedWorktrees:Be.array(Be.string()).describe("List of removed git worktree branches"),failedWorktrees:Be.array(Be.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:Be.number().describe("Number of git worktrees removed"),handedOff:Be.object({branch:Be.string(),worktreePath:Be.string(),terminal:Be.string()}).optional().describe("--self only: the worktree whose removal now runs in an Orca tab of the main checkout")},handler:Xi});import{z as Qo}from"zod";var Zi=async e=>{let{confirmedCommand:t}=e;await Ee({operation:"sync worktrees"}),await M();try{let r=await fe("release"),n=await T(),o=`${n}${de}`,s=await Us();await B(t,"Are you sure you want to proceed with these worktree changes?"),t||h.addOption("--yes",!0);let{branchesToRemove:i}=VA({releasePRsList:s,currentWorktrees:r}),a=await fr({branches:i,worktreeDir:o,projectRoot:n});return await yr({projectRoot:n,worktreeDir:o,removedWorktrees:a.removed}),Ao(a),h.print(),Oo({result:a,operation:"sync worktrees"})}catch(r){throw Re(r)||r instanceof f?r:(u.error({error:r},"\u274C Error managing worktrees"),new f(r,{operation:"sync worktrees with remote",remediation:"ensure 'gh auth status' is ok and you can reach origin"}))}},VA=e=>{let{releasePRsList:t,currentWorktrees:r}=e;return{branchesToRemove:r.filter(s=>xr(s)).filter(s=>!t.includes(s))}},nu=S({name:"worktrees-sync",description:"Remove worktrees whose release PR is no longer open (stale cleanup). Only removes \u2014 never creates; use worktrees-add to create worktrees for new releases. The CLI confirmation is auto-skipped for MCP calls, so the caller is responsible for gating. A branch git refuses to remove is listed in failedWorktrees and the result carries isError; a leftover that git already unregistered and that holds only tool state (.omc/state, .omc/sessions, .DS_Store) is swept automatically.",inputSchema:{},outputSchema:{removedWorktrees:Qo.array(Qo.string()).describe("List of removed worktree branches"),failedWorktrees:Qo.array(Qo.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:Qo.number().describe("Number of worktrees removed during sync")},handler:Zi});var ou=[{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"}],dr=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["dev"],longRunning:!0},{cliName:"dev-status",menuGroup:"develop",mcpTool:Ec,mcpExposed:!0,mutating:!1,groupPath:["dev-status"]},{cliName:"e2e",menuGroup:"develop",mcpTool:Bl,mcpExposed:!1,mutating:!0,groupPath:["e2e"]},{cliName:"merge-dev",menuGroup:"release",mcpTool:Hl,mcpExposed:!0,mutating:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:dd,mcpExposed:!0,mutating:!1,groupPath:["release","list"]},{cliName:"release-create",menuGroup:"release",mcpTool:Pd,mcpExposed:!0,mutating:!0,groupPath:["release","create"]},{cliName:"release-edit",menuGroup:"release",mcpTool:xd,mcpExposed:!0,mutating:!0,groupPath:["release","edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:ad,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:ld,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:zl,mcpExposed:!1,mutating:!0,humanOnly:!0,groupPath:["release","deliver"]},{cliName:"release-remove",menuGroup:"release",mcpTool:Dd,mcpExposed:!0,mutating:!0,groupPath:["release","remove"]},{cliName:"local-deploy-all",menuGroup:null,mcpTool:wd,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-all"]},{cliName:"local-deploy-selected",menuGroup:null,mcpTool:kd,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-selected"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:eu,mcpExposed:!0,mutating:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:tu,mcpExposed:!0,mutating:!1,groupPath:["worktrees","list"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:ru,mcpExposed:!0,mutating:!0,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:nu,mcpExposed:!0,mutating:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:Ul,mcpExposed:!0,mutating:!1,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:ym,mcpExposed:!0,mutating:!1,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:Da,mcpExposed:!0,mutating:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:Vl,mcpExposed:!0,mutating:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:Jl,mcpExposed:!0,mutating:!1,groupPath:["env-token-list"]},{cliName:"config-get",menuGroup:"configuration",mcpTool:Sc,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:Yd,mcpExposed:!0,mutating:!1,groupPath:["vendor","check"]},{cliName:"vendor-config",menuGroup:"vendor",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["vendor","config"]},{cliName:"vendor-sync",menuGroup:"vendor",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["vendor","sync"]},{cliName:"setup",menuGroup:"setup",mcpTool:Bd,mcpExposed:!0,mutating:!0,groupPath:["setup"]},{cliName:"doctor",menuGroup:"setup",mcpTool:$l,mcpExposed:!0,mutating:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:kc,mcpExposed:!0,mutating:!1,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:zd,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 su=e=>dr.filter(t=>t.menuGroup===e),iu=e=>dr.some(t=>t.longRunning===!0&&t.groupPath.join(" ")===e);var UA=(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},Jy=e=>ou.flatMap(({key:t,label:r})=>su(t).flatMap(n=>{let o=UA(e,n.groupPath);return o?[{name:n.groupPath.join(" "),description:o.description(),group:r}]:[]}));import au from"node:process";var JA="MODULE_TYPELESS_PACKAGE_JSON",GA=(e,t)=>typeof e=="object"&&e!==null?e.code:t,Gy=!1,cu=()=>{if(Gy)return;Gy=!0;let e=au.emitWarning.bind(au);au.emitWarning=((t,...r)=>{GA(r[0],r[1])!==JA&&e(t,...r)})};import{Command as SI,InvalidArgumentError as PI}from"commander";import{resolve as EI}from"node:path";import We from"node:process";import{cd as xI}from"zx";import Ky from"node:process";import{$ as KA}from"zx";var lu=async()=>{let e=await H(),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 ho(e.userProject,r),o=r?yo(n):"";u.info(`Project name: ${e.projectName}
428
438
  `),u.info(`Config merge chain (later overrides earlier):
429
- `);for(let i of t){let a=i.exists?" [\u2713]":" [ ]",c=i.path===e.userProject&&o!==""?` ${o}`:"";u.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}},au=async()=>{let e=await H(),t=Ly.env.EDITOR||Ly.env.VISUAL||"vi",r=await Xr(e);r.createdConfig&&u.info(Zr(r)),u.info(`Opening ${v(e.userProject)} in ${t} (per-machine override \u2014 every key except "mcp")`),await OA({stdio:"inherit"})`${t} ${e.userProject}`,vt();let n={path:e.userProject,editor:t};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}};var cu=async({key:e,global:t})=>{js(e,"config-unset");let r=t?"global":"project",{file:n,previous:o,changed:s}=await Fs(r,e,a=>e in a?Object.fromEntries(Object.entries(a).filter(([c])=>c!==e)):null);u.info(s?`Removed ${e} from the ${Hn[r]} (${v(n)})`:`${e} is not set in the ${Hn[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}};var By="https://dashboard.doppler.com/workplace/projects",IA=(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}"): ${By}/${e}`],lu=async({env:e})=>{let r=!!(await Be())?.envs[e];await Qp(e);let n=await Kt(),o=await kt();r?u.info(`Removed the "${e}" service token from ${v(o)}.`):u.info(`No "${e}" service token was stored in ${v(o)} \u2014 nothing to remove.`);for(let i of IA(n,e))u.warn(i);let s={env:e,removed:r,storePath:o,revokeUrl:`${By}/${n}`};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}};import DA from"@inquirer/confirm";import NA from"@inquirer/input";import _A from"@inquirer/password";import MA from"@inquirer/select";import jA from"node:fs/promises";import nt from"node:process";import{$ as Xi}from"zx";var FA=async({stdin:e,fromEnv:t})=>{if(e)return{token:await Wy(),source:"stdin"};if(t){let n=nt.env[t];if(!n)throw new Error(`${t} is not set (or is empty) \u2014 nothing to store.`);return{token:n,source:"env"}}if(!nt.stdin.isTTY){let n=await Wy();if(n)return{token:n,source:"stdin"};if(!J())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 O(n=>_A({message:"Paste the Doppler service token (input is hidden)",mask:!0},n),{output:nt.stderr,whenHeadless:{refuse:"stdin"}})).trim(),source:"prompt"}},Wy=async()=>{let e=[];nt.stdin.setEncoding("utf8");for await(let t of nt.stdin)e.push(t);return e.join("").trim()},du="DOPPLER_CONFIG",LA=3e4,BA=async(e,t,r)=>{let n=Xi.quiet;Xi.quiet=!0;let o;try{o=(await Xi({env:In(e)})`doppler secrets download --no-file --format json --project ${t} --config ${r}`.timeout(LA)).stdout}catch(s){throw WA(s,r)}finally{Xi.quiet=n}return Aa(o)},WA=(e,t)=>{let r=yp(e)??(e instanceof Error?e.message:String(e));if(zp(r)!=="auth")return e instanceof Error?e:new Error(String(e));let n=Xp(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(`
430
- `))},VA=e=>[`Could not verify this token's scope: the Doppler payload for "${e}" carries no ${du}.`,"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(`
431
- `),Uy=async(e,t,r,n)=>{let o=await BA(e,t,r);$a(o,r);let s=o.some(([i])=>i===du);if(!s&&!n)throw new Error(VA(r));return s},Vy="\0new-env",UA=async()=>{if(J()||!nt.stdin.isTTY)throw new x({status:"argument_required",argument:"env",agentMode:N.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([dm(),Be()]),r=Math.max(0,...e.map(({env:s})=>s.length));h.setInteractive();let n=await O(s=>MA({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:Vy}]},s),{output:nt.stderr,whenHeadless:"refuse"});return n!==Vy?n:(await O(s=>NA({message:"Doppler config name",validate:i=>/^\S+$/.test(i.trim())||"Enter a config name without spaces"},s),{output:nt.stderr,whenHeadless:"refuse"})).trim()},JA=async(e,t,r)=>O(n=>DA({message:`Replace the "${e}" token ${we(t)} with ${we(r)}?`,default:!0},n),{output:nt.stderr,whenHeadless:"refuse"}),GA=(e,t,r,n)=>{switch(t){case"stored":return`Stored the "${e}" service token (${we(r)})`;case"replaced":return`Replaced the "${e}" service token ${we(n??"")} \u2192 ${we(r)}`;case"unchanged":return`The "${e}" service token is already ${we(r)} \u2014 nothing to write`;case"kept":return`Kept the existing "${e}" service token ${we(n??"")} \u2014 nothing was written`;default:return Ae(t)}},uu=async({env:e,stdin:t,fromEnv:r,force:n})=>{let o=await Kt(),s=e??await UA(),{token:i,source:a}=await FA({stdin:t,fromEnv:r});if(!i)throw new Error("No token provided \u2014 nothing was written.");let c=await Uy(i,o,s,n),l=(await Be())?.envs[s],d;l===i?d="unchanged":l!==void 0&&a==="prompt"&&!await JA(s,l,i)?d="kept":(await xa({[s]:i}),d=l===void 0?"stored":"replaced");let p=await kt();u.info(`${GA(s,d,i,l)} in ${v(p)} (mode 0600).`),c||u.warn(`Scope was NOT verified (no ${du} in the payload) \u2014 accepted because --force was given.`);let m={env:s,status:d,source:a,redactedToken:we(i),previousRedactedToken:l===void 0?null:we(l),storePath:p,scopeVerified:c};return h.print(),{content:k(JSON.stringify(m,null,2)),structuredContent:m}},KA=e=>/^(["']).*\1$/.test(e)?e.slice(1,-1):e,Jy=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?KA(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},HA=e=>(e instanceof Error?e.message:String(e)).split(`
432
- `)[0]??"",qA=(e,t)=>e===void 0?"stored":e===t?"unchanged":"replaced",YA=async(e,t,r,n)=>{let o=we(e.token);try{let s=await Uy(e.token,t,e.env,n);return{env:e.env,status:qA(r,e.token),redactedToken:o,scopeVerified:s}}catch(s){return{env:e.env,status:"failed",redactedToken:o,scopeVerified:!1,error:HA(s)}}},pu=async({fromFile:e,force:t})=>{let r=await Kt(),n=Jy(await jA.readFile(e,"utf8")),o=await Be(),s=await Promise.all(n.map(p=>YA(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 xa(i);let a=await kt(),c=Math.max(...s.map(({env:p})=>p.length));u.info(`Token import from ${v(e)} \u2192 ${v(a)}:`);for(let p of s){let m=p.error?` ${p.error}`:"";u.info(` ${p.env.padEnd(c)} ${p.status.padEnd(9)} ${p.redactedToken}${m}`)}u.warn(`${v(e)} still holds live tokens in plain text \u2014 delete it.`);let l=s.filter(p=>p.status==="failed").length;l>0&&(nt.exitCode=1);let d={storePath:a,rows:s,failedCount:l};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}};var mu=async(e,t,r=!0)=>{let{from:n,version:o,env:s,services:i,skipTerraform:a,yes:c,dryRun:l,printEnv:d}=e,p=await rd(n);if(r&&h.addOption("--from",p),td(p,{"--version":o,"--skip-terraform":a,"--dry-run":l,"--print-env":d}),p==="local")throw new f(void 0,{operation:"deploy --from local",remediation:"use --from ci to dispatch the release workflow",stderrExcerpt:"local deploys are disabled for now \u2014 deploys run in CI only"});return t==="all"?Si({version:o,env:s,skipTerraform:a,confirmedCommand:c}):Pi({version:o,env:s,services:i,skipTerraform:a,confirmedCommand:c})},fu=async e=>mu(e,"all"),gu=async e=>mu(e,"selected"),Zi=async(e,t)=>{let r=`release deploy-${t} --from local`;return u.warn(`\`local deploy-${t}\` is deprecated and will be removed \u2014 use \`${r}\` instead.`),mu({...e,from:"local"},t,!1)};import{VENDOR_CONFIG_FILE as Ky}from"@slip-stream-kit/config/internal";import hu from"node:fs/promises";import hn from"node:path";import Gy from"node:process";import{pathToFileURL as zA}from"node:url";var Hy="~/projects",yu=async(e={})=>{if(e.init){await ZA(e.cwd);return}await XA()},XA=async()=>{let e=en(),t=await Z(e);if(u.info(`Factory config: ${v(e)} ${t?"[\u2713]":"[ ]"}`),!t){u.info("\nNot found \u2014 run `infra-kit vendor config --init` to scaffold it."),Gy.exitCode=1;return}let{workspaceDir:r,source:n,targets:o}=await ri(),s=tn(r),i=await Z(s),a=hn.join(s,n),c=await Z(a);u.info(`workspaceDir: ${r} (resolved: ${s}) ${i?"[\u2713 exists]":"[ ] not found"}`),u.info(`Source: ${c?"[\u2713]":"[ ]"} ${n} ${v(a)}${c?"":" (not found \u2014 clone it)"}`),u.info("Targets:");let l=i&&c;for(let d of o){let p=hn.join(s,d),m=await Z(p);m||(l=!1);let g=m?"[\u2713]":"[ ]",y=m?"":" (not found \u2014 clone or remove)";u.info(` ${g} ${d} ${v(p)}${y}`)}l||(Gy.exitCode=1)},ZA=async e=>{let t=en();if(await Z(t)){u.info(`Factory config already exists at ${v(t)} \u2014 leaving it untouched.`);return}let r=e??await T(),n=await QA(r);await hu.mkdir(hn.dirname(t),{recursive:!0}),await hu.writeFile(t,eO(hn.basename(r),n),"utf-8"),u.info(`\u2713 Created ${v(t)}`),n.length>0&&u.info(` Seeded ${n.length} target(s) from the source ${Ky}.`),u.info(` Edit \`workspaceDir\` (placeholder: ${Hy}) to point at where your repos live.`),u.info(` \`source\` is seeded with ${hn.basename(r)} (this repo); change it if the source is another repo.`),n.length===0&&u.info(" Add at least one repo name to `targets` before running vendor sync/manifest/diff.")},QA=async e=>{try{let t=hn.join(e,Ky),r=await hu.stat(t),s=(await import(`${zA(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[]},eO=(e,t)=>`${JSON.stringify({workspaceDir:Hy,source:e,targets:t},null,2)}
433
- `;import{existsSync as XO}from"node:fs";import ZO from"node:fs/promises";import hv from"node:path";import yv from"node:process";import{z as QO}from"zod";import{chmodSync as cO,copyFileSync as lO,lstatSync as dO,mkdirSync as nv,readdirSync as uO,readlinkSync as pO,rmdirSync as ov,symlinkSync as mO,unlinkSync as fO,writeFileSync as gO}from"node:fs";import ke from"node:path";import{lstatSync as tO,readlinkSync as qy}from"node:fs";import rO from"node:path";var nO=new Set(["ENOENT","ENOTDIR"]),Qi=e=>{let t;try{t=tO(e)}catch(r){if(nO.has(r.code??""))return null;throw r}return t.isSymbolicLink()?{kind:"link",text:qy(e)}:t.isFile()?{kind:"file",executable:(t.mode&64)!==0,sha:wr(e)}:{kind:"other"}},Yy=(e,t)=>{let r=rO.join(e,t.path),n=t.mode==="120000"?{kind:"link",text:qy(r)}:{kind:"file",executable:t.mode==="100755",sha:wr(r)};return{...t,fingerprint:n}},zy=(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 oO}from"zx";var ee=async(e,t,r={})=>{let{input:n,allowFailure:o=!1}=r,s=await oO({cwd:e,quiet:!0,input:n,nothrow:o})`git ${t}`;return s.exitCode===0?s.stdout:""},ea=e=>e.slice(0,7),Bt=e=>e.split("\0").filter(t=>t.length>0);import sO from"node:path";var vu=`${Q}/`,Wt=`${Q}/README.md`,zo=`${Q}/${je}`,Zy=e=>e.startsWith(vu),Xy=e=>{let t=sO.posix.normalize(e);return t.endsWith("/")?t.slice(0,-1):t},Qy=e=>{let t=Xy(e.path),r=e.target===void 0?t:Xy(e.target);return{path:t,target:r,vendored:Zy(r)}},ev=e=>e.copy.map(Qy),Xo=(e,t)=>t.length===0?!1:e.split("/").some(r=>t.includes(r)),Zo=(e,t)=>e.filter(r=>!Xo(r.path,t)),ta=(e,t)=>e===t.path?t.target:`${t.target}${e.slice(t.path.length)}`,yn=e=>[...new Set(e)].sort(),tv=e=>e.startsWith(vu)?e.slice(vu.length):null;var ra=e=>`# vendor/ \u2014 mirrored from ${e}
439
+ `);for(let i of t){let a=i.exists?" [\u2713]":" [ ]",c=i.path===e.userProject&&o!==""?` ${o}`:"";u.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}},du=async()=>{let e=await H(),t=Ky.env.EDITOR||Ky.env.VISUAL||"vi",r=await en(e);r.createdConfig&&u.info(tn(r)),u.info(`Opening ${v(e.userProject)} in ${t} (per-machine override \u2014 every key except "mcp")`),await KA({stdio:"inherit"})`${t} ${e.userProject}`,kt();let n={path:e.userProject,editor:t};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}};var uu=async({key:e,global:t})=>{Ls(e,"config-unset");let r=t?"global":"project",{file:n,previous:o,changed:s}=await Bs(r,e,a=>e in a?Object.fromEntries(Object.entries(a).filter(([c])=>c!==e)):null);u.info(s?`Removed ${e} from the ${zn[r]} (${v(n)})`:`${e} is not set in the ${zn[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}};var Hy="https://dashboard.doppler.com/workplace/projects",HA=(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}"): ${Hy}/${e}`],pu=async({env:e})=>{let r=!!(await Ve())?.envs[e];await rm(e);let n=await qt(),o=await Rt();r?u.info(`Removed the "${e}" service token from ${v(o)}.`):u.info(`No "${e}" service token was stored in ${v(o)} \u2014 nothing to remove.`);for(let i of HA(n,e))u.warn(i);let s={env:e,removed:r,storePath:o,revokeUrl:`${Hy}/${n}`};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}};import qA from"@inquirer/confirm";import YA from"@inquirer/input";import zA from"@inquirer/password";import XA from"@inquirer/select";import ZA from"node:fs/promises";import it from"node:process";import{$ as Qi}from"zx";var QA=async({stdin:e,fromEnv:t})=>{if(e)return{token:await qy(),source:"stdin"};if(t){let n=it.env[t];if(!n)throw new Error(`${t} is not set (or is empty) \u2014 nothing to store.`);return{token:n,source:"env"}}if(!it.stdin.isTTY){let n=await qy();if(n)return{token:n,source:"stdin"};if(!J())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 O(n=>zA({message:"Paste the Doppler service token (input is hidden)",mask:!0},n),{output:it.stderr,whenHeadless:{refuse:"stdin"}})).trim(),source:"prompt"}},qy=async()=>{let e=[];it.stdin.setEncoding("utf8");for await(let t of it.stdin)e.push(t);return e.join("").trim()},mu="DOPPLER_CONFIG",eO=3e4,tO=async(e,t,r)=>{let n=Qi.quiet;Qi.quiet=!0;let o;try{o=(await Qi({env:_n(e)})`doppler secrets download --no-file --format json --project ${t} --config ${r}`.timeout(eO)).stdout}catch(s){throw rO(s,r)}finally{Qi.quiet=n}return Ia(o)},rO=(e,t)=>{let r=kp(e)??(e instanceof Error?e.message:String(e));if(Qp(r)!=="auth")return e instanceof Error?e:new Error(String(e));let n=em(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(`
440
+ `))},nO=e=>[`Could not verify this token's scope: the Doppler payload for "${e}" carries no ${mu}.`,"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(`
441
+ `),zy=async(e,t,r,n)=>{let o=await tO(e,t,r);Oa(o,r);let s=o.some(([i])=>i===mu);if(!s&&!n)throw new Error(nO(r));return s},Yy="\0new-env",oO=async()=>{if(J()||!it.stdin.isTTY)throw new C({status:"argument_required",argument:"env",agentMode:N.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([fm(),Ve()]),r=Math.max(0,...e.map(({env:s})=>s.length));h.setInteractive();let n=await O(s=>XA({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:Yy}]},s),{output:it.stderr,whenHeadless:"refuse"});return n!==Yy?n:(await O(s=>YA({message:"Doppler config name",validate:i=>/^\S+$/.test(i.trim())||"Enter a config name without spaces"},s),{output:it.stderr,whenHeadless:"refuse"})).trim()},sO=async(e,t,r)=>O(n=>qA({message:`Replace the "${e}" token ${we(t)} with ${we(r)}?`,default:!0},n),{output:it.stderr,whenHeadless:"refuse"}),iO=(e,t,r,n)=>{switch(t){case"stored":return`Stored the "${e}" service token (${we(r)})`;case"replaced":return`Replaced the "${e}" service token ${we(n??"")} \u2192 ${we(r)}`;case"unchanged":return`The "${e}" service token is already ${we(r)} \u2014 nothing to write`;case"kept":return`Kept the existing "${e}" service token ${we(n??"")} \u2014 nothing was written`;default:return Ie(t)}},fu=async({env:e,stdin:t,fromEnv:r,force:n})=>{let o=await qt(),s=e??await oO(),{token:i,source:a}=await QA({stdin:t,fromEnv:r});if(!i)throw new Error("No token provided \u2014 nothing was written.");let c=await zy(i,o,s,n),l=(await Ve())?.envs[s],d;l===i?d="unchanged":l!==void 0&&a==="prompt"&&!await sO(s,l,i)?d="kept":(await Ca({[s]:i}),d=l===void 0?"stored":"replaced");let p=await Rt();u.info(`${iO(s,d,i,l)} in ${v(p)} (mode 0600).`),c||u.warn(`Scope was NOT verified (no ${mu} in the payload) \u2014 accepted because --force was given.`);let m={env:s,status:d,source:a,redactedToken:we(i),previousRedactedToken:l===void 0?null:we(l),storePath:p,scopeVerified:c};return h.print(),{content:k(JSON.stringify(m,null,2)),structuredContent:m}},aO=e=>/^(["']).*\1$/.test(e)?e.slice(1,-1):e,Xy=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?aO(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},cO=e=>(e instanceof Error?e.message:String(e)).split(`
442
+ `)[0]??"",lO=(e,t)=>e===void 0?"stored":e===t?"unchanged":"replaced",dO=async(e,t,r,n)=>{let o=we(e.token);try{let s=await zy(e.token,t,e.env,n);return{env:e.env,status:lO(r,e.token),redactedToken:o,scopeVerified:s}}catch(s){return{env:e.env,status:"failed",redactedToken:o,scopeVerified:!1,error:cO(s)}}},gu=async({fromFile:e,force:t})=>{let r=await qt(),n=Xy(await ZA.readFile(e,"utf8")),o=await Ve(),s=await Promise.all(n.map(p=>dO(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 Ca(i);let a=await Rt(),c=Math.max(...s.map(({env:p})=>p.length));u.info(`Token import from ${v(e)} \u2192 ${v(a)}:`);for(let p of s){let m=p.error?` ${p.error}`:"";u.info(` ${p.env.padEnd(c)} ${p.status.padEnd(9)} ${p.redactedToken}${m}`)}u.warn(`${v(e)} still holds live tokens in plain text \u2014 delete it.`);let l=s.filter(p=>p.status==="failed").length;l>0&&(it.exitCode=1);let d={storePath:a,rows:s,failedCount:l};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}};var hu=async(e,t,r=!0)=>{let{from:n,version:o,env:s,services:i,skipTerraform:a,yes:c,dryRun:l,printEnv:d}=e,p=await sd(n);if(r&&h.addOption("--from",p),od(p,{"--version":o,"--skip-terraform":a,"--dry-run":l,"--print-env":d}),p==="local")throw new f(void 0,{operation:"deploy --from local",remediation:"use --from ci to dispatch the release workflow",stderrExcerpt:"local deploys are disabled for now \u2014 deploys run in CI only"});return t==="all"?Pi({version:o,env:s,skipTerraform:a,confirmedCommand:c}):Ei({version:o,env:s,services:i,skipTerraform:a,confirmedCommand:c})},yu=async e=>hu(e,"all"),vu=async e=>hu(e,"selected"),ea=async(e,t)=>{let r=`release deploy-${t} --from local`;return u.warn(`\`local deploy-${t}\` is deprecated and will be removed \u2014 use \`${r}\` instead.`),hu({...e,from:"local"},t,!1)};import{VENDOR_CONFIG_FILE as Qy}from"@slip-stream-kit/config/internal";import wu from"node:fs/promises";import wn from"node:path";import Zy from"node:process";import{pathToFileURL as uO}from"node:url";var ev="~/projects",ku=async(e={})=>{if(e.init){await mO(e.cwd);return}await pO()},pO=async()=>{let e=nn(),t=await Z(e);if(u.info(`Factory config: ${v(e)} ${t?"[\u2713]":"[ ]"}`),!t){u.info("\nNot found \u2014 run `infra-kit vendor config --init` to scaffold it."),Zy.exitCode=1;return}let{workspaceDir:r,source:n,targets:o}=await oi(),s=on(r),i=await Z(s),a=wn.join(s,n),c=await Z(a);u.info(`workspaceDir: ${r} (resolved: ${s}) ${i?"[\u2713 exists]":"[ ] not found"}`),u.info(`Source: ${c?"[\u2713]":"[ ]"} ${n} ${v(a)}${c?"":" (not found \u2014 clone it)"}`),u.info("Targets:");let l=i&&c;for(let d of o){let p=wn.join(s,d),m=await Z(p);m||(l=!1);let g=m?"[\u2713]":"[ ]",y=m?"":" (not found \u2014 clone or remove)";u.info(` ${g} ${d} ${v(p)}${y}`)}l||(Zy.exitCode=1)},mO=async e=>{let t=nn();if(await Z(t)){u.info(`Factory config already exists at ${v(t)} \u2014 leaving it untouched.`);return}let r=e??await T(),n=await fO(r);await wu.mkdir(wn.dirname(t),{recursive:!0}),await wu.writeFile(t,gO(wn.basename(r),n),"utf-8"),u.info(`\u2713 Created ${v(t)}`),n.length>0&&u.info(` Seeded ${n.length} target(s) from the source ${Qy}.`),u.info(` Edit \`workspaceDir\` (placeholder: ${ev}) to point at where your repos live.`),u.info(` \`source\` is seeded with ${wn.basename(r)} (this repo); change it if the source is another repo.`),n.length===0&&u.info(" Add at least one repo name to `targets` before running vendor sync/manifest/diff.")},fO=async e=>{try{let t=wn.join(e,Qy),r=await wu.stat(t),s=(await import(`${uO(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[]},gO=(e,t)=>`${JSON.stringify({workspaceDir:ev,source:e,targets:t},null,2)}
443
+ `;import{existsSync as pI}from"node:fs";import mI from"node:fs/promises";import Sv from"node:path";import Pv from"node:process";import{z as fI}from"zod";import{chmodSync as SO,copyFileSync as PO,lstatSync as EO,mkdirSync as dv,readdirSync as xO,readlinkSync as TO,rmdirSync as uv,symlinkSync as CO,unlinkSync as $O,writeFileSync as AO}from"node:fs";import ke from"node:path";import{lstatSync as hO,readlinkSync as tv}from"node:fs";import yO from"node:path";var vO=new Set(["ENOENT","ENOTDIR"]),ta=e=>{let t;try{t=hO(e)}catch(r){if(vO.has(r.code??""))return null;throw r}return t.isSymbolicLink()?{kind:"link",text:tv(e)}:t.isFile()?{kind:"file",executable:(t.mode&64)!==0,sha:kr(e)}:{kind:"other"}},rv=(e,t)=>{let r=yO.join(e,t.path),n=t.mode==="120000"?{kind:"link",text:tv(r)}:{kind:"file",executable:t.mode==="100755",sha:kr(r)};return{...t,fingerprint:n}},nv=(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 wO}from"zx";var ee=async(e,t,r={})=>{let{input:n,allowFailure:o=!1}=r,s=await wO({cwd:e,quiet:!0,input:n,nothrow:o})`git ${t}`;return s.exitCode===0?s.stdout:""},ra=e=>e.slice(0,7),Vt=e=>e.split("\0").filter(t=>t.length>0);import kO from"node:path";var bu=`${Q}/`,Ut=`${Q}/README.md`,es=`${Q}/${Le}`,sv=e=>e.startsWith(bu),ov=e=>{let t=kO.posix.normalize(e);return t.endsWith("/")?t.slice(0,-1):t},iv=e=>{let t=ov(e.path),r=e.target===void 0?t:ov(e.target);return{path:t,target:r,vendored:sv(r)}},av=e=>e.copy.map(iv),ts=(e,t)=>t.length===0?!1:e.split("/").some(r=>t.includes(r)),rs=(e,t)=>e.filter(r=>!ts(r.path,t)),na=(e,t)=>e===t.path?t.target:`${t.target}${e.slice(t.path.length)}`,kn=e=>[...new Set(e)].sort(),cv=e=>e.startsWith(bu)?e.slice(bu.length):null;var oa=e=>`# vendor/ \u2014 mirrored from ${e}
434
444
 
435
445
  **DO NOT EDIT files in this folder here.**
436
446
 
@@ -441,19 +451,19 @@ fail \`ik vendor check\` in CI.
441
451
  To change a vendored package, edit it in \`${e}\` and re-run the sync there.
442
452
 
443
453
  See \`.sync-manifest.json\` for the source commit and per-file checksums.
444
- `;var iO=new Set(["100644","100755","120000"]),aO=(e,t)=>{let r=new Map;for(let n of Bt(e)){let o=n.indexOf(" "),s=n.slice(0,n.indexOf(" ")),i=n.slice(o+1);o<0||!iO.has(s)||Xo(i,t)||r.set(i,{path:i,mode:s})}return[...r.values()]},wu=async(e,t,r)=>{let n=await ee(e,["--literal-pathspecs","ls-files","-z","-s","--",t]);return aO(n,r)},rv=async e=>Bt(await ee(e,["--literal-pathspecs","ls-files","-z","--",Q]));var vn=e=>["git","-C",e.root,"--literal-pathspecs","checkout","HEAD","--",...e.recoveryPaths],sv=e=>{let t=Qi(e);t!==null&&(t.kind==="other"?ov(e):fO(e))},hO=(e,t,r)=>{let n=ke.join(e,r.source),o=ke.join(t,r.target);if(nv(ke.dirname(o),{recursive:!0}),sv(o),r.mode==="120000"){mO(pO(n),o);return}lO(n,o),cO(o,r.mode==="100755"?493:420)},yO=async(e,t)=>{let r=new Set;for(let n of Bt(await ee(e,["ls-files","-z"]))){if(t.has(n))continue;let o=ke.posix.dirname(n);for(;o!==".";)r.add(o),o=ke.posix.dirname(o)}return r},vO=async(e,t)=>{if(t.length===0)return;let r=await yO(e,new Set(t)),n=[...new Set(t.map(o=>ke.dirname(ke.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)&&!(!dO(s,{throwIfNoEntry:!1})?.isDirectory()||uO(s).length>0||r.has(ke.relative(e,s).split(ke.sep).join("/")));)ov(s),s=ke.dirname(s)}},iv=(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,Wt,...s].map(tv).filter(a=>a!==null&&!Bi(a));return yn(i)},av=async(e,t,r,n)=>{let o=ke.join(e,Q);nv(o,{recursive:!0}),gO(ke.join(e,Wt),ra(t.name));let s=iv(r,await rv(e),n);Vd(o,{source:t.name,commit:t.headSha},s)},ku=async({source:e,plan:t,onBeforeFirstWrite:r})=>{if(t.status!=="changed")return{touched:[],manifestWritten:!1};r?.(vn(t));let n=ke.resolve(t.root),o=t.entries.flatMap(a=>a.deletes);for(let a of o)sv(ke.join(n,a));await vO(n,o);let s=t.entries.flatMap(a=>a.writes);for(let a of s)hO(e.root,n,a);let i=s.map(a=>a.target);return t.writeVendorMeta?(await av(n,e,t.entries,o),{touched:yn([...o,...i,Wt,zo]),manifestWritten:!0}):{touched:yn([...o,...i]),manifestWritten:!1}},bu=async(e,t)=>(await av(e,t,[],[]),[Wt,zo]);var Ru=(e,t)=>`[ROOT] vendor: sync from ${e}@${ea(t)}`,wO=e=>{let{stdout:t,stderr:r}=e;return[t,r].filter(o=>typeof o=="string"&&o.trim().length>0).join(`
445
- `).trim()||String(e)},Su=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 ee(e,["--literal-pathspecs","add","-A",...o],{input:n}),await ee(e,["--literal-pathspecs","commit","--only","-m",r,...o],{input:n}),{ok:!0}}catch(s){return{ok:!1,output:wO(s)}}};var kO=20,bO=20,cv=(e,t)=>e.length<=t?[...e]:[...e.slice(0,t),`\u2026and ${e.length-t} more`],lv=(e,t,r)=>{let{entry:n}=e,o=new Set(t.tracked),s=[],i=[];for(let d of Zo(e.files,r)){let p=ta(d.path,n);if(s.push(p),zy(d.fingerprint,t.onDisk[p]??null))continue;let m=o.has(p)?"modified":"added";i.push({source:d.path,target:p,mode:d.mode,change:m})}let a=new Set(s),c=Zo(t.tracked.map(d=>({path:d})),r).map(d=>d.path).filter(d=>!a.has(d)),l=i.filter(d=>d.change==="added").length;return{...n,targetPaths:s,writes:i,deletes:c,counts:{added:l,modified:i.length-l,removed:c.length}}},Qo=(e,t,r,n=[])=>({name:e.name,root:e.root,status:t,message:r,notes:n,warnings:[],entries:[],writeVendorMeta:!1,recoveryPaths:[]}),Pu=e=>e.entries.map(t=>t.entry.target),RO=(e,t,r)=>{let n=["git","-C",t.root,"--literal-pathspecs","status","--",...Pu(e)];return Qo(t,"fail",`blocked: ${r.length} uncommitted path(s) under synced paths`,[...cv(r,kO),mt(n)])},SO=(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=ea(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}`,...cv(e.lines,bO)],warnings:[]}},PO=e=>{let{added:t,modified:r,removed:n}=e.counts;return t+r+n===0?null:`${e.target}: ${t} added, ${r} modified, ${n} removed`},EO=e=>{let t=r=>e.reduce((n,o)=>n+o.counts[r],0);return`${t("added")} added, ${t("modified")} modified, ${t("removed")} removed`},xO=(e,t,r)=>{let n=e.flatMap(o=>[...o.writes.filter(i=>i.change==="modified").map(i=>i.target),...o.deletes]);return yn([...n,...r?t.headVendorMeta:[]])},TO=(e,t)=>{if(t.dirty.length>0)return RO(e,t,t.dirty);let r=e.entries.map((d,p)=>{let m=t.entries[p]??{target:d.entry.target,tracked:[],onDisk:{}};return lv(d,m,e.exclude)}),n=r.some(d=>d.vendored),o=r.some(d=>d.writes.length+d.deletes.length>0),s=n&&(!t.readmeCurrent||!t.manifestPresent),i={...Qo(t,"ok","up to date"),branch:t.branch,entries:r,writeVendorMeta:n};if(!o&&!s)return i;let a=SO(t.changelog,e.name),c=t.manifestSource!==null&&t.manifestSource!==e.name?[`vendor/ was last synced from ${t.manifestSource}, not ${e.name}: this sync replaces it`]:[],l=r.map(PO).filter(d=>d!==null);return{...i,status:"changed",message:`${EO(r)} on ${t.branch}`,notes:[...l,...s?["vendor/README.md and manifest rewritten"]:[],...a.notes],warnings:[...c,...a.warnings],recoveryPaths:xO(r,t,n)}},na=(e,t)=>{switch(t.kind){case"missing":return Qo(t,"skipped",`not checked out at ${t.root}`);case"source":return Qo(t,"skipped","this is the source repo");case"not-git":return Qo(t,"fail",`not a git repo: ${t.reason}`);case"repo":return TO(e,t)}};import{existsSync as CO,readFileSync as $O,realpathSync as oa}from"node:fs";import sa from"node:path";var Eu=async(e,t)=>{let r=t.exclude??[],n=(await ee(e,["rev-parse","HEAD"])).trim(),o=await Le(e),s=await Promise.all(ev(t).map(async i=>{let a=await wu(e,i.path,r);return{entry:i,files:a.map(c=>Yy(e,c))}}));return{root:e,selfRoots:[...new Set([oa(e),oa(o)])],name:sa.basename(o),headSha:n,entries:s,exclude:r}},ia=e=>{let t=Bt(e)[Symbol.iterator](),r=[];for(let n of t)r.push(n.slice(3)),/^[RC]|^.[RC]/u.test(n)&&t.next();return r},AO=async(e,t)=>{let r=await ee(t,["--literal-pathspecs","status","--porcelain","-z","--untracked-files=all","--",...Pu(e)]);return ia(r).filter(n=>!Xo(n,e.exclude))},OO=async(e,t)=>Promise.all(e.entries.map(async({entry:r,files:n})=>{let o=await wu(t,r.target,e.exclude),s={};for(let i of Zo(n,e.exclude)){let a=ta(i.path,r);s[a]=Qi(sa.join(t,a))}return{target:r.target,tracked:o.map(i=>i.path),onDisk:s}})),IO=async e=>{try{return Bt(await ee(e,["--literal-pathspecs","ls-tree","-z","--name-only","HEAD","--",Wt,zo]))}catch{return[]}},DO=e=>{try{let{commit:t,source:r}=Jo(sa.join(e,Q));return{commit:t,source:r}}catch{return null}},NO=async(e,t)=>{if(t===null)return{kind:"unknown-sha"};if(await $e(e.root,t)===null)return{kind:"unresolvable",sha:t};let r=e.entries.map(({entry:s})=>s.path),o=(await ee(e.root,["--literal-pathspecs","log","--oneline",`${t}..HEAD`,"--",...r])).split(`
446
- `).filter(s=>s.length>0);return{kind:"log",sha:t,lines:o}},_O=(e,t)=>{try{return $O(sa.join(e,Wt),"utf8")===ra(t)}catch{return!1}},MO=async e=>{try{return{toplevel:(await ee(e,["rev-parse","--show-toplevel"])).trim()}}catch(t){return{reason:String(t.stderr??t).trim().split(`
447
- `)[0]??"git rev-parse failed"}}},jO=async e=>{try{return(await ee(e,["rev-parse","--abbrev-ref","HEAD"])).trim()}catch{return"HEAD"}},aa=async(e,t)=>{if(!CO(t.root))return{...t,kind:"missing"};let r=oa(t.root);if(e.selfRoots.includes(r))return{...t,kind:"source"};let n=await MO(t.root);if("reason"in n)return{...t,kind:"not-git",reason:n.reason};if(oa(n.toplevel)!==r)return{...t,kind:"not-git",reason:`it sits inside the repo at ${n.toplevel}`};let o=DO(t.root),s=o?.commit??null,[i,a,c,l,d]=await Promise.all([jO(t.root),AO(e,t.root),OO(e,t.root),IO(t.root),NO(e,s)]);return{...t,kind:"repo",branch:i,dirty:a,entries:c,headVendorMeta:l,readmeCurrent:_O(t.root,e.name),manifestPresent:o!==null,manifestSource:o?.source??null,changelog:d}};var FO=20,LO=(e,t)=>!t.commit||e.status!=="changed"||e.branch===void 0?e.notes:[...e.notes,`--commit lands on ${e.branch}`],BO=(e,t)=>{let{plan:r}=e,n=t.manifestOnly?"manifest":"sync";if(e.error!==void 0)return{name:n,status:"fail",message:`apply failed: ${e.error}`,notes:["restore the tracked paths with:",mt(vn(r))]};let o=e.applied?`wrote ${r.message}`:r.message;return{name:n,status:r.status,message:o,notes:t.mode==="applied"?r.notes:LO(r,t)}},WO=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(`
448
- `).slice(0,FO)},VO=(e,t)=>{let r=e.plan.warnings.map(n=>({name:"changelog",status:"warn",message:n}));return{label:e.plan.name,rows:[BO(e,t),...r,...e.commit?[WO(e.commit)]:[]]}},UO={preview:"infra-kit vendor sync (preview)",check:"infra-kit vendor sync --check",applied:"infra-kit vendor sync"},xu=(e,t,r)=>{let n=r.mode==="preview"?["re-run with --yes from a real terminal to apply"]:[];return{title:UO[r.mode],sections:[{label:"source",rows:[...e]},...t.map(o=>VO(o,r))],hints:n}},dv=e=>e.sections.some(t=>t.rows.some(r=>r.status==="fail")),uv=(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 JO=20,Tu=async(e,t)=>(await ee(e,t,{allowFailure:!0})).trim(),GO=async e=>ia(await ee(e,["status","--porcelain","-z","--untracked-files=normal"])),KO=async e=>(await Tu(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"]},HO=async e=>{let[t,r]=await Promise.all([Tu(e,["symbolic-ref","--quiet","--short","refs/remotes/origin/HEAD"]),Tu(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}`}},pv=async e=>{let t=await GO(e);if(t.length>0){let n=t.slice(0,JO),o=t.length>n.length?`, and ${t.length-n.length} more`:"";throw new x({status:"refused",reason:"source-dirty",paths:t},1,{operation:`sync vendored files from ${e}`,stderrExcerpt:`the source has ${t.length} uncommitted path(s)`,remediation:`commit or stash them first, so every target records a commit holding exactly the files it got: ${n.join(", ")}${o}`})}let r=await Promise.all([KO(e),HO(e)]);return[{name:"working tree",status:"ok",message:"clean"},...r.filter(n=>n!==null)]};import qO from"node:path";var mv=(e,t)=>{let r=t.filter(s=>!e.targets.includes(s));if(r.length>0)throw new x({status:"refused",reason:"unknown-target",unknown:r,valid:e.targets},2,{operation:`sync vendored files to ${r.join(", ")}`,stderrExcerpt:`not a target in ~/.infra-kit/vendor.json: ${r.join(", ")}`,remediation:`name one of: ${e.targets.join(", ")}`});let n=tn(e.workspaceDir);return(t.length>0?e.targets.filter(s=>t.includes(s)):e.targets).map(s=>({name:s,root:qO.join(n,s)}))},YO="rewrite vendor/README.md and vendor/.sync-manifest.json from the tracked vendor/ files",zO=async(e,t)=>{let r=await aa(e,t),n=na(e,r);return r.kind!=="repo"||n.status==="fail"?n:{...n,status:"changed",message:`${YO} on ${r.branch}`,notes:[],warnings:[],branch:r.branch,entries:[],writeVendorMeta:!0,recoveryPaths:r.headVendorMeta}},fv=async(e,t,r)=>Promise.all(t.map(async n=>r?zO(e,n):na(e,await aa(e,n))));var vv="sync vendored files",eI=e=>{let t=hv.join(tn(e.workspaceDir),e.source);if(XO(t))return t;throw new x({status:"refused",reason:"source-missing",source:t},1,{operation:vv,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'})},Cu=(e,t)=>new x({status:"refused",reason:"not-a-vendor-source"},1,{operation:vv,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`}),tI=async e=>{let t=hv.join(e,"infra-kit.json"),r;try{r=JSON.parse(await ZO.readFile(t,"utf8"))}catch(s){throw Cu(t,`is unreadable: ${s instanceof Error?s.message:String(s)}`)}let n=r?.vendorSource;if(n==null)throw Cu(t,"has no vendorSource block");let o=Dp.safeParse(n);if(!o.success)throw Cu(t,`has an invalid vendorSource: ${QO.prettifyError(o.error)}`);return o.data},gv=(e,t)=>{yv.stderr.write(`${e.name}: if this run dies, restore the tracked paths with:
449
- ${mt(t)}
450
- `)},rI=async(e,t,r)=>r?(gv(t,vn(t)),bu(t.root,e)):(await ku({source:e,plan:t,onBeforeFirstWrite:o=>{gv(t,o)}})).touched,nI=async(e,t,r)=>{if(t.status!=="changed")return{plan:t,applied:!1};let n;try{n=await rI(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 Su(t.root,n,Ru(e.name,e.headSha));return{plan:t,applied:!0,commit:o}},oI=async(e,t,r)=>{let n=[];for(let o of t)n.push(await nI(e,o,r));return n},wv=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})),$u=({mode:e,report:t,outcomes:r,source:n,print:o})=>{o&&ze(t);let s=r.map(a=>a.plan);return{structuredContent:{mode:e,source:{root:n.root,name:n.name,headSha:n.headSha},targets:wv(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:dv(t),report:t.sections}}},sI=async e=>{let t=await ri(),r=eI(t),n=await pv(r),o=await tI(r),s=mv(t,e.targets??[]),i=await Eu(r,o),a=await fv(i,s,!!e.manifestOnly);return{source:i,sourceRows:n,plans:a}},Au=async(e={})=>{let{source:t,sourceRows:r,plans:n}=await sI(e),o=n.map(m=>({plan:m,applied:!1})),s={commit:e.commit,manifestOnly:e.manifestOnly},i=e.check?"check":"preview",a=xu(r,o,{...s,mode:i}),c=!n.some(m=>m.status==="changed");if(e.check||c)return $u({mode:i,report:a,outcomes:o,source:t,print:!0});let l=!e.confirmedCommand&&!J();if(l&&!yv.stdin.isTTY)return ze(a),$u({mode:"preview",report:a,outcomes:o,source:t,print:!1});l&&ze({...a,hints:[]}),await V(e.confirmedCommand,`Sync vendored files from ${t.name} into these targets?`,{plan:wv(n),throwOnDecline:!0});let d=await oI(t,n,e),p=xu(r,d,{...s,mode:"applied"});if(l){let m=d.filter(g=>g.applied).map(g=>g.plan.name);ze(uv(a,p,m))}return $u({mode:"applied",report:p,outcomes:d,source:t,print:!l})};var ca=(e,t=!0)=>({line:e,reproducible:t});import la from"node:fs";import iI from"node:os";import aI from"node:path";import Sv from"node:process";var da="INFRA_KIT_SESSION_REPORT",Ou=null,kv=!1,bv=[],Pv=(e=Sv.env)=>{kv||(Ou=e[da]??null,kv=!0,delete e[da])};var Ev=(e,t)=>{if(!Ou)return;let r=e.summary??(bv.length>0?[...bv]:void 0),n={...e,...r?{summary:r}:{}},o=t?.write??((s,i)=>{la.writeFileSync(s,i)});try{o(Ou,JSON.stringify(n))}catch{}},Rv=0,xv=e=>{let t=e?.tmpdir?.()??iI.tmpdir(),r=e?.pid??Sv.pid;return Rv+=1,aI.join(t,`infra-kit-session-${r}-${Rv}.json`)},Tv=(e,t)=>{if(!(t?.exists??(i=>la.existsSync(i)))(e))return null;let n=t?.read??(i=>la.readFileSync(i,"utf-8")),o=t?.unlink??(i=>la.unlinkSync(i)),s;try{s=n(e)}catch{return null}finally{try{o(e)}catch{}}try{return JSON.parse(s)}catch{return null}};var Iu=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(Iu)};var Du=e=>{e.options.some(r=>r.long==="--debug")||e.option("--debug","Raise the log level to debug (logs stay on stderr)"),e.commands.forEach(Du)};var pI=(e,t)=>[...t,e],Cv=(e,t)=>{if(!(typeof e>"u")){if(e===!0)return"workspace";if(e===!1)return"none";if(typeof e=="string"&&yr.includes(e))return e;throw new Error(`Invalid ${t} value "${String(e)}". Expected one of: ${yr.join(", ")}.`)}},mI=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 Of(()=>wi({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}));A(r),r.structuredContent.failedMerges>0&&(Fe.exitCode=1)}),$v=e=>(Fe.stdout.write(`${e.structuredContent.filePath}
451
- `),A(e)),fI=e=>e.description("List all release branches").action(async()=>{A(await Ei())}),gI=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".',pI,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let n=t.release.map(wl),o=n.length>0?n:void 0;A(await Ai({releases:o,confirmedCommand:t.yes}))}),hI=e=>{if(e==="")return e;try{return ar(e)}catch(t){throw t instanceof cn?new lI(t.message):t}},yI=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)',hI).option("-y, --yes","Skip confirmation prompt").action(async t=>{A(await Oi({version:t.version,description:t.description,releaseDate:t.releaseDate,confirmedCommand:t.yes}))}),Av=e=>e.option("-f, --from <where>",`Where the deploy runs: ${_t.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"),vI=e=>Av(e).description("Deploy every service to any environment, in CI or from this machine").action(async t=>{A(await fu({from:t.from,version:t.version,env:t.env,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),wI=e=>Av(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=>{A(await gu({from:t.from,version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),kI=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=>{A(await Ri({version:t.version,confirmedCommand:t.yes}))}),bI=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=>{A(await ji({version:t.version,moveIssuesTo:t.moveIssuesTo,skipJira:t.skipJira,confirmedCommand:t.yes}))}),RI=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{A(await zi({confirmedCommand:t.yes}))}),SI=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("-i, --ide [mode]","Editor mode for created worktrees: workspace (default) | none").option("--no-ide","Skip the editor (alias for --ide none)").option("-c, --cursor [mode]","Deprecated alias for --ide").option("--no-cursor","Deprecated alias for --no-ide").option("-g, --github-desktop","Open created worktrees in GitHub Desktop").option("--no-github-desktop","Skip GitHub Desktop prompt").option("--orca","Open created worktrees in Orca (pane layout from worktrees.orca.layout)").option("--no-orca","Skip the Orca prompt").action(async t=>{let r=Cv(t.ide,"--ide")??Cv(t.cursor,"--cursor");A(await Hi({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature,base:t.base,ide:r,githubDesktop:t.githubDesktop,orca:t.orca}))}),PI=e=>e.description("List all git worktrees with detailed information").action(async()=>{A(await qi())}),EI=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").action(async t=>{A(await Yi({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature}))}),xI=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=>{A(await yu({init:t.init}))}),TI=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await Ji();A(t),t.structuredContent.ok||(Fe.exitCode=1)}),CI=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 Au({targets:t,confirmedCommand:r.yes,check:r.check,commit:r.commit,manifestOnly:r.manifestOnly})}catch(a){if(!ot(a))throw a;u.info("Operation cancelled.");return}A(n);let{failed:o,changed:s,mode:i}=n.structuredContent;(o||i==="check"&&s)&&(Fe.exitCode=1)}),$I=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{A(await iu())}),AI=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{A(await au())}),OI=new Set(["version"]),ua=e=>{let t=[];for(let r=e;r&&r.parent;r=r.parent)t.unshift(r.name());return t.join(" ")},Nu=()=>{let e=new cI().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");mI(t.command("merge-dev")),fI(t.command("list")),gI(t.command("create")),yI(t.command("edit")),vI(t.command("deploy-all")),wI(t.command("deploy-selected")),kI(t.command("deliver")),bI(t.command("remove"));let r=e.command("worktrees").description("Git worktree management commands");SI(r.command("add")),PI(r.command("list")),EI(r.command("remove")),RI(r.command("sync"));let n=e.command("config").description("Manage infra-kit configuration files");$I(n.command("path")),AI(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. ide)").action(async a=>{A(await Ls({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, ide)").argument("<value>",`JSON value, or a bare string (e.g. cli-only, '[{"provider":"orca"}]')`).option("--global","Write ~/.infra-kit/infra-kit.json (every project on this machine) instead").action(async(a,c,l)=>{A(await kc({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)=>{A(await cu({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=>{A(await Zi({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=>{A(await Zi({env:a.env,services:a.service,yes:a.yes,dryRun:a.dryRun,printEnv:a.printEnv},"selected"))}),e.command("audit").description("Audit against infra-kit.config.ts rules (--all for every package, --root for the monorepo root)").option("-a, --all","Audit every non-vendor workspace package").option("-r, --root","Audit the monorepo root (turbo pipeline + root commands)").option("--fix","Write the infra-kit guidance block into CLAUDE.md for the audited scope before checking (CLI-only)").option("--design","With --fix: scaffold DESIGN.md for frontend/mobile packages that lack one").action(async a=>{if(a.design&&!a.fix){u.error("--design requires --fix (it scaffolds DESIGN.md; there is nothing to scaffold without a fix run)"),Fe.exitCode=1;return}let c=await Ms({all:a.all,root:a.root,fix:a.fix,design:a.design});A(c);let{allPassed:l,fixed:d}=c.structuredContent,p=(d??[]).some(m=>m.action==="failed");(!l||p)&&(Fe.exitCode=1)});let i=e.command("vendor").description("Mirror and verify the vendored starter files");return TI(i.command("check")),xI(i.command("config")),CI(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 pi({fix:!!a.fix});Jt.enabled||Ac(c.structuredContent.checks,{ascii:!!a.ascii}),c.structuredContent.checks.some(d=>d.name==="plugin installed"&&d.status==="fail")&&(Fe.exitCode=1),A(c)}),e.command("dev").description("Run local dev servers for a preset or an app (or every app); api + ui").argument("[preset]","A devServersPresets name, or an app \u2014 its api/ui plus the backends its routes can run locally (omit to run every app)").option("-w, --watch","Rebuild and restart on file save (the default)").option("--no-watch","Build once and never restart on save").option("--app <names>","Further narrow to these app folder names (comma-separated)").option("--target <keys>","Run exactly these <app>/api|<app>/ui packages (comma-separated); part-level, unlike --app").option("--orca","Run each app in its own Orca pane (one tab, N panes; falls back to single terminal when Orca is not running)").option("--self","Run only the app of the current directory (infer from cwd; use inside apps/<app>/\u2026)").option("-V, --verbose","Print full boot narration (default: quiet; full detail always in the session log)").option("--routes","Print each app\u2019s registered METHOD /path routes at startup (default: off)").option("--reuse","For test runners: start nothing when this worktree already serves one of these apps, exit on a boot failure").option("--no-ui-health","Do not probe the frontends\u2019 liveness (vite\u2019s HMR ping); their rows carry no health dot (also: INFRA_KIT_NO_UI_HEALTH=1)").action(async(a,c)=>{let{runDevServerCli:l}=await import("./dev-server.js"),d=!!(Fe.stdout.isTTY&&Fe.stdin.isTTY);await l({...c,preset:a},d,Jt.enabled)}),e.command("dev-status").description("Show what `infra-kit dev` currently has running (reads dev-context fragments; starts nothing)").action(async()=>{A(await Bs())}),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)=>{A(await fi({app:c.app,dryRun:c.dryRun,yes:c.yes,cloud:c.cloud,playwrightArgs:a}))}),e.command("setup").description("Set this machine up: shell integration, agent files, the Claude Code skills plugin, then the external tools").option("--tools <ids...>","Limit to these tools (brew, git, aws, gh, doppler, portless)").option("--update [ids...]","Update what is already installed; never install a missing tool").option("--skip-tools","Do the local setup only, then REPORT what each tool needs \u2014 installs nothing").option("--ascii","Render the report with ASCII markers instead of unicode glyphs (row messages are unchanged)").action(async a=>{A(await Li({tools:a.tools,update:a.update,skipTools:a.skipTools,ascii:!!a.ascii}))}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{A(await Gi())}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{A(await yi())}),e.command("env-list").description("List available Doppler configs for the detected project, and whether a service token resolves for each").action(async()=>{A(await pm())}),e.command("env-load").description("Load Doppler env vars for a config. Source the returned file path to apply.").option("-c, --config <config>","Environment config name to load (e.g. dev, arthur)").action(async a=>{$v(await Ca({config:a.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{$v(await hi())}),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.");A(await pu({fromFile:c.fromFile,force:c.force}));return}A(await uu({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=>{A(await vi({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=>{A(await lu({env:a}))}),e.commands.forEach(hp),Iu(e),Du(e),e.hook("preAction",async(a,c)=>{let{C:l}=e.opts();l!==void 0&&uI(dI(Fe.cwd(),l)),h.start(ua(c)),Jt.enabled=!!c.optsWithGlobals().json,Jt.enabled&&(u.level="warn"),N.source=us({env:Fe.env,stdinIsTTY:Fe.stdin.isTTY===!0,flag:!!c.optsWithGlobals().agent}),OI.has(ua(c))||await Zc()}),e.hook("postAction",(a,c)=>{let l=ua(c);if(nu(l))return;let p=h.snapshot()?.formattedOptions??"",m=p?` ${p}`:"",g=`infra-kit ${l}${m}`;Ev({equivalent:ca(g,!0)})}),e};import II from"node:process";var DI={exit:II.exit,emit:A,logger:u},Ov=(e,t=DI)=>be(e)?(t.logger.info("Operation cancelled."),t.exit(0)):e instanceof x?(t.emit({structuredContent:e.structuredContent}),t.logger.error(e.message),t.exit(e.exitCode)):(t.logger.error(e instanceof Error?e.message:String(e)),t.exit(1));var _u=(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 NI from"node:fs";import Mu from"node:path";import wn from"node:process";var Nv=new Set([...Ip,bn,"XDG_CACHE_HOME","CLAUDE_PROJECT_DIR","CLAUDE_PLUGIN_ROOT"]),_v=null,pa=new Set,ju=null,Iv=!1;var Dv=e=>{try{return NI.statSync(e)}catch{return null}},_I=()=>{if(Iv)return null;try{return Rr()}catch{return Iv=!0,u.debug(`session-env: ${bn} unset \u2014 no overlay`),null}},MI=e=>{let t=Mu.join(e,kr),r=Mu.join(e,ts),n=Dv(t),o=Dv(r);return n&&!(o&&o.mtimeMs>n.mtimeMs)?qu(Mu.join(e,rs),wn.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"}},jI=e=>e.kind==="load"?{kind:"load",vars:Gu(e.file),signature:e.signature}:e.kind==="clear"?{kind:"clear",unset:Ku(e.file),signature:e.signature}:e;var FI=()=>{let e=_I();if(e===null)return{kind:"no-session"};let t=MI(e);return t.signature===ju?null:jI(t)},LI=()=>{for(let e of pa){let t=_v[e];t===void 0?delete wn.env[e]:wn.env[e]=t}pa.clear()},BI=(e,t,r)=>{if(Nv.has(t)){e.skipped.push(t);return}wn.env[t]=r,pa.add(t),e.set.push(t)},WI=(e,t)=>{if(Nv.has(t)){e.skipped.push(t);return}delete wn.env[t],pa.add(t),e.unset.push(t)},VI=e=>{let t={set:[],unset:[],skipped:[]};if(e.kind==="load")for(let[r,n]of Object.entries(e.vars))BI(t,r,n);if(e.kind==="clear")for(let r of e.unset)WI(t,r);return t},UI=e=>e.kind==="load"?`load, ${Object.keys(e.vars).length} vars`:e.kind,Fu=(e=FI())=>{if(_v??={...wn.env},e===null||e.kind==="no-session"||e.signature===ju)return{set:[],unset:[],changed:!1};LI();let{set:t,unset:r,skipped:n}=VI(e);return ju=e.signature,n.length>0&&u.warn(`session-env: skipped protected names [${n.join(", ")}]`),u.debug(`session-env applied: set [${t.join(", ")}] unset [${r.join(", ")}] (${UI(e)})`),{set:t,unset:r,changed:!0}};import{chalkStderr as dD}from"chalk";import{spawn as uD}from"node:child_process";import Te from"node:process";import{Chalk as JI}from"chalk";var kn=new JI({level:1}),Ue={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."},GI={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"}},Mv={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},jv={unicode:"\u2500",ascii:"-"},KI=3,Lu=e=>e,HI={ok:e=>kn.green(e),findings:e=>kn.yellow(e),failed:e=>kn.red(e),cancelled:e=>kn.gray(e)},Wu=e=>e?{dim:t=>kn.dim(t),bold:t=>kn.bold(t)}:{dim:Lu,bold:Lu},qI=(e,t)=>e?HI[t]:Lu,Bu=e=>[...e].length,YI=(e,t)=>{if(t==null)return e;let r=Math.max(0,t-1);return Bu(e)<=r?e:[...e].slice(0,r).join("")},Fv=e=>{let t=Wu(e.color===!0).dim,r=GI[e.canSuspend?"suspend":"plain"],n=e.ascii===!0?r.ascii:r.unicode;return t(YI(n,e.width))},Lv=(e,t={})=>{let r=Wu(t.color===!0);return`${r.dim(Ue.reproPrefix.trim())} ${r.bold(e)}`},zI=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,XI=(e,t)=>e==="findings"?t!=null?`${t} ${Ue.findingsSuffix}`:Ue.findingsPlain:{ok:Ue.ok,failed:Ue.failed,cancelled:Ue.cancelled}[e],ZI=(e,t,r,n)=>{if(t==null)return"";let o=t-2-e;return o<KI?"":` ${n(r.repeat(o))}`},Bv=e=>{let t=e.color===!0,r=Wu(t),n=qI(t,e.outcome),o=e.ascii===!0,s=e.equivalent.reproducible?Ue.reproPrefix:Ue.nonReproPrefix,i=o?Mv[e.outcome].ascii:Mv[e.outcome].unicode,a=XI(e.outcome,e.findingsCount),c=[zI(e.durationMs)],l=e.summary?.[0]?.split(`
452
- `)[0];l!=null&&l.length>0&&c.push(l);let d=`${i} ${a}`,p=`${Ue.sep}${c.join(Ue.sep)}`,m=Bu(d)+Bu(p),g=ZI(m,e.width,o?jv.ascii:jv.unicode,r.dim),y=[`${n(d)}${r.dim(p)}${g}`];return e.showEquivalent!==!1&&y.unshift(`${r.dim(s.trim())} ${r.bold(e.equivalent.line)}`),e.envNotice===!0&&y.push(r.dim(Ue.envNotice)),y.join(`
453
- `)};var QI=new Set([130,143]),Wv=(e,t,r,n=!1)=>r?t!=null||e===0?"ok":"findings":n&&e!=null&&QI.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import eD from"node:process";var tD={3:"quit",4:"quit",26:"suspend",27:"quit"},rD=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":tD[t]??"continue"},nD=150,oD="\r\x1B[2K",sD=`\r
454
- `,Vv=(e,t)=>{Uv(e),e.stdin.on("data",t),e.listener=t},Uv=e=>{e.listener!==null&&(e.stdin.off("data",e.listener),e.listener=null)},Jv=(e,t)=>{Kp(),e.stdin.setRawMode(!0),e.stdin.isPaused()&&e.stdin.resume(),Vv(e,t)},Gv=e=>{e.hintOnScreen&&(e.hintOnScreen=!1,e.deps.write(oD)),Uv(e),e.stdin.isTTY===!0&&e.stdin.isRaw===!0&&e.stdin.setRawMode(!1),Hp()},iD=e=>{e.settled||(e.settled=!0,Gv(e))},Kv=(e,t)=>{let r=Fv({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},aD=async e=>{await new Promise(t=>{setTimeout(t,e)})},cD=(e,t,r)=>{Gv(e),t(),Jv(e,r),Kv(e,sD)},lD=async e=>new Promise(t=>{let r=n=>{let o=rD(n),s=e.deps.suspend;if(o==="quit"){t("quit");return}if(o==="suspend"&&s!==void 0){cD(e,s,r);return}t("palette")};Vv(e,r),Kv(e,"")}),Hv=async(e,t)=>{if(e.quitRequested())return"quit";let r=t.stdin??eD.stdin;if(r.isTTY!==!0)return"palette";let n={deps:t,stdin:r,listener:null,hintOnScreen:!1,settled:!1};try{return Jv(n,()=>{}),e.armed(),await aD(t.drainMs??nD),await lD(n)}finally{iD(n)}};import qv from"node:process";var Vt={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},Yv=(e,t)=>{let r=t?.write??(s=>{qv.stderr.write(s)}),n=t?.stdin??qv.stdin,o=[Vt.saveCursor,Vt.scrollRegion,Vt.restoreCursor,Vt.column,Vt.sgr,Vt.cursor,Vt.wrap];e.entersAltScreen===!0&&o.push(Vt.primaryBuffer),r(o.join("")),n.isTTY===!0&&n.isRaw===!0&&n.setRawMode?.(!1)};var zv=e=>`infra-kit ${e.groupPath.join(" ")}`,pD=()=>{mD();let e=Te.stderr.columns;return e!=null&&e>0?e:void 0},mD=()=>{let e=Te.stderr;typeof e._refreshSize=="function"&&e._refreshSize()},fD=e=>new Promise(t=>{e.on("exit",(r,n)=>{t({code:r,signal:n})}),e.on("error",()=>{t({code:1,signal:null})})}),gD=async(e,t,r)=>{let n=xv(),o={...t.env,[da]:n,INFRA_KIT_NO_AUTO_UPDATE:"1"},s=t.now(),i={code:1,signal:null};r();try{let p=t.spawn(Te.execPath,[t.cliPath,...e.groupPath],{stdio:"inherit",env:o});i=await fD(p)}catch{i={code:1,signal:null}}finally{t.resetTerminal({entersAltScreen:e.entersAltScreen})}let a=Tv(n),c=Wv(i.code,i.signal,a!=null,e.longRunning),l=zv(e),d=a?.equivalent??ca(l,!0);return Bv({equivalent:d,outcome:c,durationMs:t.now()-s,summary:a?.summary,envNotice:e.sessionEnvNotice,ascii:t.ascii,color:t.color,width:t.columns(),showEquivalent:!(d.reproducible&&d.line===l)})},hD=1e3,yD=(e,t)=>e!=null&&t-e<=hD,Vu=e=>{e.resetTerminal(),e.exit(0)},vD=(e,t)=>{let r=null,n=!1,o=()=>{let c=e();if(c==="child"){r=t.now();return}c!=="pause"&&Vu(t)},s=()=>{let c=e();if(c==="palette"){Vu(t);return}if(!yD(r,t.now())){if(c==="pause"){Vu(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}},Xv=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),wD=Te.platform==="win32"?void 0:()=>{qp()},kD=(e,t)=>r=>Hv(r,{write:e,columns:t.columns,ascii:t.ascii,color:t.color,suspend:wD}),Zv=async(e,t)=>{let r={spawn:t.spawn??uD,now:t.now??(()=>Date.now()),env:t.env??Te.env,cliPath:t.cliPath,ascii:t.ascii??!(Te.stdout.isTTY&&Te.env.TERM!=="dumb"),color:t.color??dD.level>0,columns:t.columns??pD,resetTerminal:t.resetTerminal??(d=>{Yv(d)})},n=t.write??(d=>Te.stderr.write(d)),o="palette",s=t.signals??{register:(d,p)=>{Te.on(d,p)},unregister:(d,p)=>{Te.off(d,p)},exit:d=>{Te.exit(d)},raise:d=>{Te.kill(Te.pid,d)},now:()=>Date.now(),resetTerminal:()=>{o==="pause"&&n("\r\x1B[2K"),r.resetTerminal({entersAltScreen:!1})}},i={dispose:()=>{},childStarted:()=>{},quitRequested:()=>!1},a=t.installSignals===!1?i:vD(()=>o,s),c={armed:()=>{o="pause"},quitRequested:()=>a.quitRequested()},l=t.afterRun??kD(n,r);try{for(;;){if(a.quitRequested())return;o="palette";let d=await t.renderPalette(e);if(d==null)return;let p=t.resolveCommand(d);if(!p)continue;let m=Lv(zv(p),{color:r.color});n(`
454
+ `;var bO=new Set(["100644","100755","120000"]),RO=(e,t)=>{let r=new Map;for(let n of Vt(e)){let o=n.indexOf(" "),s=n.slice(0,n.indexOf(" ")),i=n.slice(o+1);o<0||!bO.has(s)||ts(i,t)||r.set(i,{path:i,mode:s})}return[...r.values()]},Ru=async(e,t,r)=>{let n=await ee(e,["--literal-pathspecs","ls-files","-z","-s","--",t]);return RO(n,r)},lv=async e=>Vt(await ee(e,["--literal-pathspecs","ls-files","-z","--",Q]));var bn=e=>["git","-C",e.root,"--literal-pathspecs","checkout","HEAD","--",...e.recoveryPaths],pv=e=>{let t=ta(e);t!==null&&(t.kind==="other"?uv(e):$O(e))},OO=(e,t,r)=>{let n=ke.join(e,r.source),o=ke.join(t,r.target);if(dv(ke.dirname(o),{recursive:!0}),pv(o),r.mode==="120000"){CO(TO(n),o);return}PO(n,o),SO(o,r.mode==="100755"?493:420)},IO=async(e,t)=>{let r=new Set;for(let n of Vt(await ee(e,["ls-files","-z"]))){if(t.has(n))continue;let o=ke.posix.dirname(n);for(;o!==".";)r.add(o),o=ke.posix.dirname(o)}return r},DO=async(e,t)=>{if(t.length===0)return;let r=await IO(e,new Set(t)),n=[...new Set(t.map(o=>ke.dirname(ke.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)&&!(!EO(s,{throwIfNoEntry:!1})?.isDirectory()||xO(s).length>0||r.has(ke.relative(e,s).split(ke.sep).join("/")));)uv(s),s=ke.dirname(s)}},mv=(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,Ut,...s].map(cv).filter(a=>a!==null&&!Wi(a));return kn(i)},fv=async(e,t,r,n)=>{let o=ke.join(e,Q);dv(o,{recursive:!0}),AO(ke.join(e,Ut),oa(t.name));let s=mv(r,await lv(e),n);Gd(o,{source:t.name,commit:t.headSha},s)},Su=async({source:e,plan:t,onBeforeFirstWrite:r})=>{if(t.status!=="changed")return{touched:[],manifestWritten:!1};r?.(bn(t));let n=ke.resolve(t.root),o=t.entries.flatMap(a=>a.deletes);for(let a of o)pv(ke.join(n,a));await DO(n,o);let s=t.entries.flatMap(a=>a.writes);for(let a of s)OO(e.root,n,a);let i=s.map(a=>a.target);return t.writeVendorMeta?(await fv(n,e,t.entries,o),{touched:kn([...o,...i,Ut,es]),manifestWritten:!0}):{touched:kn([...o,...i]),manifestWritten:!1}},Pu=async(e,t)=>(await fv(e,t,[],[]),[Ut,es]);var Eu=(e,t)=>`[ROOT] vendor: sync from ${e}@${ra(t)}`,NO=e=>{let{stdout:t,stderr:r}=e;return[t,r].filter(o=>typeof o=="string"&&o.trim().length>0).join(`
455
+ `).trim()||String(e)},xu=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 ee(e,["--literal-pathspecs","add","-A",...o],{input:n}),await ee(e,["--literal-pathspecs","commit","--only","-m",r,...o],{input:n}),{ok:!0}}catch(s){return{ok:!1,output:NO(s)}}};var _O=20,MO=20,gv=(e,t)=>e.length<=t?[...e]:[...e.slice(0,t),`\u2026and ${e.length-t} more`],hv=(e,t,r)=>{let{entry:n}=e,o=new Set(t.tracked),s=[],i=[];for(let d of rs(e.files,r)){let p=na(d.path,n);if(s.push(p),nv(d.fingerprint,t.onDisk[p]??null))continue;let m=o.has(p)?"modified":"added";i.push({source:d.path,target:p,mode:d.mode,change:m})}let a=new Set(s),c=rs(t.tracked.map(d=>({path:d})),r).map(d=>d.path).filter(d=>!a.has(d)),l=i.filter(d=>d.change==="added").length;return{...n,targetPaths:s,writes:i,deletes:c,counts:{added:l,modified:i.length-l,removed:c.length}}},ns=(e,t,r,n=[])=>({name:e.name,root:e.root,status:t,message:r,notes:n,warnings:[],entries:[],writeVendorMeta:!1,recoveryPaths:[]}),Tu=e=>e.entries.map(t=>t.entry.target),jO=(e,t,r)=>{let n=["git","-C",t.root,"--literal-pathspecs","status","--",...Tu(e)];return ns(t,"fail",`blocked: ${r.length} uncommitted path(s) under synced paths`,[...gv(r,_O),Ae(n)])},FO=(e,t)=>{if(e.kind==="unknown-sha")return{notes:[],warnings:["no manifest commit recorded, so the source commits since the last sync are unknown"]};let r=ra(e.sha);return e.kind==="unresolvable"?{notes:[],warnings:[`manifest commit ${r} is not in ${t}, so the changelog is unknown`]}:{notes:[`${e.lines.length} ${t} commit(s) since ${r}`,...gv(e.lines,MO)],warnings:[]}},LO=e=>{let{added:t,modified:r,removed:n}=e.counts;return t+r+n===0?null:`${e.target}: ${t} added, ${r} modified, ${n} removed`},BO=e=>{let t=r=>e.reduce((n,o)=>n+o.counts[r],0);return`${t("added")} added, ${t("modified")} modified, ${t("removed")} removed`},WO=(e,t,r)=>{let n=e.flatMap(o=>[...o.writes.filter(i=>i.change==="modified").map(i=>i.target),...o.deletes]);return kn([...n,...r?t.headVendorMeta:[]])},VO=(e,t)=>{if(t.dirty.length>0)return jO(e,t,t.dirty);let r=e.entries.map((d,p)=>{let m=t.entries[p]??{target:d.entry.target,tracked:[],onDisk:{}};return hv(d,m,e.exclude)}),n=r.some(d=>d.vendored),o=r.some(d=>d.writes.length+d.deletes.length>0),s=n&&(!t.readmeCurrent||!t.manifestPresent),i={...ns(t,"ok","up to date"),branch:t.branch,entries:r,writeVendorMeta:n};if(!o&&!s)return i;let a=FO(t.changelog,e.name),c=t.manifestSource!==null&&t.manifestSource!==e.name?[`vendor/ was last synced from ${t.manifestSource}, not ${e.name}: this sync replaces it`]:[],l=r.map(LO).filter(d=>d!==null);return{...i,status:"changed",message:`${BO(r)} on ${t.branch}`,notes:[...l,...s?["vendor/README.md and manifest rewritten"]:[],...a.notes],warnings:[...c,...a.warnings],recoveryPaths:WO(r,t,n)}},sa=(e,t)=>{switch(t.kind){case"missing":return ns(t,"skipped",`not checked out at ${t.root}`);case"source":return ns(t,"skipped","this is the source repo");case"not-git":return ns(t,"fail",`not a git repo: ${t.reason}`);case"repo":return VO(e,t)}};import{existsSync as UO,readFileSync as JO,realpathSync as ia}from"node:fs";import aa from"node:path";var Cu=async(e,t)=>{let r=t.exclude??[],n=(await ee(e,["rev-parse","HEAD"])).trim(),o=await be(e),s=await Promise.all(av(t).map(async i=>{let a=await Ru(e,i.path,r);return{entry:i,files:a.map(c=>rv(e,c))}}));return{root:e,selfRoots:[...new Set([ia(e),ia(o)])],name:aa.basename(o),headSha:n,entries:s,exclude:r}},ca=e=>{let t=Vt(e)[Symbol.iterator](),r=[];for(let n of t)r.push(n.slice(3)),/^[RC]|^.[RC]/u.test(n)&&t.next();return r},GO=async(e,t)=>{let r=await ee(t,["--literal-pathspecs","status","--porcelain","-z","--untracked-files=all","--",...Tu(e)]);return ca(r).filter(n=>!ts(n,e.exclude))},KO=async(e,t)=>Promise.all(e.entries.map(async({entry:r,files:n})=>{let o=await Ru(t,r.target,e.exclude),s={};for(let i of rs(n,e.exclude)){let a=na(i.path,r);s[a]=ta(aa.join(t,a))}return{target:r.target,tracked:o.map(i=>i.path),onDisk:s}})),HO=async e=>{try{return Vt(await ee(e,["--literal-pathspecs","ls-tree","-z","--name-only","HEAD","--",Ut,es]))}catch{return[]}},qO=e=>{try{let{commit:t,source:r}=qo(aa.join(e,Q));return{commit:t,source:r}}catch{return null}},YO=async(e,t)=>{if(t===null)return{kind:"unknown-sha"};if(await Oe(e.root,t)===null)return{kind:"unresolvable",sha:t};let r=e.entries.map(({entry:s})=>s.path),o=(await ee(e.root,["--literal-pathspecs","log","--oneline",`${t}..HEAD`,"--",...r])).split(`
456
+ `).filter(s=>s.length>0);return{kind:"log",sha:t,lines:o}},zO=(e,t)=>{try{return JO(aa.join(e,Ut),"utf8")===oa(t)}catch{return!1}},XO=async e=>{try{return{toplevel:(await ee(e,["rev-parse","--show-toplevel"])).trim()}}catch(t){return{reason:String(t.stderr??t).trim().split(`
457
+ `)[0]??"git rev-parse failed"}}},ZO=async e=>{try{return(await ee(e,["rev-parse","--abbrev-ref","HEAD"])).trim()}catch{return"HEAD"}},la=async(e,t)=>{if(!UO(t.root))return{...t,kind:"missing"};let r=ia(t.root);if(e.selfRoots.includes(r))return{...t,kind:"source"};let n=await XO(t.root);if("reason"in n)return{...t,kind:"not-git",reason:n.reason};if(ia(n.toplevel)!==r)return{...t,kind:"not-git",reason:`it sits inside the repo at ${n.toplevel}`};let o=qO(t.root),s=o?.commit??null,[i,a,c,l,d]=await Promise.all([ZO(t.root),GO(e,t.root),KO(e,t.root),HO(t.root),YO(e,s)]);return{...t,kind:"repo",branch:i,dirty:a,entries:c,headVendorMeta:l,readmeCurrent:zO(t.root,e.name),manifestPresent:o!==null,manifestSource:o?.source??null,changelog:d}};var QO=20,eI=(e,t)=>!t.commit||e.status!=="changed"||e.branch===void 0?e.notes:[...e.notes,`--commit lands on ${e.branch}`],tI=(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:",Ae(bn(r))]};let o=e.applied?`wrote ${r.message}`:r.message;return{name:n,status:r.status,message:o,notes:t.mode==="applied"?r.notes:eI(r,t)}},rI=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(`
458
+ `).slice(0,QO)},nI=(e,t)=>{let r=e.plan.warnings.map(n=>({name:"changelog",status:"warn",message:n}));return{label:e.plan.name,rows:[tI(e,t),...r,...e.commit?[rI(e.commit)]:[]]}},oI={preview:"infra-kit vendor sync (preview)",check:"infra-kit vendor sync --check",applied:"infra-kit vendor sync"},$u=(e,t,r)=>{let n=r.mode==="preview"?["re-run with --yes from a real terminal to apply"]:[];return{title:oI[r.mode],sections:[{label:"source",rows:[...e]},...t.map(o=>nI(o,r))],hints:n}},yv=e=>e.sections.some(t=>t.rows.some(r=>r.status==="fail")),vv=(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 sI=20,Au=async(e,t)=>(await ee(e,t,{allowFailure:!0})).trim(),iI=async e=>ca(await ee(e,["status","--porcelain","-z","--untracked-files=normal"])),aI=async e=>(await Au(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"]},cI=async e=>{let[t,r]=await Promise.all([Au(e,["symbolic-ref","--quiet","--short","refs/remotes/origin/HEAD"]),Au(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}`}},wv=async e=>{let t=await iI(e);if(t.length>0){let n=t.slice(0,sI),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([aI(e),cI(e)]);return[{name:"working tree",status:"ok",message:"clean"},...r.filter(n=>n!==null)]};import lI from"node:path";var kv=(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=on(e.workspaceDir);return(t.length>0?e.targets.filter(s=>t.includes(s)):e.targets).map(s=>({name:s,root:lI.join(n,s)}))},dI="rewrite vendor/README.md and vendor/.sync-manifest.json from the tracked vendor/ files",uI=async(e,t)=>{let r=await la(e,t),n=sa(e,r);return r.kind!=="repo"||n.status==="fail"?n:{...n,status:"changed",message:`${dI} on ${r.branch}`,notes:[],warnings:[],branch:r.branch,entries:[],writeVendorMeta:!0,recoveryPaths:r.headVendorMeta}},bv=async(e,t,r)=>Promise.all(t.map(async n=>r?uI(e,n):sa(e,await la(e,n))));var Ev="sync vendored files",gI=e=>{let t=Sv.join(on(e.workspaceDir),e.source);if(pI(t))return t;throw new C({status:"refused",reason:"source-missing",source:t},1,{operation:Ev,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'})},Ou=(e,t)=>new C({status:"refused",reason:"not-a-vendor-source"},1,{operation:Ev,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`}),hI=async e=>{let t=Sv.join(e,"infra-kit.json"),r;try{r=JSON.parse(await mI.readFile(t,"utf8"))}catch(s){throw Ou(t,`is unreadable: ${s instanceof Error?s.message:String(s)}`)}let n=r?.vendorSource;if(n==null)throw Ou(t,"has no vendorSource block");let o=Mp.safeParse(n);if(!o.success)throw Ou(t,`has an invalid vendorSource: ${fI.prettifyError(o.error)}`);return o.data},Rv=(e,t)=>{Pv.stderr.write(`${e.name}: if this run dies, restore the tracked paths with:
459
+ ${Ae(t)}
460
+ `)},yI=async(e,t,r)=>r?(Rv(t,bn(t)),Pu(t.root,e)):(await Su({source:e,plan:t,onBeforeFirstWrite:o=>{Rv(t,o)}})).touched,vI=async(e,t,r)=>{if(t.status!=="changed")return{plan:t,applied:!1};let n;try{n=await yI(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 xu(t.root,n,Eu(e.name,e.headSha));return{plan:t,applied:!0,commit:o}},wI=async(e,t,r)=>{let n=[];for(let o of t)n.push(await vI(e,o,r));return n},xv=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})),Iu=({mode:e,report:t,outcomes:r,source:n,print:o})=>{o&&Qe(t);let s=r.map(a=>a.plan);return{structuredContent:{mode:e,source:{root:n.root,name:n.name,headSha:n.headSha},targets:xv(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:yv(t),report:t.sections}}},kI=async e=>{let t=await oi(),r=gI(t),n=await wv(r),o=await hI(r),s=kv(t,e.targets??[]),i=await Cu(r,o),a=await bv(i,s,!!e.manifestOnly);return{source:i,sourceRows:n,plans:a}},Du=async(e={})=>{let{source:t,sourceRows:r,plans:n}=await kI(e),o=n.map(m=>({plan:m,applied:!1})),s={commit:e.commit,manifestOnly:e.manifestOnly},i=e.check?"check":"preview",a=$u(r,o,{...s,mode:i}),c=!n.some(m=>m.status==="changed");if(e.check||c)return Iu({mode:i,report:a,outcomes:o,source:t,print:!0});let l=!e.confirmedCommand&&!J();if(l&&!Pv.stdin.isTTY)return Qe(a),Iu({mode:"preview",report:a,outcomes:o,source:t,print:!1});l&&Qe({...a,hints:[]}),await B(e.confirmedCommand,`Sync vendored files from ${t.name} into these targets?`,{plan:xv(n),throwOnDecline:!0});let d=await wI(t,n,e),p=$u(r,d,{...s,mode:"applied"});if(l){let m=d.filter(g=>g.applied).map(g=>g.plan.name);Qe(vv(a,p,m))}return Iu({mode:"applied",report:p,outcomes:d,source:t,print:!l})};var da=(e,t=!0)=>({line:e,reproducible:t});import ua from"node:fs";import bI from"node:os";import RI from"node:path";import Av from"node:process";var pa="INFRA_KIT_SESSION_REPORT",Nu=null,Tv=!1,Cv=[],Ov=(e=Av.env)=>{Tv||(Nu=e[pa]??null,Tv=!0,delete e[pa])};var Iv=(e,t)=>{if(!Nu)return;let r=e.summary??(Cv.length>0?[...Cv]:void 0),n={...e,...r?{summary:r}:{}},o=t?.write??((s,i)=>{ua.writeFileSync(s,i)});try{o(Nu,JSON.stringify(n))}catch{}},$v=0,Dv=e=>{let t=e?.tmpdir?.()??bI.tmpdir(),r=e?.pid??Av.pid;return $v+=1,RI.join(t,`infra-kit-session-${r}-${$v}.json`)},Nv=(e,t)=>{if(!(t?.exists??(i=>ua.existsSync(i)))(e))return null;let n=t?.read??(i=>ua.readFileSync(i,"utf-8")),o=t?.unlink??(i=>ua.unlinkSync(i)),s;try{s=n(e)}catch{return null}finally{try{o(e)}catch{}}try{return JSON.parse(s)}catch{return null}};var _u=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(_u)};var Mu=e=>{e.options.some(r=>r.long==="--debug")||e.option("--debug","Raise the log level to debug (logs stay on stderr)"),e.commands.forEach(Mu)};var TI=(e,t)=>[...t,e],_v=(e,t)=>{if(!(typeof e>"u")){if(e===!0)return"workspace";if(e===!1)return"none";if(typeof e=="string"&&vr.includes(e))return e;throw new Error(`Invalid ${t} value "${String(e)}". Expected one of: ${vr.join(", ")}.`)}},CI=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 _f(()=>bi({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}));A(r),r.structuredContent.failedMerges>0&&(We.exitCode=1)}),Mv=e=>(We.stdout.write(`${e.structuredContent.filePath}
461
+ `),A(e)),$I=e=>e.description("List all release branches").action(async()=>{A(await xi())}),AI=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".',TI,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let n=t.release.map(bl),o=n.length>0?n:void 0;A(await Oi({releases:o,confirmedCommand:t.yes}))}),OI=e=>{if(e==="")return e;try{return cr(e)}catch(t){throw t instanceof un?new PI(t.message):t}},II=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)',OI).option("-y, --yes","Skip confirmation prompt").action(async t=>{A(await Ii({version:t.version,description:t.description,releaseDate:t.releaseDate,confirmedCommand:t.yes}))}),jv=e=>e.option("-f, --from <where>",`Where the deploy runs: ${Ft.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"),DI=e=>jv(e).description("Deploy every service to any environment, in CI or from this machine").action(async t=>{A(await yu({from:t.from,version:t.version,env:t.env,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),NI=e=>jv(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=>{A(await vu({from:t.from,version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),_I=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=>{A(await Si({version:t.version,confirmedCommand:t.yes}))}),MI=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=>{A(await Fi({version:t.version,moveIssuesTo:t.moveIssuesTo,skipJira:t.skipJira,confirmedCommand:t.yes}))}),jI=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{A(await Zi({confirmedCommand:t.yes}))}),FI=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("-i, --ide [mode]","Editor mode for created worktrees: workspace (default) | none").option("--no-ide","Skip the editor (alias for --ide none)").option("-c, --cursor [mode]","Deprecated alias for --ide").option("--no-cursor","Deprecated alias for --no-ide").option("-g, --github-desktop","Open created worktrees in GitHub Desktop").option("--no-github-desktop","Skip GitHub Desktop prompt").option("--orca","Open created worktrees in Orca (pane layout from worktrees.orca.layout)").option("--no-orca","Skip the Orca prompt").action(async t=>{let r=_v(t.ide,"--ide")??_v(t.cursor,"--cursor");A(await qi({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature,base:t.base,ide:r,githubDesktop:t.githubDesktop,orca:t.orca}))}),LI=e=>e.description("List all git worktrees with detailed information").action(async()=>{A(await Yi())}),BI=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=>{A(await Xi({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature,self:t.self}))}),WI=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=>{A(await ku({init:t.init}))}),VI=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await Gi();A(t),t.structuredContent.ok||(We.exitCode=1)}),UI=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 Du({targets:t,confirmedCommand:r.yes,check:r.check,commit:r.commit,manifestOnly:r.manifestOnly})}catch(a){if(!at(a))throw a;u.info("Operation cancelled.");return}A(n);let{failed:o,changed:s,mode:i}=n.structuredContent;(o||i==="check"&&s)&&(We.exitCode=1)}),JI=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{A(await lu())}),GI=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{A(await du())}),KI=new Set(["version"]),ma=e=>{let t=[];for(let r=e;r&&r.parent;r=r.parent)t.unshift(r.name());return t.join(" ")},ju=()=>{let e=new SI().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");CI(t.command("merge-dev")),$I(t.command("list")),AI(t.command("create")),II(t.command("edit")),DI(t.command("deploy-all")),NI(t.command("deploy-selected")),_I(t.command("deliver")),MI(t.command("remove"));let r=e.command("worktrees").description("Git worktree management commands");FI(r.command("add")),LI(r.command("list")),BI(r.command("remove")),jI(r.command("sync"));let n=e.command("config").description("Manage infra-kit configuration files");JI(n.command("path")),GI(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. ide)").action(async a=>{A(await Ws({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, ide)").argument("<value>",`JSON value, or a bare string (e.g. cli-only, '[{"provider":"orca"}]')`).option("--global","Write ~/.infra-kit/infra-kit.json (every project on this machine) instead").action(async(a,c,l)=>{A(await Rc({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)=>{A(await uu({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=>{A(await ea({env:a.env,yes:a.yes,dryRun:a.dryRun,printEnv:a.printEnv},"all"))}),s(o.command("deploy-selected")).description("Deprecated \u2014 use `release deploy-selected --from local`").option("-s, --service <name...>","Service name(s), as in deploy-<name>.sh (prompts when omitted)").action(async a=>{A(await ea({env:a.env,services:a.service,yes:a.yes,dryRun:a.dryRun,printEnv:a.printEnv},"selected"))}),e.command("audit").description("Audit against infra-kit.config.ts rules (--all for every package, --root for the monorepo root)").option("-a, --all","Audit every non-vendor workspace package").option("-r, --root","Audit the monorepo root (turbo pipeline + root commands)").option("--fix","Write the infra-kit guidance block into CLAUDE.md for the audited scope before checking (CLI-only)").option("--design","With --fix: scaffold DESIGN.md for frontend/mobile packages that lack one").action(async a=>{if(a.design&&!a.fix){u.error("--design requires --fix (it scaffolds DESIGN.md; there is nothing to scaffold without a fix run)"),We.exitCode=1;return}let c=await Fs({all:a.all,root:a.root,fix:a.fix,design:a.design});A(c);let{allPassed:l,fixed:d}=c.structuredContent,p=(d??[]).some(m=>m.action==="failed");(!l||p)&&(We.exitCode=1)});let i=e.command("vendor").description("Mirror and verify the vendored starter files");return VI(i.command("check")),WI(i.command("config")),UI(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 fi({fix:!!a.fix});Kt.enabled||Ic(c.structuredContent.checks,{ascii:!!a.ascii}),c.structuredContent.checks.some(d=>d.name==="plugin installed"&&d.status==="fail")&&(We.exitCode=1),A(c)}),e.command("dev").description("Run local dev servers for a preset or an app (or every app); api + ui").argument("[preset]","A devServersPresets name, or an app \u2014 its api/ui plus the backends its routes can run locally (omit to run every app)").option("-w, --watch","Rebuild and restart on file save (the default)").option("--no-watch","Build once and never restart on save").option("--app <names>","Further narrow to these app folder names (comma-separated)").option("--target <keys>","Run exactly these <app>/api|<app>/ui packages (comma-separated); part-level, unlike --app").option("--orca","Run each app in its own Orca pane (one tab, N panes; falls back to single terminal when Orca is not running)").option("--self","Run only the app of the current directory (infer from cwd; use inside apps/<app>/\u2026)").option("-V, --verbose","Print full boot narration (default: quiet; full detail always in the session log)").option("--routes","Print each app\u2019s registered METHOD /path routes at startup (default: off)").option("--reuse","For test runners: start nothing when this worktree already serves one of these apps, exit on a boot failure").option("--no-ui-health","Do not probe the frontends\u2019 liveness (vite\u2019s HMR ping); their rows carry no health dot (also: INFRA_KIT_NO_UI_HEALTH=1)").action(async(a,c)=>{let{runDevServerCli:l}=await import("./dev-server.js"),d=!!(We.stdout.isTTY&&We.stdin.isTTY);await l({...c,preset:a},d,Kt.enabled)}),e.command("dev-status").description("Show what `infra-kit dev` currently has running (reads dev-context fragments; starts nothing)").action(async()=>{A(await Vs())}),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)=>{A(await hi({app:c.app,dryRun:c.dryRun,yes:c.yes,cloud:c.cloud,playwrightArgs:a}))}),e.command("setup").description("Set this machine up: shell integration, agent files, the Claude Code skills plugin, then the external tools").option("--tools <ids...>","Limit to these tools (brew, git, aws, gh, doppler, portless)").option("--update [ids...]","Update what is already installed; never install a missing tool").option("--skip-tools","Do the local setup only, then REPORT what each tool needs \u2014 installs nothing").option("--ascii","Render the report with ASCII markers instead of unicode glyphs (row messages are unchanged)").action(async a=>{A(await Bi({tools:a.tools,update:a.update,skipTools:a.skipTools,ascii:!!a.ascii}))}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{A(await Ki())}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{A(await wi())}),e.command("env-list").description("List available Doppler configs for the detected project, and whether a service token resolves for each").action(async()=>{A(await hm())}),e.command("env-load").description("Load Doppler env vars for a config. Source the returned file path to apply.").option("-c, --config <config>","Environment config name to load (e.g. dev, arthur)").action(async a=>{Mv(await Aa({config:a.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{Mv(await vi())}),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.");A(await gu({fromFile:c.fromFile,force:c.force}));return}A(await fu({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=>{A(await ki({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=>{A(await pu({env:a}))}),e.commands.forEach(wp),_u(e),Mu(e),e.hook("preAction",async(a,c)=>{let{C:l}=e.opts();l!==void 0&&xI(EI(We.cwd(),l)),h.start(ma(c)),Kt.enabled=!!c.optsWithGlobals().json,Kt.enabled&&(u.level="warn"),N.source=gs({env:We.env,stdinIsTTY:We.stdin.isTTY===!0,flag:!!c.optsWithGlobals().agent}),KI.has(ma(c))||await el()}),e.hook("postAction",(a,c)=>{let l=ma(c);if(iu(l))return;let p=h.snapshot()?.formattedOptions??"",m=p?` ${p}`:"",g=`infra-kit ${l}${m}`;Iv({equivalent:da(g,!0)})}),e};import HI from"node:process";var qI={exit:HI.exit,emit:A,logger:u},Fv=(e,t=qI)=>Re(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 Fu=(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 YI from"node:fs";import Lu from"node:path";import Rn from"node:process";var Wv=new Set([..._p,Pn,"XDG_CACHE_HOME","CLAUDE_PROJECT_DIR","CLAUDE_PLUGIN_ROOT"]),Vv=null,fa=new Set,Bu=null,Lv=!1;var Bv=e=>{try{return YI.statSync(e)}catch{return null}},zI=()=>{if(Lv)return null;try{return Pr()}catch{return Lv=!0,u.debug(`session-env: ${Pn} unset \u2014 no overlay`),null}},XI=e=>{let t=Lu.join(e,Rr),r=Lu.join(e,ss),n=Bv(t),o=Bv(r);return n&&!(o&&o.mtimeMs>n.mtimeMs)?Xu(Lu.join(e,is),Rn.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"}},ZI=e=>e.kind==="load"?{kind:"load",vars:qu(e.file),signature:e.signature}:e.kind==="clear"?{kind:"clear",unset:Yu(e.file),signature:e.signature}:e;var QI=()=>{let e=zI();if(e===null)return{kind:"no-session"};let t=XI(e);return t.signature===Bu?null:ZI(t)},eD=()=>{for(let e of fa){let t=Vv[e];t===void 0?delete Rn.env[e]:Rn.env[e]=t}fa.clear()},tD=(e,t,r)=>{if(Wv.has(t)){e.skipped.push(t);return}Rn.env[t]=r,fa.add(t),e.set.push(t)},rD=(e,t)=>{if(Wv.has(t)){e.skipped.push(t);return}delete Rn.env[t],fa.add(t),e.unset.push(t)},nD=e=>{let t={set:[],unset:[],skipped:[]};if(e.kind==="load")for(let[r,n]of Object.entries(e.vars))tD(t,r,n);if(e.kind==="clear")for(let r of e.unset)rD(t,r);return t},oD=e=>e.kind==="load"?`load, ${Object.keys(e.vars).length} vars`:e.kind,Wu=(e=QI())=>{if(Vv??={...Rn.env},e===null||e.kind==="no-session"||e.signature===Bu)return{set:[],unset:[],changed:!1};eD();let{set:t,unset:r,skipped:n}=nD(e);return Bu=e.signature,n.length>0&&u.warn(`session-env: skipped protected names [${n.join(", ")}]`),u.debug(`session-env applied: set [${t.join(", ")}] unset [${r.join(", ")}] (${oD(e)})`),{set:t,unset:r,changed:!0}};import{chalkStderr as ED}from"chalk";import{spawn as xD}from"node:child_process";import Ce from"node:process";import{Chalk as sD}from"chalk";var Sn=new sD({level:1}),Ge={ok:"ok",findingsPlain:"completed with findings",failed:"failed",cancelled:"cancelled",findingsSuffix:"findings",sep:" \xB7 ",reproPrefix:"$ ",nonReproPrefix:"\u2248 ",envNotice:"Applies to infra-kit commands in this terminal and to new shells; this zsh prompt itself needs the env-load function."},iD={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"}},Uv={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},Jv={unicode:"\u2500",ascii:"-"},aD=3,Vu=e=>e,cD={ok:e=>Sn.green(e),findings:e=>Sn.yellow(e),failed:e=>Sn.red(e),cancelled:e=>Sn.gray(e)},Ju=e=>e?{dim:t=>Sn.dim(t),bold:t=>Sn.bold(t)}:{dim:Vu,bold:Vu},lD=(e,t)=>e?cD[t]:Vu,Uu=e=>[...e].length,dD=(e,t)=>{if(t==null)return e;let r=Math.max(0,t-1);return Uu(e)<=r?e:[...e].slice(0,r).join("")},Gv=e=>{let t=Ju(e.color===!0).dim,r=iD[e.canSuspend?"suspend":"plain"],n=e.ascii===!0?r.ascii:r.unicode;return t(dD(n,e.width))},Kv=(e,t={})=>{let r=Ju(t.color===!0);return`${r.dim(Ge.reproPrefix.trim())} ${r.bold(e)}`},uD=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,pD=(e,t)=>e==="findings"?t!=null?`${t} ${Ge.findingsSuffix}`:Ge.findingsPlain:{ok:Ge.ok,failed:Ge.failed,cancelled:Ge.cancelled}[e],mD=(e,t,r,n)=>{if(t==null)return"";let o=t-2-e;return o<aD?"":` ${n(r.repeat(o))}`},Hv=e=>{let t=e.color===!0,r=Ju(t),n=lD(t,e.outcome),o=e.ascii===!0,s=e.equivalent.reproducible?Ge.reproPrefix:Ge.nonReproPrefix,i=o?Uv[e.outcome].ascii:Uv[e.outcome].unicode,a=pD(e.outcome,e.findingsCount),c=[uD(e.durationMs)],l=e.summary?.[0]?.split(`
462
+ `)[0];l!=null&&l.length>0&&c.push(l);let d=`${i} ${a}`,p=`${Ge.sep}${c.join(Ge.sep)}`,m=Uu(d)+Uu(p),g=mD(m,e.width,o?Jv.ascii:Jv.unicode,r.dim),y=[`${n(d)}${r.dim(p)}${g}`];return e.showEquivalent!==!1&&y.unshift(`${r.dim(s.trim())} ${r.bold(e.equivalent.line)}`),e.envNotice===!0&&y.push(r.dim(Ge.envNotice)),y.join(`
463
+ `)};var fD=new Set([130,143]),qv=(e,t,r,n=!1)=>r?t!=null||e===0?"ok":"findings":n&&e!=null&&fD.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import gD from"node:process";var hD={3:"quit",4:"quit",26:"suspend",27:"quit"},yD=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":hD[t]??"continue"},vD=150,wD="\r\x1B[2K",kD=`\r
464
+ `,Yv=(e,t)=>{zv(e),e.stdin.on("data",t),e.listener=t},zv=e=>{e.listener!==null&&(e.stdin.off("data",e.listener),e.listener=null)},Xv=(e,t)=>{Yp(),e.stdin.setRawMode(!0),e.stdin.isPaused()&&e.stdin.resume(),Yv(e,t)},Zv=e=>{e.hintOnScreen&&(e.hintOnScreen=!1,e.deps.write(wD)),zv(e),e.stdin.isTTY===!0&&e.stdin.isRaw===!0&&e.stdin.setRawMode(!1),zp()},bD=e=>{e.settled||(e.settled=!0,Zv(e))},Qv=(e,t)=>{let r=Gv({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},RD=async e=>{await new Promise(t=>{setTimeout(t,e)})},SD=(e,t,r)=>{Zv(e),t(),Xv(e,r),Qv(e,kD)},PD=async e=>new Promise(t=>{let r=n=>{let o=yD(n),s=e.deps.suspend;if(o==="quit"){t("quit");return}if(o==="suspend"&&s!==void 0){SD(e,s,r);return}t("palette")};Yv(e,r),Qv(e,"")}),ew=async(e,t)=>{if(e.quitRequested())return"quit";let r=t.stdin??gD.stdin;if(r.isTTY!==!0)return"palette";let n={deps:t,stdin:r,listener:null,hintOnScreen:!1,settled:!1};try{return Xv(n,()=>{}),e.armed(),await RD(t.drainMs??vD),await PD(n)}finally{bD(n)}};import tw from"node:process";var Jt={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},rw=(e,t)=>{let r=t?.write??(s=>{tw.stderr.write(s)}),n=t?.stdin??tw.stdin,o=[Jt.saveCursor,Jt.scrollRegion,Jt.restoreCursor,Jt.column,Jt.sgr,Jt.cursor,Jt.wrap];e.entersAltScreen===!0&&o.push(Jt.primaryBuffer),r(o.join("")),n.isTTY===!0&&n.isRaw===!0&&n.setRawMode?.(!1)};var nw=e=>`infra-kit ${e.groupPath.join(" ")}`,TD=()=>{CD();let e=Ce.stderr.columns;return e!=null&&e>0?e:void 0},CD=()=>{let e=Ce.stderr;typeof e._refreshSize=="function"&&e._refreshSize()},$D=e=>new Promise(t=>{e.on("exit",(r,n)=>{t({code:r,signal:n})}),e.on("error",()=>{t({code:1,signal:null})})}),AD=async(e,t,r)=>{let n=Dv(),o={...t.env,[pa]:n,INFRA_KIT_NO_AUTO_UPDATE:"1"},s=t.now(),i={code:1,signal:null};r();try{let p=t.spawn(Ce.execPath,[t.cliPath,...e.groupPath],{stdio:"inherit",env:o});i=await $D(p)}catch{i={code:1,signal:null}}finally{t.resetTerminal({entersAltScreen:e.entersAltScreen})}let a=Nv(n),c=qv(i.code,i.signal,a!=null,e.longRunning),l=nw(e),d=a?.equivalent??da(l,!0);return Hv({equivalent:d,outcome:c,durationMs:t.now()-s,summary:a?.summary,envNotice:e.sessionEnvNotice,ascii:t.ascii,color:t.color,width:t.columns(),showEquivalent:!(d.reproducible&&d.line===l)})},OD=1e3,ID=(e,t)=>e!=null&&t-e<=OD,Gu=e=>{e.resetTerminal(),e.exit(0)},DD=(e,t)=>{let r=null,n=!1,o=()=>{let c=e();if(c==="child"){r=t.now();return}c!=="pause"&&Gu(t)},s=()=>{let c=e();if(c==="palette"){Gu(t);return}if(!ID(r,t.now())){if(c==="pause"){Gu(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}},ow=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),ND=Ce.platform==="win32"?void 0:()=>{Xp()},_D=(e,t)=>r=>ew(r,{write:e,columns:t.columns,ascii:t.ascii,color:t.color,suspend:ND}),sw=async(e,t)=>{let r={spawn:t.spawn??xD,now:t.now??(()=>Date.now()),env:t.env??Ce.env,cliPath:t.cliPath,ascii:t.ascii??!(Ce.stdout.isTTY&&Ce.env.TERM!=="dumb"),color:t.color??ED.level>0,columns:t.columns??TD,resetTerminal:t.resetTerminal??(d=>{rw(d)})},n=t.write??(d=>Ce.stderr.write(d)),o="palette",s=t.signals??{register:(d,p)=>{Ce.on(d,p)},unregister:(d,p)=>{Ce.off(d,p)},exit:d=>{Ce.exit(d)},raise:d=>{Ce.kill(Ce.pid,d)},now:()=>Date.now(),resetTerminal:()=>{o==="pause"&&n("\r\x1B[2K"),r.resetTerminal({entersAltScreen:!1})}},i={dispose:()=>{},childStarted:()=>{},quitRequested:()=>!1},a=t.installSignals===!1?i:DD(()=>o,s),c={armed:()=>{o="pause"},quitRequested:()=>a.quitRequested()},l=t.afterRun??_D(n,r);try{for(;;){if(a.quitRequested())return;o="palette";let d=await t.renderPalette(e);if(d==null)return;let p=t.resolveCommand(d);if(!p)continue;let m=Kv(nw(p),{color:r.color});n(`
455
465
  ${m}
456
- `),a.childStarted();let g=await gD(p,r,()=>{o="child"});if(n(`
466
+ `),a.childStarted();let g=await AD(p,r,()=>{o="child"});if(n(`
457
467
  ${g}
458
- `),await l(c)==="quit")return}}finally{a.dispose()}};su();Pv();var rw=Nu(),ew=async(e=Ce.argv)=>{Fu(),Jp(e);try{await rw.parseAsync(e)}catch(t){Ov(t)}},ED=()=>{try{if(Ce.env.INFRA_KIT_NO_LOCATION_WARN||Ce.argv.includes("--json"))return;Zu({selfRealPath:SD(tw(import.meta.url)),cwd:Ce.cwd(),env:Ce.env,realpath:he,home:PD(),exists:RD})&&u.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};ED();gp((e,t)=>{u.debug(e,t)});el(K.version);var nw=()=>jy(rw.commands),xD=async()=>{let e=nw(),t=null;try{if(Ce.stdout.isTTY&&Ce.stdin.isTTY){let{runCommandPalette:r}=await import("./boot-LC2ESPY6.js");t=await r(e)}else{let r=_u(e.map(o=>[o.name,o.description])),n=e.flatMap((o,s)=>[...e[s-1]?.group===o.group?[]:[new Qv(" "),new Qv(`\u2014 ${o.group} \u2014`)],{name:r[s]??o.name,value:o.name}]);t=await O(o=>bD({message:"Select a command to run",choices:n},o),{output:Ce.stderr})}}catch(r){if(!be(r))throw r}return t},TD=async()=>{let{runCommandPalette:e}=await import("./boot-LC2ESPY6.js"),t=tw(import.meta.url),r=new Map(lr.map(n=>[n.groupPath.join(" "),n]));await Zv(nw(),{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(Ce.argv.length<=2){let e={stdoutIsTTY:!!Ce.stdout.isTTY,stdinIsTTY:!!Ce.stdin.isTTY,stderrIsTTY:!!Ce.stderr.isTTY};if(Xv(Ce.env,e))await TD();else{let t=await xD();t&&await ew(["node","infra-kit",...t.split(" ")])}}else await ew();
468
+ `),await l(c)==="quit")return}}finally{a.dispose()}};cu();Ov();var lw=ju(),aw=async(e=$e.argv)=>{Wu(),Hp(e);try{await lw.parseAsync(e)}catch(t){Fv(t)}},BD=()=>{try{if($e.env.INFRA_KIT_NO_LOCATION_WARN||$e.argv.includes("--json"))return;tp({selfRealPath:FD(cw(import.meta.url)),cwd:$e.cwd(),env:$e.env,realpath:he,home:LD(),exists:jD})&&u.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};BD();vp((e,t)=>{u.debug(e,t)});rl(K.version);var dw=()=>Jy(lw.commands),WD=async()=>{let e=dw(),t=null;try{if($e.stdout.isTTY&&$e.stdin.isTTY){let{runCommandPalette:r}=await import("./boot-LC2ESPY6.js");t=await r(e)}else{let r=Fu(e.map(o=>[o.name,o.description])),n=e.flatMap((o,s)=>[...e[s-1]?.group===o.group?[]:[new iw(" "),new iw(`\u2014 ${o.group} \u2014`)],{name:r[s]??o.name,value:o.name}]);t=await O(o=>MD({message:"Select a command to run",choices:n},o),{output:$e.stderr})}}catch(r){if(!Re(r))throw r}return t},VD=async()=>{let{runCommandPalette:e}=await import("./boot-LC2ESPY6.js"),t=cw(import.meta.url),r=new Map(dr.map(n=>[n.groupPath.join(" "),n]));await sw(dw(),{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($e.argv.length<=2){let e={stdoutIsTTY:!!$e.stdout.isTTY,stdinIsTTY:!!$e.stdin.isTTY,stderrIsTTY:!!$e.stderr.isTTY};if(ow($e.env,e))await VD();else{let t=await WD();t&&await aw(["node","infra-kit",...t.split(" ")])}}else await aw();
459
469
  //# sourceMappingURL=cli.js.map