infra-kit 0.40.0 → 0.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
- import{c as Of,e as Jr,f as Lf,g as Wt,h as ui,i as Bf,j as Uf,k as Wf,l as Vf,m as Gf,n as Jf,o as Kf,p as Hf,s as Lc,t as zf,u as Oe}from"./chunk-TNT65LOE.js";import{a as Fm,b as Ue,c as Lm,d as Ec,e as Bm,f as Um,g as Wm,h as Vm,i as Xn,j as Gm,k as Jm,l as Km,m as Hm,n as qm,o as Zn,p as Ym,q as zm,r as Xm,s as Zm,t as Pc,u as Qs,v as jt,w as Qm,x as ei,y as ef}from"./chunk-PP44RGIU.js";import{a as ue,b as q,c as Bt,d as to,e as Ac,f as ii,g as ai,h as Oc,i as ro,j as ur,k as Dc,l as ci,m as Pf,n as St,o as no,p as Nc,q as _c,r as Mc,s as Nf,u as jc}from"./chunk-QS7RKE5P.js";import{b as zn,c as Xs,d as Sc,e as Im,f as Zs,g as Nm,i as _m,k as Mm,m as xe,o as jm}from"./chunk-REDCBY4O.js";import{a as Af}from"./chunk-V2ZLQPLI.js";import{B as so,D as Uc,H as Wc,I as Vc,a as b,b as C,c as _f,d as Mf,e as dr,f as jf,g as pr,h as Ff,i as Fc,j as qf,k as oo,l as Vt,m as Kr,n as it,o as di,p as Gt,q as Yf,r as pi,s as Xf,t as Zf,u as at,y as Bc}from"./chunk-KTWOAA5C.js";import{a as y,b as Et,c as xf,d as Tf,e as _,f as li,g as J,i as Ut,j as Qe,k as Df,l as Ic,m as If}from"./chunk-LSZFL3CV.js";import{$ as Ft,A as cf,B as lf,C as uf,D as ni,E as oi,F as Ce,G as Qn,H as Gr,I as si,J as df,K as pf,L as mf,M as Tc,N as Cc,O as ff,P as d,Q as We,R as oe,S as w,T as Ze,U as gf,V as hf,W as yf,X as O,Y as wf,Z as kf,_ as bf,a as lr,aa as Rf,b as D,ba as $c,c as tf,ca as Sf,d as j,da as Ef,e as he,ea as ee,f as X,fa as K,g as ti,ga as eo,h as rf,ha as Lt,i as g,j as nf,k as ri,l as Q,m as ke,n as Te,o as of,p as xc,q as le,r as ne,s as Wr,t as sf,u as st,v as be,w as $,x as Ae,y as Vr,z as af}from"./chunk-SIEUC4SP.js";import{a as vf}from"./chunk-MFAFQVTW.js";import{a as L}from"./chunk-T5WMUJID.js";import{a as Fr,b as Js,c as Ks,d as Yn,e as Cm,f as Lr,g as Hs,h as qs,i as $m,j as Ys,k as zs,l as Am,m as Om,n as Rt,o as Br,p as Mt,q as ge,r as Dm,s as Ur}from"./chunk-GCOYOWGH.js";import{a as Cf,b as $f}from"./chunk-QWVLAZ6N.js";import RL,{Separator as hR}from"@inquirer/select";import{existsSync as SL,realpathSync as EL}from"node:fs";import{homedir as PL}from"node:os";import Be from"node:process";import{fileURLToPath as vR}from"node:url";import Qg from"node:process";import{z as Ne}from"zod";import ig from"node:fs";import qr from"node:path";import{packageConfigSchema as tg}from"@slip-stream-kit/config/internal";import rg from"node:fs/promises";import mi from"node:path";import{pathToFileURL as TR}from"node:url";import{z as ng}from"zod";import Qf from"node:path";var io=["frontend","backend","lib","e2e","mobile"],bR={ui:"frontend",api:"backend",tests:"e2e"},RR="mobile-app",SR=[{type:"e2e",packages:["@playwright/test"]},{type:"mobile",packages:["@capacitor/core","@capacitor/cli"]},{type:"backend",packages:["serverless"]}],ER=(e,t)=>{let r=Qf.relative(t,e).split(Qf.sep).filter(s=>s!==""&&s!=="."),[n,,o]=r;if(r.length===3&&n==="apps"&&o!==void 0){let s=bR[o];if(s)return s}return r.at(-1)===RR?"mobile":null},PR=e=>{let t=new Set([...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{}),...Object.keys(e.peerDependencies??{})]);for(let n of SR)if(n.packages.some(o=>t.has(o)))return n.type;return t.has("vite")&&t.has("react")&&!!e.scripts?.dev?"frontend":null},ao=({packageDir:e,repoRoot:t,pkgJson:r,declaredType:n})=>n??ER(e,t)??PR(r)??"lib";var ct={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},eg=2e3,Gc={"e2e-test":"pnpm exec playwright test","e2e-test-ui":"pnpm exec playwright test --ui","e2e-test-ui-demo":`E2E_SLOW_MO=\${E2E_SLOW_MO:-${eg}} 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"},mr={requiredScripts:["build","test","qa","infra-kit-check","fix"],requiredFiles:["turbo.json","pnpm-workspace.yaml"],turboTasks:["build","test","ts-check","eslint-check","prettier-check","infra-kit-check"]},co=(e,t=ct)=>({requiredScripts:e.requiredScripts??[...t.requiredScripts],requiredFiles:e.requiredFiles??[...t.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...t.turboTasks]});import xR from"node:fs/promises";var De=async e=>{try{return await xR.access(e),!0}catch{return!1}};var de="infra-kit.config.ts",fr=async e=>{try{let t=await rg.readFile(mi.join(e,"package.json"),"utf-8");return JSON.parse(t)}catch{return{}}},Jc=async e=>{let t=await rg.stat(e),o=(await import(`${TR(e).href}?mtime=${Number(t.mtimeMs)}`)).default;if(o===void 0)throw new Error(`${de} at ${e} has no default export`);return typeof o=="function"?await o():o},Pt=async e=>{let t=mi.join(e,de);if(await De(t))try{let n=(await Jc(t))?.type;return io.find(o=>o===n)}catch{return}},og=e=>e,lo=async(e,t=ct)=>{let r=mi.join(e,de);if(!await De(r))throw new Error(`${de} not found at ${r}`);let n=await Jc(r),o=tg.safeParse(n);if(!o.success)throw new Error(`Invalid ${de} at ${r}: ${ng.prettifyError(o.error)}`);return co(og(o.data),t)},lt=async e=>{let t=mi.join(e,de);if(!await De(t))return;let r=tg.safeParse(await Jc(t));if(!r.success)throw new Error(`Invalid ${de} at ${t}: ${ng.prettifyError(r.error)}`);return og(r.data)};import sg from"node:fs/promises";import fi from"node:path";import CR from"yaml";var $R="pnpm-workspace.yaml",AR=async e=>(await sg.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(r=>r.isDirectory()).map(r=>fi.join(e,r.name)),OR=async(e,t)=>{let r=[];for(let n of e){if(t==="*"){r.push(...await AR(n));continue}let o=fi.join(n,t);await De(o)&&r.push(o)}return r},DR=async(e,t)=>{let r=[e];for(let n of t.split("/"))r=await OR(r,n);return r},Re=async e=>{let t=await sg.readFile(fi.join(e,$R),"utf-8"),n=((CR.parse(t)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),o=new Set;for(let s of n){let i=await DR(e,s);for(let a of i)await De(fi.join(a,"package.json"))&&o.add(a)}return[...o].sort()};import uo from"node:path";var po=async e=>{let t=uo.resolve(e);for(;t!==uo.dirname(t);){if(await De(uo.join(t,"package.json")))return t;t=uo.dirname(t)}if(await De(uo.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 Ve=(e,t,r)=>{let n=e.indexOf(t),o=e.indexOf(r);return n!==-1&&o!==-1&&o>=n},Jt=(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}`:"")},gr=(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},gi=(e,t,r)=>`${e}
2
+ import{c as Ff,e as Yr,f as Kf,g as Vt,h as fi,i as Hf,j as qf,k as Yf,l as zf,m as Xf,n as Zf,o as Qf,p as eg,s as Gc,t as ng,u as Ie}from"./chunk-2SDWSDM2.js";import{a as Jm,b as Ge,c as Km,d as Cc,e as Hm,f as qm,g as Ym,h as zm,i as no,j as Xm,k as Zm,l as Qm,m as ef,n as tf,o as oo,p as rf,q as nf,r as of,s as sf,t as $c,u as ni,v as Lt,w as af,x as oi,y as cf}from"./chunk-PP44RGIU.js";import{a as de,b as z,c as Wt,d as ao,e as Nc,f as ui,g as di,h as _c,i as co,j as pr,k as Mc,l as pi,m as Df,n as Pt,o as lo,p as Fc,q as Lc,r as Bc,s as Uf,u as Uc}from"./chunk-QS7RKE5P.js";import{b as ro,c as ti,d as Tc,e as Bm,f as ri,g as Um,i as Wm,k as Gm,m as Ce,o as Vm}from"./chunk-REDCBY4O.js";import{a as jf}from"./chunk-V2ZLQPLI.js";import{B as po,D as Jc,H as Kc,I as Hc,a as R,b as C,c as Wf,d as Gf,e as mr,f as Vf,g as fr,h as Jf,i as Wc,j as tg,k as uo,l as Jt,m as zr,n as ct,o as gi,p as Kt,q as rg,r as hi,s as og,t as sg,u as lt,y as Vc}from"./chunk-A67SJCCI.js";import{a as y,b as xt,c as If,d as Nf,e as M,f as mi,g as H,i as Gt,j as tt,k as Lf,l as jc,m as Bf}from"./chunk-6EGHDLFA.js";import{$ as Bt,A as gf,B as hf,C as yf,D as ai,E as ci,F as Ae,G as so,H as qr,I as li,J as vf,K as wf,L as kf,M as Oc,N as Dc,O as bf,P as d,Q as Ve,R as se,S as w,T as et,U as Rf,V as Sf,W as Ef,X as D,Y as xf,Z as Tf,_ as Cf,a as dr,aa as $f,b as I,ba as Ic,c as lf,ca as Af,d as F,da as Of,e as ye,ea as Y,f as Q,fa as J,g as si,ga as io,h as uf,ha as Ut,i as g,j as df,k as ii,l as ee,m as Re,n as $e,o as pf,p as Ac,q as ue,r as oe,s as Kr,t as mf,u as at,v as Se,w as A,x as De,y as Hr,z as ff}from"./chunk-4G7F5ELE.js";import{a as Pf}from"./chunk-MFAFQVTW.js";import{a as U}from"./chunk-KFQKVU6O.js";import{a as Wr,b as Ys,c as zs,d as to,e as _m,f as Gr,g as Xs,h as Zs,i as Mm,j as Qs,k as ei,l as jm,m as Fm,n as Et,o as Vr,p as Ft,q as he,r as Lm,s as Jr}from"./chunk-GCOYOWGH.js";import{a as _f,b as Mf}from"./chunk-QWVLAZ6N.js";import OL,{Separator as kR}from"@inquirer/select";import{existsSync as DL,realpathSync as IL}from"node:fs";import{homedir as NL}from"node:os";import We from"node:process";import{fileURLToPath as RR}from"node:url";import ih from"node:process";import{z as Me}from"zod";import mg from"node:fs";import Zr from"node:path";import{packageConfigSchema as cg}from"@slip-stream-kit/config/internal";import lg from"node:fs/promises";import yi from"node:path";import{pathToFileURL as OR}from"node:url";import{z as ug}from"zod";import ig from"node:path";var mo=["frontend","backend","lib","e2e","mobile"],PR={ui:"frontend",api:"backend",tests:"e2e"},xR="mobile-app",TR=[{type:"e2e",packages:["@playwright/test"]},{type:"mobile",packages:["@capacitor/core","@capacitor/cli"]},{type:"backend",packages:["serverless"]}],CR=(e,t)=>{let r=ig.relative(t,e).split(ig.sep).filter(s=>s!==""&&s!=="."),[n,,o]=r;if(r.length===3&&n==="apps"&&o!==void 0){let s=PR[o];if(s)return s}return r.at(-1)===xR?"mobile":null},$R=e=>{let t=new Set([...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{}),...Object.keys(e.peerDependencies??{})]);for(let n of TR)if(n.packages.some(o=>t.has(o)))return n.type;return t.has("vite")&&t.has("react")&&!!e.scripts?.dev?"frontend":null},fo=({packageDir:e,repoRoot:t,pkgJson:r,declaredType:n})=>n??CR(e,t)??$R(r)??"lib";var ut={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},ag=2e3,qc={"e2e-test":"pnpm exec playwright test","e2e-test-ui":"pnpm exec playwright test --ui","e2e-test-ui-demo":`E2E_SLOW_MO=\${E2E_SLOW_MO:-${ag}} 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"},gr={requiredScripts:["build","test","qa","infra-kit-check","fix"],requiredFiles:["turbo.json","pnpm-workspace.yaml"],turboTasks:["build","test","ts-check","eslint-check","prettier-check","infra-kit-check"]},go=(e,t=ut)=>({requiredScripts:e.requiredScripts??[...t.requiredScripts],requiredFiles:e.requiredFiles??[...t.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...t.turboTasks]});import AR from"node:fs/promises";var Ne=async e=>{try{return await AR.access(e),!0}catch{return!1}};var pe="infra-kit.config.ts",hr=async e=>{try{let t=await lg.readFile(yi.join(e,"package.json"),"utf-8");return JSON.parse(t)}catch{return{}}},Yc=async e=>{let t=await lg.stat(e),o=(await import(`${OR(e).href}?mtime=${Number(t.mtimeMs)}`)).default;if(o===void 0)throw new Error(`${pe} at ${e} has no default export`);return typeof o=="function"?await o():o},Tt=async e=>{let t=yi.join(e,pe);if(await Ne(t))try{let n=(await Yc(t))?.type;return mo.find(o=>o===n)}catch{return}},dg=e=>e,ho=async(e,t=ut)=>{let r=yi.join(e,pe);if(!await Ne(r))throw new Error(`${pe} not found at ${r}`);let n=await Yc(r),o=cg.safeParse(n);if(!o.success)throw new Error(`Invalid ${pe} at ${r}: ${ug.prettifyError(o.error)}`);return go(dg(o.data),t)},dt=async e=>{let t=yi.join(e,pe);if(!await Ne(t))return;let r=cg.safeParse(await Yc(t));if(!r.success)throw new Error(`Invalid ${pe} at ${t}: ${ug.prettifyError(r.error)}`);return dg(r.data)};import pg from"node:fs/promises";import vi from"node:path";import DR from"yaml";var IR="pnpm-workspace.yaml",NR=async e=>(await pg.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(r=>r.isDirectory()).map(r=>vi.join(e,r.name)),_R=async(e,t)=>{let r=[];for(let n of e){if(t==="*"){r.push(...await NR(n));continue}let o=vi.join(n,t);await Ne(o)&&r.push(o)}return r},MR=async(e,t)=>{let r=[e];for(let n of t.split("/"))r=await _R(r,n);return r},Ee=async e=>{let t=await pg.readFile(vi.join(e,IR),"utf-8"),n=((DR.parse(t)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),o=new Set;for(let s of n){let i=await MR(e,s);for(let a of i)await Ne(vi.join(a,"package.json"))&&o.add(a)}return[...o].sort()};import yo from"node:path";var vo=async e=>{let t=yo.resolve(e);for(;t!==yo.dirname(t);){if(await Ne(yo.join(t,"package.json")))return t;t=yo.dirname(t)}if(await Ne(yo.join(t,"package.json")))return t;throw new Error(`No package.json found in or above ${e} \u2014 cd into a package directory, or pass --root to audit a monorepo root`)};var Je=(e,t,r)=>{let n=e.indexOf(t),o=e.indexOf(r);return n!==-1&&o!==-1&&o>=n},Ht=(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}`:"")},yr=(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},wi=(e,t,r)=>`${e}
4
4
  ${t}
5
- ${r}`,Hr=({content:e,body:t,startMarker:r,endMarker:n,placement:o="replace-in-place"})=>{let s=gi(r,t,n),i=Ve(e,r,n);if(o==="replace-in-place"&&i){let l=e.indexOf(r),u=e.indexOf(n)+n.length;return e.slice(0,l)+s+e.slice(u)}let c=(i?Jt(e,r,n)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
5
+ ${r}`,Xr=({content:e,body:t,startMarker:r,endMarker:n,placement:o="replace-in-place"})=>{let s=wi(r,t,n),i=Je(e,r,n);if(o==="replace-in-place"&&i){let l=e.indexOf(r),u=e.indexOf(n)+n.length;return e.slice(0,l)+s+e.slice(u)}let c=(i?Ht(e,r,n)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
6
6
  ${s}
7
7
  `:`${s}
8
- `};var Se="<!-- infra-kit:begin -->",Ie="<!-- infra-kit:end -->",hr="<!-- infra-kit:version ",Ge="<!-- infra-kit:package:begin -->",et="<!-- infra-kit:package:end -->",xt="<!-- infra-kit:package:version ";var IR=e=>{let t=e.indexOf(Ge)+Ge.length;return e.slice(t,e.indexOf(et))},NR=e=>{let t=e.indexOf(xt);if(t===-1)return null;let r=e.slice(t+xt.length).match(/^\S+\s+([^\s>]+)/)?.[1];return io.find(n=>n===r)??null},Tt=e=>{if(e===null)return{state:"missing"};if(!Ve(e,Ge,et))return e.includes(Ge)||e.includes(et)?{state:"malformed"}:Ve(e,Se,Ie)?{state:"foreign-block"}:{state:"no-block"};let t=IR(e);if(t.trim()==="")return{state:"malformed"};let r={state:"ok"},n=gr(t,xt),o=NR(t);return n!==null&&(r.version=n),o!==null&&(r.type=o),r};import _R from"node:fs";var ut=e=>{try{return _R.readFileSync(e,"utf-8")}catch{return null}};var ag="pnpm-workspace.yaml",MR="CLAUDE.md",Hc=e=>{let t=qr.resolve(e);for(;t!==qr.dirname(t);){if(ig.existsSync(qr.join(t,ag)))return t;t=qr.dirname(t)}return ig.existsSync(qr.join(t,ag))?t:null},Kc=new Map,hi=()=>{Kc.clear()},jR=async e=>{let t;try{t=await Re(e)}catch{return{adopted:!1,workspaceRoot:e}}for(let r of t){let n=qr.join(r,MR),o=ut(n);if(o!==null&&Tt(o).state==="ok")return{adopted:!0,workspaceRoot:e,evidencePath:n}}return{adopted:!1,workspaceRoot:e}},Yr=async e=>{if(e===null)return{adopted:!1,workspaceRoot:null};let t=Kc.get(e);if(t)return t;let r=await jR(e);return Kc.set(e,r),r};import yr from"node:fs";import Kt from"node:path";var cg=`---
8
+ `};var Pe="<!-- infra-kit:begin -->",_e="<!-- infra-kit:end -->",vr="<!-- infra-kit:version ",Ke="<!-- infra-kit:package:begin -->",rt="<!-- infra-kit:package:end -->",Ct="<!-- infra-kit:package:version ";var jR=e=>{let t=e.indexOf(Ke)+Ke.length;return e.slice(t,e.indexOf(rt))},FR=e=>{let t=e.indexOf(Ct);if(t===-1)return null;let r=e.slice(t+Ct.length).match(/^\S+\s+([^\s>]+)/)?.[1];return mo.find(n=>n===r)??null},$t=e=>{if(e===null)return{state:"missing"};if(!Je(e,Ke,rt))return e.includes(Ke)||e.includes(rt)?{state:"malformed"}:Je(e,Pe,_e)?{state:"foreign-block"}:{state:"no-block"};let t=jR(e);if(t.trim()==="")return{state:"malformed"};let r={state:"ok"},n=yr(t,Ct),o=FR(t);return n!==null&&(r.version=n),o!==null&&(r.type=o),r};import LR from"node:fs";var pt=e=>{try{return LR.readFileSync(e,"utf-8")}catch{return null}};var fg="pnpm-workspace.yaml",BR="CLAUDE.md",Xc=e=>{let t=Zr.resolve(e);for(;t!==Zr.dirname(t);){if(mg.existsSync(Zr.join(t,fg)))return t;t=Zr.dirname(t)}return mg.existsSync(Zr.join(t,fg))?t:null},zc=new Map,ki=()=>{zc.clear()},UR=async e=>{let t;try{t=await Ee(e)}catch{return{adopted:!1,workspaceRoot:e}}for(let r of t){let n=Zr.join(r,BR),o=pt(n);if(o!==null&&$t(o).state==="ok")return{adopted:!0,workspaceRoot:e,evidencePath:n}}return{adopted:!1,workspaceRoot:e}},Qr=async e=>{if(e===null)return{adopted:!1,workspaceRoot:null};let t=zc.get(e);if(t)return t;let r=await UR(e);return zc.set(e,r),r};import wr from"node:fs";import qt from"node:path";var gg=`---
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 lg=`# {{packageName}}
77
+ `;var hg=`# {{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 ug="# {{packageName}}\n\nWorkspace package at `{{relDir}}` \u2014 type: **{{type}}**.\nThis block is generated by `infra-kit audit --fix` \u2014 edit text _outside_ the markers, never inside.\n\n## Read first\n\n- {{readmeBullet}}\n- `infra-kit.config.ts` \u2014 the audit rules this package must satisfy.\n\n## Checks\n\n- `infra-kit audit` \u2014 validate this package against its infra-kit rules.\n- {{checksBullet}}\n- `pnpm run qa` at the repo root \u2014 the full gate; run it before claiming completion.\n\n## Rules\n\n- Specs run on Playwright. The `e2e-test*` scripts and the `E2E_SLOW_MO` / trace settings in `playwright.config.ts` are shared across repos and checked by `infra-kit audit` \u2014 never rename or fork them locally.\n- {{e2eDocBullet}}\n- `e2e-test-ui-demo` (visible browser, one worker) is for showing a flow to a person. It sets `E2E_SLOW_MO=2000` \u2014 2 s before every action \u2014 unless the variable is already set; debug with `e2e-test-ui` instead, and everywhere else `E2E_SLOW_MO` stays unset, which the config reads as 0.\n- HTTP Basic Auth credentials are `E2E__BASIC_AUTH_USERNAME` / `E2E__BASIC_AUTH_PASSWORD` (double underscore) in every suite \u2014 the names the dev proxy injects and the loaded env provides. 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`, the release pass is `/infra-kit:ultraqa`) or wherever `CI` is set (no dev server can run there), against the URL the loaded env holds in the target app's `deployedUrlEnv` (`ik env-load -c <env>`). Read the base URL from Playwright's `baseURL`, never from that variable: locally it still holds the deployed URL. The one exception is a suite that must run against a production build it serves itself: it declares `e2e: { server: 'static' }` in `infra-kit.config.ts` and sets `baseURL` and `webServer` itself.\n\n## Structure\n\n- Specs live in `src/tests/<domain>/`, one folder per business domain \u2014 never per page, browser, device, or environment (those are Playwright projects).\n- A domain folder's root holds only its `*.spec.ts` files. Everything else always goes in a subfolder, even a single file: `pages/` (`.page.ts`, `.component.ts`), `fixtures/` (`.fixture.ts`), `mocks/` (`.mock.ts`), `data/` (`.data.ts`), `lib/` (domain-private helpers).\n- Never nest specs in subfolders \u2014 when a domain has too many specs to scan, split it into two domains (`luggage/`, `luggage-pricing/`).\n- Anything two domains share moves up to `src/pages/`, `src/fixtures/`, `src/mocks/`, or `src/lib/`; a domain never imports from a sibling domain.\n- API and contract specs stay in their domain folder, told apart by suffix: `<flow>.api.spec.ts`, `<flow>.contract.spec.ts`. A suffix exists only when that suite runs in its own Playwright project.\n- Visual-regression specs live in `src/visual/<domain>/<flow>.visual.spec.ts`, so baseline screenshots stay out of the domain folders.\n- Auth and data preparation are `src/setup/*.setup.ts` / `*.teardown.ts`, wired as Playwright setup projects \u2014 never `globalSetup`. Saved auth state goes to the gitignored `.auth/`.\n\n## Naming\n\n- Every Playwright spec is `*.spec.ts`; `.test.ts` is never used in an e2e package.\n- Files and folders are kebab-case.\n- A spec file names a stable flow: `<feature-or-flow>.spec.ts`. No ticket ids, sequence numbers, or `common` / `main` / `smoke`.\n- Non-spec files never carry `.spec` / `.test`. A spec never imports another spec.\n- `describe` is a short domain context in Title Case (`Checkout`).\n- `test` is a lowercase behaviour phrase \u2014 action or condition plus the observable outcome (`rejects an expired coupon without changing the total`). No `should`, `test \u2026`, `works`, or case numbers.\n- `test.step` is a verb plus a business operation (`Pay with the saved card`), 3\u20136 per long flow \u2014 never one step per click or fill.\n- Screenshot baselines are named by UI state (`checkout-payment-error.png`), never `screenshot-1.png`.\n\n## Tags\n\nRun categories are tags (`{ tag: [...] }`), never file names. Only these four exist:\n\n- `@smoke` \u2014 the fast post-deploy check; every domain has at least one.\n- `@readonly` \u2014 creates and changes nothing, so it is safe against any shared environment.\n- `@mocked` \u2014 every backend call is mocked; runs without a live API.\n- `@slow` \u2014 excluded from local runs with `--grep-invert @slow`.\n\nNever tag a browser, device, or environment, and never add `@flaky`; fix the test, or skip it with a linked issue once a person approves (see Repair).\n\nLint enforces the mechanical part: `@wl/e2e-file-layout` the Structure folders and the `.spec.ts` suffix, `@wl/e2e-file-order` imports first and then the class, the `extend` call, the `test.*` calls, the mock function or a `lib/` file's exports \u2014 constants and helpers below, `@wl/e2e-page-object-member-order` fields \u2192 constructor \u2192 getters \u2192 public \u2192 private methods, `@wl/e2e-top-level-describe` one top-level describe holding the setup, hooks and tests, `@wl/e2e-describe-order` setup \u2192 hooks \u2192 tests inside it, `@wl/e2e-test-tags` the tag list, `@wl/e2e-test-title` the missing `should`. The rest of Naming \u2014 `describe` in Title Case, no ticket ids, outcome-bearing titles, `test.step` wording \u2014 is on the author and the reviewer.\n\n## Repair\n\nFor a failing spec, before editing anything:\n\n- Classify the failure: product defect, intentional product change, test defect, test data or environment, or flake. Say which, and why, in the change.\n- Diagnose from `infra-kit e2e --json`: read `failures[]` (title, `file:line`, error) and open its `tracePath` with `pnpm exec playwright show-trace`, rather than reading the full log. Re-run one test with `infra-kit e2e --json -- <spec> --grep \"<title>\"`.\n- Never take the expected behaviour from what the UI shows now. It comes from the spec's intent, the ticket, or a person; when it is unclear, stop and report instead of editing.\n- Never without a person's explicit approval: delete or weaken an assertion, add `test.skip` / `test.fixme` / `test.fail`, update a snapshot or visual baseline, widen a timeout, or add retries. A product defect is reported, not tested around.\n";var dg="# {{packageName}}\n\nWorkspace package at `{{relDir}}` \u2014 type: **{{type}}**.\nThis block is generated by `infra-kit audit --fix` \u2014 edit text _outside_ the markers, never inside.\n\n## Read first\n\n- {{readmeBullet}}\n- `DESIGN.md` \u2014 the visual language (colors, typography, spacing, components). It is the source of truth for UI decisions; if it is absent, ask before inventing one.\n- `infra-kit.config.ts` \u2014 the audit rules this package must satisfy.\n\n## Checks\n\n- `infra-kit audit` \u2014 validate this package against its infra-kit rules.\n- {{checksBullet}}\n- `pnpm run qa` at the repo root \u2014 the full gate; run it before claiming completion.\n\n## Rules\n\n- Start the app with `infra-kit dev`, never a bare `vite` \u2014 dev URLs are proxied and port-free.\n- Backend calls go through the path prefixes declared in `dev.proxy` in `infra-kit.config.ts`. Never hardcode an API base URL or a port.\n- A loaded env var that breaks local dev \u2014 one meant for another build mode, e.g. a mobile-only absolute origin that bypasses the proxy \u2014 goes in `dev.env.unset` (or `dev.env.set` to override it) in `infra-kit.config.ts`. Never remove it from Doppler or patch it out in `vite.config.ts`.\n- Use the tokens in `DESIGN.md` rather than ad-hoc colors, spacing, or type scales.\n";var pg=`# {{packageName}}
98
+ `;var yg="# {{packageName}}\n\nWorkspace package at `{{relDir}}` \u2014 type: **{{type}}**.\nThis block is generated by `infra-kit audit --fix` \u2014 edit text _outside_ the markers, never inside.\n\n## Read first\n\n- {{readmeBullet}}\n- `infra-kit.config.ts` \u2014 the audit rules this package must satisfy.\n\n## Checks\n\n- `infra-kit audit` \u2014 validate this package against its infra-kit rules.\n- {{checksBullet}}\n- `pnpm run qa` at the repo root \u2014 the full gate; run it before claiming completion.\n\n## Rules\n\n- Specs run on Playwright. The `e2e-test*` scripts and the `E2E_SLOW_MO` / trace settings in `playwright.config.ts` are shared across repos and checked by `infra-kit audit` \u2014 never rename or fork them locally.\n- {{e2eDocBullet}}\n- `e2e-test-ui-demo` (visible browser, one worker) is for showing a flow to a person. It sets `E2E_SLOW_MO=2000` \u2014 2 s before every action \u2014 unless the variable is already set; debug with `e2e-test-ui` instead, and everywhere else `E2E_SLOW_MO` stays unset, which the config reads as 0.\n- HTTP Basic Auth credentials are `E2E__BASIC_AUTH_USERNAME` / `E2E__BASIC_AUTH_PASSWORD` (double underscore) in every suite \u2014 the names the dev proxy injects and the loaded env provides. 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`, the release pass is `/infra-kit:ultraqa`) or wherever `CI` is set (no dev server can run there), against the URL the loaded env holds in the target app's `deployedUrlEnv` (`ik env-load -c <env>`). Read the base URL from Playwright's `baseURL`, never from that variable: locally it still holds the deployed URL. The one exception is a suite that must run against a production build it serves itself: it declares `e2e: { server: 'static' }` in `infra-kit.config.ts` and sets `baseURL` and `webServer` itself.\n\n## Structure\n\n- Specs live in `src/tests/<domain>/`, one folder per business domain \u2014 never per page, browser, device, or environment (those are Playwright projects).\n- A domain folder's root holds only its `*.spec.ts` files. Everything else always goes in a subfolder, even a single file: `pages/` (`.page.ts`, `.component.ts`), `fixtures/` (`.fixture.ts`), `mocks/` (`.mock.ts`), `data/` (`.data.ts`), `lib/` (domain-private helpers).\n- Never nest specs in subfolders \u2014 when a domain has too many specs to scan, split it into two domains (`luggage/`, `luggage-pricing/`).\n- Anything two domains share moves up to `src/pages/`, `src/fixtures/`, `src/mocks/`, or `src/lib/`; a domain never imports from a sibling domain.\n- API and contract specs stay in their domain folder, told apart by suffix: `<flow>.api.spec.ts`, `<flow>.contract.spec.ts`. A suffix exists only when that suite runs in its own Playwright project.\n- Visual-regression specs live in `src/visual/<domain>/<flow>.visual.spec.ts`, so baseline screenshots stay out of the domain folders.\n- Auth and data preparation are `src/setup/*.setup.ts` / `*.teardown.ts`, wired as Playwright setup projects \u2014 never `globalSetup`. Saved auth state goes to the gitignored `.auth/`.\n\n## Naming\n\n- Every Playwright spec is `*.spec.ts`; `.test.ts` is never used in an e2e package.\n- Files and folders are kebab-case.\n- A spec file names a stable flow: `<feature-or-flow>.spec.ts`. No ticket ids, sequence numbers, or `common` / `main` / `smoke`.\n- Non-spec files never carry `.spec` / `.test`. A spec never imports another spec.\n- `describe` is a short domain context in Title Case (`Checkout`).\n- `test` is a lowercase behaviour phrase \u2014 action or condition plus the observable outcome (`rejects an expired coupon without changing the total`). No `should`, `test \u2026`, `works`, or case numbers.\n- `test.step` is a verb plus a business operation (`Pay with the saved card`), 3\u20136 per long flow \u2014 never one step per click or fill.\n- Screenshot baselines are named by UI state (`checkout-payment-error.png`), never `screenshot-1.png`.\n\n## Tags\n\nRun categories are tags (`{ tag: [...] }`), never file names. Only these four exist:\n\n- `@smoke` \u2014 the fast post-deploy check; every domain has at least one.\n- `@readonly` \u2014 creates and changes nothing, so it is safe against any shared environment.\n- `@mocked` \u2014 every backend call is mocked; runs without a live API.\n- `@slow` \u2014 excluded from local runs with `--grep-invert @slow`.\n\nNever tag a browser, device, or environment, and never add `@flaky`; fix the test, or skip it with a linked issue once a person approves (see Repair).\n\nLint enforces the mechanical part: `@wl/e2e-file-layout` the Structure folders and the `.spec.ts` suffix, `@wl/e2e-file-order` imports first and then the class, the `extend` call, the `test.*` calls, the mock function or a `lib/` file's exports \u2014 constants and helpers below, `@wl/e2e-page-object-member-order` fields \u2192 constructor \u2192 getters \u2192 public \u2192 private methods, `@wl/e2e-top-level-describe` one top-level describe holding the setup, hooks and tests, `@wl/e2e-describe-order` setup \u2192 hooks \u2192 tests inside it, `@wl/e2e-test-tags` the tag list, `@wl/e2e-test-title` the missing `should`. The rest of Naming \u2014 `describe` in Title Case, no ticket ids, outcome-bearing titles, `test.step` wording \u2014 is on the author and the reviewer.\n\n## Repair\n\nFor a failing spec, before editing anything:\n\n- Classify the failure: product defect, intentional product change, test defect, test data or environment, or flake. Say which, and why, in the change.\n- Diagnose from `infra-kit e2e --json`: read `failures[]` (title, `file:line`, error) and open its `tracePath` with `pnpm exec playwright show-trace`, rather than reading the full log. Re-run one test with `infra-kit e2e --json -- <spec> --grep \"<title>\"`.\n- Never take the expected behaviour from what the UI shows now. It comes from the spec's intent, the ticket, or a person; when it is unclear, stop and report instead of editing.\n- Never without a person's explicit approval: delete or weaken an assertion, add `test.skip` / `test.fixme` / `test.fail`, update a snapshot or visual baseline, widen a timeout, or add retries. A product defect is reported, not tested around.\n";var vg="# {{packageName}}\n\nWorkspace package at `{{relDir}}` \u2014 type: **{{type}}**.\nThis block is generated by `infra-kit audit --fix` \u2014 edit text _outside_ the markers, never inside.\n\n## Read first\n\n- {{readmeBullet}}\n- `DESIGN.md` \u2014 the visual language (colors, typography, spacing, components). It is the source of truth for UI decisions; if it is absent, ask before inventing one.\n- `infra-kit.config.ts` \u2014 the audit rules this package must satisfy.\n\n## Checks\n\n- `infra-kit audit` \u2014 validate this package against its infra-kit rules.\n- {{checksBullet}}\n- `pnpm run qa` at the repo root \u2014 the full gate; run it before claiming completion.\n\n## Rules\n\n- Start the app with `infra-kit dev`, never a bare `vite` \u2014 dev URLs are proxied and port-free.\n- Backend calls go through the path prefixes declared in `dev.proxy` in `infra-kit.config.ts`. Never hardcode an API base URL or a port.\n- A loaded env var that breaks local dev \u2014 one meant for another build mode, e.g. a mobile-only absolute origin that bypasses the proxy \u2014 goes in `dev.env.unset` (or `dev.env.set` to override it) in `infra-kit.config.ts`. Never remove it from Doppler or patch it out in `vite.config.ts`.\n- Use the tokens in `DESIGN.md` rather than ad-hoc colors, spacing, or type scales.\n";var wg=`# {{packageName}}
99
99
 
100
100
  Workspace package at \`{{relDir}}\` \u2014 type: **{{type}}**.
101
101
  This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_ the markers, never inside.
@@ -116,7 +116,7 @@ This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_
116
116
  - {{surfaceBullet}}
117
117
  - {{buildBullet}}
118
118
  - No app-specific logic belongs here.
119
- `;var mg=`# {{packageName}}
119
+ `;var kg=`# {{packageName}}
120
120
 
121
121
  Workspace package at \`{{relDir}}\` \u2014 type: **{{type}}**.
122
122
  This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_ the markers, never inside.
@@ -138,49 +138,49 @@ This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_
138
138
  - The native shell is Capacitor; its settings live in \`capacitor.config.*\`.
139
139
  - The web build feeds the native shell, so a device run needs a rebuild first.
140
140
  - Use the tokens in \`DESIGN.md\` rather than ad-hoc colors, spacing, or type scales.
141
- `;var fg="# infra-kit\n\nThis repository uses the **infra-kit** CLI for environment, worktree, and release workflows.\nThis block is generated by `ik audit --fix --root` \u2014 edit text _outside_ the markers, never inside.\n\n## Commands (`ik` = `infra-kit`, the global CLI)\n\n- `ik env-load [-c <config>]` / `ik env-clear` / `ik env-status` \u2014 load, clear, or inspect Doppler env vars for a config (e.g. `dev`). Source the returned file to apply. Without `-c`, an agent loads the project's `defaultEnv` (set yours with `ik config-set defaultEnv <env>`); with none set it is refused and must ask the human.\n- `ik dev [app]` / `ik dev-status` \u2014 run this worktree's dev servers, or report what is running. An app (`ik dev client`) runs its api and ui plus every backend its proxy routes can run locally; no name runs every app. App names are per-repo: an unknown one is refused with the apps as choices, never guess one.\n- `ik e2e [--app <app>]` \u2014 run an app's Playwright suite locally: against this worktree's dev server when it runs, otherwise the package's `infraKitE2e()` Playwright config starts `ik dev <app> --reuse` for the run and stops it after. Plain `playwright test` / `pnpm e2e-test` behave the same way. `--cloud` runs against the deployed app instead \u2014 the URL the loaded env (`ik env-load -c <env>`) holds in the target app's `deployedUrlEnv` \u2014 previews, and needs `--yes`; `--dry-run` prints the target.\n- `ik worktrees add` / `worktrees list` / `worktrees remove` / `worktrees sync` \u2014 manage release and feature git worktrees. `ik worktrees add --feature <name> [--base <dev|main|release>]` creates `feature/<name>` at `<root>-worktrees/feature/<name>`, cut from `dev` by default (the default branch in a repo without `dev`); `worktrees remove --feature <name>` removes it. To close the worktree a session runs in (\"close this worktree\"), run `infra-kit worktrees remove --self` from inside it: it previews, and its `--yes` re-run hands the removal to an Orca tab of the main checkout, which closes every tab of the worktree \u2014 this session included. The `/infra-kit:worktrees` skill is the agent entry point for feature worktrees \u2014 never create one with raw `git worktree add` or Claude Code's `EnterWorktree`, which skip `pnpm install`, the editor/Orca wiring and the `feature/` layout.\n- `ik release create` / `release remove` / `release list` / `release deploy-all` / `release deploy-selected` / `release deliver` / `release edit` \u2014 release-branch and deploy flow.\n- `ik release merge-dev` \u2014 merge the dev branch into every release branch; `--keep-conflicts` hands off any real conflict to a CLI-owned resolution worktree, `--continue`/`--abort` resume or drop that hand-off. The `/infra-kit:merge-dev` skill is the agent entry point for the whole flow.\n- `ik audit` \u2014 audit packages against their `infra-kit.config.ts` rules (`--root`: the repo root against the `audit` block in `infra-kit.json`).\n- `ik audit --fix` \u2014 regenerate this repo's infra-kit guidance blocks (`--all` for every package, `--root` for this file).\n- `ik doctor` \u2014 check gh / doppler / aws install + auth and repo setup.\n- `ik setup` \u2014 set up infra-kit on this machine: shell integration, the Claude Code skills plugin, and the external CLIs (brew, git, aws, gh, doppler, portless).\n\n## Conventions\n\n- Tickets are prefixed by area: `[FE]` frontend, `[BE]` backend, `[DO]` DevOps/infra, `[APP]` mobile app, `[IDEA]` proposal, `[ROOT]` cross-cutting. Pick the single dominant area.\n- Config is split by level: repo-wide settings live in the root `infra-kit.json` (personal overrides in `~/.infra-kit/`), per-package settings in that package's `infra-kit.config.ts`. The root has no `infra-kit.config.ts`.\n- Environment variables are managed through Doppler via `ik env-load` \u2014 never commit secrets.\n- Every workspace package has its own CLAUDE.md with package-scoped rules \u2014 read it before editing that package.\n- Launch Claude Code at the repository root: the infra-kit plugin (the `/infra-kit:*` skills) and this repo's `.claude/settings.json` hooks load only from there. If the `/infra-kit:*` skills are absent, this is a subdirectory session \u2014 restart Claude Code at the root.\n\n## Agents\n\n- Agents drive the same CLI over Bash: `infra-kit <command> --agent --json`. The `/infra-kit:*` skills are the entry points and they run the CLI on `PATH`.\n- A confirm-gated command (`release create|remove|edit|merge-dev|deploy-all|deploy-selected`, `release merge-dev --continue|--abort`, `worktrees add|remove|sync`, `vendor sync`) previews its plan and exits without acting; re-run the same argv with `--yes` to execute. Never put a mutating command behind a prefix allow \u2014 that makes the `--yes` re-run unprompted (`ik doctor` warns on such a pattern).\n- `env-load`, `env-clear` and `infra-kit setup` have no confirm step and run once: the host's prompt on the argv is the approval. `release deliver` is human-only and is refused under agent mode.\n- A command that needs a human choice returns a structured `argument_required` refusal naming the option; pass the value instead of retrying.\n\n## Writing code\n\n- Comment the **why**, never the **what**. If a comment would only restate what the code already says (a name, a type, an obvious assignment), delete it \u2014 and if code needs a comment to be _understood_, prefer renaming/refactoring until it reads on its own. Reserve comments for the genuinely non-obvious: external quirks, ordering constraints, fail-safe branches, workarounds, business-logic definitions. Keep them compact. When a comment explains a bug, outage, or upstream issue, link the source of truth instead of describing it.\n- Unit tests are `*.test.ts(x)` in a `__tests__/` folder beside the code they test (`src/foo/__tests__/foo.test.ts`), never next to the source file; inside a frontend feature, all of them go in the feature root's `features/<name>/__tests__/`. `*.spec.ts` is only for Playwright specs in an e2e package. The `@wl/test-location` lint rule enforces it.\n";var zr={"root/body":fg.trimEnd(),"package/frontend":dg.trimEnd(),"package/backend":lg.trimEnd(),"package/lib":pg.trimEnd(),"package/e2e":ug.trimEnd(),"package/mobile":mg.trimEnd(),"design/skeleton":cg.trimEnd()};var qc=/\{\{(\w+)\}\}/g,JR=/^- \{\{(\w+)\}\}$/,KR=e=>new Set([...e.matchAll(qc)].map(t=>t[1])),HR=(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(", ")}`)},qR=(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(", ")}`)},YR=(e,t)=>e.filter(r=>{let n=JR.exec(r);return n===null||t[n[1]]!==""}),zR=(e,t)=>{for(let r of e)for(let n of r.matchAll(qc)){let o=t[n[1]];if(o!==void 0&&o.includes(`
142
- `)&&n.index!==0)throw new Error(`renderTemplate: multi-line value for {{${n[1]}}} must start its line (found at column ${n.index})`)}},Xr=(e,t)=>{let r=KR(e);qR(r,t),HR(r,t);let n=YR(e.split(`
143
- `),t);return zR(n,t),n.join(`
144
- `).replace(qc,(o,s)=>t[s])};var XR="name: TODO",Yc=e=>{let t=Xr(zr["design/skeleton"],{packageName:e}),r=`name: ${e}`;return`${t.replace(XR,()=>r)}
145
- `};var ZR=(e,t)=>`${xt}${e} ${t} -->`,QR="`README.md` \u2014 what this package is and how to run it.",zc="docs/e2e-playwright.md",eS=`\`${zc}\` at the repo root \u2014 env setup, run modes, \`E2E_SLOW_MO\`, traces after a failure.`,tS=["ts-check","eslint-check","test"],rS="The public surface is what `package.json` exposes \u2014 its `exports` map, or `bin` for a CLI; changing it is a breaking change for every dependent package.",nS="Run `pnpm run build` before a dependent package can see a change.",gg=(e,t)=>e?.includes(t)??!0,oS=e=>{let t=tS.filter(r=>gg(e,r)).map(r=>`pnpm run ${r}`);return t.length===0?"":`\`${t.join(" && ")}\` \u2014 this package only.`},Xc=e=>{let{version:t,type:r,packageName:n,relDir:o,hasReadme:s,hasE2eDoc:i,scripts:a,hasPublicSurface:c=!0}=e,l=Xr(zr[`package/${r}`],{packageName:n,relDir:o,type:r,readmeBullet:s?QR:"",checksBullet:oS(a),...r==="e2e"?{e2eDocBullet:i?eS:""}:{},...r==="lib"?{surfaceBullet:c?rS:"",buildBullet:gg(a,"build")?nS:""}:{}});return[ZR(t,r),"",l,""].join(`
146
- `)};var sS=e=>`${hr}${e} -->`,mo=e=>{let t=Xr(zr["root/body"],{});return[sS(e),"",t,""].join(`
147
- `)};import Zr from"node:fs";import iS from"node:path";var yi=e=>{let t;try{t=Zr.lstatSync(e)}catch{return}if(t.isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},fo=(e,t)=>{let r=go(e,t);return r!=="unchanged"&&(Zr.mkdirSync(iS.dirname(e),{recursive:!0}),Zr.writeFileSync(e,t,"utf-8")),r},go=(e,t)=>{yi(e);let r=Zr.existsSync(e)?Zr.readFileSync(e,"utf-8"):null;return r===t?"unchanged":r===null?"created":"updated"},Zc=(e,t,r)=>{let n=Zr.readFileSync(e,"utf-8");if(!Ve(n,t,r))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},hg=(e,t,r)=>Ve(e,t,r)?{before:e.slice(0,e.indexOf(t)),after:e.slice(e.indexOf(r)+r.length)}:null,Qc=(e,t,r,n)=>{let o=hg(e,r,n),s=hg(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 wi="<!-- infra-kit:import:begin -->",ki="<!-- infra-kit:import:end -->",aS="AGENTS.md",yg="CLAUDE.md",cS="README.md",el="DESIGN.md",lS=["frontend","mobile"],uS=e=>yr.existsSync(e)?yr.readFileSync(e,"utf-8"):null,tl=(e,t)=>{try{return yr.readdirSync(e).includes(t)}catch{return!1}},vi=(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},vg=({filePath:e,body:t,startMarker:r,endMarker:n,prepare:o,dryRun:s})=>{let i=uS(e),a=i===null?"":o?.(i)??i,c=Hr({content:a,body:t,startMarker:r,endMarker:n,placement:"replace-in-place"});if(s)return go(e,c);let l=fo(e,c);return Zc(e,r,n),i!==null&&Qc(a,c,r,n),l},dS=(e,t)=>{if(!yr.existsSync(e))return"unchanged";yi(e);let r=yr.readFileSync(e,"utf-8"),n=Jt(r,Se,Ie);return n===null?"unchanged":n.trim()===""?(t||yr.rmSync(e),"removed"):t?go(e,n):fo(e,n)},pS=(e,t,r)=>vg({filePath:e,dryRun:r,body:mo(t),startMarker:Se,endMarker:Ie,prepare:n=>Jt(n,wi,ki)??n}),ho=async(e,{version:t,dryRun:r=!1})=>{let n=Kt.join(e,yg),o=Kt.join(e,aS),s=[];try{s.push({path:n,action:pS(n,t,r)})}catch(i){s.push(vi(n,i))}try{s.push({path:o,action:dS(o,r)})}catch(i){s.push(vi(o,i))}return s},mS=(e,t,r,n)=>{if(!lS.includes(r)||tl(e,el))return null;let o=Kt.join(e,el),s=Yc(t);try{return{path:o,action:n?go(o,s):fo(o,s),type:r}}catch(i){return vi(o,i,r)}},bi=async(e,{repoRoot:t,version:r,declaredType:n})=>{let o=await fr(e),s=o.name??Kt.basename(e),i=ao({packageDir:e,repoRoot:t,pkgJson:o,declaredType:n});return{body:Xc({version:r,type:i,packageName:s,relDir:Kt.relative(t,e).split(Kt.sep).join("/"),hasReadme:tl(e,cS),hasDesign:tl(e,el),hasE2eDoc:yr.existsSync(Kt.join(t,zc)),scripts:Object.keys(o.scripts??{}),hasPublicSurface:o.exports!==void 0||o.bin!==void 0}),type:i,packageName:s}},yo=async(e,{repoRoot:t,version:r,design:n,declaredType:o,dryRun:s=!1})=>{let i=Kt.join(e,yg),{body:a,type:c,packageName:l}=await bi(e,{repoRoot:t,version:r,declaredType:o}),u=[];try{u.push({path:i,action:vg({filePath:i,body:a,startMarker:Ge,endMarker:et,dryRun:s}),type:c})}catch(p){u.push(vi(i,p,c))}if(n){let p=mS(e,l,c,s);p&&u.push(p)}return u};import _S from"node:path";import wg from"node:path";var rl="agent-guidance",vo="CLAUDE.md",fS="\u2014 run: infra-kit audit --fix",gS={missing:`${vo} missing`,"no-block":`${vo} has no infra-kit block (expected ${Ge} \u2026 ${et})`,malformed:`${vo} block is malformed (end marker precedes start, or body is empty)`,"foreign-block":`${vo} carries the ROOT infra-kit block (${Se}); a package needs the package block`},hS=e=>e.adopted?` (workspace adopted: ${wg.relative(e.workspaceRoot,e.evidencePath)} carries a package block)`:"",nl=(e,t)=>{let r=Tt(ut(wg.join(e,vo)));if(r.state==="ok"){let s=r.version??"unknown",i=r.type??"unknown";return{name:rl,status:"pass",message:`present (block from infra-kit ${s}, type ${i})`}}let n=`${gS[r.state]} ${fS}`,o=r.state==="missing"?`${n}${hS(t)}`:n;return t.adopted?{name:rl,status:"fail",message:o}:{name:rl,status:"pass",message:`not yet adopted \u2014 ${o}`}};import yS from"node:path";var ol=async(e,t=ct)=>{try{let r=await lo(e,t);return{check:{name:de,status:"pass",message:"present and valid"},rules:r}}catch(r){return{check:{name:de,status:"fail",message:r.message},rules:null}}},kg="infra-kit.json",vS=async e=>await De(yS.join(e,de))?{name:de,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,sl=async(e,t=mr)=>{let r=await vS(e),n=r?[r]:[];try{let{audit:o={}}=await K();return{checks:[{name:kg,status:"pass",message:"present and valid"},...n],rules:co(o,t)}}catch(o){return{checks:[{name:kg,status:"fail",message:o.message},...n],rules:null}}};import Ri from"node:fs/promises";import Qr from"node:path";import{$ as wS}from"zx";var wo="playwright.config.ts",kS=[{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')"}],bg=e=>Object.entries(Gc).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"}}),bS="infra-kit-e2e",Rg=async(e,t={})=>{let r=Qr.join(e,wo),n=await Ri.readFile(r,"utf-8").catch(()=>null);return n===null?[{name:`e2e-config:${wo}`,status:"fail",message:`missing ${wo}`}]:kS.map(o=>{let s=`e2e-config:${o.name}`;return t.staticServer&&o.name===bS?{name:s,status:"pass",message:"not required \u2014 e2e.server is 'static', the suite serves its own build"}:o.pattern.test(n)?{name:s,status:"pass",message:"present"}:{name:s,status:"fail",message:`${wo} lacks the shared e2e convention \u2014 expected: ${o.expected}`}})},RS=/['"`](?:[^'"`\n]*\/)?\.auth['"/`]/u,SS=/\.[cm]?[jt]sx?$/u,il=async(e,t)=>(await Ri.readdir(e,{recursive:t,withFileTypes:!0}).catch(()=>[])).filter(n=>n.isFile()&&SS.test(n.name)).map(n=>Qr.join(n.parentPath,n.name)),ES=async e=>{let t=await il(Qr.join(e,"src"),!0);for(let r of[Qr.join(e,wo),...t]){let n=await Ri.readFile(r,"utf-8").catch(()=>"");if(RS.test(n))return!0}return!1},Sg=async e=>{let t="e2e-auth:gitignored";if(!await ES(e))return{name:t,status:"pass",message:"no saved auth state referenced"};let r=await wS({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}`}},al="E2E__BASIC_AUTH_USERNAME",cl="E2E__BASIC_AUTH_PASSWORD",PS=/\bE2E_\w*BASIC_AUTH_\w+/gu,xS=/_(?:USER(?:NAME)?|PASS(?:WORD)?)$/u,TS=/\/\*[\s\S]*?\*\//gu,CS=/(^|[^:])\/\/[^\n]*/gu,$S=e=>/USER(?:NAME)?$/u.test(e)?al:cl,AS=e=>e.replace(TS,"").replace(CS,"$1"),Eg=async e=>{let t="e2e-env:basic-auth",r=[...await il(e,!1),...await il(Qr.join(e,"src"),!0)],n=[];for(let o of r){let s=await Ri.readFile(o,"utf-8").catch(()=>""),i=new Set([...AS(s).matchAll(PS)].map(a=>a[0]).filter(a=>xS.test(a)&&a!==al&&a!==cl));for(let a of i)n.push(`${a} \u2192 ${$S(a)} (${Qr.relative(e,o)})`)}return n.length===0?{name:t,status:"pass",message:`basic auth read only from ${al} / ${cl}`}:{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("; ")}`}},ll=async(e,t,r={})=>[...bg(t),...await Rg(e,r),await Sg(e),await Eg(e)];import OS from"node:fs/promises";import DS from"node:path";var ul=async(e,t)=>Promise.all(t.map(async r=>{let n=await OS.stat(DS.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 dl=(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 IS from"node:fs/promises";import NS from"node:path";var en="turbo.json",pl=async(e,t)=>{if(t.length===0)return[];let r;try{let o=await IS.readFile(NS.join(e,en),"utf-8");r=JSON.parse(o)}catch(o){return[{name:en,status:"fail",message:`cannot read/parse ${en}: ${o.message}`}]}let n=r.tasks;return n===null||typeof n!="object"?[{name:en,status:"fail",message:`no "tasks" object defined in ${en}`}]: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 ${en}`}})};var MS=async(e,t)=>{let{check:r,rules:n}=await ol(e,t);return{checks:[r],rules:n}},jS={adopted:!1,workspaceRoot:null},FS=async(e,t,r)=>ao({packageDir:e,repoRoot:r??e,pkgJson:t,declaredType:await Pt(e)}),LS=async e=>(await lt(e).catch(()=>{}))?.e2e?.server==="static",ml=async(e,t=ct,r={})=>{let n=await fr(e),o=n.name??_S.basename(e),{checks:s,rules:i}=r.isRoot?await sl(e,t):await MS(e,t);r.isRoot||s.push(nl(e,r.adoption??jS)),i&&(s.push(...dl(n.scripts??{},i.requiredScripts)),s.push(...await ul(e,i.requiredFiles)),s.push(...await pl(e,i.turboTasks))),!r.isRoot&&await FS(e,n,r.repoRoot)==="e2e"&&s.push(...await ll(e,n.scripts??{},{staticServer:await LS(e)}));let a=s.every(c=>c.status!=="fail");return{packageDir:e,packageName:o,checks:s,passed:a}};var fl=["plugin","marketplace","add",Bt],gl=["plugin","install",q,"--scope","project"],Pg=(e,t)=>ur({projectPath:e,home:t}).kind==="installed",Si=e=>((e??"").split(`
148
- `).find(r=>r.trim().length>0)??"").trim(),BS=(e,t)=>{if(ro(t))return null;d.debug({msg:`Running: ${to} ${fl.join(" ")}`});let r=e({args:fl});return r.ok?null:{step:"marketplace",error:Si(r.output)}},US=(e,t)=>{d.debug({msg:`Running: ${to} ${ai.join(" ")}`});let r=e({args:ai});if(!r.ok)return{status:"update-failed",error:Si(r.output)};d.debug({msg:`Running: ${to} ${ii.join(" ")}`});let n=e({args:ii,cwd:t});return n.ok?{status:"updated"}:{status:"update-failed",error:Si(n.output)}},hl=e=>{let{projectRoot:t,home:r}=e,n=e.run??Oc;if(!n({args:Ac}).ok)return{status:"claude-missing"};if(Pg(t,r))return e.cliIsStale?.()===!0?{status:"skipped-cli-stale"}:US(n,t);let o=BS(n,r);if(o!==null)return{status:"failed",...o};d.debug({msg:`Running: ${to} ${gl.join(" ")}`});let s=n({args:gl,cwd:t});return s.ok?Pg(t,r)?{status:"installed"}:{status:"unverified"}:{status:"failed",step:"install",error:Si(s.output)}};import WS from"node:fs";import VS from"node:path";var Je=".mcp.json",dt="mcpServers",GS="infra-kit",JS=["mcp"],KS="/infra-kit/dist/mcp.js",yl=" ",vr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),xg=e=>{if(!vr(e))return!1;let{command:t,args:r}=e;return Array.isArray(r)?t===GS&&r[0]===JS[0]?!0:r.some(n=>typeof n=="string"&&n.endsWith(KS)):!1},Tg=e=>/\n([ \t]+)"/.exec(e)?.[1]??yl,vl=e=>{try{return{kind:"raw",raw:WS.readFileSync(e,"utf-8")}}catch(t){return t.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable",error:t}}},wl=e=>{try{return JSON.parse(e)}catch{return}},kl=e=>e instanceof Error?e.message:String(e),tn=e=>{let t=vl(VS.join(e,Je));if(t.kind==="absent")return{kind:"missing-file"};if(t.kind==="unreadable")return{kind:"unparseable"};let r=wl(t.raw);if(!vr(r)||!vr(r[dt]))return{kind:"unparseable"};let n=r[dt];if(ue in n)return{kind:"stale"};let o=Object.keys(n).find(s=>xg(n[s]));return o===void 0?{kind:"absent"}:{kind:"wrong-key",key:o}};import Ei from"node:fs";import HS from"node:path";var Ct=`claude plugin install ${q} --scope project`,rn=`claude plugin marketplace update ${ue} && claude plugin update ${q} --scope project`,bl=`claude plugin marketplace add ${Bt}`,Ag=" ",Og=()=>({source:{source:"github",repo:Bt}}),qS=()=>({extraKnownMarketplaces:{[ue]:Og()},enabledPlugins:{[q]:!0}}),Dg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),YS=e=>/\n([ \t]+)"/.exec(e)?.[1]??Ag,Cg=(e,t,r,n)=>{let o=e[t];return o===void 0?(e[t]={[r]:n},`${t}.${r}`):!Dg(o)||r in o?null:(o[r]=n,`${t}.${r}`)},$g=e=>[Cg(e,"extraKnownMarketplaces",ue,Og()),Cg(e,"enabledPlugins",q,!0)].filter(r=>r!==null),zS=e=>{try{return Ei.readFileSync(e,"utf-8")}catch{return null}},XS=e=>(Ei.mkdirSync(HS.dirname(e),{recursive:!0}),Ei.writeFileSync(e,`${JSON.stringify(qS(),null,Ag)}
149
- `,"utf-8"),{status:"created",path:e,added:[`extraKnownMarketplaces.${ue}`,`enabledPlugins.${q}`]}),Rl=(e,{write:t=!0}={})=>{let r=zS(e);if(r===null)return t?XS(e):{status:"withheld",path:e,added:$g({})};let n;try{n=JSON.parse(r)}catch{n=void 0}if(!Dg(n))return d.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 o=$g(n);if(o.length===0)return{status:"unchanged",path:e,added:[]};if(!t)return{status:"withheld",path:e,added:o};let s=YS(r),i=r.endsWith(`
141
+ `;var bg='# infra-kit\n\nThis repository uses the **infra-kit** CLI for environment, worktree, and release workflows.\nThis block is generated by `ik audit --fix --root` \u2014 edit text _outside_ the markers, never inside.\n\n## Commands (`ik` = `infra-kit`, the global CLI)\n\n- `ik env-load [-c <config>]` / `ik env-clear` / `ik env-status` \u2014 load, clear, or inspect Doppler env vars for a config (e.g. `dev`). Source the returned file to apply. Without `-c`, an agent loads the project\'s `defaultEnv` (set yours with `ik config-set defaultEnv <env>`); with none set it is refused and must ask the human.\n- `ik dev [app]` / `ik dev-status` \u2014 run this worktree\'s dev servers, or report what is running. An app (`ik dev client`) runs its api and ui plus every backend its proxy routes can run locally; no name runs every app. App names are per-repo: an unknown one is refused with the apps as choices, never guess one.\n- `ik e2e [--app <app>]` \u2014 run an app\'s Playwright suite locally: against this worktree\'s dev server when it runs, otherwise the package\'s `infraKitE2e()` Playwright config starts `ik dev <app> --reuse` for the run and stops it after. Plain `playwright test` / `pnpm e2e-test` behave the same way. `--cloud` runs against the deployed app instead \u2014 the URL the loaded env (`ik env-load -c <env>`) holds in the target app\'s `deployedUrlEnv` \u2014 previews, and needs `--yes`; `--dry-run` prints the target.\n- `ik worktrees add` / `worktrees list` / `worktrees remove` / `worktrees sync` \u2014 manage release and feature git worktrees. `ik worktrees add --feature <name> [--base <dev|main|release>]` creates `feature/<name>` at `<root>-worktrees/feature/<name>`, cut from the integration branch by default \u2014 `dev`, or `main` in a repo with `"gitFlow": "main"` (or 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 integration branch (`dev`, or `main` under `"gitFlow": "main"`) 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- The git flow is the root `infra-kit.json` key `gitFlow`: `"dev"` (default) cuts features and regular releases from `dev` and delivers through a `dev \u2192 main` RC PR, hotfixes from `main`; `"main"` cuts everything from `main` and delivers straight into it, with no hotfix type. Never branch from `dev` in a `"main"` repo, even if a stale `dev` exists.\n- Every workspace package has its own CLAUDE.md with package-scoped rules \u2014 read it before editing that package.\n- Launch Claude Code at the repository root: the infra-kit plugin (the `/infra-kit:*` skills) and this repo\'s `.claude/settings.json` hooks load only from there. If the `/infra-kit:*` skills are absent, this is a subdirectory session \u2014 restart Claude Code at the root.\n\n## Agents\n\n- Agents drive the same CLI over Bash: `infra-kit <command> --agent --json`. The `/infra-kit:*` skills are the entry points and they run the CLI on `PATH`.\n- A confirm-gated command (`release create|remove|edit|merge-dev|deploy-all|deploy-selected`, `release merge-dev --continue|--abort`, `worktrees add|remove|sync`, `vendor sync`) previews its plan and exits without acting; re-run the same argv with `--yes` to execute. Never put a mutating command behind a prefix allow \u2014 that makes the `--yes` re-run unprompted (`ik doctor` warns on such a pattern).\n- `env-load`, `env-clear` and `infra-kit setup` have no confirm step and run once: the host\'s prompt on the argv is the approval. `release deliver` is human-only and is refused under agent mode.\n- A command that needs a human choice returns a structured `argument_required` refusal naming the option; pass the value instead of retrying.\n\n## Writing code\n\n- Comment the **why**, never the **what**. If a comment would only restate what the code already says (a name, a type, an obvious assignment), delete it \u2014 and if code needs a comment to be _understood_, prefer renaming/refactoring until it reads on its own. Reserve comments for the genuinely non-obvious: external quirks, ordering constraints, fail-safe branches, workarounds, business-logic definitions. Keep them compact. When a comment explains a bug, outage, or upstream issue, link the source of truth instead of describing it.\n- Unit tests are `*.test.ts(x)` in a `__tests__/` folder beside the code they test (`src/foo/__tests__/foo.test.ts`), never next to the source file; inside a frontend feature, all of them go in the feature root\'s `features/<name>/__tests__/`. `*.spec.ts` is only for Playwright specs in an e2e package. The `@wl/test-location` lint rule enforces it.\n';var en={"root/body":bg.trimEnd(),"package/frontend":vg.trimEnd(),"package/backend":hg.trimEnd(),"package/lib":wg.trimEnd(),"package/e2e":yg.trimEnd(),"package/mobile":kg.trimEnd(),"design/skeleton":gg.trimEnd()};var Zc=/\{\{(\w+)\}\}/g,YR=/^- \{\{(\w+)\}\}$/,zR=e=>new Set([...e.matchAll(Zc)].map(t=>t[1])),XR=(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(", ")}`)},ZR=(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(", ")}`)},QR=(e,t)=>e.filter(r=>{let n=YR.exec(r);return n===null||t[n[1]]!==""}),eS=(e,t)=>{for(let r of e)for(let n of r.matchAll(Zc)){let o=t[n[1]];if(o!==void 0&&o.includes(`
142
+ `)&&n.index!==0)throw new Error(`renderTemplate: multi-line value for {{${n[1]}}} must start its line (found at column ${n.index})`)}},tn=(e,t)=>{let r=zR(e);ZR(r,t),XR(r,t);let n=QR(e.split(`
143
+ `),t);return eS(n,t),n.join(`
144
+ `).replace(Zc,(o,s)=>t[s])};var tS="name: TODO",Qc=e=>{let t=tn(en["design/skeleton"],{packageName:e}),r=`name: ${e}`;return`${t.replace(tS,()=>r)}
145
+ `};var rS=(e,t)=>`${Ct}${e} ${t} -->`,nS="`README.md` \u2014 what this package is and how to run it.",el="docs/e2e-playwright.md",oS=`\`${el}\` at the repo root \u2014 env setup, run modes, \`E2E_SLOW_MO\`, traces after a failure.`,sS=["ts-check","eslint-check","test"],iS="The public surface is what `package.json` exposes \u2014 its `exports` map, or `bin` for a CLI; changing it is a breaking change for every dependent package.",aS="Run `pnpm run build` before a dependent package can see a change.",Rg=(e,t)=>e?.includes(t)??!0,cS=e=>{let t=sS.filter(r=>Rg(e,r)).map(r=>`pnpm run ${r}`);return t.length===0?"":`\`${t.join(" && ")}\` \u2014 this package only.`},tl=e=>{let{version:t,type:r,packageName:n,relDir:o,hasReadme:s,hasE2eDoc:i,scripts:a,hasPublicSurface:c=!0}=e,l=tn(en[`package/${r}`],{packageName:n,relDir:o,type:r,readmeBullet:s?nS:"",checksBullet:cS(a),...r==="e2e"?{e2eDocBullet:i?oS:""}:{},...r==="lib"?{surfaceBullet:c?iS:"",buildBullet:Rg(a,"build")?aS:""}:{}});return[rS(t,r),"",l,""].join(`
146
+ `)};var lS=e=>`${vr}${e} -->`,wo=e=>{let t=tn(en["root/body"],{});return[lS(e),"",t,""].join(`
147
+ `)};import rn from"node:fs";import uS from"node:path";var bi=e=>{let t;try{t=rn.lstatSync(e)}catch{return}if(t.isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},ko=(e,t)=>{let r=bo(e,t);return r!=="unchanged"&&(rn.mkdirSync(uS.dirname(e),{recursive:!0}),rn.writeFileSync(e,t,"utf-8")),r},bo=(e,t)=>{bi(e);let r=rn.existsSync(e)?rn.readFileSync(e,"utf-8"):null;return r===t?"unchanged":r===null?"created":"updated"},rl=(e,t,r)=>{let n=rn.readFileSync(e,"utf-8");if(!Je(n,t,r))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},Sg=(e,t,r)=>Je(e,t,r)?{before:e.slice(0,e.indexOf(t)),after:e.slice(e.indexOf(r)+r.length)}:null,nl=(e,t,r,n)=>{let o=Sg(e,r,n),s=Sg(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 Si="<!-- infra-kit:import:begin -->",Ei="<!-- infra-kit:import:end -->",dS="AGENTS.md",Eg="CLAUDE.md",pS="README.md",ol="DESIGN.md",mS=["frontend","mobile"],fS=e=>wr.existsSync(e)?wr.readFileSync(e,"utf-8"):null,sl=(e,t)=>{try{return wr.readdirSync(e).includes(t)}catch{return!1}},Ri=(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},Pg=({filePath:e,body:t,startMarker:r,endMarker:n,prepare:o,dryRun:s})=>{let i=fS(e),a=i===null?"":o?.(i)??i,c=Xr({content:a,body:t,startMarker:r,endMarker:n,placement:"replace-in-place"});if(s)return bo(e,c);let l=ko(e,c);return rl(e,r,n),i!==null&&nl(a,c,r,n),l},gS=(e,t)=>{if(!wr.existsSync(e))return"unchanged";bi(e);let r=wr.readFileSync(e,"utf-8"),n=Ht(r,Pe,_e);return n===null?"unchanged":n.trim()===""?(t||wr.rmSync(e),"removed"):t?bo(e,n):ko(e,n)},hS=(e,t,r)=>Pg({filePath:e,dryRun:r,body:wo(t),startMarker:Pe,endMarker:_e,prepare:n=>Ht(n,Si,Ei)??n}),Ro=async(e,{version:t,dryRun:r=!1})=>{let n=qt.join(e,Eg),o=qt.join(e,dS),s=[];try{s.push({path:n,action:hS(n,t,r)})}catch(i){s.push(Ri(n,i))}try{s.push({path:o,action:gS(o,r)})}catch(i){s.push(Ri(o,i))}return s},yS=(e,t,r,n)=>{if(!mS.includes(r)||sl(e,ol))return null;let o=qt.join(e,ol),s=Qc(t);try{return{path:o,action:n?bo(o,s):ko(o,s),type:r}}catch(i){return Ri(o,i,r)}},Pi=async(e,{repoRoot:t,version:r,declaredType:n})=>{let o=await hr(e),s=o.name??qt.basename(e),i=fo({packageDir:e,repoRoot:t,pkgJson:o,declaredType:n});return{body:tl({version:r,type:i,packageName:s,relDir:qt.relative(t,e).split(qt.sep).join("/"),hasReadme:sl(e,pS),hasDesign:sl(e,ol),hasE2eDoc:wr.existsSync(qt.join(t,el)),scripts:Object.keys(o.scripts??{}),hasPublicSurface:o.exports!==void 0||o.bin!==void 0}),type:i,packageName:s}},So=async(e,{repoRoot:t,version:r,design:n,declaredType:o,dryRun:s=!1})=>{let i=qt.join(e,Eg),{body:a,type:c,packageName:l}=await Pi(e,{repoRoot:t,version:r,declaredType:o}),u=[];try{u.push({path:i,action:Pg({filePath:i,body:a,startMarker:Ke,endMarker:rt,dryRun:s}),type:c})}catch(p){u.push(Ri(i,p,c))}if(n){let p=yS(e,l,c,s);p&&u.push(p)}return u};import LS from"node:path";import xg from"node:path";var il="agent-guidance",Eo="CLAUDE.md",vS="\u2014 run: infra-kit audit --fix",wS={missing:`${Eo} missing`,"no-block":`${Eo} has no infra-kit block (expected ${Ke} \u2026 ${rt})`,malformed:`${Eo} block is malformed (end marker precedes start, or body is empty)`,"foreign-block":`${Eo} carries the ROOT infra-kit block (${Pe}); a package needs the package block`},kS=e=>e.adopted?` (workspace adopted: ${xg.relative(e.workspaceRoot,e.evidencePath)} carries a package block)`:"",al=(e,t)=>{let r=$t(pt(xg.join(e,Eo)));if(r.state==="ok"){let s=r.version??"unknown",i=r.type??"unknown";return{name:il,status:"pass",message:`present (block from infra-kit ${s}, type ${i})`}}let n=`${wS[r.state]} ${vS}`,o=r.state==="missing"?`${n}${kS(t)}`:n;return t.adopted?{name:il,status:"fail",message:o}:{name:il,status:"pass",message:`not yet adopted \u2014 ${o}`}};import bS from"node:path";var cl=async(e,t=ut)=>{try{let r=await ho(e,t);return{check:{name:pe,status:"pass",message:"present and valid"},rules:r}}catch(r){return{check:{name:pe,status:"fail",message:r.message},rules:null}}},Tg="infra-kit.json",RS=async e=>await Ne(bS.join(e,pe))?{name:pe,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,ll=async(e,t=gr)=>{let r=await RS(e),n=r?[r]:[];try{let{audit:o={}}=await J();return{checks:[{name:Tg,status:"pass",message:"present and valid"},...n],rules:go(o,t)}}catch(o){return{checks:[{name:Tg,status:"fail",message:o.message},...n],rules:null}}};import xi from"node:fs/promises";import nn from"node:path";import{$ as SS}from"zx";var Po="playwright.config.ts",ES=[{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')"}],Cg=e=>Object.entries(qc).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"}}),PS="infra-kit-e2e",$g=async(e,t={})=>{let r=nn.join(e,Po),n=await xi.readFile(r,"utf-8").catch(()=>null);return n===null?[{name:`e2e-config:${Po}`,status:"fail",message:`missing ${Po}`}]:ES.map(o=>{let s=`e2e-config:${o.name}`;return t.staticServer&&o.name===PS?{name:s,status:"pass",message:"not required \u2014 e2e.server is 'static', the suite serves its own build"}:o.pattern.test(n)?{name:s,status:"pass",message:"present"}:{name:s,status:"fail",message:`${Po} lacks the shared e2e convention \u2014 expected: ${o.expected}`}})},xS=/['"`](?:[^'"`\n]*\/)?\.auth['"/`]/u,TS=/\.[cm]?[jt]sx?$/u,ul=async(e,t)=>(await xi.readdir(e,{recursive:t,withFileTypes:!0}).catch(()=>[])).filter(n=>n.isFile()&&TS.test(n.name)).map(n=>nn.join(n.parentPath,n.name)),CS=async e=>{let t=await ul(nn.join(e,"src"),!0);for(let r of[nn.join(e,Po),...t]){let n=await xi.readFile(r,"utf-8").catch(()=>"");if(xS.test(n))return!0}return!1},Ag=async e=>{let t="e2e-auth:gitignored";if(!await CS(e))return{name:t,status:"pass",message:"no saved auth state referenced"};let r=await SS({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}`}},dl="E2E__BASIC_AUTH_USERNAME",pl="E2E__BASIC_AUTH_PASSWORD",$S=/\bE2E_\w*BASIC_AUTH_\w+/gu,AS=/_(?:USER(?:NAME)?|PASS(?:WORD)?)$/u,OS=/\/\*[\s\S]*?\*\//gu,DS=/(^|[^:])\/\/[^\n]*/gu,IS=e=>/USER(?:NAME)?$/u.test(e)?dl:pl,NS=e=>e.replace(OS,"").replace(DS,"$1"),Og=async e=>{let t="e2e-env:basic-auth",r=[...await ul(e,!1),...await ul(nn.join(e,"src"),!0)],n=[];for(let o of r){let s=await xi.readFile(o,"utf-8").catch(()=>""),i=new Set([...NS(s).matchAll($S)].map(a=>a[0]).filter(a=>AS.test(a)&&a!==dl&&a!==pl));for(let a of i)n.push(`${a} \u2192 ${IS(a)} (${nn.relative(e,o)})`)}return n.length===0?{name:t,status:"pass",message:`basic auth read only from ${dl} / ${pl}`}:{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("; ")}`}},ml=async(e,t,r={})=>[...Cg(t),...await $g(e,r),await Ag(e),await Og(e)];import _S from"node:fs/promises";import MS from"node:path";var fl=async(e,t)=>Promise.all(t.map(async r=>{let n=await _S.stat(MS.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 gl=(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 jS from"node:fs/promises";import FS from"node:path";var on="turbo.json",hl=async(e,t)=>{if(t.length===0)return[];let r;try{let o=await jS.readFile(FS.join(e,on),"utf-8");r=JSON.parse(o)}catch(o){return[{name:on,status:"fail",message:`cannot read/parse ${on}: ${o.message}`}]}let n=r.tasks;return n===null||typeof n!="object"?[{name:on,status:"fail",message:`no "tasks" object defined in ${on}`}]: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 ${on}`}})};var BS=async(e,t)=>{let{check:r,rules:n}=await cl(e,t);return{checks:[r],rules:n}},US={adopted:!1,workspaceRoot:null},WS=async(e,t,r)=>fo({packageDir:e,repoRoot:r??e,pkgJson:t,declaredType:await Tt(e)}),GS=async e=>(await dt(e).catch(()=>{}))?.e2e?.server==="static",yl=async(e,t=ut,r={})=>{let n=await hr(e),o=n.name??LS.basename(e),{checks:s,rules:i}=r.isRoot?await ll(e,t):await BS(e,t);r.isRoot||s.push(al(e,r.adoption??US)),i&&(s.push(...gl(n.scripts??{},i.requiredScripts)),s.push(...await fl(e,i.requiredFiles)),s.push(...await hl(e,i.turboTasks))),!r.isRoot&&await WS(e,n,r.repoRoot)==="e2e"&&s.push(...await ml(e,n.scripts??{},{staticServer:await GS(e)}));let a=s.every(c=>c.status!=="fail");return{packageDir:e,packageName:o,checks:s,passed:a}};var vl=["plugin","marketplace","add",Wt],wl=["plugin","install",z,"--scope","project"],Dg=(e,t)=>pr({projectPath:e,home:t}).kind==="installed",Ti=e=>((e??"").split(`
148
+ `).find(r=>r.trim().length>0)??"").trim(),VS=(e,t)=>{if(co(t))return null;d.debug({msg:`Running: ${ao} ${vl.join(" ")}`});let r=e({args:vl});return r.ok?null:{step:"marketplace",error:Ti(r.output)}},JS=(e,t)=>{d.debug({msg:`Running: ${ao} ${di.join(" ")}`});let r=e({args:di});if(!r.ok)return{status:"update-failed",error:Ti(r.output)};d.debug({msg:`Running: ${ao} ${ui.join(" ")}`});let n=e({args:ui,cwd:t});return n.ok?{status:"updated"}:{status:"update-failed",error:Ti(n.output)}},kl=e=>{let{projectRoot:t,home:r}=e,n=e.run??_c;if(!n({args:Nc}).ok)return{status:"claude-missing"};if(Dg(t,r))return e.cliIsStale?.()===!0?{status:"skipped-cli-stale"}:JS(n,t);let o=VS(n,r);if(o!==null)return{status:"failed",...o};d.debug({msg:`Running: ${ao} ${wl.join(" ")}`});let s=n({args:wl,cwd:t});return s.ok?Dg(t,r)?{status:"installed"}:{status:"unverified"}:{status:"failed",step:"install",error:Ti(s.output)}};import KS from"node:fs";import HS from"node:path";var He=".mcp.json",mt="mcpServers",qS="infra-kit",YS=["mcp"],zS="/infra-kit/dist/mcp.js",bl=" ",kr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ig=e=>{if(!kr(e))return!1;let{command:t,args:r}=e;return Array.isArray(r)?t===qS&&r[0]===YS[0]?!0:r.some(n=>typeof n=="string"&&n.endsWith(zS)):!1},Ng=e=>/\n([ \t]+)"/.exec(e)?.[1]??bl,Rl=e=>{try{return{kind:"raw",raw:KS.readFileSync(e,"utf-8")}}catch(t){return t.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable",error:t}}},Sl=e=>{try{return JSON.parse(e)}catch{return}},El=e=>e instanceof Error?e.message:String(e),sn=e=>{let t=Rl(HS.join(e,He));if(t.kind==="absent")return{kind:"missing-file"};if(t.kind==="unreadable")return{kind:"unparseable"};let r=Sl(t.raw);if(!kr(r)||!kr(r[mt]))return{kind:"unparseable"};let n=r[mt];if(de in n)return{kind:"stale"};let o=Object.keys(n).find(s=>Ig(n[s]));return o===void 0?{kind:"absent"}:{kind:"wrong-key",key:o}};import Ci from"node:fs";import XS from"node:path";var At=`claude plugin install ${z} --scope project`,an=`claude plugin marketplace update ${de} && claude plugin update ${z} --scope project`,Pl=`claude plugin marketplace add ${Wt}`,jg=" ",Fg=()=>({source:{source:"github",repo:Wt}}),ZS=()=>({extraKnownMarketplaces:{[de]:Fg()},enabledPlugins:{[z]:!0}}),Lg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),QS=e=>/\n([ \t]+)"/.exec(e)?.[1]??jg,_g=(e,t,r,n)=>{let o=e[t];return o===void 0?(e[t]={[r]:n},`${t}.${r}`):!Lg(o)||r in o?null:(o[r]=n,`${t}.${r}`)},Mg=e=>[_g(e,"extraKnownMarketplaces",de,Fg()),_g(e,"enabledPlugins",z,!0)].filter(r=>r!==null),eE=e=>{try{return Ci.readFileSync(e,"utf-8")}catch{return null}},tE=e=>(Ci.mkdirSync(XS.dirname(e),{recursive:!0}),Ci.writeFileSync(e,`${JSON.stringify(ZS(),null,jg)}
149
+ `,"utf-8"),{status:"created",path:e,added:[`extraKnownMarketplaces.${de}`,`enabledPlugins.${z}`]}),xl=(e,{write:t=!0}={})=>{let r=eE(e);if(r===null)return t?tE(e):{status:"withheld",path:e,added:Mg({})};let n;try{n=JSON.parse(r)}catch{n=void 0}if(!Lg(n))return d.warn(`Could not parse ${e} \u2014 left it untouched. Add "${z}" to enabledPlugins by hand, or fix the JSON and re-run: infra-kit setup --skip-tools`),{status:"unparseable",path:e,added:[]};let o=Mg(n);if(o.length===0)return{status:"unchanged",path:e,added:[]};if(!t)return{status:"withheld",path:e,added:o};let s=QS(r),i=r.endsWith(`
150
150
  `)?`
151
- `:"";return Ei.writeFileSync(e,`${JSON.stringify(n,null,s)}${i}`,"utf-8"),{status:"added",path:e,added:o}};var ZS="empty-rules",QS=["requiredScripts","requiredFiles"],Ig=(e,t,r)=>QS.filter(n=>e[n]?.length===0).map(n=>({name:ZS,status:"warn",message:`${r} sets ${n}: [], which disables the check instead of relaxing it \u2014 delete the key to inherit the defaults (${t[n].join(", ")}), or list what this target really has`})),Ng=async(e,t)=>{try{if(t){let{audit:r={}}=await K();return Ig(r,mr,'infra-kit.json "audit"')}return Ig(await lt(e)??{},ct,"infra-kit.config.ts")}catch{return[]}};import rE from"node:path";import nE from"node:process";import Sl from"node:fs/promises";import _g from"node:path";var eE="infra-kit.json",Mg=["requiredScripts","requiredFiles","turbo"],ko=(e,t)=>[{path:e,action:"failed",message:t}],tE=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),jg=async e=>{let t=_g.join(e,de),r=_g.join(e,eE),n;try{n=await lt(e)}catch(c){return ko(t,c.message)}if(!n)return[];let o={...n},s=Object.keys(o).filter(c=>!Mg.includes(c));if(s.length>0)return ko(t,`declares ${s.join(", ")}, which mean nothing at the repo root \u2014 remove them, then re-run`);let i=Object.fromEntries(Mg.filter(c=>o[c]!==void 0).map(c=>[c,o[c]])),a=[];if(Object.keys(i).length>0)try{let c=await Sl.stat(r),l=await Sl.readFile(r,"utf8"),u=JSON.parse(l);if(!tE(u))return ko(r,"is not a JSON object");if("audit"in u)return ko(r,`already has an "audit" block \u2014 merge ${de}'s rules into it by hand, then delete ${de}`);await hf({path:r,raw:l,migrated:{...u,audit:i},expectedMtimeMs:c.mtimeMs}),a.push({path:r,action:"updated"})}catch(c){return ko(r,c.message)}try{await Sl.rm(t),a.push({path:t,action:"removed"})}catch(c){a.push({path:t,action:"failed",message:c.message})}return a};var oE=["unchanged","created"],sE=["unchanged","created","updated","removed","failed"],Fg=async(e,t,r)=>{let n=await Pt(e);return yo(e,{repoRoot:t,version:L.version,design:r,declaredType:n})},iE=async(e,t)=>{if(e.root)return[...await jg(t),...await ho(t,{version:L.version})];if(e.all){let n=[];for(let o of await Re(t))n.push(...await Fg(o,t,e.design));return n}let r=await po(e.cwd??nE.cwd());return Fg(r,t,e.design)},aE=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 ${sE.filter(n=>oE.includes(n)||(t.get(n)??0)>0).map(n=>`${t.get(n)??0} ${n}`).join(", ")} (infra-kit ${L.version})`},cE=(e,t)=>{for(let r of e){if(r.action==="unchanged")continue;let n=rE.relative(t,r.path),o=r.type?` (${r.type})`:"",s=r.action==="failed"&&r.message?` \u2014 ${r.message}`:"";d.info(` ${r.action.padEnd(9)} ${n}${o}${s}`)}d.info(aE(e))},lE=e=>{let t={path:e.path,action:e.action};return e.type&&(t.type=e.type),t},Lg=async(e,t)=>{let r=await $();hi();let n=await Yr(t),o=await iE(e,r);cE(o,r),hi();let s=await Yr(t),i=!e.all&&!e.root;return{fixed:o.map(lE),adoptionFlipped:i&&!n.adopted&&s.adopted}};import Pi from"node:fs/promises";import xi from"node:path";import uE from"yaml";var bo="dependency-drift",El="@slip-stream-kit/",dE="infra-kit",pE=["dependencies","devDependencies","optionalDependencies"],Wg=e=>e.startsWith("workspace:")||e.startsWith("link:")||e.startsWith("file:"),xl=e=>e.startsWith("catalog:"),mE=(e,t,r)=>{if(!xl(e))return e;let n=e.slice(8);return n===""||n==="default"?t.default[r]:t.named[n]?.[r]},Bg=e=>{let t=e.slice(Math.max(e.search(/\d/),0)).match(/^(\d+)\.(\d+)\.\d/);return t?[Number(t[1]),Number(t[2])]:null},fE=(e,t)=>{let r=Bg(e),n=Bg(t);return!r||!n?!1:r[0]<n[0]||r[0]===n[0]&&r[1]<n[1]},gE=e=>{let t=new Map;for(let r of e){let n=t.get(r.name);n?n.push(r):t.set(r.name,[r])}return t},Pl=e=>e.map(t=>`${t.file} "${t.spec}"`).join(", "),hE=(e,t)=>[...gE(e)].flatMap(([r,n])=>{if(t.default[r]!==void 0){let o=n.filter(s=>!xl(s.spec));return o.length===0?[]:[{name:`${bo}:catalog`,status:"warn",message:`${r} has a catalog entry (${t.default[r]}) but ${Pl(o)} bypass it \u2014 run \`ik audit --fix --root\` to rewrite them to "catalog:", then pnpm install`}]}return new Set(n.map(o=>o.spec)).size<=1?[]:[{name:`${bo}:catalog`,status:"warn",message:`${r} is pinned at more than one range: ${Pl(n)} \u2014 add one entry to the pnpm-workspace.yaml catalog, then run \`ik audit --fix --root\``}]}),yE=(e,t,r)=>{let n=new Map;for(let o of e){let s=mE(o.spec,t,o.name);s!==void 0&&fE(s,r)&&n.set(`${o.name}@${s}`,o.name)}return[...n.keys()].map(o=>({name:`${bo}:lockstep`,status:"warn",message:`${o} is behind the infra-kit ${r} lockstep release \u2014 bump it to ^${r}`}))},vE=e=>{let t=e.filter(r=>r.name===dE);return t.length===0?[]:[{name:`${bo}:infra-kit-pin`,status:"warn",message:`${Pl(t)} \u2014 the repo runs the global infra-kit CLI; a local dependency is a second copy that can skew from it`}]},wE=(e,t,r)=>{let n=e.filter(i=>!Wg(i.spec)),o=n.filter(i=>i.name.startsWith(El)),s=[...hE(o,t),...yE(o,t,r),...vE(n)];return s.length>0?s:[{name:bo,status:"pass",message:`no ${El}* or infra-kit dependency drift`}]},kE=async e=>{try{return JSON.parse(await Pi.readFile(e,"utf-8"))}catch{return null}},bE=async e=>{try{let t=uE.parse(await Pi.readFile(xi.join(e,"pnpm-workspace.yaml"),"utf-8"))??{};return{default:t.catalog??{},named:t.catalogs??{}}}catch{return{default:{},named:{}}}},RE=async e=>{let t=await Re(e).catch(()=>[]);return[e,...t].map(r=>xi.join(r,"package.json"))},Ug=async e=>{let t=[];for(let r of await RE(e)){let n=await kE(r);if(!n)continue;let o=xi.relative(e,r);for(let s of pE){let i=n[s]??{};for(let[a,c]of Object.entries(i))typeof c=="string"&&t.push({file:o,section:s,name:a,spec:c})}}return t},SE=async(e,t,r)=>{let n=t.filter(s=>s.name.startsWith(El)&&!Wg(s.spec)&&!xl(s.spec)&&r.default[s.name]!==void 0),o=[...new Set(n.map(s=>s.file))];for(let s of o){let i=xi.join(e,s),a=await Pi.readFile(i,"utf-8"),c=JSON.parse(a);for(let u of n)u.file===s&&(c[u.section][u.name]="catalog:");let l=a.match(/^[ \t]+(?=")/m)?.[0]??" ";await Pi.writeFile(i,`${JSON.stringify(c,null,l)}
152
- `,"utf-8")}return o},Vg=async(e,t,r=L.version)=>{let n=await bE(e),o=await Ug(e),s=t?await SE(e,o,n):[],i=s.length>0?await Ug(e):o;return{checks:wE(i,n,r),rewritten:s}};import Jg from"node:path";var Ti="agent-guidance:drift",EE={root:"ik audit --fix --root",all:"ik audit --fix --all",package:"ik audit --fix"},Gg=(e,t)=>e.split(`
151
+ `:"";return Ci.writeFileSync(e,`${JSON.stringify(n,null,s)}${i}`,"utf-8"),{status:"added",path:e,added:o}};var rE="empty-rules",nE=["requiredScripts","requiredFiles"],Bg=(e,t,r)=>nE.filter(n=>e[n]?.length===0).map(n=>({name:rE,status:"warn",message:`${r} sets ${n}: [], which disables the check instead of relaxing it \u2014 delete the key to inherit the defaults (${t[n].join(", ")}), or list what this target really has`})),Ug=async(e,t)=>{try{if(t){let{audit:r={}}=await J();return Bg(r,gr,'infra-kit.json "audit"')}return Bg(await dt(e)??{},ut,"infra-kit.config.ts")}catch{return[]}};import iE from"node:path";import aE from"node:process";import Tl from"node:fs/promises";import Wg from"node:path";var oE="infra-kit.json",Gg=["requiredScripts","requiredFiles","turbo"],xo=(e,t)=>[{path:e,action:"failed",message:t}],sE=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Vg=async e=>{let t=Wg.join(e,pe),r=Wg.join(e,oE),n;try{n=await dt(e)}catch(c){return xo(t,c.message)}if(!n)return[];let o={...n},s=Object.keys(o).filter(c=>!Gg.includes(c));if(s.length>0)return xo(t,`declares ${s.join(", ")}, which mean nothing at the repo root \u2014 remove them, then re-run`);let i=Object.fromEntries(Gg.filter(c=>o[c]!==void 0).map(c=>[c,o[c]])),a=[];if(Object.keys(i).length>0)try{let c=await Tl.stat(r),l=await Tl.readFile(r,"utf8"),u=JSON.parse(l);if(!sE(u))return xo(r,"is not a JSON object");if("audit"in u)return xo(r,`already has an "audit" block \u2014 merge ${pe}'s rules into it by hand, then delete ${pe}`);await Sf({path:r,raw:l,migrated:{...u,audit:i},expectedMtimeMs:c.mtimeMs}),a.push({path:r,action:"updated"})}catch(c){return xo(r,c.message)}try{await Tl.rm(t),a.push({path:t,action:"removed"})}catch(c){a.push({path:t,action:"failed",message:c.message})}return a};var cE=["unchanged","created"],lE=["unchanged","created","updated","removed","failed"],Jg=async(e,t,r)=>{let n=await Tt(e);return So(e,{repoRoot:t,version:U.version,design:r,declaredType:n})},uE=async(e,t)=>{if(e.root)return[...await Vg(t),...await Ro(t,{version:U.version})];if(e.all){let n=[];for(let o of await Ee(t))n.push(...await Jg(o,t,e.design));return n}let r=await vo(e.cwd??aE.cwd());return Jg(r,t,e.design)},dE=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 ${lE.filter(n=>cE.includes(n)||(t.get(n)??0)>0).map(n=>`${t.get(n)??0} ${n}`).join(", ")} (infra-kit ${U.version})`},pE=(e,t)=>{for(let r of e){if(r.action==="unchanged")continue;let n=iE.relative(t,r.path),o=r.type?` (${r.type})`:"",s=r.action==="failed"&&r.message?` \u2014 ${r.message}`:"";d.info(` ${r.action.padEnd(9)} ${n}${o}${s}`)}d.info(dE(e))},mE=e=>{let t={path:e.path,action:e.action};return e.type&&(t.type=e.type),t},Kg=async(e,t)=>{let r=await A();ki();let n=await Qr(t),o=await uE(e,r);pE(o,r),ki();let s=await Qr(t),i=!e.all&&!e.root;return{fixed:o.map(mE),adoptionFlipped:i&&!n.adopted&&s.adopted}};import $i from"node:fs/promises";import Ai from"node:path";import fE from"yaml";var To="dependency-drift",Cl="@slip-stream-kit/",gE="infra-kit",hE=["dependencies","devDependencies","optionalDependencies"],Yg=e=>e.startsWith("workspace:")||e.startsWith("link:")||e.startsWith("file:"),Al=e=>e.startsWith("catalog:"),yE=(e,t,r)=>{if(!Al(e))return e;let n=e.slice(8);return n===""||n==="default"?t.default[r]:t.named[n]?.[r]},Hg=e=>{let t=e.slice(Math.max(e.search(/\d/),0)).match(/^(\d+)\.(\d+)\.\d/);return t?[Number(t[1]),Number(t[2])]:null},vE=(e,t)=>{let r=Hg(e),n=Hg(t);return!r||!n?!1:r[0]<n[0]||r[0]===n[0]&&r[1]<n[1]},wE=e=>{let t=new Map;for(let r of e){let n=t.get(r.name);n?n.push(r):t.set(r.name,[r])}return t},$l=e=>e.map(t=>`${t.file} "${t.spec}"`).join(", "),kE=(e,t)=>[...wE(e)].flatMap(([r,n])=>{if(t.default[r]!==void 0){let o=n.filter(s=>!Al(s.spec));return o.length===0?[]:[{name:`${To}:catalog`,status:"warn",message:`${r} has a catalog entry (${t.default[r]}) but ${$l(o)} bypass it \u2014 run \`ik audit --fix --root\` to rewrite them to "catalog:", then pnpm install`}]}return new Set(n.map(o=>o.spec)).size<=1?[]:[{name:`${To}:catalog`,status:"warn",message:`${r} is pinned at more than one range: ${$l(n)} \u2014 add one entry to the pnpm-workspace.yaml catalog, then run \`ik audit --fix --root\``}]}),bE=(e,t,r)=>{let n=new Map;for(let o of e){let s=yE(o.spec,t,o.name);s!==void 0&&vE(s,r)&&n.set(`${o.name}@${s}`,o.name)}return[...n.keys()].map(o=>({name:`${To}:lockstep`,status:"warn",message:`${o} is behind the infra-kit ${r} lockstep release \u2014 bump it to ^${r}`}))},RE=e=>{let t=e.filter(r=>r.name===gE);return t.length===0?[]:[{name:`${To}:infra-kit-pin`,status:"warn",message:`${$l(t)} \u2014 the repo runs the global infra-kit CLI; a local dependency is a second copy that can skew from it`}]},SE=(e,t,r)=>{let n=e.filter(i=>!Yg(i.spec)),o=n.filter(i=>i.name.startsWith(Cl)),s=[...kE(o,t),...bE(o,t,r),...RE(n)];return s.length>0?s:[{name:To,status:"pass",message:`no ${Cl}* or infra-kit dependency drift`}]},EE=async e=>{try{return JSON.parse(await $i.readFile(e,"utf-8"))}catch{return null}},PE=async e=>{try{let t=fE.parse(await $i.readFile(Ai.join(e,"pnpm-workspace.yaml"),"utf-8"))??{};return{default:t.catalog??{},named:t.catalogs??{}}}catch{return{default:{},named:{}}}},xE=async e=>{let t=await Ee(e).catch(()=>[]);return[e,...t].map(r=>Ai.join(r,"package.json"))},qg=async e=>{let t=[];for(let r of await xE(e)){let n=await EE(r);if(!n)continue;let o=Ai.relative(e,r);for(let s of hE){let i=n[s]??{};for(let[a,c]of Object.entries(i))typeof c=="string"&&t.push({file:o,section:s,name:a,spec:c})}}return t},TE=async(e,t,r)=>{let n=t.filter(s=>s.name.startsWith(Cl)&&!Yg(s.spec)&&!Al(s.spec)&&r.default[s.name]!==void 0),o=[...new Set(n.map(s=>s.file))];for(let s of o){let i=Ai.join(e,s),a=await $i.readFile(i,"utf-8"),c=JSON.parse(a);for(let u of n)u.file===s&&(c[u.section][u.name]="catalog:");let l=a.match(/^[ \t]+(?=")/m)?.[0]??" ";await $i.writeFile(i,`${JSON.stringify(c,null,l)}
152
+ `,"utf-8")}return o},zg=async(e,t,r=U.version)=>{let n=await PE(e),o=await qg(e),s=t?await TE(e,o,n):[],i=s.length>0?await qg(e):o;return{checks:SE(i,n,r),rewritten:s}};import Zg from"node:path";var Oi="agent-guidance:drift",CE={root:"ik audit --fix --root",all:"ik audit --fix --all",package:"ik audit --fix"},Xg=(e,t)=>e.split(`
153
153
  `).filter(r=>!r.startsWith(t)).join(`
154
- `),Kg=({content:e,expectedBody:t,startMarker:r,endMarker:n,versionPrefix:o,current:s,scope:i})=>{let a=e.slice(e.indexOf(r),e.indexOf(n)+n.length),c=gi(r,t,n);if(Gg(a,o)===Gg(c,o))return{name:Ti,status:"pass",message:`matches infra-kit ${s}`};let l=gr(a,o),u=EE[i];return l!==null&&St(l,s)?{name:Ti,status:"warn",message:`block from infra-kit ${l} is newer than this CLI (${s}) \u2014 CLI behind the block, run \`pnpm add -g infra-kit@${l}\``}:l!==null&&St(s,l)?{name:Ti,status:"warn",message:`block from infra-kit ${l} differs from what infra-kit ${s} generates \u2014 run \`${u}\``}:{name:Ti,status:"warn",message:`block differs from what infra-kit ${s} generates (edited inside the markers?) \u2014 run \`${u}\``}},Hg=(e,t=L.version)=>{let r=ut(Jg.join(e,"CLAUDE.md"));return r===null||!Ve(r,Se,Ie)?null:Kg({content:r,expectedBody:mo(t),startMarker:Se,endMarker:Ie,versionPrefix:hr,current:t,scope:"root"})},qg=async(e,t,r,n=L.version)=>{let o=ut(Jg.join(e,"CLAUDE.md"));if(o===null||Tt(o).state!=="ok")return null;let s;try{({body:s}=await bi(e,{repoRoot:t,version:n,declaredType:await Pt(e)}))}catch{return null}return Kg({content:o,expectedBody:s,startMarker:Ge,endMarker:et,versionPrefix:xt,current:n,scope:r})};import zg from"node:fs";import Xg from"node:path";var Tl="ik-mcp",Yg=(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:Tl,args:r}};var Ci="run `infra-kit setup` (or `infra-kit audit --root --fix`)",PE=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((r,n)=>r===t[n]),Cl=e=>vr(e)&&e.command===Tl,xE=(e,t)=>({...e??{},type:t.type,command:t.command,args:t.args}),TE=(e,t,r)=>{let n=[],o={...e},s=!1;for(let[i,a]of Object.entries(t)){let c=Yg(i,a),l=e[i];if(l!==void 0&&!Cl(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 ${Ci}, or drop mcp.${i} from infra-kit.json`});continue}if(Cl(l)&&l.type===c.type&&PE(l.args,c.args)){n.push({name:i,status:"unchanged",message:""});continue}if(r){o[i]=xE(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: ${Ci}`:`"${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: ${Ci}`})}for(let[i,a]of Object.entries(e))Object.hasOwn(t,i)||!Cl(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}},CE=(e,t,r)=>{let n=r===null?yl:Tg(r),o=r===null||r.endsWith(`
154
+ `),Qg=({content:e,expectedBody:t,startMarker:r,endMarker:n,versionPrefix:o,current:s,scope:i})=>{let a=e.slice(e.indexOf(r),e.indexOf(n)+n.length),c=wi(r,t,n);if(Xg(a,o)===Xg(c,o))return{name:Oi,status:"pass",message:`matches infra-kit ${s}`};let l=yr(a,o),u=CE[i];return l!==null&&Pt(l,s)?{name:Oi,status:"warn",message:`block from infra-kit ${l} is newer than this CLI (${s}) \u2014 CLI behind the block, run \`pnpm add -g infra-kit@${l}\``}:l!==null&&Pt(s,l)?{name:Oi,status:"warn",message:`block from infra-kit ${l} differs from what infra-kit ${s} generates \u2014 run \`${u}\``}:{name:Oi,status:"warn",message:`block differs from what infra-kit ${s} generates (edited inside the markers?) \u2014 run \`${u}\``}},eh=(e,t=U.version)=>{let r=pt(Zg.join(e,"CLAUDE.md"));return r===null||!Je(r,Pe,_e)?null:Qg({content:r,expectedBody:wo(t),startMarker:Pe,endMarker:_e,versionPrefix:vr,current:t,scope:"root"})},th=async(e,t,r,n=U.version)=>{let o=pt(Zg.join(e,"CLAUDE.md"));if(o===null||$t(o).state!=="ok")return null;let s;try{({body:s}=await Pi(e,{repoRoot:t,version:n,declaredType:await Tt(e)}))}catch{return null}return Qg({content:o,expectedBody:s,startMarker:Ke,endMarker:rt,versionPrefix:Ct,current:n,scope:r})};import nh from"node:fs";import oh from"node:path";var Ol="ik-mcp",rh=(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:Ol,args:r}};var Di="run `infra-kit setup` (or `infra-kit audit --root --fix`)",$E=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((r,n)=>r===t[n]),Dl=e=>kr(e)&&e.command===Ol,AE=(e,t)=>({...e??{},type:t.type,command:t.command,args:t.args}),OE=(e,t,r)=>{let n=[],o={...e},s=!1;for(let[i,a]of Object.entries(t)){let c=rh(i,a),l=e[i];if(l!==void 0&&!Dl(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 ${Di}, or drop mcp.${i} from infra-kit.json`});continue}if(Dl(l)&&l.type===c.type&&$E(l.args,c.args)){n.push({name:i,status:"unchanged",message:""});continue}if(r){o[i]=AE(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: ${Di}`:`"${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: ${Di}`})}for(let[i,a]of Object.entries(e))Object.hasOwn(t,i)||!Dl(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}},DE=(e,t,r)=>{let n=r===null?bl:Ng(r),o=r===null||r.endsWith(`
155
155
  `)?`
156
- `:"";try{return zg.mkdirSync(Xg.dirname(e),{recursive:!0}),zg.writeFileSync(e,`${JSON.stringify(t,null,n)}${o}`,"utf-8"),!0}catch(s){return d.warn(`Could not write ${e} (${kl(s)}) \u2014 the ik-mcp entries were not updated.`),!1}},Ro=({projectRoot:e,proxies:t,write:r})=>{let n=Xg.join(e,Je),o=vl(n);if(o.kind==="unreadable")return d.warn(`Could not read ${n} (${kl(o.error)}) \u2014 left it untouched.`),{status:"unreadable",path:n,entries:[],wrote:!1};let s=o.kind==="raw"?o.raw:null,i=s===null?{}:wl(s);if(!vr(i))return d.warn(`Could not parse ${n} \u2014 left it untouched. Fix the JSON, then ${Ci}.`),{status:"unparseable",path:n,entries:[],wrote:!1};let a=i[dt];if(a!==void 0&&!vr(a))return d.warn(`${n} has a "${dt}" that is not an object \u2014 left it untouched.`),{status:"unparseable",path:n,entries:[],wrote:!1};let c=TE(a??{},t,r);if(!c.changed)return{status:"ok",path:n,entries:c.entries,wrote:!1};let l=CE(n,{...i,[dt]:c.servers},s);return{status:l?"ok":"failed",path:n,entries:c.entries,wrote:l}};var Zg=async(e,t)=>{let r;try{r=(await K()).mcp}catch{return null}if(!r||Object.keys(r).length===0)return null;let n=Ro({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(a=>a.status!=="unchanged"&&a.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(a=>({name:`mcp:${a.name}`,status:"fail",message:a.message})),i=s.every(a=>a.status!=="fail");return{packageDir:e,packageName:"mcp",checks:s,passed:i}};var $E="workspace adopted \u2014 every other package now needs a CLAUDE.md: run infra-kit audit --fix --all",AE=async e=>e.root?[{dir:await $(),baseline:mr,isRoot:!0}]:e.all?(await Re(await $())).map(r=>({dir:r})):[{dir:await po(e.cwd??Qg.cwd())}],OE=async e=>e.root||e.all?await $():e.cwd??Qg.cwd(),DE=async()=>{try{return await $()}catch{return}},IE=e=>{let t=0,r=0,n=0;for(let c of e)for(let l of c.checks)t+=1,l.status==="fail"?(r+=1,d.info(`[FAIL] ${c.packageName} ${l.name}: ${l.message}`)):l.status==="warn"&&(n+=1,d.info(`[WARN] ${c.packageName} ${l.name}: ${l.message}`));let o=e.every(c=>c.passed),s=(c,l)=>`${c} ${l}${c===1?"":"s"}`,i=`${s(t,"check")}, ${s(e.length,"target")}`,a=n>0?` (${s(n,"warning")})`:"";return d.info(o?`\u2705 audit passed \u2014 ${i}${a}`:`\u274C audit failed \u2014 ${r}/${i}${a}`),{allPassed:o,warnCount:n}},NE=async(e,t)=>{let{fixed:r,adoptionFlipped:n}=await Lg(e,t);return n&&d.info($E),r},_E=e=>{if(tn(e).kind!=="stale")return null;let t=`${Je} 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 d.info(`[INFO] mcp mcp:legacy-key: ${t}`),{packageDir:e,packageName:"mcp",checks:[{name:"mcp:legacy-key",status:"pass",message:t}],passed:!0}},ME=e=>e.root?"root":e.all?"all":"package",jE=async(e,t,r)=>{let n=await Ng(e.dir,e.isRoot===!0);if(!e.isRoot){let a=await qg(e.dir,r??e.dir,ME(t));return a?[a,...n]:n}let o=Hg(e.dir),{checks:s,rewritten:i}=await Vg(e.dir,t.fix===!0);for(let a of i)d.info(` ${"updated".padEnd(9)} ${a} (@slip-stream-kit/* \u2192 catalog:)`);return[...o?[o]:[],...n,...s]},$i=async(e={})=>{let t=Hc(await OE(e)),r=e.fix?await NE(e,t):void 0,n=await AE(e),o=await Yr(t),s=await DE(),i=[];for(let u of n){let p=await ml(u.dir,u.baseline,{adoption:o,isRoot:u.isRoot,repoRoot:s});p.checks.push(...await jE(u,e,s)),p.passed=p.checks.every(m=>m.status!=="fail"),i.push(p)}if(e.root){let u=await Zg(n[0].dir,e.fix===!0);u&&i.push(u);let p=_E(n[0].dir);p&&i.push(p)}let{allPassed:a,warnCount:c}=IE(i),l={allPassed:a,warnCount:c,packages:i.map(u=>({name:u.packageName,passed:u.passed,checks:u.checks}))};return r&&(l.fixed=r),{content:b(JSON.stringify(l,null,2)),structuredContent:l}},FE={all:Ne.boolean().optional().describe("Audit every non-vendor workspace package"),root:Ne.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},LE={allPassed:Ne.boolean().describe("Whether every audited package passed all checks (warnings do not fail it)"),warnCount:Ne.number().int().describe("How many checks reported a warning"),packages:Ne.array(Ne.object({name:Ne.string(),passed:Ne.boolean(),checks:Ne.array(Ne.object({name:Ne.string(),status:Ne.enum(["pass","warn","fail"]),message:Ne.string()}))})).describe("Per-package check results")},$l=C({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:FE,outputSchema:LE,handler:e=>$i({all:e.all,root:e.root})});import{z as F}from"zod";import{$ as YE}from"zx";var Al=1.959963984540054,BE=[/^co-authored-by:\s*claude\b/imu,/^claude-session:/imu],Ol=/\b(?:fix(?:es|ed)?|hotfix|bugfix|regression)\b/iu,Dl=["pnpm-lock.yaml","package-lock.json","yarn.lock","bun.lockb","CHANGELOG.md"],UE=/This reverts commit ([0-9a-f]{7,40})/u,th=/^Revert "(.*)"(?: \(#\d+\))?$/u,rh="",Ai="",nh=`--format=${rh}%H${Ai}%ct${Ai}%B${Ai}`,oh=e=>e.split(rh).filter(t=>t.trim()!=="").map(t=>{let[r="",n="0",o="",s=""]=t.split(Ai),i=o.trim();return{hash:r,committedAt:Number(n),subject:i.split(`
156
+ `:"";try{return nh.mkdirSync(oh.dirname(e),{recursive:!0}),nh.writeFileSync(e,`${JSON.stringify(t,null,n)}${o}`,"utf-8"),!0}catch(s){return d.warn(`Could not write ${e} (${El(s)}) \u2014 the ik-mcp entries were not updated.`),!1}},Co=({projectRoot:e,proxies:t,write:r})=>{let n=oh.join(e,He),o=Rl(n);if(o.kind==="unreadable")return d.warn(`Could not read ${n} (${El(o.error)}) \u2014 left it untouched.`),{status:"unreadable",path:n,entries:[],wrote:!1};let s=o.kind==="raw"?o.raw:null,i=s===null?{}:Sl(s);if(!kr(i))return d.warn(`Could not parse ${n} \u2014 left it untouched. Fix the JSON, then ${Di}.`),{status:"unparseable",path:n,entries:[],wrote:!1};let a=i[mt];if(a!==void 0&&!kr(a))return d.warn(`${n} has a "${mt}" that is not an object \u2014 left it untouched.`),{status:"unparseable",path:n,entries:[],wrote:!1};let c=OE(a??{},t,r);if(!c.changed)return{status:"ok",path:n,entries:c.entries,wrote:!1};let l=DE(n,{...i,[mt]:c.servers},s);return{status:l?"ok":"failed",path:n,entries:c.entries,wrote:l}};var sh=async(e,t)=>{let r;try{r=(await J()).mcp}catch{return null}if(!r||Object.keys(r).length===0)return null;let n=Co({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(a=>a.status!=="unchanged"&&a.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(a=>({name:`mcp:${a.name}`,status:"fail",message:a.message})),i=s.every(a=>a.status!=="fail");return{packageDir:e,packageName:"mcp",checks:s,passed:i}};var IE="workspace adopted \u2014 every other package now needs a CLAUDE.md: run infra-kit audit --fix --all",NE=async e=>e.root?[{dir:await A(),baseline:gr,isRoot:!0}]:e.all?(await Ee(await A())).map(r=>({dir:r})):[{dir:await vo(e.cwd??ih.cwd())}],_E=async e=>e.root||e.all?await A():e.cwd??ih.cwd(),ME=async()=>{try{return await A()}catch{return}},jE=e=>{let t=0,r=0,n=0;for(let c of e)for(let l of c.checks)t+=1,l.status==="fail"?(r+=1,d.info(`[FAIL] ${c.packageName} ${l.name}: ${l.message}`)):l.status==="warn"&&(n+=1,d.info(`[WARN] ${c.packageName} ${l.name}: ${l.message}`));let o=e.every(c=>c.passed),s=(c,l)=>`${c} ${l}${c===1?"":"s"}`,i=`${s(t,"check")}, ${s(e.length,"target")}`,a=n>0?` (${s(n,"warning")})`:"";return d.info(o?`\u2705 audit passed \u2014 ${i}${a}`:`\u274C audit failed \u2014 ${r}/${i}${a}`),{allPassed:o,warnCount:n}},FE=async(e,t)=>{let{fixed:r,adoptionFlipped:n}=await Kg(e,t);return n&&d.info(IE),r},LE=e=>{if(sn(e).kind!=="stale")return null;let t=`${He} 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 d.info(`[INFO] mcp mcp:legacy-key: ${t}`),{packageDir:e,packageName:"mcp",checks:[{name:"mcp:legacy-key",status:"pass",message:t}],passed:!0}},BE=e=>e.root?"root":e.all?"all":"package",UE=async(e,t,r)=>{let n=await Ug(e.dir,e.isRoot===!0);if(!e.isRoot){let a=await th(e.dir,r??e.dir,BE(t));return a?[a,...n]:n}let o=eh(e.dir),{checks:s,rewritten:i}=await zg(e.dir,t.fix===!0);for(let a of i)d.info(` ${"updated".padEnd(9)} ${a} (@slip-stream-kit/* \u2192 catalog:)`);return[...o?[o]:[],...n,...s]},Ii=async(e={})=>{let t=Xc(await _E(e)),r=e.fix?await FE(e,t):void 0,n=await NE(e),o=await Qr(t),s=await ME(),i=[];for(let u of n){let p=await yl(u.dir,u.baseline,{adoption:o,isRoot:u.isRoot,repoRoot:s});p.checks.push(...await UE(u,e,s)),p.passed=p.checks.every(m=>m.status!=="fail"),i.push(p)}if(e.root){let u=await sh(n[0].dir,e.fix===!0);u&&i.push(u);let p=LE(n[0].dir);p&&i.push(p)}let{allPassed:a,warnCount:c}=jE(i),l={allPassed:a,warnCount:c,packages:i.map(u=>({name:u.packageName,passed:u.passed,checks:u.checks}))};return r&&(l.fixed=r),{content:R(JSON.stringify(l,null,2)),structuredContent:l}},WE={all:Me.boolean().optional().describe("Audit every non-vendor workspace package"),root:Me.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},GE={allPassed:Me.boolean().describe("Whether every audited package passed all checks (warnings do not fail it)"),warnCount:Me.number().int().describe("How many checks reported a warning"),packages:Me.array(Me.object({name:Me.string(),passed:Me.boolean(),checks:Me.array(Me.object({name:Me.string(),status:Me.enum(["pass","warn","fail"]),message:Me.string()}))})).describe("Per-package check results")},Il=C({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:WE,outputSchema:GE,handler:e=>Ii({all:e.all,root:e.root})});import{z as L}from"zod";import{$ as QE}from"zx";var Nl=1.959963984540054,VE=[/^co-authored-by:\s*claude\b/imu,/^claude-session:/imu],_l=/\b(?:fix(?:es|ed)?|hotfix|bugfix|regression)\b/iu,Ml=["pnpm-lock.yaml","package-lock.json","yarn.lock","bun.lockb","CHANGELOG.md"],JE=/This reverts commit ([0-9a-f]{7,40})/u,ch=/^Revert "(.*)"(?: \(#\d+\))?$/u,lh="",Ni="",uh=`--format=${lh}%H${Ni}%ct${Ni}%B${Ni}`,dh=e=>e.split(lh).filter(t=>t.trim()!=="").map(t=>{let[r="",n="0",o="",s=""]=t.split(Ni),i=o.trim();return{hash:r,committedAt:Number(n),subject:i.split(`
157
157
  `)[0]??"",body:i,files:s.split(`
158
- `).map(a=>a.trim()).filter(Boolean)}}),WE=e=>BE.some(t=>t.test(e.body))?"agent":"human",Il=e=>th.test(e.subject),VE=e=>!Il(e)&&Ol.test(e.subject),GE=(e,t)=>{if(t===0)return null;let r=e/t,n=Al*Al,o=1+n/t,s=(r+n/(2*t))/o,i=Al*Math.sqrt(r*(1-r)/t+n/(4*t*t))/o;return{low:Math.max(0,s-i),high:Math.min(1,s+i)}},Oi=e=>Math.round(e*1e4)/1e4,eh=(e,t)=>{let r=GE(e,t);return{hits:e,n:t,rate:t===0?null:Oi(e/t),ci95:r&&{low:Oi(r.low),high:Oi(r.high)}}},JE=e=>{let t=new Set;for(let[r,n]of e.entries()){if(!Il(n))continue;let o=e.slice(0,r),s=UE.exec(n.body)?.[1],i=th.exec(n.subject)?.[1],a=s?o.find(c=>c.hash.startsWith(s)):o.findLast(c=>c.subject===i);a&&t.add(a.hash)}return t},KE=(e,t)=>{let r=new Set(e.files.filter(n=>!Dl.includes(n.split("/").at(-1)??n)));return t.files.some(n=>r.has(n))},HE=(e,t,r)=>r.slice(t+1).some(n=>n.committedAt-e.committedAt<=259200&&VE(n)&&KE(e,n)),sh=(e,t)=>{let r=JE(e),n=o=>{let s=e.map((u,p)=>({commit:u,position:p})).filter(({commit:u})=>o(WE(u))),i=s.filter(({commit:u})=>!Il(u)),a=i.filter(({commit:u})=>t-u.committedAt>=259200),c=i.filter(({commit:u})=>r.has(u.hash)).length,l=a.filter(({commit:u,position:p})=>HE(u,p,e)).length;return{commits:s.length,reverts:s.length-i.length,changes:i.length,revertRate:eh(c,i.length),followUpFixRate:eh(l,a.length)}};return{agent:n(o=>o==="agent"),human:n(o=>o==="human"),total:n(()=>!0)}},Nl=(e,t)=>{let r=[e.n<30?`agent n=${e.n}`:null,t.n<30?`human n=${t.n}`:null].filter(Boolean);return r.length>0||e.rate===null||t.rate===null||!e.ci95||!t.ci95?{suppressed:!0,reason:`${r.join(", ")} < 30`,difference:null,intervalsOverlap:null}:{suppressed:!1,reason:null,difference:Oi(e.rate-t.rate),intervalsOverlap:e.ci95.low<=t.ci95.high&&t.ci95.low<=e.ci95.high}};var So=90,zE=864e5,XE=async(e,t)=>{if(await Ce(e,"HEAD")===null)return[];let r=`--since=${t}`,n=await YE({cwd:e,quiet:!0})`git log --no-merges --name-only ${r} ${nh}`;return oh(n.stdout).toReversed().sort((o,s)=>o.committedAt-s.committedAt)},uh=async({cwd:e,sinceDays:t,nowMs:r})=>{let n=new Date(r-t*zE).toISOString(),o=await XE(e,n),s=sh(o,Math.floor(r/1e3));return{repoRoot:e,sinceDays:t,from:n,until:new Date(r).toISOString(),classes:s,comparison:{minN:30,revertRate:Nl(s.agent.revertRate,s.human.revertRate),followUpFixRate:Nl(s.agent.followUpFixRate,s.human.followUpFixRate)},heuristics:{agentTrailers:["Co-Authored-By: Claude\u2026","Claude-Session:"],fixSubjectPattern:Ol.source,followUpWindowHours:72,followUpIgnoredFiles:Dl,mergesExcluded:!0}}},Di=e=>`${(e*100).toFixed(1)}%`,ih=e=>e.rate===null||!e.ci95?"n/a (n=0)":`${Di(e.rate)} (${e.hits}/${e.n}, 95% CI ${Di(e.ci95.low)}\u2013${Di(e.ci95.high)})`,_l=(e,t)=>[` ${e}: ${t.commits} commits (${t.reverts} reverts)`,` revert rate: ${ih(t.revertRate)}`,` ${72}h follow-up-fix rate: ${ih(t.followUpFixRate)}`].join(`
159
- `),Ii=async({since:e=So})=>{let t=await uh({cwd:await $(),sinceDays:e,nowMs:Date.now()}),{classes:r,comparison:n}=t;d.info(`Change stats for ${t.repoRoot} \u2014 last ${e} days (${t.from.slice(0,10)} \u2192 ${t.until.slice(0,10)}, merges excluded)`),d.info(_l("agent",r.agent)),d.info(_l("human",r.human)),d.info(_l("total",r.total));let o=(s,i)=>{if(i.suppressed)return` ${s}: comparison suppressed (${i.reason})`;let a=i.intervalsOverlap?"intervals overlap":"intervals do not overlap";return` ${s}: agent \u2212 human = ${Di(i.difference??0)} (${a})`};return d.info(["Agent vs human:",o("revert rate",n.revertRate),o("follow-up-fix rate",n.followUpFixRate)].join(`
160
- `)),{content:b(JSON.stringify(t,null,2)),structuredContent:t}},ah=F.object({hits:F.number().describe("Changes that hit the metric"),n:F.number().describe("Changes the rate is computed over"),rate:F.number().nullable().describe("hits / n, rounded to 4 places; null when n is 0"),ci95:F.object({low:F.number(),high:F.number()}).nullable().describe("Wilson 95% score interval; null when n is 0")}),Ml=F.object({commits:F.number().describe("Non-merge commits in range for this class"),reverts:F.number().describe("Of those, revert commits (excluded from both rate denominators)"),changes:F.number().describe("Non-revert commits \u2014 the revert-rate denominator"),revertRate:ah.describe("Changes later reverted by an in-range commit"),followUpFixRate:ah.describe("Changes at least 72h old followed within 72h by a fix-subject commit touching a shared file")}),ch=F.object({suppressed:F.boolean().describe("True when either class has n below minN"),reason:F.string().nullable(),difference:F.number().nullable().describe("agent rate \u2212 human rate"),intervalsOverlap:F.boolean().nullable().describe("Whether the two Wilson intervals overlap")}),jl=C({name:"change-stats",description:"Read-only change-failure baseline for the git repo at cwd: commits classified agent (Claude trailers) vs human, with revert rate and 72h follow-up-fix rate per class, each with n and a Wilson 95% interval. The agent-vs-human comparison is suppressed when either n < 30.",inputSchema:{since:F.number().int().positive().optional().describe(`Window in days, ending now (default ${So})`)},outputSchema:{repoRoot:F.string().describe("git toplevel the stats were read from"),sinceDays:F.number(),from:F.string().describe("ISO start of the window"),until:F.string().describe("ISO end of the window (now)"),classes:F.object({agent:Ml,human:Ml,total:Ml}),comparison:F.object({minN:F.number(),revertRate:ch,followUpFixRate:ch}),heuristics:F.object({agentTrailers:F.array(F.string()),fixSubjectPattern:F.string(),followUpWindowHours:F.number(),followUpIgnoredFiles:F.array(F.string()),mergesExcluded:F.boolean()})},handler:Ii});import{z as Ht}from"zod";import Fl from"node:fs/promises";import ZE from"node:path";var nn=()=>Object.keys(bf.shape).filter(e=>e!=="$schema"&&e!=="configVersion"),QE=new Set(["protectedEnvs"]),Eo={project:"per-project override",global:"user-global override"},Ni=(e,t)=>{if(he()&&QE.has(e))throw new O({status:"refused",agentMode:j.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(!nn().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: ${nn().join(", ")}.`)}},dh=e=>{try{return JSON.parse(e)}catch{return e}},eP=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),tP=async e=>{let t;try{t=await Fl.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 ${w(e)}: ${n.message} \u2014 fix it with \`infra-kit config edit\`.`)}if(!eP(r))throw new Error(`${w(e)} is not a JSON object \u2014 fix it with \`infra-kit config edit\`.`);return{raw:t,data:r}},rP=async(e,t)=>{t===null?await Fl.rm(e,{force:!0}):Mt(e,t,420),eo()},_i=async(e,t,r)=>{let n=await ee(),o=e==="global"?n.userGlobal:n.userProject,{raw:s,data:i}=await tP(o),a=i[t],c=r({...i});if(c===null)return{file:o,previous:a,changed:!1};await Fl.mkdir(ZE.dirname(o),{recursive:!0}),Mt(o,`${JSON.stringify(c,null,2)}
161
- `,420),eo();try{await K({autoMigrate:"off"})}catch(l){throw await rP(o,s),new Error(`${l.message}
162
- ${w(o)} was left unchanged.`)}return{file:o,previous:a,changed:!0}},Ll=async({key:e,value:t,global:r})=>{Ni(e,"config-set");let n=r?"global":"project",o=dh(t),{file:s,previous:i}=await _i(n,e,c=>({...c,[e]:o}));d.info(`Set ${e} = ${JSON.stringify(o)} in the ${Eo[n]} (${w(s)})`);let a={key:e,value:o,previous:i??null,scope:n,path:s};return{content:b(JSON.stringify(a,null,2)),structuredContent:a}};var Mi=async({key:e}={})=>{let[t,r]=await Promise.all([K(),ee()]),n=t;if(e===void 0){let s=Object.keys(t).sort();d.info(`Merged config for ${r.projectName} \u2014 ${s.length} section(s): ${s.join(", ")}`),d.info(` source: ${r.main}`)}else{if(!nn().includes(e))throw new Error(`Unknown config key "${e}". Top-level keys: ${nn().join(", ")}.`);d.info(`${e} = ${JSON.stringify(n[e]??null,null,2)}`)}let o={config:n,configPath:r.main,projectName:r.projectName,...e===void 0?{}:{key:e,value:n[e]??null}};return{content:b(JSON.stringify(o,null,2)),structuredContent:o}},nP={config:Ht.record(Ht.string(),Ht.unknown()).describe("The fully resolved infra-kit configuration \u2014 the same object every command sees at runtime, after the project infra-kit.json, the user-global, and the user-scope per-project override layers are merged (later layers win). Top-level sections include envManagement, worktrees, and protectedEnvs."),configPath:Ht.string().describe("Absolute path to the project-level infra-kit.json (the base layer / committed source of truth)."),key:Ht.string().optional().describe("The top-level key asked for, when one was."),value:Ht.unknown().optional().describe("The merged value of `key` (null when no layer sets it)."),projectName:Ht.string().describe("Repository name the config is keyed to (the main-repo basename; shared across all worktrees of the repo).")},Bl=C({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:Ht.string().optional().describe("Report only this top-level key as `value` (e.g. `ide`).")},outputSchema:nP,handler:e=>Mi(e)});import lP from"node:fs";import{z as pe}from"zod";import xo from"node:fs";import on from"node:path";import oP from"node:process";var sP=on.join(".infra-kit","dev-context"),iP=".infra-kit",ph=(e,t)=>{let r=on.resolve(e);for(;;){let n=on.join(r,t);if(xo.existsSync(n))return n;let o=on.dirname(r);if(o===r)return;r=o}},aP=e=>{let t=ph(e,sP);if(t)return t;let r=ph(e,iP);return r?on.join(r,"dev-context"):void 0},Ul=e=>typeof e=="number"&&Number.isFinite(e)?e:0,Po=e=>typeof e=="string"?e:"",cP=(e,t,r)=>{let n=on.join(e,t);try{let o=xo.statSync(n),s=JSON.parse(xo.readFileSync(n,"utf-8"));if(typeof s!="object"||s===null)return null;let i=s;return{app:t.replace(/\.json$/,""),package:Po(i.package),port:Ul(i.port),alias:Po(i.alias),origin:Po(i.origin),release:Po(i.release),env:Po(i.env),pid:Ul(i.pid),writtenAt:Ul(i.writtenAt),mtimeMs:Math.round(o.mtimeMs),ageMs:Math.max(0,Math.round(r-o.mtimeMs))}}catch{return null}},To=(e=oP.cwd())=>{let t=Date.now(),r=aP(e);if(!r||!xo.existsSync(r))return{session:"none",fragmentDir:r,readAt:t,apps:[]};let n;try{n=xo.readdirSync(r).filter(s=>s.endsWith(".json"))}catch{return{session:"none",fragmentDir:r,readAt:t,apps:[]}}let o=n.map(s=>cP(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 ji=async(e={})=>{let t=e.now??Date.now,r=e.isListening??Xn,n=To(e.cwd),o=t(),s=await Promise.all(n.apps.map(async p=>{let m=Math.max(0,Math.round((o-p.mtimeMs)/1e3)),f=await r(p.port);return{app:p.app,package:p.package,port:p.port,pid:p.pid,alias:p.alias,origin:p.origin,release:p.release,env:p.env||null,writtenAt:p.writtenAt>0?new Date(p.writtenAt).toISOString():null,fragmentMtime:new Date(p.mtimeMs).toISOString(),ageSeconds:m,live:f}})),i=s.length>0,a=n.fragmentDir??null,c=a!==null&&(lP.statSync(a,{throwIfNoEntry:!1})?.isDirectory()??!1),l=a===null?"nothing (no .infra-kit anchor exists up-tree)":a;if(i){d.info(`infra-kit dev: ${s.length} app(s) with a dev-context fragment in ${l}:`);for(let p of s){let m=p.live?"live":"NOT responding",f=`written ${p.ageSeconds}s ago`;d.info(` ${p.app} (${p.package}) \u2192 ${p.origin} on :${p.port} \u2014 ${m}, ${f}`)}}else{let p=c?"no readable fragment found there":"that directory does not exist";d.info(`No active infra-kit dev session \u2014 searched ${l} (${p}).`)}let u={active:i,apps:s,contextDir:a,contextDirExists:c};return{content:b(JSON.stringify(u,null,2)),structuredContent:u}},uP={active:pe.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:pe.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:pe.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:pe.array(pe.object({app:pe.string().describe("App folder name (the fragment filename without .json)."),package:pe.string().describe("The app package name the vite helper reads to decide a local route."),port:pe.number().describe("The actual bound port the dev server is listening on."),pid:pe.number().describe("PID of the dev-server process that wrote the fragment (ownership / staleness metadata)."),alias:pe.string().describe("Registered portless hostname for the app."),origin:pe.string().describe("Authoritative local origin the vite helper proxies to for this app."),release:pe.string().describe("Release slug the runner recorded for this worktree."),env:pe.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:pe.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:pe.string().describe("ISO 8601 filesystem mtime of the fragment file \u2014 the AUTHORITATIVE freshness signal."),ageSeconds:pe.number().describe("Seconds since the fragment was last written on disk. A large value with live:false means a stale/abandoned fragment."),live:pe.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.")},Wl=C({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:uP,handler:()=>ji()});import{spawnSync as gv}from"node:child_process";import ae from"node:fs";import hv from"node:os";import ve from"node:path";import ht from"node:process";import{z as Ee}from"zod";import{execFileSync as dP}from"node:child_process";var mh=(e,t)=>{let r=e.filter(n=>!n.live).map(n=>n.name);return t?{prunable:[],withheld:r}:{prunable:r,withheld:[]}},pP=[/\binfra-kit\s+dev\b/,/cli\.js\s+dev\b/,/dev-server\.(?:js|ts)\b/],mP=e=>pP.some(t=>t.test(e)),fP="/bin/ps",gP=()=>dP(fP,["-eo","command="],{encoding:"utf8",maxBuffer:8<<20}).split(`
163
- `),fh=(e=gP)=>{try{return e().some(mP)}catch{return!0}};import{Chalk as hP}from"chalk";import Vl from"node:process";var Gl={unicode:{ok:"\u2713",changed:"+",skipped:"-",manual:">",warn:"!",fail:"\u2717",separator:"\xB7",rule:"\u2500"},ascii:{ok:"ok",changed:"++",skipped:"--",manual:">>",warn:"!?",fail:"!!",separator:"-",rule:"-"}},yP=new Set(["warn","fail"]),vP=24,sn=" ",gh=" ",wP=(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:[""]},hh=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},kP=e=>{let t=new hP({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)}},yh=(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),bP=(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=yh(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}},RP=(e,t,r,n)=>{let o=bP(hh(e.rows),e.rows.length,t,r),s=Math.max(1,n-sn.length-e.label.length-o.plainWidth);return`${sn}${t.header(e.label)}${" ".repeat(s)}${o.text}`},SP=(e,t,r,n,o)=>{let s=yP.has(e.status),i=n.ok.length,a=e.name.padEnd(t),c=r[e.status],l=s?c(a):a,u=gh.length+i+1+t+2,p=Math.max(vP,o-u),[m,...f]=wP(e.message,p),h=" ".repeat(u),S=A=>s?A:r.dim(A);return[`${gh}${c(n[e.status])} ${l} ${S(m??"")}`.trimEnd(),...f.map(A=>`${h}${S(A)}`),...(e.notes??[]).map(A=>`${h}${A}`.trimEnd())]},EP=(e,t,r,n,o)=>{let s=hh(t),i=n.rule.repeat(Math.max(12,Math.min(o-sn.length,56))),a=yh(s,()=>"warned"),c=[r.ok(`${s.ok} passed`),...a.map(u=>r[u.status](u.plain))].join(` ${n.separator} `),l=(e.hints??[]).map(u=>` ${r.dim(u)}`);return[`${sn}${r.dim(i)}`,`${sn}${c}${l.join("")}`]},Jl=(e,t={})=>{let r=t.width??80,n=kP(t.color??!1),o=t.unicode??!0?Gl.unicode:Gl.ascii,s=e.sections.filter(u=>u.rows.length>0),i=s.flatMap(u=>u.rows),a=n.bold(e.title);if(i.length===0)return[a,"",`${sn}${n.dim(e.emptyMessage??"Nothing ran.")}`];let c=Math.max(...i.map(u=>u.name.length)),l=s.flatMap(u=>[RP(u,n,o,r),...u.rows.flatMap(p=>SP(p,c,n,o,r)),""]);return[a,"",...l,...EP(e,i,n,o,r)]},PP=new Set(["","0","false","none"]),xP=["LC_ALL","LC_CTYPE","LANG"],TP=(e,t)=>e.NO_COLOR!==void 0&&e.NO_COLOR!==""?!1:e.FORCE_COLOR!==void 0?!PP.has(e.FORCE_COLOR.toLowerCase()):!!t.isTTY,CP=(e,t)=>{if(t)return!1;let r=xP.map(n=>e[n]).find(n=>n!==void 0&&n!=="");return r===void 0?!0:/UTF-?8/i.test(r)},Kl=(e={})=>{let t=e.env??Vl.env,r=e.stream??Vl.stderr;return{color:TP(t,r),unicode:CP(t,e.ascii??!1),width:r.columns??80}},pt=(e,t={})=>{(t.write??(n=>{Vl.stderr.write(n)}))(`${Jl(e,Kl(t)).join(`
158
+ `).map(a=>a.trim()).filter(Boolean)}}),KE=e=>VE.some(t=>t.test(e.body))?"agent":"human",jl=e=>ch.test(e.subject),HE=e=>!jl(e)&&_l.test(e.subject),qE=(e,t)=>{if(t===0)return null;let r=e/t,n=Nl*Nl,o=1+n/t,s=(r+n/(2*t))/o,i=Nl*Math.sqrt(r*(1-r)/t+n/(4*t*t))/o;return{low:Math.max(0,s-i),high:Math.min(1,s+i)}},_i=e=>Math.round(e*1e4)/1e4,ah=(e,t)=>{let r=qE(e,t);return{hits:e,n:t,rate:t===0?null:_i(e/t),ci95:r&&{low:_i(r.low),high:_i(r.high)}}},YE=e=>{let t=new Set;for(let[r,n]of e.entries()){if(!jl(n))continue;let o=e.slice(0,r),s=JE.exec(n.body)?.[1],i=ch.exec(n.subject)?.[1],a=s?o.find(c=>c.hash.startsWith(s)):o.findLast(c=>c.subject===i);a&&t.add(a.hash)}return t},zE=(e,t)=>{let r=new Set(e.files.filter(n=>!Ml.includes(n.split("/").at(-1)??n)));return t.files.some(n=>r.has(n))},XE=(e,t,r)=>r.slice(t+1).some(n=>n.committedAt-e.committedAt<=259200&&HE(n)&&zE(e,n)),ph=(e,t)=>{let r=YE(e),n=o=>{let s=e.map((u,p)=>({commit:u,position:p})).filter(({commit:u})=>o(KE(u))),i=s.filter(({commit:u})=>!jl(u)),a=i.filter(({commit:u})=>t-u.committedAt>=259200),c=i.filter(({commit:u})=>r.has(u.hash)).length,l=a.filter(({commit:u,position:p})=>XE(u,p,e)).length;return{commits:s.length,reverts:s.length-i.length,changes:i.length,revertRate:ah(c,i.length),followUpFixRate:ah(l,a.length)}};return{agent:n(o=>o==="agent"),human:n(o=>o==="human"),total:n(()=>!0)}},Fl=(e,t)=>{let r=[e.n<30?`agent n=${e.n}`:null,t.n<30?`human n=${t.n}`:null].filter(Boolean);return r.length>0||e.rate===null||t.rate===null||!e.ci95||!t.ci95?{suppressed:!0,reason:`${r.join(", ")} < 30`,difference:null,intervalsOverlap:null}:{suppressed:!1,reason:null,difference:_i(e.rate-t.rate),intervalsOverlap:e.ci95.low<=t.ci95.high&&t.ci95.low<=e.ci95.high}};var $o=90,eP=864e5,tP=async(e,t)=>{if(await Ae(e,"HEAD")===null)return[];let r=`--since=${t}`,n=await QE({cwd:e,quiet:!0})`git log --no-merges --name-only ${r} ${uh}`;return dh(n.stdout).toReversed().sort((o,s)=>o.committedAt-s.committedAt)},yh=async({cwd:e,sinceDays:t,nowMs:r})=>{let n=new Date(r-t*eP).toISOString(),o=await tP(e,n),s=ph(o,Math.floor(r/1e3));return{repoRoot:e,sinceDays:t,from:n,until:new Date(r).toISOString(),classes:s,comparison:{minN:30,revertRate:Fl(s.agent.revertRate,s.human.revertRate),followUpFixRate:Fl(s.agent.followUpFixRate,s.human.followUpFixRate)},heuristics:{agentTrailers:["Co-Authored-By: Claude\u2026","Claude-Session:"],fixSubjectPattern:_l.source,followUpWindowHours:72,followUpIgnoredFiles:Ml,mergesExcluded:!0}}},Mi=e=>`${(e*100).toFixed(1)}%`,mh=e=>e.rate===null||!e.ci95?"n/a (n=0)":`${Mi(e.rate)} (${e.hits}/${e.n}, 95% CI ${Mi(e.ci95.low)}\u2013${Mi(e.ci95.high)})`,Ll=(e,t)=>[` ${e}: ${t.commits} commits (${t.reverts} reverts)`,` revert rate: ${mh(t.revertRate)}`,` ${72}h follow-up-fix rate: ${mh(t.followUpFixRate)}`].join(`
159
+ `),ji=async({since:e=$o})=>{let t=await yh({cwd:await A(),sinceDays:e,nowMs:Date.now()}),{classes:r,comparison:n}=t;d.info(`Change stats for ${t.repoRoot} \u2014 last ${e} days (${t.from.slice(0,10)} \u2192 ${t.until.slice(0,10)}, merges excluded)`),d.info(Ll("agent",r.agent)),d.info(Ll("human",r.human)),d.info(Ll("total",r.total));let o=(s,i)=>{if(i.suppressed)return` ${s}: comparison suppressed (${i.reason})`;let a=i.intervalsOverlap?"intervals overlap":"intervals do not overlap";return` ${s}: agent \u2212 human = ${Mi(i.difference??0)} (${a})`};return d.info(["Agent vs human:",o("revert rate",n.revertRate),o("follow-up-fix rate",n.followUpFixRate)].join(`
160
+ `)),{content:R(JSON.stringify(t,null,2)),structuredContent:t}},fh=L.object({hits:L.number().describe("Changes that hit the metric"),n:L.number().describe("Changes the rate is computed over"),rate:L.number().nullable().describe("hits / n, rounded to 4 places; null when n is 0"),ci95:L.object({low:L.number(),high:L.number()}).nullable().describe("Wilson 95% score interval; null when n is 0")}),Bl=L.object({commits:L.number().describe("Non-merge commits in range for this class"),reverts:L.number().describe("Of those, revert commits (excluded from both rate denominators)"),changes:L.number().describe("Non-revert commits \u2014 the revert-rate denominator"),revertRate:fh.describe("Changes later reverted by an in-range commit"),followUpFixRate:fh.describe("Changes at least 72h old followed within 72h by a fix-subject commit touching a shared file")}),gh=L.object({suppressed:L.boolean().describe("True when either class has n below minN"),reason:L.string().nullable(),difference:L.number().nullable().describe("agent rate \u2212 human rate"),intervalsOverlap:L.boolean().nullable().describe("Whether the two Wilson intervals overlap")}),Ul=C({name:"change-stats",description:"Read-only change-failure baseline for the git repo at cwd: commits classified agent (Claude trailers) vs human, with revert rate and 72h follow-up-fix rate per class, each with n and a Wilson 95% interval. The agent-vs-human comparison is suppressed when either n < 30.",inputSchema:{since:L.number().int().positive().optional().describe(`Window in days, ending now (default ${$o})`)},outputSchema:{repoRoot:L.string().describe("git toplevel the stats were read from"),sinceDays:L.number(),from:L.string().describe("ISO start of the window"),until:L.string().describe("ISO end of the window (now)"),classes:L.object({agent:Bl,human:Bl,total:Bl}),comparison:L.object({minN:L.number(),revertRate:gh,followUpFixRate:gh}),heuristics:L.object({agentTrailers:L.array(L.string()),fixSubjectPattern:L.string(),followUpWindowHours:L.number(),followUpIgnoredFiles:L.array(L.string()),mergesExcluded:L.boolean()})},handler:ji});import{z as Yt}from"zod";import Wl from"node:fs/promises";import rP from"node:path";var cn=()=>Object.keys(Cf.shape).filter(e=>e!=="$schema"&&e!=="configVersion"),nP=new Set(["protectedEnvs"]),Ao={project:"per-project override",global:"user-global override"},Fi=(e,t)=>{if(ye()&&nP.has(e))throw new D({status:"refused",agentMode:F.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(!cn().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: ${cn().join(", ")}.`)}},vh=e=>{try{return JSON.parse(e)}catch{return e}},oP=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),sP=async e=>{let t;try{t=await Wl.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 ${w(e)}: ${n.message} \u2014 fix it with \`infra-kit config edit\`.`)}if(!oP(r))throw new Error(`${w(e)} is not a JSON object \u2014 fix it with \`infra-kit config edit\`.`);return{raw:t,data:r}},iP=async(e,t)=>{t===null?await Wl.rm(e,{force:!0}):Ft(e,t,420),io()},Li=async(e,t,r)=>{let n=await Y(),o=e==="global"?n.userGlobal:n.userProject,{raw:s,data:i}=await sP(o),a=i[t],c=r({...i});if(c===null)return{file:o,previous:a,changed:!1};await Wl.mkdir(rP.dirname(o),{recursive:!0}),Ft(o,`${JSON.stringify(c,null,2)}
161
+ `,420),io();try{await J({autoMigrate:"off"})}catch(l){throw await iP(o,s),new Error(`${l.message}
162
+ ${w(o)} was left unchanged.`)}return{file:o,previous:a,changed:!0}},Gl=async({key:e,value:t,global:r})=>{Fi(e,"config-set");let n=r?"global":"project",o=vh(t),{file:s,previous:i}=await Li(n,e,c=>({...c,[e]:o}));d.info(`Set ${e} = ${JSON.stringify(o)} in the ${Ao[n]} (${w(s)})`);let a={key:e,value:o,previous:i??null,scope:n,path:s};return{content:R(JSON.stringify(a,null,2)),structuredContent:a}};var Bi=async({key:e}={})=>{let[t,r]=await Promise.all([J(),Y()]),n=t;if(e===void 0){let s=Object.keys(t).sort();d.info(`Merged config for ${r.projectName} \u2014 ${s.length} section(s): ${s.join(", ")}`),d.info(` source: ${r.main}`)}else{if(!cn().includes(e))throw new Error(`Unknown config key "${e}". Top-level keys: ${cn().join(", ")}.`);d.info(`${e} = ${JSON.stringify(n[e]??null,null,2)}`)}let o={config:n,configPath:r.main,projectName:r.projectName,...e===void 0?{}:{key:e,value:n[e]??null}};return{content:R(JSON.stringify(o,null,2)),structuredContent:o}},aP={config:Yt.record(Yt.string(),Yt.unknown()).describe("The fully resolved infra-kit configuration \u2014 the same object every command sees at runtime, after the project infra-kit.json, the user-global, and the user-scope per-project override layers are merged (later layers win). Top-level sections include envManagement, worktrees, and protectedEnvs."),configPath:Yt.string().describe("Absolute path to the project-level infra-kit.json (the base layer / committed source of truth)."),key:Yt.string().optional().describe("The top-level key asked for, when one was."),value:Yt.unknown().optional().describe("The merged value of `key` (null when no layer sets it)."),projectName:Yt.string().describe("Repository name the config is keyed to (the main-repo basename; shared across all worktrees of the repo).")},Vl=C({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:Yt.string().optional().describe("Report only this top-level key as `value` (e.g. `ide`).")},outputSchema:aP,handler:e=>Bi(e)});import mP from"node:fs";import{z as me}from"zod";import Do from"node:fs";import ln from"node:path";import cP from"node:process";var lP=ln.join(".infra-kit","dev-context"),uP=".infra-kit",wh=(e,t)=>{let r=ln.resolve(e);for(;;){let n=ln.join(r,t);if(Do.existsSync(n))return n;let o=ln.dirname(r);if(o===r)return;r=o}},dP=e=>{let t=wh(e,lP);if(t)return t;let r=wh(e,uP);return r?ln.join(r,"dev-context"):void 0},Jl=e=>typeof e=="number"&&Number.isFinite(e)?e:0,Oo=e=>typeof e=="string"?e:"",pP=(e,t,r)=>{let n=ln.join(e,t);try{let o=Do.statSync(n),s=JSON.parse(Do.readFileSync(n,"utf-8"));if(typeof s!="object"||s===null)return null;let i=s;return{app:t.replace(/\.json$/,""),package:Oo(i.package),port:Jl(i.port),alias:Oo(i.alias),origin:Oo(i.origin),release:Oo(i.release),env:Oo(i.env),pid:Jl(i.pid),writtenAt:Jl(i.writtenAt),mtimeMs:Math.round(o.mtimeMs),ageMs:Math.max(0,Math.round(r-o.mtimeMs))}}catch{return null}},Io=(e=cP.cwd())=>{let t=Date.now(),r=dP(e);if(!r||!Do.existsSync(r))return{session:"none",fragmentDir:r,readAt:t,apps:[]};let n;try{n=Do.readdirSync(r).filter(s=>s.endsWith(".json"))}catch{return{session:"none",fragmentDir:r,readAt:t,apps:[]}}let o=n.map(s=>pP(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 Ui=async(e={})=>{let t=e.now??Date.now,r=e.isListening??no,n=Io(e.cwd),o=t(),s=await Promise.all(n.apps.map(async p=>{let m=Math.max(0,Math.round((o-p.mtimeMs)/1e3)),f=await r(p.port);return{app:p.app,package:p.package,port:p.port,pid:p.pid,alias:p.alias,origin:p.origin,release:p.release,env:p.env||null,writtenAt:p.writtenAt>0?new Date(p.writtenAt).toISOString():null,fragmentMtime:new Date(p.mtimeMs).toISOString(),ageSeconds:m,live:f}})),i=s.length>0,a=n.fragmentDir??null,c=a!==null&&(mP.statSync(a,{throwIfNoEntry:!1})?.isDirectory()??!1),l=a===null?"nothing (no .infra-kit anchor exists up-tree)":a;if(i){d.info(`infra-kit dev: ${s.length} app(s) with a dev-context fragment in ${l}:`);for(let p of s){let m=p.live?"live":"NOT responding",f=`written ${p.ageSeconds}s ago`;d.info(` ${p.app} (${p.package}) \u2192 ${p.origin} on :${p.port} \u2014 ${m}, ${f}`)}}else{let p=c?"no readable fragment found there":"that directory does not exist";d.info(`No active infra-kit dev session \u2014 searched ${l} (${p}).`)}let u={active:i,apps:s,contextDir:a,contextDirExists:c};return{content:R(JSON.stringify(u,null,2)),structuredContent:u}},fP={active:me.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:me.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:me.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:me.array(me.object({app:me.string().describe("App folder name (the fragment filename without .json)."),package:me.string().describe("The app package name the vite helper reads to decide a local route."),port:me.number().describe("The actual bound port the dev server is listening on."),pid:me.number().describe("PID of the dev-server process that wrote the fragment (ownership / staleness metadata)."),alias:me.string().describe("Registered portless hostname for the app."),origin:me.string().describe("Authoritative local origin the vite helper proxies to for this app."),release:me.string().describe("Release slug the runner recorded for this worktree."),env:me.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:me.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:me.string().describe("ISO 8601 filesystem mtime of the fragment file \u2014 the AUTHORITATIVE freshness signal."),ageSeconds:me.number().describe("Seconds since the fragment was last written on disk. A large value with live:false means a stale/abandoned fragment."),live:me.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.")},Kl=C({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:fP,handler:()=>Ui()});import{spawnSync as kv}from"node:child_process";import ce from"node:fs";import bv from"node:os";import ke from"node:path";import vt from"node:process";import{z as xe}from"zod";import{execFileSync as gP}from"node:child_process";var kh=(e,t)=>{let r=e.filter(n=>!n.live).map(n=>n.name);return t?{prunable:[],withheld:r}:{prunable:r,withheld:[]}},hP=[/\binfra-kit\s+dev\b/,/cli\.js\s+dev\b/,/dev-server\.(?:js|ts)\b/],yP=e=>hP.some(t=>t.test(e)),vP="/bin/ps",wP=()=>gP(vP,["-eo","command="],{encoding:"utf8",maxBuffer:8<<20}).split(`
163
+ `),bh=(e=wP)=>{try{return e().some(yP)}catch{return!0}};import{Chalk as kP}from"chalk";import Hl from"node:process";var ql={unicode:{ok:"\u2713",changed:"+",skipped:"-",manual:">",warn:"!",fail:"\u2717",separator:"\xB7",rule:"\u2500"},ascii:{ok:"ok",changed:"++",skipped:"--",manual:">>",warn:"!?",fail:"!!",separator:"-",rule:"-"}},bP=new Set(["warn","fail"]),RP=24,un=" ",Rh=" ",SP=(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:[""]},Sh=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},EP=e=>{let t=new kP({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)}},Eh=(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),PP=(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=Eh(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}},xP=(e,t,r,n)=>{let o=PP(Sh(e.rows),e.rows.length,t,r),s=Math.max(1,n-un.length-e.label.length-o.plainWidth);return`${un}${t.header(e.label)}${" ".repeat(s)}${o.text}`},TP=(e,t,r,n,o)=>{let s=bP.has(e.status),i=n.ok.length,a=e.name.padEnd(t),c=r[e.status],l=s?c(a):a,u=Rh.length+i+1+t+2,p=Math.max(RP,o-u),[m,...f]=SP(e.message,p),h=" ".repeat(u),b=k=>s?k:r.dim(k);return[`${Rh}${c(n[e.status])} ${l} ${b(m??"")}`.trimEnd(),...f.map(k=>`${h}${b(k)}`),...(e.notes??[]).map(k=>`${h}${k}`.trimEnd())]},CP=(e,t,r,n,o)=>{let s=Sh(t),i=n.rule.repeat(Math.max(12,Math.min(o-un.length,56))),a=Eh(s,()=>"warned"),c=[r.ok(`${s.ok} passed`),...a.map(u=>r[u.status](u.plain))].join(` ${n.separator} `),l=(e.hints??[]).map(u=>` ${r.dim(u)}`);return[`${un}${r.dim(i)}`,`${un}${c}${l.join("")}`]},Yl=(e,t={})=>{let r=t.width??80,n=EP(t.color??!1),o=t.unicode??!0?ql.unicode:ql.ascii,s=e.sections.filter(u=>u.rows.length>0),i=s.flatMap(u=>u.rows),a=n.bold(e.title);if(i.length===0)return[a,"",`${un}${n.dim(e.emptyMessage??"Nothing ran.")}`];let c=Math.max(...i.map(u=>u.name.length)),l=s.flatMap(u=>[xP(u,n,o,r),...u.rows.flatMap(p=>TP(p,c,n,o,r)),""]);return[a,"",...l,...CP(e,i,n,o,r)]},$P=new Set(["","0","false","none"]),AP=["LC_ALL","LC_CTYPE","LANG"],OP=(e,t)=>e.NO_COLOR!==void 0&&e.NO_COLOR!==""?!1:e.FORCE_COLOR!==void 0?!$P.has(e.FORCE_COLOR.toLowerCase()):!!t.isTTY,DP=(e,t)=>{if(t)return!1;let r=AP.map(n=>e[n]).find(n=>n!==void 0&&n!=="");return r===void 0?!0:/UTF-?8/i.test(r)},zl=(e={})=>{let t=e.env??Hl.env,r=e.stream??Hl.stderr;return{color:OP(t,r),unicode:DP(t,e.ascii??!1),width:r.columns??80}},ft=(e,t={})=>{(t.write??(n=>{Hl.stderr.write(n)}))(`${Yl(e,zl(t)).join(`
164
164
  `)}
165
- `)};var $P="Tools & CLIs",AP="Shell & integration",OP="Project config",DP="Doppler env tokens",IP="Dev proxy (portless)",NP="Claude Code plugin",_P=`portless serving TLS on :${Ft}`,Hl=[[$P,["brew installed","git installed","gh installed","gh authenticated","doppler installed","aws installed","package manager installed","typescript-language-server installed","orca installed"]],[AP,["zshrc init block","zshenv session block","pnpm enableGlobalVirtualStore","CLAUDE.md block","Guidance version"]],[OP,["infra-kit config valid","user override path","legacy user-global config","merge-dev resolutions"]],[DP,["tokens.json present","env tokens configured","tokens.json perms"]],[IP,["portless installed","portless node","portless service target",_P,"portless CA chain valid","portless CA trusted","portless routes"]],[NP,["claude CLI","marketplace registered","plugin installed","plugin version","plugin MCP server","CLI version","background setup","claude in chrome","Agent mode","Agent allowlist"]]],vh="Other",MP=Hl.map(([e])=>e),jP=new Map(Hl.flatMap(([e,t])=>t.map(r=>[r,e]))),OV=Hl.flatMap(([,e])=>e),ql=new Set(["portless routes","tokens.json perms"]),FP=e=>{let t=new Map;for(let n of e){let o=jP.get(n.name)??vh,s=t.get(o);s?s.push(n):t.set(o,[n])}return[...MP,vh].flatMap(n=>{let o=t.get(n);return o&&o.length>0?[{label:n,checks:o}]:[]})};var LP=e=>{switch(e){case"pass":return"ok";case"fail":return"fail";case"warn":return"warn";case"skip":return"skipped";default:return We(e)}},BP=e=>{let t=e.filter(r=>r.status==="fail"&&ql.has(r.name)).length;return{title:"infra-kit doctor",emptyMessage:"No checks ran.",sections:FP(e).map(r=>({label:r.label,rows:r.checks.map(n=>({name:n.name,status:LP(n.status),message:n.message}))})),hints:t>0?[`${t} fixable \u2014 run \`infra-kit doctor --fix\``]:[]}};var Yl=(e,t={})=>{pt(BP(e),t)};var UP=e=>e.replace(/&apos;/g,"'").replace(/&quot;/g,'"').replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&amp;/g,"&"),WP=e=>[...e.matchAll(/<string>([\s\S]*?)<\/string>/g)].map(t=>UP(t[1])),VP=e=>{let t=e.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/);return t===null?null:WP(t[1])},GP=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},JP=e=>{let t=e.split(`
166
- `).find(r=>r.startsWith("ExecStart="));return t===void 0?null:GP(t.slice(10))},wh=(e,t)=>{try{return e==="darwin"?VP(t):e==="linux"?JP(t):null}catch{return null}};import{Buffer as Fh}from"node:buffer";import Me from"node:fs/promises";import tt from"node:path";import Lh from"node:process";import{$ as qi}from"zx";import KP from"node:process";var Co=class extends Error{name="PromptCancelledError";constructor(){super("Prompt cancelled")}};var kh=e=>{let t={operation:"interactive branch selection",remediation:"pass the branch selection explicitly (`--version`/`--versions`/`--all`) for non-interactive, --json, or --agent runs"};if(X())throw new O({status:"argument_required",argument:e,agentMode:j.source},2,t);if(!KP.stdin.isTTY)throw new g(void 0,t)},qt=async e=>{kh("version");let{runBranchPicker:t}=await import("./boot-ST2534PA.js"),r=await t(e);if(r===null)throw new Co;return r},Yt=async(e,t)=>{kh("versions");let{runBranchMultiPicker:r}=await import("./boot-ST2534PA.js"),n=await r(e,t);if(n===null)throw new Co;return n};import{$ as Th}from"zx";import{$ as WV}from"zx";import{$ as cn}from"zx";import{$ as bh}from"zx";var zl=async e=>{let{operation:t}=e;try{await bh({quiet:!0})`git rev-parse --git-dir`}catch(r){throw new g(r,{operation:t,remediation:"run this from inside a git repository"})}try{await bh({quiet:!0})`git remote get-url origin`}catch(r){throw new g(r,{operation:t,remediation:"this repository has no `origin` remote to fetch from or push to"})}},qP=4,an=async e=>{let{operation:t}=e,r=await af();if(r.length===0)return;d.error(`working tree has uncommitted changes:
165
+ `)};var IP="Tools & CLIs",NP="Shell & integration",_P="Project config",MP="Doppler env tokens",jP="Dev proxy (portless)",FP="Claude Code plugin",LP=`portless serving TLS on :${Bt}`,Xl=[[IP,["brew installed","git installed","gh installed","gh authenticated","doppler installed","aws installed","package manager installed","typescript-language-server installed","orca installed"]],[NP,["zshrc init block","zshenv session block","pnpm enableGlobalVirtualStore","CLAUDE.md block","Guidance version"]],[_P,["infra-kit config valid","user override path","legacy user-global config","merge-dev resolutions"]],[MP,["tokens.json present","env tokens configured","tokens.json perms"]],[jP,["portless installed","portless node","portless service target",LP,"portless CA chain valid","portless CA trusted","portless routes"]],[FP,["claude CLI","marketplace registered","plugin installed","plugin version","plugin MCP server","CLI version","background setup","claude in chrome","Agent mode","Agent allowlist"]]],Ph="Other",BP=Xl.map(([e])=>e),UP=new Map(Xl.flatMap(([e,t])=>t.map(r=>[r,e]))),BG=Xl.flatMap(([,e])=>e),Zl=new Set(["portless routes","tokens.json perms"]),WP=e=>{let t=new Map;for(let n of e){let o=UP.get(n.name)??Ph,s=t.get(o);s?s.push(n):t.set(o,[n])}return[...BP,Ph].flatMap(n=>{let o=t.get(n);return o&&o.length>0?[{label:n,checks:o}]:[]})};var GP=e=>{switch(e){case"pass":return"ok";case"fail":return"fail";case"warn":return"warn";case"skip":return"skipped";default:return Ve(e)}},VP=e=>{let t=e.filter(r=>r.status==="fail"&&Zl.has(r.name)).length;return{title:"infra-kit doctor",emptyMessage:"No checks ran.",sections:WP(e).map(r=>({label:r.label,rows:r.checks.map(n=>({name:n.name,status:GP(n.status),message:n.message}))})),hints:t>0?[`${t} fixable \u2014 run \`infra-kit doctor --fix\``]:[]}};var Ql=(e,t={})=>{ft(VP(e),t)};var JP=e=>e.replace(/&apos;/g,"'").replace(/&quot;/g,'"').replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&amp;/g,"&"),KP=e=>[...e.matchAll(/<string>([\s\S]*?)<\/string>/g)].map(t=>JP(t[1])),HP=e=>{let t=e.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/);return t===null?null:KP(t[1])},qP=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},YP=e=>{let t=e.split(`
166
+ `).find(r=>r.startsWith("ExecStart="));return t===void 0?null:qP(t.slice(10))},xh=(e,t)=>{try{return e==="darwin"?HP(t):e==="linux"?YP(t):null}catch{return null}};import{Buffer as Gh}from"node:buffer";import Fe from"node:fs/promises";import nt from"node:path";import Vh from"node:process";import{$ as Zi}from"zx";import zP from"node:process";var No=class extends Error{name="PromptCancelledError";constructor(){super("Prompt cancelled")}};var Th=e=>{let t={operation:"interactive branch selection",remediation:"pass the branch selection explicitly (`--version`/`--versions`/`--all`) for non-interactive, --json, or --agent runs"};if(Q())throw new D({status:"argument_required",argument:e,agentMode:F.source},2,t);if(!zP.stdin.isTTY)throw new g(void 0,t)},zt=async e=>{Th("version");let{runBranchPicker:t}=await import("./boot-ST2534PA.js"),r=await t(e);if(r===null)throw new No;return r},Xt=async(e,t)=>{Th("versions");let{runBranchMultiPicker:r}=await import("./boot-ST2534PA.js"),n=await r(e,t);if(n===null)throw new No;return n};import{$ as Nh}from"zx";import{$ as XG}from"zx";import{$ as Rr}from"zx";import ZP from"node:fs/promises";import QP from"node:path";import{$ as ex}from"zx";var tx="infra-kit.json",eu="dev",ve="main",Ch=e=>e==="dev"?"dev":ve,te=async()=>{let{main:e}=await Y();try{await ZP.access(e)}catch{return eu}let t=(await J()).gitFlow??eu;return t==="dev"&&await rx(e),t},rx=async e=>{let t=`origin/${ve}:${tx}`,r=await ex({quiet:!0,nothrow:!0})`git -C ${QP.dirname(e)} show ${t}`;if(r.exitCode!==0)return;let n;try{n=JSON.parse(r.stdout)}catch{return}if(n?.gitFlow==="main")throw new g(void 0,{operation:"resolve the git flow",remediation:`origin/${ve} sets "gitFlow": "main" but this checkout's infra-kit.json does not \u2014 switch to ${ve} and pull, or rebase this branch onto it, then re-run`})},br=async()=>Ch(await te());import{$ as $h}from"zx";var tu=async e=>{let{operation:t}=e;try{await $h({quiet:!0})`git rev-parse --git-dir`}catch(r){throw new g(r,{operation:t,remediation:"run this from inside a git repository"})}try{await $h({quiet:!0})`git remote get-url origin`}catch(r){throw new g(r,{operation:t,remediation:"this repository has no `origin` remote to fetch from or push to"})}},nx=4,dn=async e=>{let{operation:t}=e,r=await ff();if(r.length===0)return;d.error(`working tree has uncommitted changes:
167
167
  ${r.join(`
168
- `)}`);let n=r.slice(0,qP),o=r.length-n.length,s=o>0?`${n.join(", ")} (+${o} more)`:n.join(", ");throw new g(void 0,{operation:t,remediation:"commit or stash your changes (`git stash -u`), then retry",stderrExcerpt:`working tree has uncommitted changes: ${s}`})},$o=async e=>{let{operation:t,base:r}=e;if(await Vr()===r)return;let n=(await st(await $())).find(o=>o.branch===r);if(n)throw new g(void 0,{operation:t,remediation:"close or remove that worktree, or run the release from it",stderrExcerpt:`base branch "${r}" is checked out in the worktree at ${n.path}`})},_e=async e=>{let{operation:t}=e;if(await lf())throw new g(void 0,{operation:t,remediation:"run this from the main repository checkout, not a linked git worktree",stderrExcerpt:"command run from inside a linked worktree"});await an({operation:t})};var YP=e=>e.map(t=>({pr:t,id:Q(t.headRefName)})).filter(t=>t.id!==null).sort((t,r)=>sf(t.id,r.id,{a:t.pr.createdAt,b:r.pr.createdAt})).map(t=>t.pr),Ao=200,Rh=(e,t)=>{e.length<Ao||d.warn({source:t,limit:Ao},`\u26A0\uFE0F ${t} returned ${Ao} PRs \u2014 the page is full, so older release PRs may be missing`)},zP=async()=>{let[e,t]=await Promise.all([cn`gh pr list --limit ${Ao} --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,cn`gh pr list --limit ${Ao} --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName,createdAt`]),r=JSON.parse(e.stdout),n=JSON.parse(t.stdout);Rh(r,"release PR discovery (base dev)"),Rh(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)}))},Oo="find open release PRs",Sh=async()=>{try{let e=await zP();if(e.length===0)throw new g(void 0,{operation:Oo,remediation:"open a release PR first, or check you are in the right repo"});return YP(e)}catch(e){throw e instanceof g?e:(d.debug({err:e},"Error fetching release PRs"),new g(e,{operation:"fetch release PRs"}))}},Fi=async()=>(await Sh()).map(t=>t.headRefName),XP=e=>{let t=Do(e.baseRefName);if(t===null)throw new g(void 0,{operation:"classify release PRs",remediation:"discovery returned a PR outside the dev/main base set \u2014 this is an infra-kit bug, please report it",stderrExcerpt:`${e.headRefName} (#${e.number}) targets ${e.baseRefName}`});let r=Xl(e.title)!==t;return(r||e.dualBase)&&d.warn({branch:e.headRefName,title:e.title,baseRefName:e.baseRefName},e.dualBase?`\u26A0\uFE0F ${e.headRefName} has open PRs to both dev and main \u2014 treated as a hotfix (base main)`:`\u26A0\uFE0F ${e.headRefName} is titled "${e.title}" but targets ${e.baseRefName} \u2014 treated as ${t} by its base`),{branch:e.headRefName,number:e.number,title:e.title,createdAt:e.createdAt,baseRefName:e.baseRefName,type:t,titleMismatch:r,dualBase:e.dualBase}},G=async()=>(await Sh()).map(XP),Li=async e=>{let{branch:t,body:r}=e;try{await cn({quiet:!0})`gh pr edit ${t} --body ${r}`}catch(n){throw d.error({error:n,branch:t},`Error updating release PR body for ${t}`),n}},ZP=async(e,t)=>{let r=cn({quiet:!0,nothrow:!0}),n=await r`git ls-remote --heads origin ${e}`,o=n.exitCode!==0,s=n.stdout.trim().length>0;if(o||s){d.error({branchName:e},o?`could not reach origin to check whether ${e} was pushed \u2014 the branch is left in place; check with \`git ls-remote --heads origin ${e}\` before deleting anything`:`release branch ${e} exists on origin without a PR \u2014 left in place; delete it with \`git push origin --delete ${e}\` once you are sure`);return}await r`git switch ${t}`,(await r`git branch -D ${e}`).exitCode!==0&&d.error({branchName:e},`could not remove the local branch ${e} after a failed release \u2014 delete it with \`git branch -D ${e}\` before retrying`)},Bi=async e=>{let{id:t,jiraVersionUrl:r,type:n,description:o,baseSha:s}=e,i=of(t,n),a=mt(n),c=cn({quiet:!0}),l=Te(t),u=Io(r,o);try{await an({operation:`create release branch ${l}`});let p=(await c`git rev-parse HEAD`).stdout.trim();if(p!==s)throw new g(void 0,{operation:`create release branch ${l}`,remediation:"something moved the checkout mid-run \u2014 re-run the release",stderrExcerpt:`expected to be on ${s.slice(0,8)} (${a}) but HEAD is ${p.slice(0,8)}`});await c`git checkout -b ${l}`;try{await c`git commit --allow-empty-message --allow-empty --message ''`,await c`git push -u origin ${l}`;let m=await c`gh pr create --title ${i} --body ${u} --base ${a} --head ${l}`;return{branchName:l,prUrl:m.stdout.trim()}}catch(m){throw await ZP(l,a),m}}catch(p){throw d.error({error:p,branchName:l},`Error creating release branch ${l}`),p}finally{await cn({quiet:!0,nothrow:!0})`git switch ${a}`}};import{$ as Zl}from"zx";var ln=async e=>{let t=await Zl`gh pr list --head ${e} --state all --json number,state,title,baseRefName,headRefName --limit 1`;return JSON.parse(t.stdout)[0]??null},Ql=async e=>{let t=await Zl`gh pr list --head ${e} --state open --limit 5 --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)},Ui=async e=>{try{let t=await Zl`gh pr view ${e} --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)}catch(t){throw new g(t,{operation:`fetch PR #${e}`,remediation:`check it exists with \`gh pr view ${e}\``})}};import _o from"node:process";var QP="x-seraph-loginreason",ex="AUTHENTICATED_FAILED",tx=(e,t=160)=>{let r=e.split(`
169
- `,1)[0].trim();return r.length>t?`${r.slice(0,t)}\u2026`:r},Ph=(e,t)=>t===ex||e===401?"auth":e===403?"forbidden":e===404?"not-found-or-forbidden":"other",Eh=(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}`,un=class extends Error{status;kind;body;context;constructor(t){let r=Ph(t.status,t.seraphLoginReason),n=tx(t.body);super(n===""?`${t.context}: ${Eh(r,t.status)}`:`${t.context}: ${Eh(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 un,xh=e=>e.headers.get(QP);var dn=async(e,t)=>{if(e.ok)return;let r=await e.text(),n=new un({status:e.status,seraphLoginReason:xh(e),body:r,context:t});throw d.debug({status:e.status,kind:n.kind,body:r},t),n},wr=(e,t)=>`${e.baseUrl}/projects/${t.projectId}/versions/${t.id}/tab/release-report-all-issues`,eu=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 dn(l,"Failed to create Jira version"),{success:!0,version:await l.json()}},pn=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 dn(a,"Failed to get Jira project versions"),await a.json()},$t=async(e,t)=>(await pn(t)).find(o=>o.name===e)||null,mn=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 dn(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}},tu=async(e,t)=>{let{versionName:r}=e,n=await $t(r,t);if(!n)throw new Error(`Version "${r}" not found in Jira project`);return await mn({versionId:n.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},t)},fn=async()=>{let e=_o.env.JIRA_BASE_URL,t=_o.env.JIRA_TOKEN||_o.env.JIRA_API_TOKEN,r=_o.env.JIRA_PROJECT_ID,n=_o.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(`
170
- `);throw new Error(i)}let s=Number.parseInt(r,10);if(Number.isNaN(s))throw new TypeError(`Invalid JIRA_PROJECT_ID: "${r}" must be a numeric value (e.g., 10001)`);return{baseUrl:e.replace(/\/$/,""),token:t,projectId:s,email:n}},At=async()=>{try{return await fn()}catch(e){return d.warn({err:e},"Jira configuration not available, skipping Jira integration"),null}};var Wi=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 dn(a,"Failed to get Jira version issue counts");let c=await a.json();return{issuesFixedCount:c.issuesFixedCount,issuesAffectedCount:c.issuesAffectedCount}},ru=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 dn(c,"Failed to remove Jira version")};var Ch="dev",$h={regular:"dev",hotfix:"main"},mt=e=>$h[e],Do=e=>{let t=Object.entries($h).find(([,r])=>r===e);return t?t[0]:null},Io=(e,t)=>(t??"").trim()!==""?`${e}
168
+ `)}`);let n=r.slice(0,nx),o=r.length-n.length,s=o>0?`${n.join(", ")} (+${o} more)`:n.join(", ");throw new g(void 0,{operation:t,remediation:"commit or stash your changes (`git stash -u`), then retry",stderrExcerpt:`working tree has uncommitted changes: ${s}`})},_o=async e=>{let{operation:t,base:r}=e;if(await Hr()===r)return;let n=(await at(await A())).find(o=>o.branch===r);if(n)throw new g(void 0,{operation:t,remediation:"close or remove that worktree, or run the release from it",stderrExcerpt:`base branch "${r}" is checked out in the worktree at ${n.path}`})},je=async e=>{let{operation:t}=e;if(await hf())throw new g(void 0,{operation:t,remediation:"run this from the main repository checkout, not a linked git worktree",stderrExcerpt:"command run from inside a linked worktree"});await dn({operation:t})};var ox=e=>e.map(t=>({pr:t,id:ee(t.headRefName)})).filter(t=>t.id!==null).sort((t,r)=>mf(t.id,r.id,{a:t.pr.createdAt,b:r.pr.createdAt})).map(t=>t.pr),pn=200,ru=(e,t)=>{e.length<pn||d.warn({source:t,limit:pn},`\u26A0\uFE0F ${t} returned ${pn} PRs \u2014 the page is full, so older release PRs may be missing`)},sx=async e=>{if(e==="main"){let l=await Rr`gh pr list --limit ${pn} --base ${ve} --json number,title,headRefName,state,baseRefName,createdAt`,u=JSON.parse(l.stdout);return ru(u,`release PR discovery (base ${ve})`),u.map(p=>({...p,dualBase:!1}))}let[t,r]=await Promise.all([Rr`gh pr list --limit ${pn} --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,Rr`gh pr list --limit ${pn} --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName,createdAt`]),n=JSON.parse(t.stdout),o=JSON.parse(r.stdout);ru(n,"release PR discovery (base dev)"),ru(o,"hotfix PR discovery (base main)");let s=new Set(n.map(l=>l.headRefName)),i=new Set(o.filter(l=>s.has(l.headRefName)).map(l=>l.headRefName)),a=[...o,...n],c=new Set;return a.filter(l=>c.has(l.headRefName)?!1:(c.add(l.headRefName),!0)).map(l=>({...l,dualBase:i.has(l.headRefName)}))},Mo="find open release PRs",Ah=async e=>{try{let t=await sx(e);if(t.length===0)throw new g(void 0,{operation:Mo,remediation:"open a release PR first, or check you are in the right repo"});return ox(t)}catch(t){throw t instanceof g?t:(d.debug({err:t},"Error fetching release PRs"),new g(t,{operation:"fetch release PRs"}))}},Wi=async()=>(await Ah(await te())).map(t=>t.headRefName),ix=(e,t)=>{let r=jo(e.baseRefName,t);if(r===null)throw new g(void 0,{operation:"classify release PRs",remediation:"discovery returned a PR outside the dev/main base set \u2014 this is an infra-kit bug, please report it",stderrExcerpt:`${e.headRefName} (#${e.number}) targets ${e.baseRefName}`});let n=nu(e.title)!==r;return(n||e.dualBase)&&d.warn({branch:e.headRefName,title:e.title,baseRefName:e.baseRefName},e.dualBase?`\u26A0\uFE0F ${e.headRefName} has open PRs to both dev and main \u2014 treated as a hotfix (base main)`:`\u26A0\uFE0F ${e.headRefName} is titled "${e.title}" but targets ${e.baseRefName} \u2014 treated as ${r} by its base`),{branch:e.headRefName,number:e.number,title:e.title,createdAt:e.createdAt,baseRefName:e.baseRefName,type:r,titleMismatch:n,dualBase:e.dualBase}},K=async()=>{let e=await te();return(await Ah(e)).map(r=>ix(r,e))},Gi=async e=>{let{branch:t,body:r}=e;try{await Rr({quiet:!0})`gh pr edit ${t} --body ${r}`}catch(n){throw d.error({error:n,branch:t},`Error updating release PR body for ${t}`),n}},ax=async(e,t)=>{let r=Rr({quiet:!0,nothrow:!0}),n=await r`git ls-remote --heads origin ${e}`,o=n.exitCode!==0,s=n.stdout.trim().length>0;if(o||s){d.error({branchName:e},o?`could not reach origin to check whether ${e} was pushed \u2014 the branch is left in place; check with \`git ls-remote --heads origin ${e}\` before deleting anything`:`release branch ${e} exists on origin without a PR \u2014 left in place; delete it with \`git push origin --delete ${e}\` once you are sure`);return}await r`git switch ${t}`,(await r`git branch -D ${e}`).exitCode!==0&&d.error({branchName:e},`could not remove the local branch ${e} after a failed release \u2014 delete it with \`git branch -D ${e}\` before retrying`)},Vi=async e=>{let{id:t,jiraVersionUrl:r,type:n,description:o,baseSha:s}=e,i=pf(t,n),a=gt(n,await te()),c=Rr({quiet:!0}),l=$e(t),u=Fo(r,o);try{await dn({operation:`create release branch ${l}`});let p=(await c`git rev-parse HEAD`).stdout.trim();if(p!==s)throw new g(void 0,{operation:`create release branch ${l}`,remediation:"something moved the checkout mid-run \u2014 re-run the release",stderrExcerpt:`expected to be on ${s.slice(0,8)} (${a}) but HEAD is ${p.slice(0,8)}`});await c`git checkout -b ${l}`;try{await c`git commit --allow-empty-message --allow-empty --message ''`,await c`git push -u origin ${l}`;let m=await c`gh pr create --title ${i} --body ${u} --base ${a} --head ${l}`;return{branchName:l,prUrl:m.stdout.trim()}}catch(m){throw await ax(l,a),m}}catch(p){throw d.error({error:p,branchName:l},`Error creating release branch ${l}`),p}finally{await Rr({quiet:!0,nothrow:!0})`git switch ${a}`}};import{$ as ou}from"zx";var mn=async e=>{let t=await ou`gh pr list --head ${e} --state all --json number,state,title,baseRefName,headRefName --limit 1`;return JSON.parse(t.stdout)[0]??null},su=async e=>{let t=await ou`gh pr list --head ${e} --state open --limit 5 --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)},Ji=async e=>{try{let t=await ou`gh pr view ${e} --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)}catch(t){throw new g(t,{operation:`fetch PR #${e}`,remediation:`check it exists with \`gh pr view ${e}\``})}};import Bo from"node:process";var cx="x-seraph-loginreason",lx="AUTHENTICATED_FAILED",ux=(e,t=160)=>{let r=e.split(`
169
+ `,1)[0].trim();return r.length>t?`${r.slice(0,t)}\u2026`:r},Dh=(e,t)=>t===lx||e===401?"auth":e===403?"forbidden":e===404?"not-found-or-forbidden":"other",Oh=(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}`,fn=class extends Error{status;kind;body;context;constructor(t){let r=Dh(t.status,t.seraphLoginReason),n=ux(t.body);super(n===""?`${t.context}: ${Oh(r,t.status)}`:`${t.context}: ${Oh(r,t.status)}. Jira said: ${n}`),this.name="JiraApiError",this.status=t.status,this.kind=r,this.body=t.body,this.context=t.context}},Lo=e=>e instanceof fn,Ih=e=>e.headers.get(cx);var gn=async(e,t)=>{if(e.ok)return;let r=await e.text(),n=new fn({status:e.status,seraphLoginReason:Ih(e),body:r,context:t});throw d.debug({status:e.status,kind:n.kind,body:r},t),n},Sr=(e,t)=>`${e.baseUrl}/projects/${t.projectId}/versions/${t.id}/tab/release-report-all-issues`,iu=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 gn(l,"Failed to create Jira version"),{success:!0,version:await l.json()}},hn=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 gn(a,"Failed to get Jira project versions"),await a.json()},Ot=async(e,t)=>(await hn(t)).find(o=>o.name===e)||null,yn=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 gn(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}},au=async(e,t)=>{let{versionName:r}=e,n=await Ot(r,t);if(!n)throw new Error(`Version "${r}" not found in Jira project`);return await yn({versionId:n.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},t)},vn=async()=>{let e=Bo.env.JIRA_BASE_URL,t=Bo.env.JIRA_TOKEN||Bo.env.JIRA_API_TOKEN,r=Bo.env.JIRA_PROJECT_ID,n=Bo.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(`
170
+ `);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}},Dt=async()=>{try{return await vn()}catch(e){return d.warn({err:e},"Jira configuration not available, skipping Jira integration"),null}};var Ki=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 gn(a,"Failed to get Jira version issue counts");let c=await a.json();return{issuesFixedCount:c.issuesFixedCount,issuesAffectedCount:c.issuesAffectedCount}},cu=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 gn(c,"Failed to remove Jira version")};var lu={dev:{regular:"dev",hotfix:ve},main:{regular:ve}},wn=e=>Object.keys(lu[e]),gt=(e,t)=>{let r=lu[t][e];if(r===void 0)throw new g(void 0,{operation:`use a ${e} release`,remediation:`this repo sets "gitFlow": "${t}" in infra-kit.json, which has only ${wn(t).join(" and ")} releases \u2014 create it as a regular release`});return r},jo=(e,t)=>{let r=Object.entries(lu[t]).find(([,n])=>n===e);return r?r[0]:null},Fo=(e,t)=>(t??"").trim()!==""?`${e}
171
171
 
172
172
  ${t}`:`${e}
173
- `,nu=async(e="regular")=>{let t=mt(e),r=Th({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 Th({quiet:!0,nothrow:!0})`git rev-list --left-right --count origin/${t}...${t}`,[s="?",i="?"]=o.exitCode===0?o.stdout.trim().split(/\s+/):[],a=i!=="0"||s!=="0";throw new g(n,{operation:`fast-forward ${t} onto origin/${t}`,remediation:a?`your local ${t} has diverged \u2014 rebase or reset it to origin/${t}, then retry`:`check your access to origin and that ${t} tracks it, then retry`,...a?{stderrExcerpt:`local ${t} is ${i} commit(s) ahead and ${s} behind origin/${t}`}:{}})}return(await r`git rev-parse HEAD`).stdout.trim()},rx=async e=>{let{versionName:t,jiraConfig:r,description:n,releaseDate:o}=e,s=await $t(t,r);if(!s)return(await eu({name:t,projectId:r.projectId,description:n||"",released:!1,archived:!1,...o===void 0?{}:{releaseDate:o}},r)).version;if(s.released||s.archived)throw new g(void 0,{operation:`reuse Jira fix version "${t}"`,remediation:"pick a different version, or un-release it in Jira first",stderrExcerpt:`fix version "${t}" is already ${s.released?"released":"archived"}`});let i=n||"",a={...i!==""&&i!==(s.description??"")?{description:i}:{},...o!==void 0&&o!==(s.releaseDate??"")?{releaseDate:o}:{}};if(Object.keys(a).length===0)return s;let c=await mn({versionId:s.id,...a},r);return{...s,...a,...a.releaseDate===void 0?{}:{releaseDate:c.version.releaseDate}}},ou=async e=>{let{id:t,jiraConfig:r,description:n,releaseDate:o,type:s="regular",baseSha:i}=e,a=le(t),c=await rx({versionName:a,jiraConfig:r,description:n,...o===void 0?{}:{releaseDate:o}}),l=wr(r,c),u=await Bi({id:t,jiraVersionUrl:l,type:s,description:n,baseSha:i});return{version:ne(t),type:s,branchName:u.branchName,prUrl:u.prUrl,jiraVersionUrl:l,releaseDate:c.releaseDate||null}},Vi=async()=>{let e=new Map,t=await At();if(!t)return e;try{let r=await pn(t);for(let n of r)e.set(n.name,{description:n.description||null,releaseDate:n.releaseDate||null})}catch(r){d.warn({err:r},"Jira descriptions unavailable \u2014 the release list will render without them. If this persists, check JIRA_EMAIL / JIRA_TOKEN.")}return e},me=async()=>{let e=await Vi();return new Map([...e].flatMap(([t,{description:r}])=>r?[[t,r]]:[]))},Mo=(e,t,r)=>{let n=r?" ".repeat(r-e.length+3):" ",o=`[${t}]`.padEnd(11);return`${e}${n}${o}`},Xl=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",Gi=e=>e.flatMap(t=>{let r=Q(t);return r?[{branch:t,id:r,label:ne(r)}]:[]}),Ot=e=>{try{return Te(ke(e))}catch(t){throw new g(t,{operation:`resolve release ref "${e}"`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")',stderrExcerpt:t instanceof Error?t.message:String(t)})}},jo=e=>{if(e===Ch)return Ch;let t=Q(e);return t?ne(t):e},Dt=e=>e.flatMap(t=>{let r=Q(t);return r?[ne(r)]:[]}),nx=(e,t)=>t?t.get(e)||"regular":void 0,fe=e=>{let{branches:t,descriptions:r,types:n}=e;return Gi(t).map(({branch:o,id:s,label:i})=>({value:o,label:i,description:r.get(le(s)),type:nx(o,n)}))};import Ah from"node:fs/promises";import ox from"node:path";import{$ as su}from"zx";var V="pnpm-lock.yaml",sx=/^(?:<{7}|={7}|>{7})(?:\s|$)/m,Dh=async(e,t)=>{let r=ox.join(e,V),n=`${t}:${V}`;try{let o=await su({cwd:e,quiet:!0})`git show ${n}`;await Ah.writeFile(r,o.stdout)}catch(o){return{ok:!1,reason:`dev has no ${V} to start from: ${Oh(o)}`}}try{await su({cwd:e,quiet:!0})`pnpm install --lockfile-only --ignore-scripts --no-frozen-lockfile`}catch(o){return{ok:!1,reason:`pnpm could not merge ${V}: ${Oh(o)}`}}return sx.test(await Ah.readFile(r,"utf8"))?{ok:!1,reason:`${V} still carries conflict markers after pnpm ran`}:(await su({cwd:e,quiet:!0})`git add -- ${V}`,{ok:!0})},Oh=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim()};import{$ as kr}from"zx";var iu="Merge remote-tracking branch 'origin/dev' into ",ix=e=>{let{stderr:t,message:r}=e;return String(t?.trim()||r||e).trim()},ax=2048,cx=e=>{let{stderr:t,stdout:r,exitCode:n}=e;return[t,r].map(s=>(s??"").trim().slice(-ax)).filter(s=>s.length>0).join(`
174
- `)||`the verify command exited with code ${n??"unknown"} and printed nothing`},lx=async e=>{try{return(await kr({cwd:e,quiet:!0})`git diff --name-only --diff-filter=U`).stdout.split(`
175
- `).map(r=>r.trim()).filter(r=>r.length>0)}catch{return[]}},ux=async(e,t)=>{let r=ix(t),n=await lx(e);return n.length>0?{status:"conflict",conflictPaths:n,reason:r}:await mf(e)?{status:"hook-failed",reason:r}:{status:"error",reason:r}},Ih=async e=>{let{cwd:t,worktreePath:r,branches:n}=e,o=[],s=await Ce(t,"origin/dev");if(!s)return n.map(i=>({branch:i,status:"error",reason:"origin/dev does not resolve"}));for(let i of n){let a=Date.now(),c=await dx({cwd:t,worktreePath:r,branch:i,devSha:s});o.push({...c,durationMs:Date.now()-a})}return o},dx=async e=>{let{cwd:t,worktreePath:r,branch:n,devSha:o}=e,s=`origin/${n}`;if(!await Ce(t,s))return{branch:n,status:"error",reason:`${s} does not exist on origin`};if(await Qn(t,"origin/dev",s))return{branch:n,status:"up-to-date"};try{await Tc(r),await kr({cwd:r,quiet:!0})`git checkout --detach ${s}`;let i=`${iu}${n}`;await kr({cwd:r,quiet:!0})`git merge origin/dev --no-edit -m ${i}`;let a=(await kr({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 ux(r,i)}}finally{await Cc(r)}},Nh=e=>e.flatMap(t=>t.mergeSha?[{branch:t.branch,sha:t.mergeSha}]:[]),_h="pnpm install --frozen-lockfile",Mh=async e=>{let{worktreePath:t,refs:r,command:n}=e,o=[],s=new Map;for(let i of r)try{await Tc(t),await kr({cwd:t,quiet:!0})`git checkout --detach ${i.sha}`,await kr({cwd:t,quiet:!0})`sh -c ${n}`,o.push(i)}catch(a){s.set(i.branch,cx(a))}finally{await Cc(t)}return{kept:o,failed:s}},Fo=async(e,t,r="origin/dev")=>{await kr({cwd:e,quiet:!0})`git fetch origin --prune`;let n=[],o=[];for(let s of t)await Qn(e,r,`origin/${s.branch}`)?o.push(s.branch):n.push(s);return{kept:n,nowUpToDate:o}};import au from"node:process";var Ji=new Set,Ki=e=>(Ji.add(e),()=>{Ji.delete(e)}),px=async()=>{for(let e of[...Ji])try{await e()}catch(t){d.warn({error:t,msg:"cleanup failed during shutdown"})}Ji.clear()},mx=["SIGINT","SIGTERM"],jh=async(e,t={})=>{let{register:r=(i,a)=>{au.on(i,a)},unregister:n=(i,a)=>{au.off(i,a)},exit:o=i=>{au.exit(i)}}=t,s=new Map;for(let i of mx){let a=()=>{px().then(()=>{o(Of(i))})};s.set(i,a),r(i,a)}try{return await e()}finally{for(let[i,a]of s)n(i,a)}};var fx="pnpm install --frozen-lockfile --ignore-scripts",cu="pnpm install --frozen-lockfile",Bh=64*1024,Jh=4096,Bo=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim().slice(-Jh)},U=async(e,t)=>(await qi({cwd:e,quiet:!0})`git ${t}`).stdout,uu=e=>e.split(`
176
- `).map(t=>t.trim()).filter(t=>t.length>0),hn=e=>e.split("\0").filter(t=>t.length>0),br=async(e,t)=>{try{return(await U(e,["rev-parse","-q","--verify",t])).trim()||null}catch{return null}},Kh=async e=>tt.resolve(e,(await U(e,["rev-parse","--git-common-dir"])).trim()),du=e=>e.then(()=>!0,()=>!1),Lo=()=>({results:[],atomicPush:{attempted:!1,aborted:!1},declined:!1}),pu=e=>e?.length===1&&e[0]===V,Hh=async e=>tt.join(await Kh(e),"infra-kit","merge-dev-resolutions"),mu=async(e,t)=>tt.join(await Hh(e),`${df(t)}.json`),qh=async e=>{try{return JSON.parse(await Me.readFile(e,"utf8"))}catch{return null}},yn=async(e,t)=>{let r=await mu(e,t.branch);await Me.mkdir(tt.dirname(r),{recursive:!0}),await Me.writeFile(r,`${JSON.stringify(t,null,2)}
177
- `)},Yh=async e=>{let t=await Hh(e),r=await Me.readdir(t).catch(()=>[]);return(await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(o=>qh(tt.join(t,o))))).filter(o=>o!==null)},zh=async e=>Promise.all((await Yh(e)).map(async t=>({branch:t.branch,worktreePath:t.worktreePath,createdAt:t.createdAt,worktreeExists:await du(Me.stat(t.worktreePath))}))),Uh=(e,t)=>({worktreePath:e.worktreePath,baseSha:e.baseSha,devSha:e.devSha,conflictPaths:e.conflictPaths,...e.editablePaths?{editablePaths:e.editablePaths}:{},lockfileOnly:e.lockfileOnly,rererePreResolved:e.rererePreResolved,state:t}),gx=e=>e.editablePaths??e.conflictPaths,hx=e=>tt.posix.basename(e)==="package.json",fu=e=>e.conflictPaths.includes(V)||e.lockfileBlob!==void 0,Xh=async(e,t)=>{if(!t.editablePaths)return t.conflictPaths.includes(V);if(t.lockfileBothSides||t.lockfileBlob!==void 0)return!0;let r=hn(await U(e,["diff","--cached","--name-only","-z","--no-renames",t.autoMergeTree]));return[...await hu(e),...r].some(hx)},Zh=e=>e.editablePaths?"only the editable paths may change":"only the conflicted paths may change",gu=async(e,t,r)=>{await U(e,["worktree","remove","--force",r]).catch(()=>Me.rm(r,{recursive:!0,force:!0})),await Me.rm(await mu(e,t),{force:!0}).catch(()=>{}),await U(e,["worktree","prune"]).catch(()=>{})},Qh=async e=>hn(await U(e,["diff","--name-only","-z","--diff-filter=U"])),Hi=async e=>hn(await U(e,["status","--porcelain","-z","--untracked-files=all","--ignored=matching"])).filter(r=>r.startsWith("!! ")).map(r=>r.slice(3)),yx=async(e,t)=>{let r=(await U(e,["config","--type=bool","--get","rerere.enabled"]).catch(()=>"")).trim(),n=await du(Me.stat(tt.join(await Kh(e),"rr-cache")));if(r==="false"||r===""&&!n)return[];let o=new Set(uu(await U(e,["rerere","remaining"])));return t.filter(s=>!o.has(s))},ey=e=>e.split("/").includes("node_modules"),Yi=async(e,t)=>{let r=new Set(gx(t));t.editablePaths&&await Xh(e,t)&&r.add(V);let n=new Set([...t.ignoredAtHandoff,...t.ignoredByVerify??[]]),o=hn(await U(e,["diff","--cached","--name-only","-z","--no-renames",t.autoMergeTree])),s=[...await hu(e),...o].filter(a=>!r.has(a)),i=(await Hi(e)).filter(a=>!n.has(a)&&!ey(a));return[...new Set([...s,...i,...await vx(e)])].sort()},hu=async e=>{let t=hn(await U(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},vx=async e=>(await U(e,["ls-files","-v"])).split(`
178
- `).filter(t=>{let r=t.charAt(0);return r==="S"||r!==""&&r!==r.toUpperCase()}).map(t=>t.slice(2)),wx=async(e,t)=>{let r=`:(exclude)${V}`;try{return await U(e,["diff","--cached","--check",t,"--",".",r]),[]}catch(n){let{stdout:o="",stderr:s="",exitCode:i}=n;if(s.trim().length>0||o.trim().length===0||i!==1&&i!==2)throw new g(n,{operation:"check the staged resolution for conflict markers"});let a=new Set;for(let c of o.split(`
179
- `)){let l=/^(.*):\d+: leftover conflict marker/.exec(c);l?.[1]&&a.add(l[1])}return[...a].sort()}},kx=async(e,t)=>{let r=[];for(let n of t)(await du(Me.lstat(tt.join(e,n)))||(await U(e,["--literal-pathspecs","ls-files","--",n])).length>0)&&r.push(n);r.length>0&&await U(e,["--literal-pathspecs","add","-A","--",...r])},lu=async e=>(await U(e,["write-tree"])).trim(),ty=async e=>(await U(e,["rev-list","--parents","-n","1","HEAD"])).trim().split(" ").slice(1),bx=e=>{let t=`${cu} && `;if(e!==cu)return e?.startsWith(t)?e.slice(t.length):e},Rx=e=>e?`${cu} && ${e}`:fx,Sx=async(e,t)=>{try{return await qi({cwd:e,quiet:!0})`sh -c ${t}`,{command:t,ok:!0}}catch(r){return{command:t,ok:!1,reason:Bo(r)}}},ry=async(e,t)=>{let r=(await U(e,["diff","--cached","--stat",t.autoMergeTree])).trim(),n=async l=>(await U(e,["diff","--cached","--stat",l,"--",V])).trim(),o=fu(t)?{vsDev:await n(t.devSha),vsBase:await n(t.baseSha)}:void 0,s=await U(e,["diff","--cached",t.autoMergeTree,"--",".",`:(exclude)${V}`]),i=new Set(t.rererePreResolved),a=s.split(/^(?=diff --git )/m).map(l=>{let u=/^diff --git a\/(.*) b\//.exec(l)?.[1];return u&&i.has(u)?`# rerere (recorded resolution)
180
- ${l}`:l}).join(""),c=Fh.byteLength(a)>Bh;return{diffStat:r,...o?{lockfileDiffStat:o}:{},resolutionDiff:c?Fh.from(a).subarray(0,Bh).toString():a,resolutionDiffTruncated:c}},ny=async e=>{let{cwd:t,conflicted:r,verifyFailed:n,devSha:o,verify:s}=e,i=new Map;for(let a of r)i.set(a,await Wh(t,a,o,"conflict"));for(let a of n)i.set(a,await Wh(t,a,o,"verify-failed",s));return i},Ex=async(e,t,r)=>{let n=async(a,c)=>hn(await U(e,["diff","--name-only","-z","--no-renames",`${a}...${c}`])),o=await n(t,r),s=await n(r,t);return{editablePaths:[...new Set([...o,...s])].filter(a=>a!==V).sort(),lockfileBothSides:o.includes(V)&&s.includes(V)}},Px=async(e,t,r,n)=>{let o=await Qh(e);if(t==="verify-failed"){if(o.length>0)return{reason:"the merge now conflicts \u2014 re-run release merge-dev"};let i=await br(e,"HEAD"),a=await br(e,"MERGE_HEAD");return i!==r||a!==n?{reason:"the merge no longer reproduces (already up to date?) \u2014 re-run release merge-dev"}:{conflictPaths:[],...await Ex(e,r,n),autoMergeTree:await lu(e),rererePreResolved:[],lockfileOnly:!1}}if(o.length===0)return{reason:"the merge no longer conflicts \u2014 re-run release merge-dev"};let s=await br(e,"AUTO_MERGE");return s?{conflictPaths:o,autoMergeTree:s,rererePreResolved:await yx(e,o),lockfileOnly:pu(o)}:{reason:`git-too-old: the scope check needs AUTO_MERGE, written by git \u2265 2.42 (found ${(await U(e,["--version"])).trim()})`}},xx={conflict:"needs-agent","verify-failed":"verify-failed"},Wh=async(e,t,r,n,o)=>{let s=await qh(await mu(e,t));if(s)return{resolution:Uh(s,"exists"),reason:`resolution-exists: ${s.worktreePath} \u2014 finish it with --continue or drop it with --abort`};let i=await Ce(e,`origin/${t}`);if(!i)return{reason:`origin/${t} does not exist on origin`};let a=pf(e,t),c=()=>gu(e,t,a),l=Ki(c);try{await U(e,["worktree","prune"]),await Me.mkdir(tt.dirname(a),{recursive:!0}),await U(e,["worktree","add","--detach",a,i]),await qi({cwd:a,quiet:!0})`git merge --no-commit ${r} -m ${iu+t}`.catch(()=>{});let u=await Px(a,n,i,r);if("reason"in u)return await c(),u;let p={branch:t,worktreePath:a,baseSha:i,devSha:r,...u,...n==="verify-failed"&&o?{handOffVerify:o}:{},ignoredAtHandoff:await Hi(a),cliVersion:L.version,createdAt:new Date().toISOString()};return await yn(e,p),{resolution:Uh(p,p.lockfileOnly?"lockfile-only":xx[n])}}catch(u){return await c(),{reason:Bo(u)}}finally{l()}},oy=async e=>{let{cwd:t,versions:r,all:n}=e,o=await Yh(t),s=o.map(a=>a.branch);if(r!==void 0)return(Array.isArray(r)?r:r.split(",")).map(c=>c.trim()).filter(c=>c.length>0).map(c=>{let l=Te(ke(c)),u=o.find(p=>p.branch===l);if(!u)throw new g(void 0,{operation:`select the resolution for "${c}"`,stderrExcerpt:`${l} has no resolution in progress`,remediation:s.length>0?`pass one of: ${s.join(", ")}`:"start one with release merge-dev --keep-conflicts"});return u});if(n||o.length===0)return o;let i=await Yt(fe({branches:s,descriptions:new Map}),{required:!0});return o.filter(a=>i.includes(a.branch))},Tx=async(e,t)=>{let r=await Me.realpath(t).catch(()=>null);if(!r)return!1;let n=await st(e);for(let o of n)if(await Me.realpath(o.path).catch(()=>o.path)===r)return!0;return!1},gn=(e,t,r,n)=>({...e,blocked:{code:t,detail:r,...n&&n.length>0?{paths:n}:{}}}),sy=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 Tx(e,n))return gn(o,"parents-mismatch",`the resolution worktree ${n} is gone \u2014 run --abort, then start again`);let s=await br(n,"HEAD"),i=await br(n,"MERGE_HEAD"),a=r??bx(t.handOffVerify);return s===t.baseSha&&i===t.devSha?Dx(e,t,o,a):Cx(t,o,s,i)},Cx=async(e,t,r,n)=>{let o=e.worktreePath;if(r!==null&&r===e.unapprovedCommit)return gn(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 ty(o),i=n?null:await br(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 gn(t,"parents-mismatch",`expected HEAD ${e.baseSha} merging ${e.devSha}, or an approved merge commit of the two; found ${l}`)}let c=await Yi(o,e);return c.length>0?gn(t,"out-of-scope-edit",Zh(e),c):{...t,committed:!0,mergeSha:r,treeSha:i,lockfileMerged:fu(e),...await ry(o,e)}},Vh=async(e,t)=>{let r=uu(await U(e,["--literal-pathspecs","ls-files","-s","--",t])),[n,o,s]=r.length===1?(r[0]??"").split(/\s+/):[];return n&&s==="0"?o??null:null},$x=async(e,t)=>{let r=t.worktreePath,n=await Vh(r,V),o=t.lockfileBlob,s=o===void 0&&t.editablePaths!==void 0&&n===await br(r,`${t.autoMergeTree}:${V}`),i=await Dh(r,t.devSha);if(!i.ok)return{code:"verify-failed",detail:i.reason,paths:[V]};let a=await Vh(r,V);if(a!==null&&a!==o&&(t.lockfileBlob=a,await yn(e,t)),n!==null&&n!==a&&!s)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 c=await Yi(r,t);return c.length>0?{code:"out-of-scope-edit",detail:"merging the lockfile changed other paths",paths:c}:null},Ax=async(e,t)=>{let r=t.worktreePath,n=new Set(t.editablePaths),o=t.editablePaths?(await hu(r)).filter(c=>n.has(c)):t.conflictPaths;await kx(r,o.filter(c=>c!==V));let s=await Yi(r,t);if(s.length>0)return{code:"out-of-scope-edit",detail:Zh(t),paths:s};let i=(await Qh(r)).filter(c=>c!==V);if(i.length>0)return{code:"unmerged-paths",detail:"these paths are still unmerged",paths:i};let a;try{a=await wx(r,t.editablePaths?t.autoMergeTree:"HEAD")}catch(c){return{code:"markers-remaining",detail:`the marker check could not run: ${Bo(c)}`}}return a.length>0?{code:"markers-remaining",detail:"conflict markers are still staged",paths:a}:await Xh(r,t)?$x(e,t):null},Ox=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 Hi(o)),i=await Sx(o,n),a=(await Hi(o)).filter(c=>!s.has(c)&&!ey(c)&&tt.posix.basename(c)!==".gitignore");return t.ignoredByVerify=[...new Set([...t.ignoredByVerify??[],...a])],await yn(e,t),i},Dx=async(e,t,r,n)=>{let o=t.worktreePath,s=await Ax(e,t);if(s)return{...r,blocked:s};let i=fu(t),a=await lu(o),c=await Ox(e,t,a,Rx(n)),l={...r,treeSha:a,lockfileMerged:i,verify:c};if(!c.ok)return gn(l,"verify-failed",c.reason??"the verify command failed");let u=await Yi(o,t),p=uu(await U(o,["diff","--name-only"]));return u.length>0||p.length>0||await lu(o)!==a?gn(l,"verify-mutated-tree","the verify step changed the tree",[...new Set([...u,...p])]):(c.reused||(t.verified={treeSha:a,command:c.command},await yn(e,t)),{...l,...await ry(o,t)})},Ix=12e4,Nx=async(e,t=Ix)=>{let r=qi({cwd:e,quiet:!0,detached:!0,stdio:["ignore","pipe","pipe"],env:{...Lh.env,GIT_TERMINAL_PROMPT:"0"}})`git commit --no-edit --cleanup=strip`,n=!1,o=setTimeout(()=>{n=!0;let s=r.child?.pid;try{s&&Lh.kill(-s,"SIGKILL")}catch{}},t);try{return await r,{ok:!0}}catch(s){if(!n)return{ok:!1,reason:Bo(s)};let i=(await U(e,["rev-parse","--git-path","index.lock"])).trim();return await Me.rm(tt.resolve(e,i),{force:!0}),{ok:!1,reason:`git commit timed out after ${t}ms`}}finally{clearTimeout(o)}},_x={"verify-failed":"verify-failed","tree-changed":"tree-changed"},Mx=e=>{let t=e.blocked;return{branch:e.branch,status:_x[t.code]??"blocked",conflictPaths:e.conflictPaths,pushed:!1,reason:[`${t.code}: ${t.detail}`,...t.paths?[`(${t.paths.join(", ")})`]:[]].join(" "),blocked:t}},jx=async(e,t,r,n)=>{let o=r.worktreePath,s=(u,p,m={})=>({branch:t.branch,status:u,conflictPaths:t.conflictPaths,pushed:!1,reason:p,...m});if(!n)return s("tree-changed",`not approved: the preview this --yes came from had no ready tree for ${t.branch} \u2014 preview again`);if(t.treeSha!==n)return s("tree-changed",`the resolution is tree ${t.treeSha} but the approved tree is ${n} \u2014 preview again`);if(t.committed&&t.mergeSha)return{sha:t.mergeSha};let i=await Nx(o);if(!i.ok)return s("hook-failed",i.reason);let a=(await U(o,["rev-parse","HEAD"])).trim(),c=(await U(o,["rev-parse","HEAD^{tree}"])).trim();if(c!==t.treeSha)return r.unapprovedCommit=a,await yn(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 ty(o);if(l.length!==2||l[0]!==r.baseSha||l[1]!==r.devSha){let u={code:"parents-mismatch",detail:`commit parents are ${l.join(" ")}, expected ${r.baseSha} ${r.devSha}`};return s("blocked",`parents-mismatch: ${u.detail}`,{mergeSha:a,blocked:u})}return{sha:a}},Fx=async(e,t,r)=>{let n=(c,l,u)=>({branch:t.branch,status:c,mergeSha:r,conflictPaths:t.conflictPaths,pushed:!1,...l?{reason:l}:{},...u?{blocked:u}:{}}),o;try{o=(await Fo(e,[{branch:t.branch,sha:r}],t.devSha)).nowUpToDate}catch(c){let l={code:"parents-mismatch",detail:`origin/${t.branch}: ${Bo(c)}`};return n("blocked",`parents-mismatch: ${l.detail}`,l)}if(o.includes(t.branch))return n("up-to-date",`origin/${t.branch} already carries ${t.devSha}`);let s=await Ce(e,`origin/${t.branch}`);if(s===t.baseSha)return"keep";let i=s!==null&&await Qn(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)},Lx=e=>{d.info(`
181
- \u{1F4CB} Resolution preview:`);for(let t of e)t.blocked?d.info(` ${t.branch} \u2014 BLOCKED ${t.blocked.code}: ${t.blocked.detail}`):d.info(` ${t.branch} \u2014 ready${t.committed?" (already committed)":""}: tree ${t.treeSha}`)},iy=async e=>{let{cwd:t,versions:r,all:n,verify:o,trees:s=new Map,confirmedCommand:i}=e,a=await oy({cwd:t,versions:r,all:n});if(a.length===0)return d.info("\u2139\uFE0F No merge-dev resolutions in progress"),Lo();if(i)return Gh(t,a,o,s);let c=[];for(let m of a){let f=await sy(t,m,o);!f.blocked&&!f.committed&&f.treeSha&&(m.previewedTree=f.treeSha,await yn(t,m)),c.push(f)}Lx(c);let l={branches:c},u=c.filter(m=>!m.blocked&&m.treeSha!==void 0);if(u.length===0)throw new O({status:"refused",plan:l,agentMode:j.source},2,{operation:"continue the merge-dev resolutions",stderrExcerpt:"every selected resolution is blocked",remediation:"fix the paths each row names, then preview again \u2014 or drop it with --abort"});let p=new Map(u.map(m=>[m.branch,m.treeSha]));try{await J(i,`Commit and push the resolved merges for: ${[...p.keys()].join(", ")}?`,{plan:l,throwOnDecline:!0,rerun:Bx(p)})}catch(m){if(!Et(m))throw m;return{...Lo(),declined:!0}}return Gh(t,a,o,p)},ay=e=>{let t=new Map,r=(Array.isArray(e)?e:[e??""]).flatMap(n=>n.split(","));for(let n of r.map(o=>o.trim())){if(n.length===0)continue;let o=/^(.+)=([0-9a-f]{40,64})$/.exec(n);if(!o?.[1]||!o[2])throw new g(void 0,{operation:"read --tree",stderrExcerpt:`"${n}" is not <branch>=<tree sha>`,remediation:"run the rerun a --continue preview printed, unchanged"});t.set(o[1],o[2])}return t},Bx=e=>{let t=[],r=!1;for(let o of Tf())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"]},Ux=async(e,t,r,n)=>{let o=await sy(e,t,r);if(o.blocked)return Mx(o);let s=await jx(e,o,t,n);if(!("sha"in s))return s;let i=await Fx(e,t,s.sha);return i==="keep"?s:i},Wx=async(e,t)=>{if(t.length===0)return{results:[],atomicPush:{attempted:!1,aborted:!1}};let r=t.map(s=>({branch:s.record.branch,sha:s.sha}));d.info(`
182
- \u2B06\uFE0F Pushing atomically: ${r.map(s=>s.branch).join(", ")}`);let n=await si(e,r),o=[];for(let s of t){let i=n.pushed||await Gr(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(-Jh)}})}return{results:o,atomicPush:{attempted:!0,aborted:!n.pushed,abortedBy:n.stderr?.split(`
183
- `)[0]}}},Gh=async(e,t,r,n)=>{let o=[],s=[];for(let u of t){let p=await Ux(e,u,r,n.get(u.branch));"sha"in p?s.push({record:u,sha:p.sha}):o.push(p)}let i=await Wx(e,s),a=[...o,...i.results],c=t.filter(u=>a.some(p=>p.branch===u.branch&&(p.pushed||p.status==="up-to-date")));for(let u of c)await gu(e,u.branch,u.worktreePath);let l=t.map(u=>u.branch);return a.sort((u,p)=>l.indexOf(u.branch)-l.indexOf(p.branch)),{results:a,atomicPush:i.atomicPush,declined:!1}},cy=async e=>{let{cwd:t,versions:r,all:n,confirmedCommand:o}=e,s=await oy({cwd:t,versions:r,all:n});if(s.length===0)return d.info("\u2139\uFE0F No merge-dev resolutions in progress"),Lo();let i={branches:s.map(a=>({branch:a.branch,worktreePath:a.worktreePath}))};try{await J(o,`Discard the resolution worktrees for: ${s.map(a=>a.branch).join(", ")}?`,{plan:i,throwOnDecline:!0})}catch(a){if(!Et(a))throw a;return{...Lo(),declined:!0}}for(let a of s)await gu(t,a.branch,a.worktreePath),d.info(`\u{1F5D1}\uFE0F Discarded the resolution for ${a.branch}`);return{...Lo(),results:s.map(a=>({branch:a.branch,status:"aborted",conflictPaths:a.conflictPaths,pushed:!1}))}};import Vx from"node:fs";import Gx from"node:os";import Jx from"node:path";var Kx="infra-kit.json",Hx="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)",qx="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 $()}catch{return null}let t=e.trim();return t===""||t===Gx.homedir()?null:t},ly=async()=>{let e=await Uo();return e===null&&d.info(Hx),e},Yx=async()=>{let e=await Uo();return e===null?null:Vx.existsSync(Jx.join(e,Kx))?e:(d.info(qx),null)};var zx=async e=>{try{return await Re(e)}catch(t){return d.debug({err:t,msg:"Skipped per-package agent guidance \u2014 no workspace packages could be discovered."}),[]}},uy=async({dryRun:e=!1}={})=>{let t=await Yx(),r=L.version;if(t===null)return{skipped:!0,root:null,version:r,written:[]};let n=[...await ho(t,{version:r,dryRun:e})];for(let o of await zx(t)){let s=await Pt(o);n.push(...await yo(o,{repoRoot:t,version:r,declaredType:s,dryRun:e}))}return{skipped:!1,root:t,version:r,written:n}};import ye from"node:fs";import ra from"node:os";import ie from"node:path";import Tu from"node:process";import yu from"node:fs";import dy from"node:os";import py from"node:path";import Xx from"node:process";import{z as Xi}from"zod";var my=e=>{try{return yu.readFileSync(e,"utf-8")}catch{return null}},vn="claude in chrome",Zx="com.anthropic.claude_code_browser_extension",zi="run `/chrome` inside Claude Code to set up Claude in Chrome",Qx={darwin:["Library","Application Support","Google","Chrome","NativeMessagingHosts"],linux:[".config","google-chrome","NativeMessagingHosts"]},eT=e=>{try{return yu.accessSync(e,yu.constants.X_OK),!0}catch{return!1}},fy=e=>{try{return JSON.parse(e)}catch{return null}},tT=/^exec\s+(?<target>\S+)\s+--chrome-native-host\b/m,Wo=(e={})=>{let t=e.platform??Xx.platform,r=e.home??dy.homedir(),n=e.readText??my,o=e.isExecutable??eT,s=Qx[t];if(s===void 0)return{name:vn,status:"skip",message:`no Chrome native host location known for ${t}`};let i=py.join(r,...s,`${Zx}.json`),a=n(i);if(a===null)return{name:vn,status:"warn",message:`Chrome native host not registered \u2014 ${zi}`};let c=Xi.object({path:Xi.string().min(1)}).safeParse(fy(a));if(!c.success)return{name:vn,status:"fail",message:`${w(i)} has no host path \u2014 ${zi} again`};let l=c.data.path;if(!o(l))return{name:vn,status:"fail",message:`Chrome native host ${w(l)} is missing or not executable \u2014 ${zi} again`};let u=tT.exec(n(l)??"")?.groups?.target;return u!==void 0&&!o(u)?{name:vn,status:"fail",message:`Chrome native host runs ${w(u)}, which no longer exists \u2014 ${zi} again`}:{name:vn,status:"pass",message:`Native host registered (${w(l)}); /infra-kit:doctor checks the live connection`}},vu=(e={})=>{let t=e.home??dy.homedir(),r=e.readText??my,n=Xi.object({claudeInChromeDefaultEnabled:Xi.boolean().optional()}).safeParse(fy(r(py.join(t,".claude.json"))??""));return n.success&&n.data.claudeInChromeDefaultEnabled===!0};import Qi from"node:fs/promises";import rT from"node:path";import nT from"node:process";var gy=` // // Editor tooling only \u2014 a JSON Schema URL for completion and validation. Ignored at runtime.
173
+ `,uu=async(e="regular")=>{let t=gt(e,await te()),r=Nh({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 Nh({quiet:!0,nothrow:!0})`git rev-list --left-right --count origin/${t}...${t}`,[s="?",i="?"]=o.exitCode===0?o.stdout.trim().split(/\s+/):[],a=i!=="0"||s!=="0";throw new g(n,{operation:`fast-forward ${t} onto origin/${t}`,remediation:a?`your local ${t} has diverged \u2014 rebase or reset it to origin/${t}, then retry`:`check your access to origin and that ${t} tracks it, then retry`,...a?{stderrExcerpt:`local ${t} is ${i} commit(s) ahead and ${s} behind origin/${t}`}:{}})}return(await r`git rev-parse HEAD`).stdout.trim()},dx=async e=>{let{versionName:t,jiraConfig:r,description:n,releaseDate:o}=e,s=await Ot(t,r);if(!s)return(await iu({name:t,projectId:r.projectId,description:n||"",released:!1,archived:!1,...o===void 0?{}:{releaseDate:o}},r)).version;if(s.released||s.archived)throw new g(void 0,{operation:`reuse Jira fix version "${t}"`,remediation:"pick a different version, or un-release it in Jira first",stderrExcerpt:`fix version "${t}" is already ${s.released?"released":"archived"}`});let i=n||"",a={...i!==""&&i!==(s.description??"")?{description:i}:{},...o!==void 0&&o!==(s.releaseDate??"")?{releaseDate:o}:{}};if(Object.keys(a).length===0)return s;let c=await yn({versionId:s.id,...a},r);return{...s,...a,...a.releaseDate===void 0?{}:{releaseDate:c.version.releaseDate}}},du=async e=>{let{id:t,jiraConfig:r,description:n,releaseDate:o,type:s="regular",baseSha:i}=e,a=ue(t),c=await dx({versionName:a,jiraConfig:r,description:n,...o===void 0?{}:{releaseDate:o}}),l=Sr(r,c),u=await Vi({id:t,jiraVersionUrl:l,type:s,description:n,baseSha:i});return{version:oe(t),type:s,branchName:u.branchName,prUrl:u.prUrl,jiraVersionUrl:l,releaseDate:c.releaseDate||null}},Hi=async()=>{let e=new Map,t=await Dt();if(!t)return e;try{let r=await hn(t);for(let n of r)e.set(n.name,{description:n.description||null,releaseDate:n.releaseDate||null})}catch(r){d.warn({err:r},"Jira descriptions unavailable \u2014 the release list will render without them. If this persists, check JIRA_EMAIL / JIRA_TOKEN.")}return e},fe=async()=>{let e=await Hi();return new Map([...e].flatMap(([t,{description:r}])=>r?[[t,r]]:[]))},Uo=(e,t,r)=>{let n=r?" ".repeat(r-e.length+3):" ",o=`[${t}]`.padEnd(11);return`${e}${n}${o}`},nu=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",qi=e=>e.flatMap(t=>{let r=ee(t);return r?[{branch:t,id:r,label:oe(r)}]:[]}),It=e=>{try{return $e(Re(e))}catch(t){throw new g(t,{operation:`resolve release ref "${e}"`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")',stderrExcerpt:t instanceof Error?t.message:String(t)})}},Wo=e=>{let t=ee(e);return t?oe(t):e},Nt=e=>e.flatMap(t=>{let r=ee(t);return r?[oe(r)]:[]}),px=(e,t)=>t?t.get(e)||"regular":void 0,ge=e=>{let{branches:t,descriptions:r,types:n}=e;return qi(t).map(({branch:o,id:s,label:i})=>({value:o,label:i,description:r.get(ue(s)),type:px(o,n)}))};import _h from"node:fs/promises";import mx from"node:path";import{$ as pu}from"zx";var V="pnpm-lock.yaml",fx=/^(?:<{7}|={7}|>{7})(?:\s|$)/m,jh=async(e,t)=>{let r=mx.join(e,V),n=`${t}:${V}`;try{let o=await pu({cwd:e,quiet:!0})`git show ${n}`;await _h.writeFile(r,o.stdout)}catch(o){return{ok:!1,reason:`dev has no ${V} to start from: ${Mh(o)}`}}try{await pu({cwd:e,quiet:!0})`pnpm install --lockfile-only --ignore-scripts --no-frozen-lockfile`}catch(o){return{ok:!1,reason:`pnpm could not merge ${V}: ${Mh(o)}`}}return fx.test(await _h.readFile(r,"utf8"))?{ok:!1,reason:`${V} still carries conflict markers after pnpm ran`}:(await pu({cwd:e,quiet:!0})`git add -- ${V}`,{ok:!0})},Mh=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim()};import{$ as Er}from"zx";var mu=(e,t)=>`Merge remote-tracking branch '${e}' into ${t}`,gx=e=>{let{stderr:t,message:r}=e;return String(t?.trim()||r||e).trim()},hx=2048,yx=e=>{let{stderr:t,stdout:r,exitCode:n}=e;return[t,r].map(s=>(s??"").trim().slice(-hx)).filter(s=>s.length>0).join(`
174
+ `)||`the verify command exited with code ${n??"unknown"} and printed nothing`},vx=async e=>{try{return(await Er({cwd:e,quiet:!0})`git diff --name-only --diff-filter=U`).stdout.split(`
175
+ `).map(r=>r.trim()).filter(r=>r.length>0)}catch{return[]}},wx=async(e,t)=>{let r=gx(t),n=await vx(e);return n.length>0?{status:"conflict",conflictPaths:n,reason:r}:await kf(e)?{status:"hook-failed",reason:r}:{status:"error",reason:r}},Fh=async e=>{let{cwd:t,worktreePath:r,branches:n,integrationRef:o}=e,s=[],i=await Ae(t,o);if(!i)return n.map(a=>({branch:a,status:"error",reason:`${o} does not resolve`}));for(let a of n){let c=Date.now(),l=await kx({cwd:t,worktreePath:r,branch:a,devSha:i,integrationRef:o});s.push({...l,durationMs:Date.now()-c})}return s},kx=async e=>{let{cwd:t,worktreePath:r,branch:n,devSha:o,integrationRef:s}=e,i=`origin/${n}`;if(!await Ae(t,i))return{branch:n,status:"error",reason:`${i} does not exist on origin`};if(await so(t,s,i))return{branch:n,status:"up-to-date"};try{await Oc(r),await Er({cwd:r,quiet:!0})`git checkout --detach ${i}`;let a=mu(s,n);await Er({cwd:r,quiet:!0})`git merge ${s} --no-edit -m ${a}`;let c=(await Er({cwd:r,quiet:!0})`git rev-parse HEAD`).stdout.trim();return{branch:n,status:c===o?"fast-forward":"merged",mergeSha:c}}catch(a){return{branch:n,...await wx(r,a)}}finally{await Dc(r)}},Lh=e=>e.flatMap(t=>t.mergeSha?[{branch:t.branch,sha:t.mergeSha}]:[]),Bh="pnpm install --frozen-lockfile",Uh=async e=>{let{worktreePath:t,refs:r,command:n}=e,o=[],s=new Map;for(let i of r)try{await Oc(t),await Er({cwd:t,quiet:!0})`git checkout --detach ${i.sha}`,await Er({cwd:t,quiet:!0})`sh -c ${n}`,o.push(i)}catch(a){s.set(i.branch,yx(a))}finally{await Dc(t)}return{kept:o,failed:s}},Go=async(e,t,r)=>{await Er({cwd:e,quiet:!0})`git fetch origin --prune`;let n=[],o=[];for(let s of t)await so(e,r,`origin/${s.branch}`)?o.push(s.branch):n.push(s);return{kept:n,nowUpToDate:o}};import fu from"node:process";var Yi=new Set,zi=e=>(Yi.add(e),()=>{Yi.delete(e)}),bx=async()=>{for(let e of[...Yi])try{await e()}catch(t){d.warn({error:t,msg:"cleanup failed during shutdown"})}Yi.clear()},Rx=["SIGINT","SIGTERM"],Wh=async(e,t={})=>{let{register:r=(i,a)=>{fu.on(i,a)},unregister:n=(i,a)=>{fu.off(i,a)},exit:o=i=>{fu.exit(i)}}=t,s=new Map;for(let i of Rx){let a=()=>{bx().then(()=>{o(Ff(i))})};s.set(i,a),r(i,a)}try{return await e()}finally{for(let[i,a]of s)n(i,a)}};var Sx="pnpm install --frozen-lockfile --ignore-scripts",gu="pnpm install --frozen-lockfile",Jh=64*1024,zh=4096,Jo=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim().slice(-zh)},W=async(e,t)=>(await Zi({cwd:e,quiet:!0})`git ${t}`).stdout,yu=e=>e.split(`
176
+ `).map(t=>t.trim()).filter(t=>t.length>0),bn=e=>e.split("\0").filter(t=>t.length>0),Pr=async(e,t)=>{try{return(await W(e,["rev-parse","-q","--verify",t])).trim()||null}catch{return null}},Xh=async e=>nt.resolve(e,(await W(e,["rev-parse","--git-common-dir"])).trim()),vu=e=>e.then(()=>!0,()=>!1),Vo=()=>({results:[],atomicPush:{attempted:!1,aborted:!1},declined:!1}),wu=e=>e?.length===1&&e[0]===V,Zh=async e=>nt.join(await Xh(e),"infra-kit","merge-dev-resolutions"),ku=async(e,t)=>nt.join(await Zh(e),`${vf(t)}.json`),Qh=async e=>{try{return JSON.parse(await Fe.readFile(e,"utf8"))}catch{return null}},Rn=async(e,t)=>{let r=await ku(e,t.branch);await Fe.mkdir(nt.dirname(r),{recursive:!0}),await Fe.writeFile(r,`${JSON.stringify(t,null,2)}
177
+ `)},ey=async e=>{let t=await Zh(e),r=await Fe.readdir(t).catch(()=>[]);return(await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(o=>Qh(nt.join(t,o))))).filter(o=>o!==null)},ty=async e=>Promise.all((await ey(e)).map(async t=>({branch:t.branch,worktreePath:t.worktreePath,createdAt:t.createdAt,worktreeExists:await vu(Fe.stat(t.worktreePath))}))),Kh=(e,t)=>({worktreePath:e.worktreePath,baseSha:e.baseSha,devSha:e.devSha,conflictPaths:e.conflictPaths,...e.editablePaths?{editablePaths:e.editablePaths}:{},lockfileOnly:e.lockfileOnly,rererePreResolved:e.rererePreResolved,state:t}),Ex=e=>e.editablePaths??e.conflictPaths,Px=e=>nt.posix.basename(e)==="package.json",bu=e=>e.conflictPaths.includes(V)||e.lockfileBlob!==void 0,ry=async(e,t)=>{if(!t.editablePaths)return t.conflictPaths.includes(V);if(t.lockfileBothSides||t.lockfileBlob!==void 0)return!0;let r=bn(await W(e,["diff","--cached","--name-only","-z","--no-renames",t.autoMergeTree]));return[...await Su(e),...r].some(Px)},ny=e=>e.editablePaths?"only the editable paths may change":"only the conflicted paths may change",Ru=async(e,t,r)=>{await W(e,["worktree","remove","--force",r]).catch(()=>Fe.rm(r,{recursive:!0,force:!0})),await Fe.rm(await ku(e,t),{force:!0}).catch(()=>{}),await W(e,["worktree","prune"]).catch(()=>{})},oy=async e=>bn(await W(e,["diff","--name-only","-z","--diff-filter=U"])),Xi=async e=>bn(await W(e,["status","--porcelain","-z","--untracked-files=all","--ignored=matching"])).filter(r=>r.startsWith("!! ")).map(r=>r.slice(3)),xx=async(e,t)=>{let r=(await W(e,["config","--type=bool","--get","rerere.enabled"]).catch(()=>"")).trim(),n=await vu(Fe.stat(nt.join(await Xh(e),"rr-cache")));if(r==="false"||r===""&&!n)return[];let o=new Set(yu(await W(e,["rerere","remaining"])));return t.filter(s=>!o.has(s))},sy=e=>e.split("/").includes("node_modules"),Qi=async(e,t)=>{let r=new Set(Ex(t));t.editablePaths&&await ry(e,t)&&r.add(V);let n=new Set([...t.ignoredAtHandoff,...t.ignoredByVerify??[]]),o=bn(await W(e,["diff","--cached","--name-only","-z","--no-renames",t.autoMergeTree])),s=[...await Su(e),...o].filter(a=>!r.has(a)),i=(await Xi(e)).filter(a=>!n.has(a)&&!sy(a));return[...new Set([...s,...i,...await Tx(e)])].sort()},Su=async e=>{let t=bn(await W(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},Tx=async e=>(await W(e,["ls-files","-v"])).split(`
178
+ `).filter(t=>{let r=t.charAt(0);return r==="S"||r!==""&&r!==r.toUpperCase()}).map(t=>t.slice(2)),Cx=async(e,t)=>{let r=`:(exclude)${V}`;try{return await W(e,["diff","--cached","--check",t,"--",".",r]),[]}catch(n){let{stdout:o="",stderr:s="",exitCode:i}=n;if(s.trim().length>0||o.trim().length===0||i!==1&&i!==2)throw new g(n,{operation:"check the staged resolution for conflict markers"});let a=new Set;for(let c of o.split(`
179
+ `)){let l=/^(.*):\d+: leftover conflict marker/.exec(c);l?.[1]&&a.add(l[1])}return[...a].sort()}},$x=async(e,t)=>{let r=[];for(let n of t)(await vu(Fe.lstat(nt.join(e,n)))||(await W(e,["--literal-pathspecs","ls-files","--",n])).length>0)&&r.push(n);r.length>0&&await W(e,["--literal-pathspecs","add","-A","--",...r])},hu=async e=>(await W(e,["write-tree"])).trim(),iy=async e=>(await W(e,["rev-list","--parents","-n","1","HEAD"])).trim().split(" ").slice(1),Ax=e=>{let t=`${gu} && `;if(e!==gu)return e?.startsWith(t)?e.slice(t.length):e},Ox=e=>e?`${gu} && ${e}`:Sx,Dx=async(e,t)=>{try{return await Zi({cwd:e,quiet:!0})`sh -c ${t}`,{command:t,ok:!0}}catch(r){return{command:t,ok:!1,reason:Jo(r)}}},ay=async(e,t)=>{let r=(await W(e,["diff","--cached","--stat",t.autoMergeTree])).trim(),n=async l=>(await W(e,["diff","--cached","--stat",l,"--",V])).trim(),o=bu(t)?{vsDev:await n(t.devSha),vsBase:await n(t.baseSha)}:void 0,s=await W(e,["diff","--cached",t.autoMergeTree,"--",".",`:(exclude)${V}`]),i=new Set(t.rererePreResolved),a=s.split(/^(?=diff --git )/m).map(l=>{let u=/^diff --git a\/(.*) b\//.exec(l)?.[1];return u&&i.has(u)?`# rerere (recorded resolution)
180
+ ${l}`:l}).join(""),c=Gh.byteLength(a)>Jh;return{diffStat:r,...o?{lockfileDiffStat:o}:{},resolutionDiff:c?Gh.from(a).subarray(0,Jh).toString():a,resolutionDiffTruncated:c}},cy=async e=>{let{cwd:t,conflicted:r,verifyFailed:n,devSha:o,integrationRef:s,verify:i}=e,a=new Map;for(let c of r)a.set(c,await Hh(t,c,o,s,"conflict"));for(let c of n)a.set(c,await Hh(t,c,o,s,"verify-failed",i));return a},Ix=async(e,t,r)=>{let n=async(a,c)=>bn(await W(e,["diff","--name-only","-z","--no-renames",`${a}...${c}`])),o=await n(t,r),s=await n(r,t);return{editablePaths:[...new Set([...o,...s])].filter(a=>a!==V).sort(),lockfileBothSides:o.includes(V)&&s.includes(V)}},Nx=async(e,t,r,n)=>{let o=await oy(e);if(t==="verify-failed"){if(o.length>0)return{reason:"the merge now conflicts \u2014 re-run release merge-dev"};let i=await Pr(e,"HEAD"),a=await Pr(e,"MERGE_HEAD");return i!==r||a!==n?{reason:"the merge no longer reproduces (already up to date?) \u2014 re-run release merge-dev"}:{conflictPaths:[],...await Ix(e,r,n),autoMergeTree:await hu(e),rererePreResolved:[],lockfileOnly:!1}}if(o.length===0)return{reason:"the merge no longer conflicts \u2014 re-run release merge-dev"};let s=await Pr(e,"AUTO_MERGE");return s?{conflictPaths:o,autoMergeTree:s,rererePreResolved:await xx(e,o),lockfileOnly:wu(o)}:{reason:`git-too-old: the scope check needs AUTO_MERGE, written by git \u2265 2.42 (found ${(await W(e,["--version"])).trim()})`}},_x={conflict:"needs-agent","verify-failed":"verify-failed"},Hh=async(e,t,r,n,o,s)=>{let i=await Qh(await ku(e,t));if(i)return{resolution:Kh(i,"exists"),reason:`resolution-exists: ${i.worktreePath} \u2014 finish it with --continue or drop it with --abort`};let a=await Ae(e,`origin/${t}`);if(!a)return{reason:`origin/${t} does not exist on origin`};let c=wf(e,t),l=()=>Ru(e,t,c),u=zi(l);try{await W(e,["worktree","prune"]),await Fe.mkdir(nt.dirname(c),{recursive:!0}),await W(e,["worktree","add","--detach",c,a]);let p=mu(n,t);await Zi({cwd:c,quiet:!0})`git merge --no-commit ${r} -m ${p}`.catch(()=>{});let m=await Nx(c,o,a,r);if("reason"in m)return await l(),m;let f={branch:t,worktreePath:c,baseSha:a,devSha:r,...m,...o==="verify-failed"&&s?{handOffVerify:s}:{},ignoredAtHandoff:await Xi(c),cliVersion:U.version,createdAt:new Date().toISOString()};return await Rn(e,f),{resolution:Kh(f,f.lockfileOnly?"lockfile-only":_x[o])}}catch(p){return await l(),{reason:Jo(p)}}finally{u()}},ly=async e=>{let{cwd:t,versions:r,all:n}=e,o=await ey(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=$e(Re(c)),u=o.find(p=>p.branch===l);if(!u)throw new g(void 0,{operation:`select the resolution for "${c}"`,stderrExcerpt:`${l} has no resolution in progress`,remediation:s.length>0?`pass one of: ${s.join(", ")}`:"start one with release merge-dev --keep-conflicts"});return u});if(n||o.length===0)return o;let i=await Xt(ge({branches:s,descriptions:new Map}),{required:!0});return o.filter(a=>i.includes(a.branch))},Mx=async(e,t)=>{let r=await Fe.realpath(t).catch(()=>null);if(!r)return!1;let n=await at(e);for(let o of n)if(await Fe.realpath(o.path).catch(()=>o.path)===r)return!0;return!1},kn=(e,t,r,n)=>({...e,blocked:{code:t,detail:r,...n&&n.length>0?{paths:n}:{}}}),uy=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 Mx(e,n))return kn(o,"parents-mismatch",`the resolution worktree ${n} is gone \u2014 run --abort, then start again`);let s=await Pr(n,"HEAD"),i=await Pr(n,"MERGE_HEAD"),a=r??Ax(t.handOffVerify);return s===t.baseSha&&i===t.devSha?Ux(e,t,o,a):jx(t,o,s,i)},jx=async(e,t,r,n)=>{let o=e.worktreePath;if(r!==null&&r===e.unapprovedCommit)return kn(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 iy(o),i=n?null:await Pr(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 kn(t,"parents-mismatch",`expected HEAD ${e.baseSha} merging ${e.devSha}, or an approved merge commit of the two; found ${l}`)}let c=await Qi(o,e);return c.length>0?kn(t,"out-of-scope-edit",ny(e),c):{...t,committed:!0,mergeSha:r,treeSha:i,lockfileMerged:bu(e),...await ay(o,e)}},qh=async(e,t)=>{let r=yu(await W(e,["--literal-pathspecs","ls-files","-s","--",t])),[n,o,s]=r.length===1?(r[0]??"").split(/\s+/):[];return n&&s==="0"?o??null:null},Fx=async(e,t)=>{let r=t.worktreePath,n=await qh(r,V),o=t.lockfileBlob,s=o===void 0&&t.editablePaths!==void 0&&n===await Pr(r,`${t.autoMergeTree}:${V}`),i=await jh(r,t.devSha);if(!i.ok)return{code:"verify-failed",detail:i.reason,paths:[V]};let a=await qh(r,V);if(a!==null&&a!==o&&(t.lockfileBlob=a,await Rn(e,t)),n!==null&&n!==a&&!s)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 c=await Qi(r,t);return c.length>0?{code:"out-of-scope-edit",detail:"merging the lockfile changed other paths",paths:c}:null},Lx=async(e,t)=>{let r=t.worktreePath,n=new Set(t.editablePaths),o=t.editablePaths?(await Su(r)).filter(c=>n.has(c)):t.conflictPaths;await $x(r,o.filter(c=>c!==V));let s=await Qi(r,t);if(s.length>0)return{code:"out-of-scope-edit",detail:ny(t),paths:s};let i=(await oy(r)).filter(c=>c!==V);if(i.length>0)return{code:"unmerged-paths",detail:"these paths are still unmerged",paths:i};let a;try{a=await Cx(r,t.editablePaths?t.autoMergeTree:"HEAD")}catch(c){return{code:"markers-remaining",detail:`the marker check could not run: ${Jo(c)}`}}return a.length>0?{code:"markers-remaining",detail:"conflict markers are still staged",paths:a}:await ry(r,t)?Fx(e,t):null},Bx=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 Xi(o)),i=await Dx(o,n),a=(await Xi(o)).filter(c=>!s.has(c)&&!sy(c)&&nt.posix.basename(c)!==".gitignore");return t.ignoredByVerify=[...new Set([...t.ignoredByVerify??[],...a])],await Rn(e,t),i},Ux=async(e,t,r,n)=>{let o=t.worktreePath,s=await Lx(e,t);if(s)return{...r,blocked:s};let i=bu(t),a=await hu(o),c=await Bx(e,t,a,Ox(n)),l={...r,treeSha:a,lockfileMerged:i,verify:c};if(!c.ok)return kn(l,"verify-failed",c.reason??"the verify command failed");let u=await Qi(o,t),p=yu(await W(o,["diff","--name-only"]));return u.length>0||p.length>0||await hu(o)!==a?kn(l,"verify-mutated-tree","the verify step changed the tree",[...new Set([...u,...p])]):(c.reused||(t.verified={treeSha:a,command:c.command},await Rn(e,t)),{...l,...await ay(o,t)})},Wx=12e4,Gx=async(e,t=Wx)=>{let r=Zi({cwd:e,quiet:!0,detached:!0,stdio:["ignore","pipe","pipe"],env:{...Vh.env,GIT_TERMINAL_PROMPT:"0"}})`git commit --no-edit --cleanup=strip`,n=!1,o=setTimeout(()=>{n=!0;let s=r.child?.pid;try{s&&Vh.kill(-s,"SIGKILL")}catch{}},t);try{return await r,{ok:!0}}catch(s){if(!n)return{ok:!1,reason:Jo(s)};let i=(await W(e,["rev-parse","--git-path","index.lock"])).trim();return await Fe.rm(nt.resolve(e,i),{force:!0}),{ok:!1,reason:`git commit timed out after ${t}ms`}}finally{clearTimeout(o)}},Vx={"verify-failed":"verify-failed","tree-changed":"tree-changed"},Jx=e=>{let t=e.blocked;return{branch:e.branch,status:Vx[t.code]??"blocked",conflictPaths:e.conflictPaths,pushed:!1,reason:[`${t.code}: ${t.detail}`,...t.paths?[`(${t.paths.join(", ")})`]:[]].join(" "),blocked:t}},Kx=async(e,t,r,n)=>{let o=r.worktreePath,s=(u,p,m={})=>({branch:t.branch,status:u,conflictPaths:t.conflictPaths,pushed:!1,reason:p,...m});if(!n)return s("tree-changed",`not approved: the preview this --yes came from had no ready tree for ${t.branch} \u2014 preview again`);if(t.treeSha!==n)return s("tree-changed",`the resolution is tree ${t.treeSha} but the approved tree is ${n} \u2014 preview again`);if(t.committed&&t.mergeSha)return{sha:t.mergeSha};let i=await Gx(o);if(!i.ok)return s("hook-failed",i.reason);let a=(await W(o,["rev-parse","HEAD"])).trim(),c=(await W(o,["rev-parse","HEAD^{tree}"])).trim();if(c!==t.treeSha)return r.unapprovedCommit=a,await Rn(e,r),s("tree-changed",`a commit hook rewrote the tree (${c}, approved ${t.treeSha}) \u2014 run --abort, then hand off again`,{mergeSha:a});let l=await iy(o);if(l.length!==2||l[0]!==r.baseSha||l[1]!==r.devSha){let u={code:"parents-mismatch",detail:`commit parents are ${l.join(" ")}, expected ${r.baseSha} ${r.devSha}`};return s("blocked",`parents-mismatch: ${u.detail}`,{mergeSha:a,blocked:u})}return{sha:a}},Hx=async(e,t,r)=>{let n=(c,l,u)=>({branch:t.branch,status:c,mergeSha:r,conflictPaths:t.conflictPaths,pushed:!1,...l?{reason:l}:{},...u?{blocked:u}:{}}),o;try{o=(await Go(e,[{branch:t.branch,sha:r}],t.devSha)).nowUpToDate}catch(c){let l={code:"parents-mismatch",detail:`origin/${t.branch}: ${Jo(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 Ae(e,`origin/${t.branch}`);if(s===t.baseSha)return"keep";let i=s!==null&&await so(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)},qx=e=>{d.info(`
181
+ \u{1F4CB} Resolution preview:`);for(let t of e)t.blocked?d.info(` ${t.branch} \u2014 BLOCKED ${t.blocked.code}: ${t.blocked.detail}`):d.info(` ${t.branch} \u2014 ready${t.committed?" (already committed)":""}: tree ${t.treeSha}`)},dy=async e=>{let{cwd:t,versions:r,all:n,verify:o,trees:s=new Map,confirmedCommand:i}=e,a=await ly({cwd:t,versions:r,all:n});if(a.length===0)return d.info("\u2139\uFE0F No merge-dev resolutions in progress"),Vo();if(i)return Yh(t,a,o,s);let c=[];for(let m of a){let f=await uy(t,m,o);!f.blocked&&!f.committed&&f.treeSha&&(m.previewedTree=f.treeSha,await Rn(t,m)),c.push(f)}qx(c);let l={branches:c},u=c.filter(m=>!m.blocked&&m.treeSha!==void 0);if(u.length===0)throw new D({status:"refused",plan:l,agentMode:F.source},2,{operation:"continue the merge-dev resolutions",stderrExcerpt:"every selected resolution is blocked",remediation:"fix the paths each row names, then preview again \u2014 or drop it with --abort"});let p=new Map(u.map(m=>[m.branch,m.treeSha]));try{await H(i,`Commit and push the resolved merges for: ${[...p.keys()].join(", ")}?`,{plan:l,throwOnDecline:!0,rerun:Yx(p)})}catch(m){if(!xt(m))throw m;return{...Vo(),declined:!0}}return Yh(t,a,o,p)},py=e=>{let t=new Map,r=(Array.isArray(e)?e:[e??""]).flatMap(n=>n.split(","));for(let n of r.map(o=>o.trim())){if(n.length===0)continue;let o=/^(.+)=([0-9a-f]{40,64})$/.exec(n);if(!o?.[1]||!o[2])throw new g(void 0,{operation:"read --tree",stderrExcerpt:`"${n}" is not <branch>=<tree sha>`,remediation:"run the rerun a --continue preview printed, unchanged"});t.set(o[1],o[2])}return t},Yx=e=>{let t=[],r=!1;for(let o of Nf())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"]},zx=async(e,t,r,n)=>{let o=await uy(e,t,r);if(o.blocked)return Jx(o);let s=await Kx(e,o,t,n);if(!("sha"in s))return s;let i=await Hx(e,t,s.sha);return i==="keep"?s:i},Xx=async(e,t)=>{if(t.length===0)return{results:[],atomicPush:{attempted:!1,aborted:!1}};let r=t.map(s=>({branch:s.record.branch,sha:s.sha}));d.info(`
182
+ \u2B06\uFE0F Pushing atomically: ${r.map(s=>s.branch).join(", ")}`);let n=await li(e,r),o=[];for(let s of t){let i=n.pushed||await qr(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(-zh)}})}return{results:o,atomicPush:{attempted:!0,aborted:!n.pushed,abortedBy:n.stderr?.split(`
183
+ `)[0]}}},Yh=async(e,t,r,n)=>{let o=[],s=[];for(let u of t){let p=await zx(e,u,r,n.get(u.branch));"sha"in p?s.push({record:u,sha:p.sha}):o.push(p)}let i=await Xx(e,s),a=[...o,...i.results],c=t.filter(u=>a.some(p=>p.branch===u.branch&&(p.pushed||p.status==="up-to-date")));for(let u of c)await Ru(e,u.branch,u.worktreePath);let l=t.map(u=>u.branch);return a.sort((u,p)=>l.indexOf(u.branch)-l.indexOf(p.branch)),{results:a,atomicPush:i.atomicPush,declined:!1}},my=async e=>{let{cwd:t,versions:r,all:n,confirmedCommand:o}=e,s=await ly({cwd:t,versions:r,all:n});if(s.length===0)return d.info("\u2139\uFE0F No merge-dev resolutions in progress"),Vo();let i={branches:s.map(a=>({branch:a.branch,worktreePath:a.worktreePath}))};try{await H(o,`Discard the resolution worktrees for: ${s.map(a=>a.branch).join(", ")}?`,{plan:i,throwOnDecline:!0})}catch(a){if(!xt(a))throw a;return{...Vo(),declined:!0}}for(let a of s)await Ru(t,a.branch,a.worktreePath),d.info(`\u{1F5D1}\uFE0F Discarded the resolution for ${a.branch}`);return{...Vo(),results:s.map(a=>({branch:a.branch,status:"aborted",conflictPaths:a.conflictPaths,pushed:!1}))}};import Zx from"node:fs";import Qx from"node:os";import eT from"node:path";var tT="infra-kit.json",rT="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)",nT="Skipped agent-instruction files \u2014 no infra-kit.json at the repo root (the plugin pointer, the plugin install and .mcp.json are unaffected)",Ko=async()=>{let e;try{e=await A()}catch{return null}let t=e.trim();return t===""||t===Qx.homedir()?null:t},fy=async()=>{let e=await Ko();return e===null&&d.info(rT),e},oT=async()=>{let e=await Ko();return e===null?null:Zx.existsSync(eT.join(e,tT))?e:(d.info(nT),null)};var sT=async e=>{try{return await Ee(e)}catch(t){return d.debug({err:t,msg:"Skipped per-package agent guidance \u2014 no workspace packages could be discovered."}),[]}},gy=async({dryRun:e=!1}={})=>{let t=await oT(),r=U.version;if(t===null)return{skipped:!0,root:null,version:r,written:[]};let n=[...await Ro(t,{version:r,dryRun:e})];for(let o of await sT(t)){let s=await Tt(o);n.push(...await So(o,{repoRoot:t,version:r,declaredType:s,dryRun:e}))}return{skipped:!1,root:t,version:r,written:n}};import we from"node:fs";import ia from"node:os";import ae from"node:path";import Nu from"node:process";import Eu from"node:fs";import hy from"node:os";import yy from"node:path";import iT from"node:process";import{z as ta}from"zod";var vy=e=>{try{return Eu.readFileSync(e,"utf-8")}catch{return null}},Sn="claude in chrome",aT="com.anthropic.claude_code_browser_extension",ea="run `/chrome` inside Claude Code to set up Claude in Chrome",cT={darwin:["Library","Application Support","Google","Chrome","NativeMessagingHosts"],linux:[".config","google-chrome","NativeMessagingHosts"]},lT=e=>{try{return Eu.accessSync(e,Eu.constants.X_OK),!0}catch{return!1}},wy=e=>{try{return JSON.parse(e)}catch{return null}},uT=/^exec\s+(?<target>\S+)\s+--chrome-native-host\b/m,Ho=(e={})=>{let t=e.platform??iT.platform,r=e.home??hy.homedir(),n=e.readText??vy,o=e.isExecutable??lT,s=cT[t];if(s===void 0)return{name:Sn,status:"skip",message:`no Chrome native host location known for ${t}`};let i=yy.join(r,...s,`${aT}.json`),a=n(i);if(a===null)return{name:Sn,status:"warn",message:`Chrome native host not registered \u2014 ${ea}`};let c=ta.object({path:ta.string().min(1)}).safeParse(wy(a));if(!c.success)return{name:Sn,status:"fail",message:`${w(i)} has no host path \u2014 ${ea} again`};let l=c.data.path;if(!o(l))return{name:Sn,status:"fail",message:`Chrome native host ${w(l)} is missing or not executable \u2014 ${ea} again`};let u=uT.exec(n(l)??"")?.groups?.target;return u!==void 0&&!o(u)?{name:Sn,status:"fail",message:`Chrome native host runs ${w(u)}, which no longer exists \u2014 ${ea} again`}:{name:Sn,status:"pass",message:`Native host registered (${w(l)}); /infra-kit:doctor checks the live connection`}},Pu=(e={})=>{let t=e.home??hy.homedir(),r=e.readText??vy,n=ta.object({claudeInChromeDefaultEnabled:ta.boolean().optional()}).safeParse(wy(r(yy.join(t,".claude.json"))??""));return n.success&&n.data.claudeInChromeDefaultEnabled===!0};import na from"node:fs/promises";import dT from"node:path";import pT from"node:process";var ky=` // // Editor tooling only \u2014 a JSON Schema URL for completion and validation. Ignored at runtime.
184
184
  // "$schema": "https://\u2026/infra-kit.schema.json",
185
185
  //
186
186
  // // The committed file's shape version. A CLI that reads an older version refuses the file and
@@ -227,6 +227,15 @@ ${l}`:l}).join(""),c=Fh.byteLength(a)>Bh;return{diffStat:r,...o?{lockfileDiffSta
227
227
  // // grants yourself production access with no trace in the repo.
228
228
  // "protectedEnvs": "disallow"
229
229
  //
230
+ // // Which branch releases and features are cut from. "dev" (the default): an integration branch \u2014
231
+ // // regular releases branch off dev and merge back, \`release deliver\` promotes dev to main and
232
+ // // syncs main back, hotfixes branch off main. "main": no integration branch \u2014 features and
233
+ // // releases branch off main and merge straight into it, and there is no separate hotfix type.
234
+ // //
235
+ // // PROJECT LAYER ONLY. REFUSED here and in the per-project override: every teammate's releases
236
+ // // must travel the same branches.
237
+ // "gitFlow": "dev"
238
+ //
230
239
  // // MCP servers fronted by \`ik-mcp\`, the credential-agnostic stdio proxy: one entry per server,
231
240
  // // naming the command to spawn and the env-var NAMES it reads from the \`ik env-load\` session
232
241
  // // file. \`ik setup\` derives a committed \`.mcp.json\` entry from each; \`ik audit\` guards drift.
@@ -293,7 +302,7 @@ ${l}`:l}).join(""),c=Fh.byteLength(a)>Bh;return{diffStat:r,...o?{lockfileDiffSta
293
302
  // // also fixes its modes), or by hand: both are supported, which is why the store carries no
294
303
  // // repo-identity field and no mandatory version. Pasting a token into an
295
304
  // // infra-kit.json (any layer) is REJECTED: the loader refuses to parse it and tells you to revoke
296
- // // the token first, because a config file can be committed, backed up by your editor, or shared.`,wu=()=>`// infra-kit user-global config \u2014 ~/.infra-kit/infra-kit.json
305
+ // // the token first, because a config file can be committed, backed up by your editor, or shared.`,xu=()=>`// infra-kit user-global config \u2014 ~/.infra-kit/infra-kit.json
297
306
  //
298
307
  // Merge chain (later layers override earlier ones at top-level keys):
299
308
  // 1. <repo>/infra-kit.json \u2014 committed project config (required)
@@ -302,8 +311,8 @@ ${l}`:l}).join(""),c=Fh.byteLength(a)>Bh;return{diffStat:r,...o?{lockfileDiffSta
302
311
  //
303
312
  // Merge is shallow: setting a top-level key replaces that whole section from
304
313
  // layer 1. Arrays do not concatenate. Top-level keys recognized:
305
- // $schema, configVersion, envManagement, defaultEnv, worktrees, protectedEnvs, mcp,
306
- // vendorSource, vendorTarget, audit, aliasRepo (configVersion and the last five project layer
314
+ // $schema, configVersion, envManagement, defaultEnv, worktrees, protectedEnvs, gitFlow, mcp,
315
+ // vendorSource, vendorTarget, audit, aliasRepo (configVersion, gitFlow and the last five project layer
307
316
  // only). The schema is strict \u2014 an
308
317
  // unrecognized top-level key is a parse error, not a silently ignored one.
309
318
  //
@@ -315,15 +324,15 @@ ${l}`:l}).join(""),c=Fh.byteLength(a)>Bh;return{diffStat:r,...o?{lockfileDiffSta
315
324
  // the committed project infra-kit.json (layer 1) and is usually NOT set in this
316
325
  // user-global layer \u2014 it is shown here only to document the full, valid config shape.
317
326
  {
318
- ${gy}
327
+ ${ky}
319
328
  }
320
- `,ku=e=>`// infra-kit user override for ${e} \u2014 ~/.infra-kit/projects/${e}/infra-kit.json
329
+ `,Tu=e=>`// infra-kit user override for ${e} \u2014 ~/.infra-kit/projects/${e}/infra-kit.json
321
330
  //
322
331
  // Layer 3 (highest precedence) of the config merge chain. Shallow-merged on top of
323
332
  // <repo>/infra-kit.json (layer 1) and ~/.infra-kit/infra-kit.json (layer 2) \u2014 a
324
333
  // top-level key set here replaces that whole section wholesale; arrays do not
325
334
  // concatenate. Top-level keys recognized: $schema, configVersion, envManagement, defaultEnv, worktrees,
326
- // protectedEnvs, mcp, vendorSource, vendorTarget, audit, aliasRepo (configVersion and the last five project layer only \u2014 refused here). The schema is strict \u2014 an unrecognized top-level key is a parse
335
+ // protectedEnvs, gitFlow, mcp, vendorSource, vendorTarget, audit, aliasRepo (configVersion, gitFlow and the last five project layer only \u2014 refused here). The schema is strict \u2014 an unrecognized top-level key is a parse
327
336
  // error, not a silently ignored one.
328
337
  //
329
338
  // This .example.jsonc is reference only \u2014 it is NOT loaded. Put real overrides
@@ -333,9 +342,9 @@ ${gy}
333
342
  // the committed project infra-kit.json (layer 1) and is usually NOT set in this
334
343
  // override layer \u2014 it is shown here only to document the full, valid config shape.
335
344
  {
336
- ${gy}
345
+ ${ky}
337
346
  }
338
- `,bu=()=>`// infra-kit factory registry \u2014 ~/.infra-kit/vendor.json
347
+ `,Cu=()=>`// infra-kit factory registry \u2014 ~/.infra-kit/vendor.json
339
348
  //
340
349
  // Machine-local registry the vendor commands (sync/manifest/diff) read to know
341
350
  // where your project repos live, which one is the source and which ones to stamp. This .example.jsonc is
@@ -347,110 +356,110 @@ ${gy}
347
356
  // "source": "starter-workspace", // string \u2014 the one repo \`vendor sync\` copies from (its infra-kit.json holds vendorSource)
348
357
  // "targets": ["my-repo-a", "my-repo-b"] // string[] (>=1) \u2014 repo dir names resolved under workspaceDir
349
358
  }
350
- `;var hy=!1,oT=e=>e.replace(/\.json$/,".example.jsonc"),sT=async e=>{try{return await Qi.readFile(e,"utf-8")}catch{return null}},wn=async e=>{let t=e.userProject,r=oT(t);await Qi.mkdir(rT.dirname(t),{recursive:!0});let n=!await oe(t);n&&await Qi.writeFile(t,`{}
351
- `,"utf-8");let o=ku(e.projectName),s=await sT(r)!==o;return s&&await Qi.writeFile(r,o,"utf-8"),n&&eo(),{configPath:t,examplePath:r,createdConfig:n,refreshedExample:s}},kn=e=>`Created ${w(e.configPath)} \u2014 see ${w(e.examplePath)} for the annotated reference.`,Ru=async()=>{if(nT.env.INFRA_KIT_NO_SEED||hy)return;hy=!0;let e;try{e=await ee()}catch{return}if(await oe(e.main))try{let t=await wn(e);t.createdConfig?d.info(kn(t)):t.refreshedExample&&d.debug(`Refreshed ${w(t.examplePath)} to match the current schema.`)}catch(t){d.debug({err:t,msg:`Skipped seeding ${w(e.userProject)} (config bootstrap failed).`})}};import{spawn as hT}from"node:child_process";import Py from"node:fs";import En from"node:process";import{fileURLToPath as xy}from"node:url";import ea from"node:fs";import bn from"node:path";var yy="auto-setup.json",iT="auto-setup.log",aT="auto-setup.lock",vy="auto-setup.notified",cT=3,lT=3600*1e3,uT=()=>bn.join(Rt(),yy),Rn=()=>bn.join(Rt(),iT),wy=()=>bn.join(Rt(),aT),dT=()=>bn.join(Rt(),vy),pT=new Set(["ok","attention","failed"]),mT=e=>{if(typeof e!="object"||e===null)return!1;let{root:t,status:r,notes:n}=e;return(t===null||typeof t=="string")&&typeof r=="string"&&pT.has(r)&&Array.isArray(n)&&n.every(o=>typeof o=="string")},fT=e=>{if(typeof e!="object"||e===null)return!1;let{version:t,attempts:r,startedMs:n,finishedMs:o,runs:s}=e;return typeof t=="string"&&typeof r=="number"&&Number.isInteger(r)&&typeof n=="number"&&Number.isFinite(n)&&(o===null||typeof o=="number"&&Number.isFinite(o))&&Array.isArray(s)&&s.every(mT)},Sn=(e=t=>ea.readFileSync(t,"utf8"))=>{try{let t=JSON.parse(e(uT()));return fT(t)?t:null}catch{return null}},ky=e=>{let t=Rt();ea.mkdirSync(t,{recursive:!0}),Mt(bn.join(t,yy),JSON.stringify(e),384)},gT=e=>e.finishedMs===null||e.runs.some(t=>t.status==="failed"),by=(e=t=>ea.readFileSync(t,"utf8"))=>{try{let t=Number(e(dT()).trim());return Number.isFinite(t)?t:null}catch{return null}},Ry=e=>{let t=Rt();ea.mkdirSync(t,{recursive:!0}),Mt(bn.join(t,vy),String(e),384)},Sy=(e,t,r)=>{if(e===null)return!0;let n=r-e.startedMs;return n>=0&&n<lT?!1:e.version!==t?!0:gT(e)&&e.attempts<cT};var Ey=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],Su=e=>{let{argv:t,env:r,isTty:n,selfRealPath:o,cwd:s,realpath:i}=e;return Ey.some(c=>{let l=r[c];return l!=null&&l!==""})?"opt-out":t.includes("--json")?"json":n?_m(o,s,i)?"local-install":null:"not-a-tty"};var yT=e=>{hT(En.execPath,[e,"--parent-pid",String(En.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},vT=()=>xy(new URL("./update-check.js",import.meta.url)),wT=()=>Py.realpathSync(xy(new URL("./cli.js",import.meta.url))),kT=/^[\w@./+ -]+$/,bT=e=>kT.test(e),RT=(e,t,r)=>{!e?.latestVersion||!e.updateCommand||St(e.latestVersion,t)&&e.updateCommand.every(bT)&&r(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${Zs(e.updateCommand)}`)},ST=(e,t,r,n,o)=>{if(e===null||e.finishedMs===null||e.version!==t||r===e.finishedMs)return;let s=e.runs.filter(c=>c.status==="failed").length,i=e.runs.filter(c=>c.status==="attention").length;if(s+i===0)return;let a=[s>0?`${s} failed`:null,i>0?`${i} need you`:null].filter(Boolean);n(`infra-kit ${e.version} background setup: ${a.join(", ")} \u2014 see ${w(Rn())}, or run: infra-kit setup`),o(e.finishedMs)},Eu=(e,t={})=>{try{let r=t.argv??En.argv,n=t.env??En.env,o=t.isTty??!!En.stdout.isTTY,s=t.cwd??En.cwd(),i=t.nowMs??Date.now(),a=t.selfRealPath??wT(),c=t.readCache??no,l=t.spawnChild??yT,u=t.fileExists??(h=>Py.existsSync(h)),p=t.notify??(h=>{d.info(h)});if(Su({argv:r,env:n,isTty:o,selfRealPath:a,cwd:s,realpath:xe})!==null)return;let m=c();RT(m,e,p);try{ST((t.readAutoSetup??Sn)(),e,(t.readNotified??by)(),p,t.writeNotified??Ry)}catch{}if(!Nc(m,i))return;let f=t.childPath??vT();if(!u(f))return;l(f)}catch{}};import gt from"node:fs/promises";import ft from"node:path";import{pathToFileURL as xT}from"node:url";import TT from"yaml";import{z as Tn}from"zod";import ET from"node:fs/promises";import Pu from"node:os";import xu from"node:path";import{z as PT}from"zod";import{z as Vo}from"zod";var Ty="vendor.json",Cy=Vo.object({workspaceDir:Vo.string().min(1),source:Vo.string().min(1),targets:Vo.array(Vo.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 Pn=()=>xu.join(Pu.homedir(),Cm,Ty),xn=e=>{if(e==="~")return Pu.homedir();if(e.startsWith("~/"))return xu.join(Pu.homedir(),e.slice(2));if(xu.isAbsolute(e))return e;throw new Error(`workspaceDir must be absolute or ~-prefixed, got: ${e}`)},ta=async()=>{let e=Pn(),t;try{t=await ET.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:
359
+ `;var by=!1,mT=e=>e.replace(/\.json$/,".example.jsonc"),fT=async e=>{try{return await na.readFile(e,"utf-8")}catch{return null}},En=async e=>{let t=e.userProject,r=mT(t);await na.mkdir(dT.dirname(t),{recursive:!0});let n=!await se(t);n&&await na.writeFile(t,`{}
360
+ `,"utf-8");let o=Tu(e.projectName),s=await fT(r)!==o;return s&&await na.writeFile(r,o,"utf-8"),n&&io(),{configPath:t,examplePath:r,createdConfig:n,refreshedExample:s}},Pn=e=>`Created ${w(e.configPath)} \u2014 see ${w(e.examplePath)} for the annotated reference.`,$u=async()=>{if(pT.env.INFRA_KIT_NO_SEED||by)return;by=!0;let e;try{e=await Y()}catch{return}if(await se(e.main))try{let t=await En(e);t.createdConfig?d.info(Pn(t)):t.refreshedExample&&d.debug(`Refreshed ${w(t.examplePath)} to match the current schema.`)}catch(t){d.debug({err:t,msg:`Skipped seeding ${w(e.userProject)} (config bootstrap failed).`})}};import{spawn as PT}from"node:child_process";import Ay from"node:fs";import $n from"node:process";import{fileURLToPath as Oy}from"node:url";import oa from"node:fs";import xn from"node:path";var Ry="auto-setup.json",gT="auto-setup.log",hT="auto-setup.lock",Sy="auto-setup.notified",yT=3,vT=3600*1e3,wT=()=>xn.join(Et(),Ry),Tn=()=>xn.join(Et(),gT),Ey=()=>xn.join(Et(),hT),kT=()=>xn.join(Et(),Sy),bT=new Set(["ok","attention","failed"]),RT=e=>{if(typeof e!="object"||e===null)return!1;let{root:t,status:r,notes:n}=e;return(t===null||typeof t=="string")&&typeof r=="string"&&bT.has(r)&&Array.isArray(n)&&n.every(o=>typeof o=="string")},ST=e=>{if(typeof e!="object"||e===null)return!1;let{version:t,attempts:r,startedMs:n,finishedMs:o,runs:s}=e;return typeof t=="string"&&typeof r=="number"&&Number.isInteger(r)&&typeof n=="number"&&Number.isFinite(n)&&(o===null||typeof o=="number"&&Number.isFinite(o))&&Array.isArray(s)&&s.every(RT)},Cn=(e=t=>oa.readFileSync(t,"utf8"))=>{try{let t=JSON.parse(e(wT()));return ST(t)?t:null}catch{return null}},Py=e=>{let t=Et();oa.mkdirSync(t,{recursive:!0}),Ft(xn.join(t,Ry),JSON.stringify(e),384)},ET=e=>e.finishedMs===null||e.runs.some(t=>t.status==="failed"),xy=(e=t=>oa.readFileSync(t,"utf8"))=>{try{let t=Number(e(kT()).trim());return Number.isFinite(t)?t:null}catch{return null}},Ty=e=>{let t=Et();oa.mkdirSync(t,{recursive:!0}),Ft(xn.join(t,Sy),String(e),384)},Cy=(e,t,r)=>{if(e===null)return!0;let n=r-e.startedMs;return n>=0&&n<vT?!1:e.version!==t?!0:ET(e)&&e.attempts<yT};var $y=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],Au=e=>{let{argv:t,env:r,isTty:n,selfRealPath:o,cwd:s,realpath:i}=e;return $y.some(c=>{let l=r[c];return l!=null&&l!==""})?"opt-out":t.includes("--json")?"json":n?Wm(o,s,i)?"local-install":null:"not-a-tty"};var xT=e=>{PT($n.execPath,[e,"--parent-pid",String($n.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},TT=()=>Oy(new URL("./update-check.js",import.meta.url)),CT=()=>Ay.realpathSync(Oy(new URL("./cli.js",import.meta.url))),$T=/^[\w@./+ -]+$/,AT=e=>$T.test(e),OT=(e,t,r)=>{!e?.latestVersion||!e.updateCommand||Pt(e.latestVersion,t)&&e.updateCommand.every(AT)&&r(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${ri(e.updateCommand)}`)},DT=(e,t,r,n,o)=>{if(e===null||e.finishedMs===null||e.version!==t||r===e.finishedMs)return;let s=e.runs.filter(c=>c.status==="failed").length,i=e.runs.filter(c=>c.status==="attention").length;if(s+i===0)return;let a=[s>0?`${s} failed`:null,i>0?`${i} need you`:null].filter(Boolean);n(`infra-kit ${e.version} background setup: ${a.join(", ")} \u2014 see ${w(Tn())}, or run: infra-kit setup`),o(e.finishedMs)},Ou=(e,t={})=>{try{let r=t.argv??$n.argv,n=t.env??$n.env,o=t.isTty??!!$n.stdout.isTTY,s=t.cwd??$n.cwd(),i=t.nowMs??Date.now(),a=t.selfRealPath??CT(),c=t.readCache??lo,l=t.spawnChild??xT,u=t.fileExists??(h=>Ay.existsSync(h)),p=t.notify??(h=>{d.info(h)});if(Au({argv:r,env:n,isTty:o,selfRealPath:a,cwd:s,realpath:Ce})!==null)return;let m=c();OT(m,e,p);try{DT((t.readAutoSetup??Cn)(),e,(t.readNotified??xy)(),p,t.writeNotified??Ty)}catch{}if(!Fc(m,i))return;let f=t.childPath??TT();if(!u(f))return;l(f)}catch{}};import yt from"node:fs/promises";import ht from"node:path";import{pathToFileURL as _T}from"node:url";import MT from"yaml";import{z as Dn}from"zod";import IT from"node:fs/promises";import Du from"node:os";import Iu from"node:path";import{z as NT}from"zod";import{z as qo}from"zod";var Dy="vendor.json",Iy=qo.object({workspaceDir:qo.string().min(1),source:qo.string().min(1),targets:qo.array(qo.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 An=()=>Iu.join(Du.homedir(),_m,Dy),On=e=>{if(e==="~")return Du.homedir();if(e.startsWith("~/"))return Iu.join(Du.homedir(),e.slice(2));if(Iu.isAbsolute(e))return e;throw new Error(`workspaceDir must be absolute or ~-prefixed, got: ${e}`)},sa=async()=>{let e=An(),t;try{t=await IT.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:
352
361
 
353
362
  {
354
363
  "workspaceDir": "~/projects",
355
364
  "source": "my-starter",
356
365
  "targets": ["my-repo"]
357
366
  }
358
- `)}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=Cy.safeParse(r);if(!n.success)throw new Error(`Invalid factory config at ${e}: ${PT.prettifyError(n.error)}`);return n.data};var $y=e=>e.replace(/\.json$/,".yml"),Ay=async()=>{let e;try{e=await ee()}catch{return}let t={label:"infra-kit.json",yml:$y(e.main),json:e.main,schema:Rf},r=[...Ze.withheld?[]:[t],{label:"~/.infra-kit/infra-kit.json",yml:ft.join(ft.dirname(e.userGlobal),"config.yml"),json:e.userGlobal,schema:$c},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:$y(e.userProject),json:e.userProject,schema:$c}],n=0;for(let o of r){let[s,i]=await Promise.all([oe(o.yml),oe(o.json)]);if(s){if(i){d.info(`\u26A0 Skipped ${w(o.yml)} \u2014 ${w(o.json)} already exists (remove the stale .yml manually)`);continue}try{let a=await gt.readFile(o.yml,"utf-8"),c=TT.parse(a)??{},l=o.schema.safeParse(c);if(!l.success){d.info(`\u26A0 Skipped ${w(o.yml)} \u2014 invalid config: ${Tn.prettifyError(l.error)}`);continue}await gt.mkdir(ft.dirname(o.json),{recursive:!0}),await gt.writeFile(o.json,`${JSON.stringify(l.data,null,2)}
359
- `,"utf-8"),await gt.rm(o.yml,{force:!0}),d.info(`\u2713 Migrated ${w(o.yml)} \u2192 ${w(o.json)}`),n++}catch(a){d.info(`\u26A0 Skipped ${w(o.yml)} \u2014 ${a.message}`)}}}n>0&&Lt()},Oy=async()=>{let e;try{e=await ee()}catch{return}let t=ft.dirname(e.userGlobal),r=[{from:ft.join(t,"config.json"),to:e.userGlobal},{from:ft.join(t,"config.example.jsonc"),to:ft.join(t,"infra-kit.example.jsonc")}],n=0;for(let{from:o,to:s}of r){let[i,a]=await Promise.all([oe(o),oe(s)]);if(i){if(a){d.info(`\u26A0 Skipped ${w(o)} \u2014 ${w(s)} already exists (remove the stale file manually)`);continue}try{await gt.mkdir(ft.dirname(s),{recursive:!0}),await gt.rename(o,s),d.info(`\u2713 Renamed ${w(o)} \u2192 ${w(s)}`),n++}catch(c){d.info(`\u26A0 Skipped ${w(o)} \u2014 ${c.message}`)}}}n>0&&Lt()},CT=Tn.object({workspaceDir:Tn.string().min(1),targets:Tn.array(Tn.string()).min(1)}).strict(),Dy=async()=>{let e=Pn(),t=ft.dirname(e),r=ft.join(t,"vendor.config.ts"),[n,o]=await Promise.all([oe(r),oe(e)]);if(n){if(o){d.info(`\u26A0 Skipped ${w(r)} \u2014 ${w(e)} already exists (remove the stale vendor.config.ts manually)`);return}try{let s=await gt.stat(r),c=(await import(`${xT(r).href}?mtime=${Number(s.mtimeMs)}`)).default,l=typeof c=="function",u=l?await c():c,p=CT.safeParse(u);if(!p.success){d.info(`\u26A0 Skipped ${w(r)} \u2014 invalid factory config: ${Tn.prettifyError(p.error)}`);return}await gt.mkdir(t,{recursive:!0}),await gt.writeFile(e,`${JSON.stringify(p.data,null,2)}
360
- `,"utf-8"),await gt.rm(r,{force:!0}),l?d.info(`\u26A0 Migrated ${w(r)} \u2192 ${w(e)} as a STATIC SNAPSHOT \u2014 the old file was a function (export default () => ({...})); computed values (env vars, directory globbing) were frozen at their current values and no longer re-evaluate. Edit ${w(e)} directly to change them.`):d.info(`\u2713 Migrated ${w(r)} \u2192 ${w(e)}`)}catch(s){d.info(`\u26A0 Skipped ${w(r)} \u2014 ${s.message}`)}}},Iy=async()=>{let e=await $T(),t=0;for(let r of e)if(await oe(r))try{let n=await yf(r);if(!n.changed)continue;d.info(`\u2713 Migrated ${w(r)} (removed ${n.notes.join(" and ")})`),t++}catch(n){let o=n instanceof gf?"changed while migrating":n.message;d.info(`\u26A0 Skipped ${w(r)} \u2014 ${o}`)}t>0&&Lt()},$T=async()=>{try{let e=await ee();return Ze.withheld?[e.userGlobal,e.userProject]:[e.main,e.userGlobal,e.userProject]}catch{return[Ef()]}};var Rr="# -- infra-kit:begin --",zt="# -- infra-kit:end --",AT=[["# region infra-kit","# endregion infra-kit"]],OT="# infra-kit shell functions",Cn=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},$n="Run `source ~/.zshrc` or open a new terminal to activate.",DT={step:"migrations",outcome:"unchanged",message:"Config migrations checked (legacy yml layers, user-global filename, ide structure, factory config, retired project cache)",level:"silent"},Ke=async(e,t)=>{try{return await t()}catch(r){throw new Cn(e,r)}},Cu=async e=>{let t=[],r=(...s)=>{for(let i of s)t.push(i),e?.(i)};await Ke("zshrc",()=>{r(_T())}),await Ke("zshenv",()=>{r(MT())}),await Ke("migrations",async()=>{await FT(),jT(),r(DT)}),await Ke("user-config",()=>{r(BT())});let n=await Ke("guidance",async()=>{let{entries:s,root:i}=await GT();return r(...s),i}),o=await Ke("plugin-pointer",async()=>ly());return r(...KT(o,n)),await Ke("worktrees",async()=>{r(...await XT(o))}),await Ke("plugin-pointer",async()=>{await QT(o,r)}),await Ke("mcp-proxies",async()=>{r(...await tC(o))}),await Ke("project-config",async()=>{r(...await UT(o))}),await Ke("token-perms",async()=>{r(await NT())}),await Ke("chrome",()=>{r(IT())}),r(...LT()),t},IT=()=>{let e=Wo();return e.status==="skip"?{step:"chrome",outcome:"skipped",message:e.message,level:"debug"}:e.status!=="pass"?{step:"chrome",outcome:"manual",message:`${e.message}, then choose "Enabled by default"`,level:"info"}:vu()?{step:"chrome",outcome:"unchanged",message:"Claude in Chrome is set up and enabled by default",level:"debug"}:{step:"chrome",outcome:"manual",message:'Claude in Chrome is set up but off by default \u2014 run `/chrome` inside Claude Code and choose "Enabled by default"',level:"info"}},NT=async()=>{let e=await Df();return e===null?{step:"token-perms",outcome:"skipped",message:"No token store to protect",level:"debug"}:e.length===0?{step:"token-perms",outcome:"unchanged",message:"Token store is 0600 (0700 dirs)",level:"debug"}:{step:"token-perms",outcome:"written",message:`Tightened the token store to 0600 (0700 dirs): ${e.join("; ")}`,level:"info"}};var _y=e=>{let t=ie.dirname(e);return ye.existsSync(ie.join(e,".git"))?e:t===e?null:_y(t)},My=(e,t,r,n)=>{if(!Ze.withheld)return null;if(r===n)return{step:e,outcome:"unchanged",message:`Managed block in ${t} is up to date`,level:"debug"};let o=t;try{o=ye.realpathSync(t)}catch{}return _y(ie.dirname(o))===null?null:Jo(e,ra.homedir(),o,["the infra-kit block updated"])},jy=e=>ye.existsSync(e)?ye.readFileSync(e,"utf-8"):null,_T=()=>{let e=ie.join(ra.homedir(),".zshrc"),t=jy(e),r=t===null?"":nC(t),n=Hr({content:r,body:By(),startMarker:Rr,endMarker:zt,placement:"append-end"}),o=My("zshrc",e,t,n);return o!==null?o:(ye.writeFileSync(e,n),{step:"zshrc",outcome:"written",message:`Added infra-kit shell functions to ${e}`,level:"info"})},MT=()=>{let e=ie.join(ra.homedir(),".zshenv"),t=jy(e),r=Hr({content:t??"",body:$u(),startMarker:Rr,endMarker:zt}),n=My("zshenv",e,t,r);return n!==null?n:(ye.writeFileSync(e,r),{step:"zshenv",outcome:"written",message:`Added infra-kit session-env block to ${e}`,level:"info"})},jT=()=>{ye.rmSync(ie.join(Rt(),"projects"),{recursive:!0,force:!0})},FT=async()=>{await Ay(),await Oy(),await Iy(),await Dy()},LT=()=>{let e=Tu.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:$n,level:"info"}),t},BT=()=>{let e=ie.join(ra.homedir(),".infra-kit"),t=ie.join(e,"infra-kit.json");return ye.mkdirSync(e,{recursive:!0}),ye.writeFileSync(ie.join(e,"infra-kit.example.jsonc"),wu(),"utf-8"),ye.writeFileSync(ie.join(e,"vendor.example.jsonc"),bu(),"utf-8"),ye.existsSync(t)?{step:"user-config",outcome:"unchanged",message:`User-global config already present at ${t} (refreshed reference examples)`,level:"info"}:(ye.writeFileSync(t,`{}
361
- `,"utf-8"),{step:"user-config",outcome:"written",message:`Wrote user-global config to ${t} (see the sibling .example.jsonc files for reference)`,level:"info"})},UT=async e=>{if(Tu.env.INFRA_KIT_NO_SEED)return[Go("skipped","INFRA_KIT_NO_SEED is set")];if(e===null)return[Go("skipped","not inside a git repository")];try{let t=await ee();if(!ye.existsSync(t.main))return[Go("skipped",`no project config at ${t.main}`)];let r=await wn(t);return r.createdConfig?[{step:"project-config",outcome:"written",message:kn(r),level:"info"}]:[Go("unchanged","the user-project config was already present")]}catch(t){return d.debug({err:t,msg:"Skipped seeding the user-project config (init)."}),[Go("warned",t instanceof Error?t.message:String(t))]}},Go=(e,t)=>({step:"project-config",outcome:e,message:`Skipped seeding the user-project config \u2014 ${t}`,level:"silent"}),WT=e=>{let t=[];return e.some(r=>r.type===void 0)&&t.push("infra-kit audit --fix --root"),e.some(r=>r.type!==void 0)&&t.push("infra-kit audit --fix --all"),t},VT=(e,t)=>{let r=t.filter(s=>s.action==="failed"),n=t.filter(s=>s.action!=="unchanged"&&s.action!=="failed"),o=[];return n.length===0?o.push({step:"guidance",outcome:"unchanged",message:`Agent-instruction files current (infra-kit ${e})`,level:"info"}):o.push({step:"guidance",outcome:"skipped",message:`${n.length} agent-instruction files differ from infra-kit ${e} \u2014 setup does not rewrite them; run:`,level:"info"},...WT(n).map(s=>({step:"guidance",outcome:"manual",message:s,level:"info"}))),r.length>0&&o.push({step:"guidance",outcome:"warned",message:`${r.length} agent-instruction files could not be checked \u2014 run: infra-kit audit --root && infra-kit audit --all`,level:"warn"}),o},GT=async()=>{let{skipped:e,root:t,version:r,written:n}=await uy({dryRun:!0});return e||t===null?{root:null,entries:[{step:"guidance",outcome:"skipped",message:"Agent-instruction files skipped \u2014 not an infra-kit repo",level:"silent"}]}:{root:t,entries:VT(r,n)}},na=e=>`cd ${Fm(e)} && infra-kit setup --skip-tools`,Jo=(e,t,r,n)=>({step:e,outcome:"manual",message:`${r} needs ${n.join(", ")} \u2014 left for a human to commit; run: ${na(t)}`,level:"info"}),JT=(e,t)=>{let r=ie.relative(e,t.path);return t.status==="withheld"?Jo("plugin-pointer",e,r,t.added):t.status==="created"?{step:"plugin-pointer",outcome:"written",message:` created ${r} (Claude Code plugin pointer)`,level:"info"}:t.status==="added"?{step:"plugin-pointer",outcome:"written",message:` updated ${r} \u2014 added ${t.added.join(", ")}`,level:"info"}:{step:"plugin-pointer",outcome:t.status==="unchanged"?"unchanged":"warned",message:`${r} \u2014 ${t.status}`,level:"silent"}},Ny=(e,t)=>{let r=Je;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 ${dt} from ${ie.join(e,Je)} \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"}},KT=(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"}],HT=()=>[bl,Ct].map(e=>({step:"plugin-pointer",outcome:"manual",message:e,level:"info"})),qT=e=>{let r={step:"plugin-pointer",outcome:"warned",message:`Claude Code plugin not updated \u2014 ${e.stale?`CLI ${L.version} is behind ${e.latestVersion}, update it first with the command below`:`CLI ${L.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:Zs(e.updateCommand),level:"info"}]:[r]},YT=(e,t)=>e.status==="skipped-cli-stale"?qT(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: ${rn}`,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"},...HT()]:[{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: ${Ct}`,level:"warn"}],Fy={stale:!1},zT=async()=>{let e=no(),t=e===null?await Mc(Tu.env):e.latestVersion;return t===null||!jc(t,L.version)?Fy:{stale:!0,latestVersion:t,updateCommand:e?.updateCommand??Nm(t)}},XT=async e=>{if(e===null)return[];let r=`${await Ae(e)}${ge}`,n=Object.values(Ur).filter(o=>!ye.existsSync(ie.join(r,o)));for(let o of Object.values(Ur))ye.mkdirSync(ie.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"}]},ZT=(e,t)=>t?[{step:"plugin-pointer",outcome:"skipped",message:`Claude Code plugin ${q} is installed; the update worker keeps it current`,level:"debug"}]:[Jo("plugin-pointer",e,".claude/settings.json",[`the ${q} plugin installed`])],QT=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(JT(e,Rl(ie.join(e,".claude","settings.json"),{write:!Ze.withheld})));let r=ur({projectPath:e}).kind==="installed";if(Ze.withheld){t(...ZT(e,r),Ny(e,tn(e)));return}let n=r?await zT():Fy;t(...YT(hl({projectRoot:e,cliIsStale:()=>n.stale}),n)),t(Ny(e,tn(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: ${Ct}`,level:"warn"})}},Ly=(e,t)=>{let r=ie.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},eC=(e,t)=>{let r=t.entries.filter(i=>i.status==="drifted"),n=t.entries.filter(i=>i.status!=="drifted"),o=Ly(e,{...t,entries:n});if(t.status!=="ok"||r.length===0)return o;let s=r.map(i=>`ik-mcp "${i.name}"`);return[...o,Jo("mcp-proxies",e,ie.relative(e,t.path),s)]},tC=async e=>{if(e===null)return[];if(!ye.existsSync(ie.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 K()).mcp}catch(r){let n=r instanceof Error?r.message:String(r),o=n.split(`
362
- `)[0]??n;return Ze.withheld?[Jo("mcp-proxies",e,"infra-kit.json",[`a config fix or migration (${o})`])]:[{step:"mcp-proxies",outcome:"warned",message:` ik-mcp entries not synced \u2014 infra-kit.json could not be loaded (${o})`,level:"warn"}]}return!t||Object.keys(t).length===0?[]:Ze.withheld?eC(e,Ro({projectRoot:e,proxies:t,write:!1})):Ly(e,Ro({projectRoot:e,proxies:t,write:!0}))},rC=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"),nC=e=>{let t=Jt(e,Rr,zt);if(t!==null)return t;for(let[a,c]of AT){let l=Jt(e,a,c);if(l!==null)return l}let r=e.indexOf(OT);if(r===-1)return e;let n=e.slice(0,r).replace(/\n+$/,""),o=e.slice(r).split(`
363
- `),s=0;for(;s<o.length&&rC(o[s]);)s++;let i=o.slice(s).join(`
367
+ `)}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=Iy.safeParse(r);if(!n.success)throw new Error(`Invalid factory config at ${e}: ${NT.prettifyError(n.error)}`);return n.data};var Ny=e=>e.replace(/\.json$/,".yml"),_y=async()=>{let e;try{e=await Y()}catch{return}let t={label:"infra-kit.json",yml:Ny(e.main),json:e.main,schema:$f},r=[...et.withheld?[]:[t],{label:"~/.infra-kit/infra-kit.json",yml:ht.join(ht.dirname(e.userGlobal),"config.yml"),json:e.userGlobal,schema:Ic},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:Ny(e.userProject),json:e.userProject,schema:Ic}],n=0;for(let o of r){let[s,i]=await Promise.all([se(o.yml),se(o.json)]);if(s){if(i){d.info(`\u26A0 Skipped ${w(o.yml)} \u2014 ${w(o.json)} already exists (remove the stale .yml manually)`);continue}try{let a=await yt.readFile(o.yml,"utf-8"),c=MT.parse(a)??{},l=o.schema.safeParse(c);if(!l.success){d.info(`\u26A0 Skipped ${w(o.yml)} \u2014 invalid config: ${Dn.prettifyError(l.error)}`);continue}await yt.mkdir(ht.dirname(o.json),{recursive:!0}),await yt.writeFile(o.json,`${JSON.stringify(l.data,null,2)}
368
+ `,"utf-8"),await yt.rm(o.yml,{force:!0}),d.info(`\u2713 Migrated ${w(o.yml)} \u2192 ${w(o.json)}`),n++}catch(a){d.info(`\u26A0 Skipped ${w(o.yml)} \u2014 ${a.message}`)}}}n>0&&Ut()},My=async()=>{let e;try{e=await Y()}catch{return}let t=ht.dirname(e.userGlobal),r=[{from:ht.join(t,"config.json"),to:e.userGlobal},{from:ht.join(t,"config.example.jsonc"),to:ht.join(t,"infra-kit.example.jsonc")}],n=0;for(let{from:o,to:s}of r){let[i,a]=await Promise.all([se(o),se(s)]);if(i){if(a){d.info(`\u26A0 Skipped ${w(o)} \u2014 ${w(s)} already exists (remove the stale file manually)`);continue}try{await yt.mkdir(ht.dirname(s),{recursive:!0}),await yt.rename(o,s),d.info(`\u2713 Renamed ${w(o)} \u2192 ${w(s)}`),n++}catch(c){d.info(`\u26A0 Skipped ${w(o)} \u2014 ${c.message}`)}}}n>0&&Ut()},jT=Dn.object({workspaceDir:Dn.string().min(1),targets:Dn.array(Dn.string()).min(1)}).strict(),jy=async()=>{let e=An(),t=ht.dirname(e),r=ht.join(t,"vendor.config.ts"),[n,o]=await Promise.all([se(r),se(e)]);if(n){if(o){d.info(`\u26A0 Skipped ${w(r)} \u2014 ${w(e)} already exists (remove the stale vendor.config.ts manually)`);return}try{let s=await yt.stat(r),c=(await import(`${_T(r).href}?mtime=${Number(s.mtimeMs)}`)).default,l=typeof c=="function",u=l?await c():c,p=jT.safeParse(u);if(!p.success){d.info(`\u26A0 Skipped ${w(r)} \u2014 invalid factory config: ${Dn.prettifyError(p.error)}`);return}await yt.mkdir(t,{recursive:!0}),await yt.writeFile(e,`${JSON.stringify(p.data,null,2)}
369
+ `,"utf-8"),await yt.rm(r,{force:!0}),l?d.info(`\u26A0 Migrated ${w(r)} \u2192 ${w(e)} as a STATIC SNAPSHOT \u2014 the old file was a function (export default () => ({...})); computed values (env vars, directory globbing) were frozen at their current values and no longer re-evaluate. Edit ${w(e)} directly to change them.`):d.info(`\u2713 Migrated ${w(r)} \u2192 ${w(e)}`)}catch(s){d.info(`\u26A0 Skipped ${w(r)} \u2014 ${s.message}`)}}},Fy=async()=>{let e=await FT(),t=0;for(let r of e)if(await se(r))try{let n=await Ef(r);if(!n.changed)continue;d.info(`\u2713 Migrated ${w(r)} (removed ${n.notes.join(" and ")})`),t++}catch(n){let o=n instanceof Rf?"changed while migrating":n.message;d.info(`\u26A0 Skipped ${w(r)} \u2014 ${o}`)}t>0&&Ut()},FT=async()=>{try{let e=await Y();return et.withheld?[e.userGlobal,e.userProject]:[e.main,e.userGlobal,e.userProject]}catch{return[Of()]}};var xr="# -- infra-kit:begin --",Zt="# -- infra-kit:end --",LT=[["# region infra-kit","# endregion infra-kit"]],BT="# infra-kit shell functions",In=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},Nn="Run `source ~/.zshrc` or open a new terminal to activate.",UT={step:"migrations",outcome:"unchanged",message:"Config migrations checked (legacy yml layers, user-global filename, ide structure, factory config, retired project cache)",level:"silent"},qe=async(e,t)=>{try{return await t()}catch(r){throw new In(e,r)}},_u=async e=>{let t=[],r=(...s)=>{for(let i of s)t.push(i),e?.(i)};await qe("zshrc",()=>{r(VT())}),await qe("zshenv",()=>{r(JT())}),await qe("migrations",async()=>{await HT(),KT(),r(UT)}),await qe("user-config",()=>{r(YT())});let n=await qe("guidance",async()=>{let{entries:s,root:i}=await QT();return r(...s),i}),o=await qe("plugin-pointer",async()=>fy());return r(...tC(o,n)),await qe("worktrees",async()=>{r(...await iC(o))}),await qe("plugin-pointer",async()=>{await cC(o,r)}),await qe("mcp-proxies",async()=>{r(...await uC(o))}),await qe("project-config",async()=>{r(...await zT(o))}),await qe("token-perms",async()=>{r(await GT())}),await qe("chrome",()=>{r(WT())}),r(...qT()),t},WT=()=>{let e=Ho();return e.status==="skip"?{step:"chrome",outcome:"skipped",message:e.message,level:"debug"}:e.status!=="pass"?{step:"chrome",outcome:"manual",message:`${e.message}, then choose "Enabled by default"`,level:"info"}:Pu()?{step:"chrome",outcome:"unchanged",message:"Claude in Chrome is set up and enabled by default",level:"debug"}:{step:"chrome",outcome:"manual",message:'Claude in Chrome is set up but off by default \u2014 run `/chrome` inside Claude Code and choose "Enabled by default"',level:"info"}},GT=async()=>{let e=await Lf();return e===null?{step:"token-perms",outcome:"skipped",message:"No token store to protect",level:"debug"}:e.length===0?{step:"token-perms",outcome:"unchanged",message:"Token store is 0600 (0700 dirs)",level:"debug"}:{step:"token-perms",outcome:"written",message:`Tightened the token store to 0600 (0700 dirs): ${e.join("; ")}`,level:"info"}};var By=e=>{let t=ae.dirname(e);return we.existsSync(ae.join(e,".git"))?e:t===e?null:By(t)},Uy=(e,t,r,n)=>{if(!et.withheld)return null;if(r===n)return{step:e,outcome:"unchanged",message:`Managed block in ${t} is up to date`,level:"debug"};let o=t;try{o=we.realpathSync(t)}catch{}return By(ae.dirname(o))===null?null:zo(e,ia.homedir(),o,["the infra-kit block updated"])},Wy=e=>we.existsSync(e)?we.readFileSync(e,"utf-8"):null,VT=()=>{let e=ae.join(ia.homedir(),".zshrc"),t=Wy(e),r=t===null?"":pC(t),n=Xr({content:r,body:Jy(),startMarker:xr,endMarker:Zt,placement:"append-end"}),o=Uy("zshrc",e,t,n);return o!==null?o:(we.writeFileSync(e,n),{step:"zshrc",outcome:"written",message:`Added infra-kit shell functions to ${e}`,level:"info"})},JT=()=>{let e=ae.join(ia.homedir(),".zshenv"),t=Wy(e),r=Xr({content:t??"",body:Mu(),startMarker:xr,endMarker:Zt}),n=Uy("zshenv",e,t,r);return n!==null?n:(we.writeFileSync(e,r),{step:"zshenv",outcome:"written",message:`Added infra-kit session-env block to ${e}`,level:"info"})},KT=()=>{we.rmSync(ae.join(Et(),"projects"),{recursive:!0,force:!0})},HT=async()=>{await _y(),await My(),await Fy(),await jy()},qT=()=>{let e=Nu.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:Nn,level:"info"}),t},YT=()=>{let e=ae.join(ia.homedir(),".infra-kit"),t=ae.join(e,"infra-kit.json");return we.mkdirSync(e,{recursive:!0}),we.writeFileSync(ae.join(e,"infra-kit.example.jsonc"),xu(),"utf-8"),we.writeFileSync(ae.join(e,"vendor.example.jsonc"),Cu(),"utf-8"),we.existsSync(t)?{step:"user-config",outcome:"unchanged",message:`User-global config already present at ${t} (refreshed reference examples)`,level:"info"}:(we.writeFileSync(t,`{}
370
+ `,"utf-8"),{step:"user-config",outcome:"written",message:`Wrote user-global config to ${t} (see the sibling .example.jsonc files for reference)`,level:"info"})},zT=async e=>{if(Nu.env.INFRA_KIT_NO_SEED)return[Yo("skipped","INFRA_KIT_NO_SEED is set")];if(e===null)return[Yo("skipped","not inside a git repository")];try{let t=await Y();if(!we.existsSync(t.main))return[Yo("skipped",`no project config at ${t.main}`)];let r=await En(t);return r.createdConfig?[{step:"project-config",outcome:"written",message:Pn(r),level:"info"}]:[Yo("unchanged","the user-project config was already present")]}catch(t){return d.debug({err:t,msg:"Skipped seeding the user-project config (init)."}),[Yo("warned",t instanceof Error?t.message:String(t))]}},Yo=(e,t)=>({step:"project-config",outcome:e,message:`Skipped seeding the user-project config \u2014 ${t}`,level:"silent"}),XT=e=>{let t=[];return e.some(r=>r.type===void 0)&&t.push("infra-kit audit --fix --root"),e.some(r=>r.type!==void 0)&&t.push("infra-kit audit --fix --all"),t},ZT=(e,t)=>{let r=t.filter(s=>s.action==="failed"),n=t.filter(s=>s.action!=="unchanged"&&s.action!=="failed"),o=[];return n.length===0?o.push({step:"guidance",outcome:"unchanged",message:`Agent-instruction files current (infra-kit ${e})`,level:"info"}):o.push({step:"guidance",outcome:"skipped",message:`${n.length} agent-instruction files differ from infra-kit ${e} \u2014 setup does not rewrite them; run:`,level:"info"},...XT(n).map(s=>({step:"guidance",outcome:"manual",message:s,level:"info"}))),r.length>0&&o.push({step:"guidance",outcome:"warned",message:`${r.length} agent-instruction files could not be checked \u2014 run: infra-kit audit --root && infra-kit audit --all`,level:"warn"}),o},QT=async()=>{let{skipped:e,root:t,version:r,written:n}=await gy({dryRun:!0});return e||t===null?{root:null,entries:[{step:"guidance",outcome:"skipped",message:"Agent-instruction files skipped \u2014 not an infra-kit repo",level:"silent"}]}:{root:t,entries:ZT(r,n)}},aa=e=>`cd ${Jm(e)} && infra-kit setup --skip-tools`,zo=(e,t,r,n)=>({step:e,outcome:"manual",message:`${r} needs ${n.join(", ")} \u2014 left for a human to commit; run: ${aa(t)}`,level:"info"}),eC=(e,t)=>{let r=ae.relative(e,t.path);return t.status==="withheld"?zo("plugin-pointer",e,r,t.added):t.status==="created"?{step:"plugin-pointer",outcome:"written",message:` created ${r} (Claude Code plugin pointer)`,level:"info"}:t.status==="added"?{step:"plugin-pointer",outcome:"written",message:` updated ${r} \u2014 added ${t.added.join(", ")}`,level:"info"}:{step:"plugin-pointer",outcome:t.status==="unchanged"?"unchanged":"warned",message:`${r} \u2014 ${t.status}`,level:"silent"}},Ly=(e,t)=>{let r=He;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 ${mt} from ${ae.join(e,He)} \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"}},tC=(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 ${z} plugin for that project. If that is not the repo you meant to set up, revert that file and uninstall the plugin.`,level:"warn"}],rC=()=>[Pl,At].map(e=>({step:"plugin-pointer",outcome:"manual",message:e,level:"info"})),nC=e=>{let r={step:"plugin-pointer",outcome:"warned",message:`Claude Code plugin not updated \u2014 ${e.stale?`CLI ${U.version} is behind ${e.latestVersion}, update it first with the command below`:`CLI ${U.version} is behind the published version, update it first`}. The plugin follows on the next update check after that.`,level:"warn"};return e.stale?[r,{step:"plugin-pointer",outcome:"manual",message:ri(e.updateCommand),level:"info"}]:[r]},oC=(e,t)=>e.status==="skipped-cli-stale"?nC(t):e.status==="updated"?[{step:"plugin-pointer",outcome:"unchanged",message:`Claude Code plugin ${z} 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: ${an}`,level:"warn"}]:e.status==="installed"?[{step:"plugin-pointer",outcome:"written",message:`installed Claude Code plugin ${z} (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"},...rC()]:[{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: ${At}`,level:"warn"}],Gy={stale:!1},sC=async()=>{let e=lo(),t=e===null?await Bc(Nu.env):e.latestVersion;return t===null||!Uc(t,U.version)?Gy:{stale:!0,latestVersion:t,updateCommand:e?.updateCommand??Um(t)}},iC=async e=>{if(e===null)return[];let r=`${await De(e)}${he}`,n=Object.values(Jr).filter(o=>!we.existsSync(ae.join(r,o)));for(let o of Object.values(Jr))we.mkdirSync(ae.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"}]},aC=(e,t)=>t?[{step:"plugin-pointer",outcome:"skipped",message:`Claude Code plugin ${z} is installed; the update worker keeps it current`,level:"debug"}]:[zo("plugin-pointer",e,".claude/settings.json",[`the ${z} plugin installed`])],cC=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(eC(e,xl(ae.join(e,".claude","settings.json"),{write:!et.withheld})));let r=pr({projectPath:e}).kind==="installed";if(et.withheld){t(...aC(e,r),Ly(e,sn(e)));return}let n=r?await sC():Gy;t(...oC(kl({projectRoot:e,cliIsStale:()=>n.stale}),n)),t(Ly(e,sn(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: ${At}`,level:"warn"})}},Vy=(e,t)=>{let r=ae.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},lC=(e,t)=>{let r=t.entries.filter(i=>i.status==="drifted"),n=t.entries.filter(i=>i.status!=="drifted"),o=Vy(e,{...t,entries:n});if(t.status!=="ok"||r.length===0)return o;let s=r.map(i=>`ik-mcp "${i.name}"`);return[...o,zo("mcp-proxies",e,ae.relative(e,t.path),s)]},uC=async e=>{if(e===null)return[];if(!we.existsSync(ae.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 J()).mcp}catch(r){let n=r instanceof Error?r.message:String(r),o=n.split(`
371
+ `)[0]??n;return et.withheld?[zo("mcp-proxies",e,"infra-kit.json",[`a config fix or migration (${o})`])]:[{step:"mcp-proxies",outcome:"warned",message:` ik-mcp entries not synced \u2014 infra-kit.json could not be loaded (${o})`,level:"warn"}]}return!t||Object.keys(t).length===0?[]:et.withheld?lC(e,Co({projectRoot:e,proxies:t,write:!1})):Vy(e,Co({projectRoot:e,proxies:t,write:!0}))},dC=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"),pC=e=>{let t=Ht(e,xr,Zt);if(t!==null)return t;for(let[a,c]of LT){let l=Ht(e,a,c);if(l!==null)return l}let r=e.indexOf(BT);if(r===-1)return e;let n=e.slice(0,r).replace(/\n+$/,""),o=e.slice(r).split(`
372
+ `),s=0;for(;s<o.length&&dC(o[s]);)s++;let i=o.slice(s).join(`
364
373
  `);return n+(i?`
365
- ${i}`:"")},By=()=>{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(`
366
- `)},Uy=()=>`${Rr}
367
- ${By()}
368
- ${zt}`,$u=()=>["# 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(`
369
- `),Au=()=>`${Rr}
370
- ${$u()}
371
- ${zt}`;import oC from"node:fs/promises";var Ko=async(e,t)=>{if(!t)return{hasOverrides:!1,overrideKeys:[],unreadable:!1};try{let r=await oC.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}}},Ho=e=>e.unreadable?"(unreadable \u2014 invalid JSON)":e.overrideKeys.length===0?"(empty \u2014 no overrides)":`(${e.overrideKeys.length} override(s): ${e.overrideKeys.join(", ")})`;import iC from"node:fs";import aC from"node:os";import Wy from"node:path";import cC from"node:process";import{$ as sC}from"zx";var An=()=>sC({quiet:!0});var lC=()=>[Wy.join(aC.homedir(),".local","bin"),"/opt/homebrew/bin","/usr/local/bin"],uC=async e=>{try{return(await An()`command -v ${e}`).stdout.trim()||null}catch{return null}},qo=()=>({runCommand:async e=>{let t=await An()`${e}`;return{stdout:`${t.stdout}
372
- ${t.stderr}`}},resolveBinPath:async e=>{let t=await uC(e);return t!==null?t:lC().map(r=>Wy.join(r,e)).find(r=>iC.existsSync(r))??null},realpath:xe,platform:cC.platform});var Xt=(...e)=>({steps:e,needsSudo:!1,fetchesNetworkScript:!1}),On=e=>/\d{1,10}\.\d{1,10}\.\d{1,10}/.exec(e)?.[0]??null,Dn=["darwin","linux"],aa=e=>t=>Sc(t,e)?"homebrew":"unknown",ca=(e,t)=>r=>r===null?null:t(e(r),r),Du=e=>ca(aa(e.kegName),t=>t==="homebrew"?Xt(["brew","upgrade",e.brewFormula]):null),Vy=e=>Xs(e,"Homebrew")||Xs(e,"homebrew")?"homebrew":"unknown",dC={id:"brew",binName:"brew",probeArgv:["brew","--version"],versionFrom:On,platforms:Dn,prerequisites:[],bootstrapInstall:{steps:[["/bin/bash","-c","$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"]],needsSudo:!0,fetchesNetworkScript:!0},identify:Vy,updateFor:ca(Vy,e=>e==="homebrew"?Xt(["brew","update"]):null)},Ou={brewFormula:"awscli",brewInstallSpec:"awscli",kegName:"awscli"},Ky="https://awscli.amazonaws.com/v2/install.sh",Hy={steps:[["/bin/bash","-c",`curl -fsSL ${Ky} | bash`]],needsSudo:!1,fetchesNetworkScript:!0},pC="/usr/local/aws-cli",mC=e=>zn(pC,e,xe)?{steps:[["sudo","/bin/bash","-c",`curl -fsSL ${Ky} | bash -s -- --system`]],needsSudo:!0,fetchesNetworkScript:!0}:Hy,Gy=e=>Sc(e,Ou.kegName)?"homebrew":Xs(e,"aws-cli")?"script":"unknown",fC={id:"aws",binName:"aws",...Ou,probeArgv:["aws","--version"],versionFrom:On,platforms:Dn,prerequisites:[],bootstrapInstall:Hy,identify:Gy,updateFor:ca(Gy,(e,t)=>e==="homebrew"?Xt(["brew","upgrade",Ou.brewFormula]):e==="script"?mC(t):null)},oa={brewFormula:"git",brewInstallSpec:"git",kegName:"git"},gC={id:"git",binName:"git",...oa,probeArgv:["git","--version"],versionFrom:On,platforms:Dn,prerequisites:["brew"],bootstrapInstall:Xt(["brew","install",oa.brewInstallSpec]),identify:aa(oa.kegName),updateFor:Du(oa)},sa={brewFormula:"gh",brewInstallSpec:"gh",kegName:"gh"},hC={id:"gh",binName:"gh",...sa,probeArgv:["gh","--version"],versionFrom:On,platforms:Dn,prerequisites:["brew"],bootstrapInstall:Xt(["brew","install",sa.brewInstallSpec]),identify:aa(sa.kegName),updateFor:Du(sa)},ia={brewFormula:"doppler",brewInstallSpec:"dopplerhq/cli/doppler",kegName:"doppler"},yC={id:"doppler",binName:"doppler",...ia,probeArgv:["doppler","--version"],versionFrom:On,platforms:Dn,prerequisites:["brew"],bootstrapInstall:Xt(["brew","install","gnupg"],["brew","install",ia.brewInstallSpec]),identify:aa(ia.kegName),updateFor:Du(ia)},Yo="portless",Jy=e=>Im(e,Yo)===null?"unknown":"npm",vC={id:"portless",binName:Yo,npmPackage:Yo,probeArgv:["portless","--version"],versionFrom:On,platforms:[...Dn,"win32"],prerequisites:[],bootstrapInstall:Xt(["npm","install","-g",Yo]),identify:Jy,updateFor:ca(Jy,e=>e==="npm"?Xt(["npm","install","-g",`${Yo}@latest`]):null)},Iu={brew:dC,git:gC,aws:fC,gh:hC,doppler:yC,portless:vC},Sr=Object.keys(Iu),He=e=>Iu[e],Nu=(e,t)=>e.platforms.includes(t),_u=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 He(o).prerequisites)n(i,[...s,o]);t.push(o)}};for(let o of e)n(o,[]);return t};var qy=e=>({id:e,present:!1,onPath:!1,binRealPath:null,version:null,manager:"unknown"}),Yy=async(e,t)=>{try{return await e(t)}catch{return null}},wC=async(e,t)=>{try{let r=await e.resolveBinPath(t);return r==null?null:e.realpath(r)}catch{return null}},zy=async(e,t)=>{if(!Nu(e,t.platform))return qy(e.id);let r=await Yy(t.runCommand,e.probeArgv),n=await wC(t,e.binName);if(r==null&&n==null)return qy(e.id);let o=r??(n==null?null:await Yy(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)}},zo=async(e,t)=>Promise.all(e.map(r=>zy(He(r),t)));import{$ as PC}from"zx";import{z as Xy}from"zod";var Zy=/^\d{4}-\d{2}-\d{2}$/,Xo=e=>{if(!Zy.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},Qy=e=>`Release date "${e}" is not a calendar date in yyyy-mm-dd form.`,In=class extends Error{constructor(t){super(Qy(t)),this.name="InvalidReleaseDateError"}},Er=e=>{let t=e.trim();if(!Xo(t))throw new In(t);return t},Zo=e=>{let t=e.trim();return t===""||Xo(t)?!0:Qy(t)},Mu=Xy.string().refine(Xo,{message:"Expected a calendar date in yyyy-mm-dd form."}),ju=Xy.string().refine(e=>e===""||Xo(e),{message:'Expected a calendar date in yyyy-mm-dd form, or "" to clear.'});var Zt=e=>e.slice(1).split(".").map(Number),Nn=e=>[...e].sort((t,r)=>{let[n,o,s]=Zt(t),[i,a,c]=Zt(r);return n!==i?(n??0)-(i??0):o!==a?(o??0)-(a??0):(s??0)-(c??0)});var tv="next",kC=/^v?(\d+)\.(\d+)\.(\d+)$/,bC=e=>e.replace(/^.*release\//,""),Fu=e=>{let t=bC(e.trim()),r=kC.exec(t);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null},ev=e=>`${e[0]}.${e[1]}.${e[2]}`,Lu=e=>{let t=[...e.remoteBranches??[],...e.jiraVersions??[]],r=[],n=new Set;for(let o of t){let s=Fu(o);if(!s)continue;let i=ev(s);n.has(i)||(n.add(i),r.push(s))}return Nn(r.map(o=>ev(o))).map(o=>Zt(`v${o}`))},Pr=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},Bu=(e,t)=>{if(e.length===0)throw new Pr;let r=e[e.length-1];if(t==="hotfix"){let[s,i]=r,a=e.reduce((c,l)=>l[0]===s&&l[1]===i?Math.max(c,l[2]):c,0);return`${s}.${i}.${a+1}`}let[n,o]=r;return`${n}.${o+1}.0`},_n=(e,t)=>{try{return Bu(e,t)}catch(r){if(r instanceof Pr)return null;throw r}},Uu=e=>e.trim().toLowerCase()===tv,ua=e=>Uu(e)||Fu(e)!==null?{version:e}:{name:e},RC=e=>e==="regular"||e==="hotfix",rv=e=>"name"in e,SC=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:Er(n)}},Wu=e=>{let t=e.trim();if(t==="")throw new Error("Release spec is empty");let r=t.indexOf(":"),{token:n,releaseDate:o}=SC(r===-1?t:t.slice(0,r)),s="regular",i="";if(r!==-1){let a=t.slice(r+1),c=a.indexOf(":"),l=c===-1?a.trim():a.slice(0,c).trim();i=c===-1?"":a.slice(c+1).trim();let u=l.toLowerCase();if(!RC(u))throw new Error(`Invalid release type "${l}". Expected "regular" or "hotfix".`);s=u}return la({...ua(n),type:s},{description:i,releaseDate:o})},Vu=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},la=(e,t)=>{let{description:r,releaseDate:n}=t;return{...e,...r!==void 0&&r!==""?{description:r}:{},...n===void 0?{}:{releaseDate:n}}},EC=e=>{let t=e.name.trim();return ri(t),la({id:{kind:"name",name:t,raw:t},type:e.type},e)},Gu=(e,t)=>{let r=[...t];return e.map(n=>{if(rv(n))return EC(n);let o=n.version.trim();if(o==="")throw new Error("Release entry has an empty version");if(Uu(o)){let a=Bu(r,n.type);return r.push(Zt(`v${a}`)),la({id:ke(a),type:n.type},n)}let s=Fu(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),la({id:ke(i),type:n.type},n)})},Ju=e=>e.some(t=>!rv(t)&&Uu(t.version));var xC=e=>e.split(`
373
- `).map(t=>{let r=t.indexOf(" ");return r===-1?null:Q(t.slice(r+1))}).filter(t=>t!==null&&t.kind==="version").map(t=>t.raw),TC=async()=>{let e=await PC({quiet:!0})`git ls-remote --heads origin 'release/v*'`;return xC(e.stdout)},CC=async()=>{let e=await At();return e?(await pn(e)).map(r=>r.name):[]},Qo=async()=>{let[e,t]=await Promise.allSettled([TC(),CC()]);return e.status==="rejected"&&d.warn({err:e.reason},"Failed to list remote release branches; continuing without them"),t.status==="rejected"&&d.warn({err:t.reason},"Failed to fetch Jira versions; continuing without them"),Lu({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:t.status==="fulfilled"?t.value:[]})};import $C from"node:fs";import AC from"node:path";var Ku=[".claude/settings.json",".claude/settings.local.json"],OC=["infra-kit","ik","pnpm exec infra-kit","pnpm exec ik","pnpm infra-kit"],DC=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),IC=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},NC=(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(DC).join(".*")}$`,"s").test(t)||n===t||n.startsWith(`${t} `)},_C=e=>{let t=e.groupPath.join(" ");return t===e.cliName?[t]:[t,e.cliName]},MC=()=>xr.filter(e=>e.mutating),jC=e=>{let t=IC(e);return t===null?[]:MC().filter(r=>OC.some(n=>_C(r).some(o=>NC(t,`${n} ${o}`)))).map(r=>r.groupPath.join(" "))},FC=(e,t)=>{let r;try{r=$C.readFileSync(AC.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}},nv=e=>{let t={present:[],unreadable:[],hits:[]};for(let r of Ku){let n=FC(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=jC(o);s.length>0&&t.hits.push({file:r,pattern:o,commands:s})}}}return t};var LC=e=>e.every(t=>t.status!=="fail"),BC=["brew","git","gh","doppler","aws"],UC=async e=>{let t=await zo(BC,e);return new Map(t.map(r=>[r.id,{manager:r.manager,version:r.version,present:r.present,onPath:r.onPath}]))},It=async(e,t,r,n)=>{try{return await An()`${t}`,{name:e,status:"pass",message:r}}catch{return{name:e,status:"fail",message:n}}},WC=async()=>{let e="orca installed",t=await Wt();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)"}},yv=(e,t,r,n)=>{let o=ve.join(hv.homedir(),t),s="Run: infra-kit setup --skip-tools";if(!ae.existsSync(o))return{name:e,status:"fail",message:`~/${t} not found. ${s}`};let i=ae.readFileSync(o,"utf-8"),a=i.indexOf(Rr),c=i.indexOf(zt);return a===-1||c===-1||c<a?{name:e,status:"fail",message:`infra-kit ${r} block missing from ~/${t}. ${s}`}:i.slice(a,c+zt.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`}},VC=()=>yv("zshrc init block",".zshrc","shell",Uy()),GC=()=>yv("zshenv session block",".zshenv","session-env",Au()),JC=async()=>{let e="pnpm enableGlobalVirtualStore";try{let t=await $(),r=ve.join(t,"pnpm-workspace.yaml");if(!ae.existsSync(r))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${r}`};let n=ae.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}`}}},KC=async()=>{try{return Lt(),{config:await K(),error:null}}catch(e){return{config:null,error:e}}},HC=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)"}},qC=384,Hu=448,YC=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(", "),zC=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}}})),XC=async(e,t={})=>{let r="env tokens configured",n=t.readStore??Qe,o=t.resolveToken??Ff;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 zC(await pi(),o);return{name:r,status:"pass",message:YC(s)}},ZC=()=>ht.env[pr]||void 0,QC=async(e={})=>{let t="tokens.json present",r=e.readStore??Qe,n=e.storePath??Ut;if((e.readEnvToken??ZC)())return{name:t,status:"skip",message:`${pr} is set; that channel takes precedence over the store`};let s;try{s=w(await n())}catch{return{name:t,status:"skip",message:"the token store path could not be resolved"}}let i;try{i=await r()}catch{return{name:t,status:"skip",message:`The store at ${s} is unreadable (see env tokens configured)`}}let a=i===null?[]:Object.keys(i.envs);if(a.length===0){let c=i===null?`No token store at ${s}`:`${s} holds no tokens`;return{name:t,status:"fail",message:`${c} \u2014 every project needs one to authenticate. Fix: run \`infra-kit env-token-set <env>\`. CI / agents: set ${pr} instead.`}}return{name:t,status:"pass",message:`${s} holds ${a.length} token(s): ${a.join(", ")}`}},es=(e,t)=>{let r=t(e);return r===null?null:r.mode&511},e$=async(e,t={})=>{let r="tokens.json perms",n=t.storePath??Ut,o=t.statPath??t$,s=t.chmodPath??ae.chmodSync,i;try{i=await n()}catch{return{name:r,status:"skip",message:"the token store path could not be resolved"}}if(es(i,o)===null)return{name:r,status:"skip",message:`No store to protect at ${w(i)} (see tokens.json present)`};let a=ve.dirname(i),c=ve.dirname(a),l=ve.dirname(c),p=[{target:l,expected:Hu,actual:es(l,o)},{target:c,expected:Hu,actual:es(c,o)},{target:a,expected:Hu,actual:es(a,o)},{target:i,expected:qC,actual:es(i,o)}].filter(f=>f.actual!==null&&f.actual!==f.expected);if(p.length===0)return{name:r,status:"pass",message:`${w(i)} is 0600 (0700 dirs)`};let m=p.map(f=>`${w(f.target)} is ${ov(f.actual)}, expected ${ov(f.expected)}`).join("; ");if(!e)return{name:r,status:"fail",message:`${m}. Fix: run \`infra-kit setup --skip-tools\` or \`infra-kit doctor --fix\`.`};for(let f of p)s(f.target,f.expected);return{name:r,status:"pass",message:`Tightened ${p.length} path(s): ${m}`}},ov=e=>`0${e.toString(8).padStart(3,"0")}`,t$=e=>{try{return ae.statSync(e)}catch{return null}},r$=async()=>{let e="user override path";try{let t=await ee(),r=ae.existsSync(t.userProject),n=await Ko(t.userProject,r),o=r?Ho(n):"(not created \u2014 seed failed?)";return{name:e,status:"pass",message:`${w(t.userProject)} ${o} \u2014 project: ${t.projectName}`}}catch(t){return{name:e,status:"fail",message:t.message}}},n$=async()=>{let e="legacy user-global config",t;try{t=await ee()}catch{return{name:e,status:"skip",message:"infra-kit config paths could not be resolved"}}let r=ve.join(ve.dirname(t.userGlobal),"config.json");return ae.existsSync(r)?ae.existsSync(t.userGlobal)?{name:e,status:"fail",message:`Stale legacy config.json found at ${w(r)} \u2014 ${w(t.userGlobal)} is active; remove the old file.`}:{name:e,status:"fail",message:`Legacy user-global config.json found at ${w(r)} \u2014 run \`infra-kit setup --skip-tools\` to migrate it (your overrides are not being applied).`}:{name:e,status:"pass",message:"No legacy user-global config.json"}},sv=/^\d+\.\d+\.\d+$/,iv=(e,t)=>e===t||!sv.test(e)||!sv.test(t)?!1:Nn([`v${e}`,`v${t}`])[0]===`v${e}`,o$=async e=>{let t;try{t=await Re(e)}catch{return[]}return t.flatMap(r=>{let n=Tt(ut(ve.join(r,"CLAUDE.md")));return n.state==="ok"&&n.version!==void 0?[n.version]:[]})},av=e=>Nn(e.map(t=>`v${t}`)).map(t=>t.slice(1)),s$=async(e,t,r)=>{let n="Guidance version",o=gr(t,hr),s=await o$(e),a=(o===null?s:[o,...s]).filter(p=>St(p,r));if(a.length>0){let p=av(a).at(-1);return{name:n,status:"warn",message:`${a.length} guidance ${a.length===1?"block was":"blocks were"} generated by a newer infra-kit (newest ${p}, current ${r}) \u2014 CLI behind the block, run: pnpm add -g infra-kit@${p}`}}let c=o!==null&&iv(o,r),l=s.filter(p=>iv(p,r));if(!c&&l.length===0)return{name:n,status:"pass",message:`guidance blocks match infra-kit ${r}`};let u=[...c?[`the root block is from infra-kit ${o} \u2014 run: infra-kit audit --fix --root`]:[],...l.length>0?[`${l.length} package guidance ${l.length===1?"block was":"blocks were"} generated by an older infra-kit (oldest ${av(l)[0]}, current ${r}) \u2014 run: infra-kit audit --fix --all`]:[]];return{name:n,status:"warn",message:u.join("; ")}},i$=async()=>{let e=[{name:"CLAUDE.md block",status:"skip",message:"no infra-kit config in this repo"},{name:"Guidance version",status:"skip",message:"no infra-kit config in this repo"}],t;try{t=(await ee()).main}catch{return e}if(!ae.existsSync(t))return e;let r=ve.dirname(t),n=ve.join(r,"CLAUDE.md"),o=ae.existsSync(n)?ae.readFileSync(n,"utf-8"):"",s=Ve(o,Se,Ie);return[{name:"CLAUDE.md block",status:s?"pass":"fail",message:s?"CLAUDE.md block present":"infra-kit block missing from CLAUDE.md. Run: infra-kit setup --skip-tools"},await s$(r,o,L.version)]},a$=async()=>{try{let e=(await ee()).main;return ae.existsSync(e)?ve.dirname(e):null}catch{return null}},c$=e=>{let t=Pf();return t===null||!St(t,e)?"":` \u2014 plugin ${t} is fetched but not applied. Run: ${rn}`},l$=e=>{let t=e.kind==="installed"?ci(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}${c$(t)}`}},cv=3,lv=(e,t)=>xe(e)===xe(t),u$=e=>{if(e===void 0||e.gitRoot===null)return"";let t=w(e.gitRoot);if(e.projectDir!==null){if(lv(e.projectDir,e.gitRoot))return"";let r=zn(e.gitRoot,xe(e.projectDir),xe)?"below the repo root":"not this checkout";return` \u2014 this session was launched from ${w(e.projectDir)}, ${r}: the plugin and this repo's .claude/settings.json hooks load only from ${t} (measured); restart Claude Code there`}return lv(e.cwd,e.gitRoot)?"":` \u2014 if Claude Code was launched from ${w(e.cwd)} rather than ${t}, it loaded neither the plugin nor this repo's hooks; launch it at ${t}`},d$=(e,t)=>{let r="plugin installed",n=u$(t);if(e.kind==="installed"){let{scope:c,projectPath:l}=e.installation,u=l===null?"":`, ${w(l)}`;return{name:r,status:"pass",message:`Plugin ${q} installed (${c??"unknown"} scope${u})${n}`}}if(e.kind==="absent")return{name:r,status:"fail",message:`Plugin ${q} is not installed. Run: ${Ct}${n}`};let o=e.installations.map(c=>c.projectPath===null?"(unnamed project)":w(c.projectPath)),s=o.length-cv,i=s>0?` and ${s} more`:"",a=`${o.slice(0,cv).join(", ")}${i}`;return{name:r,status:"fail",message:`Plugin ${q} is installed for ${a} only, not this project. Run: ${Ct}${n}`}},p$=()=>It("claude CLI",["claude","--version"],"Installed: claude","claude CLI not found on PATH \u2014 `infra-kit setup` cannot install the plugin; install Claude Code first");var m$=(e,...t)=>{try{return JSON.parse(ae.readFileSync(ve.join(e,...t),"utf-8"))}catch{return null}},f$=e=>{if(e.kind!=="installed")return{kind:"not-installed"};let t=ci(e.installation),{installPath:r}=e.installation;if(r===null)return{kind:"skills-only",version:t};let n=m$(r,Je),o=n!==null&&typeof n=="object"?n[dt]:void 0;return o==null||typeof o!="object"?{kind:"skills-only",version:t}:{kind:"stale-server",version:t,keys:Object.keys(o)}},uv=e=>`Plugin ${q} ${e===null?"(version unreadable)":e}`,g$=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: ${Ct}`};if(e.kind==="stale-server"){let r=e.keys.length===0?"":` (under "${e.keys.join('", "')}")`;return{name:t,status:"pass",message:`${uv(e.version)} still carries an MCP server in its ${Je}${r} \u2014 a copy from before the plugin went skills-only. Update it: infra-kit setup (or ${rn}), then restart Claude Code`}}return{name:t,status:"pass",message:`${uv(e.version)} is skills-only \u2014 no ${Je}, as shipped; the /infra-kit:* skills drive the infra-kit CLI`}},h$=(e,t)=>{let r=ur(e===null?{}:{projectPath:e}),n=ro();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}`},d$(r,t),l$(r),g$(f$(r)),{name:"CLI version",status:"pass",message:`infra-kit CLI ${L.version}`}]},y$=(e,t)=>{let r="background setup";if(e===null)return{name:r,status:"skip",message:"not run yet \u2014 it runs after the next background update check"};if(e.version!==t)return{name:r,status:"skip",message:`last ran for ${e.version}; runs for ${t} after the next background update check`};if(e.finishedMs===null)return{name:r,status:"skip",message:`a pass for ${t} is running, or was interrupted and will be retried`};let n=e.runs.filter(o=>o.status!=="ok");return n.length===0?{name:r,status:"pass",message:`ran for ${t} on the machine and ${e.runs.length-1} project(s)`}:{name:r,status:"warn",message:`${n.length} run(s) left work for you (${n.map(o=>`${o.root??"machine"}: ${o.status}`).join(", ")}) \u2014 see ${w(Rn())}, or run: infra-kit setup`}},v$=({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(", ")},w$=e=>{let t="Agent mode",r=ti(e),n=v$(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})`}},dv=4,k$=e=>{let t=e.slice(0,dv).join(", "),r=e.length-dv;return r>0?`${t} +${r} more`:t},b$=e=>{let t="Agent allowlist",{present:r,unreadable:n,hits:o}=nv(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"} (${k$(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 ${Ku.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`}},R$=(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`},S$=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 zh(e)}catch(i){return{name:r,status:"skip",message:`could not read the merge-dev state: ${i.message}`}}if(n.length===0)return{name:r,status:"pass",message:"no merge-dev hand-off in progress"};let o=n.map(i=>{let a=i.worktreeExists?w(i.worktreePath):"worktree missing";return`${i.branch} (${R$(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`}},vv=e=>Ec(["trust"],{bin:e}),E$=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),pv="ERR_TLS_CERT_ALTNAME_INVALID",wv=()=>`portless serving TLS on :${Ft}`,P$=async(e,t,r)=>{let n=wv();return await e(Ft,!0)?{name:n,status:"pass",message:`portless is serving HTTPS on :${Ft}`}:{name:n,status:"fail",message:`No portless daemon is serving HTTPS on :${Ft}. Install it once (needs root): \`${jt(t,r)}\`.`}},x$=async(e,t,r,n,o)=>{let s="portless CA chain valid",i=["localhost",...t.slice(0,1).map(u=>u.name)],c=(await Promise.all(i.map(async u=>({servername:u,result:await e(Ft,u)})))).filter(u=>!u.result.ok);if(c.length===0)return{name:s,status:"pass",message:`Served certificate chains to ${w(r)} (${i.join(", ")})`};let l=c.map(u=>u.result.ok?"":u.result.code);return l.includes(pv)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${pv} for servername(s) ${c.map(u=>u.servername).join(", ")} \u2014 doctor's probe is wrong, your trust store is not implicated. Please report this.`}:l.some(u=>E$.has(u))?{name:s,status:"fail",message:`The daemon is serving a certificate that does not chain to ${w(r)}. Its CA was regenerated \u2014 run \`${vv(n)}\`, or reinstall: \`${jt(n,o)}\`.`}:{name:s,status:"fail",message:`TLS handshake failed (${l.join(", ")})`}},T$=(e,t,r)=>{let n="portless CA trusted";return e?{name:n,status:"pass",message:`${w(t)} matches the recorded ca.trusted fingerprint`}:{name:n,status:"fail",message:`The portless CA is not trusted (or was regenerated). Run: \`${vv(r)}\` (no sudo needed).`}},C$=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 \`${Ec(["alias","--remove","<name>"],{bin:r})}\`.`}},Qt="portless service target",rs=e=>({name:Qt,status:"warn",message:e}),kv=e=>e==="darwin"?Um:e==="linux"?Wm:null,$$=e=>e==="darwin"?`sudo launchctl kickstart -k system/${Bm}`:`sudo systemctl restart ${Vm}`,A$="/bin/ps",O$=e=>{try{let t=gv(A$,["-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}},mv=e=>{try{return ae.readFileSync(e,"utf-8")}catch{return null}},D$=e=>{try{return ae.statSync(e).mtime}catch{return null}},I$=2e3,N$=e=>{try{let t=gv(e,["-p","process.version"],{encoding:"utf-8",timeout:I$}),r=t.stdout?.trim()??"";return{version:r===""?null:r,status:t.status,signal:t.signal}}catch{return{version:null,status:null,signal:null}}},_$=(e,t)=>({platform:e.platform??ht.platform,readServiceFile:e.readServiceFile??mv,readFile:e.readFile??mv,exists:e.exists??ae.existsSync,realpath:e.realpath??xe,mtime:e.mtime??D$,execPath:e.execPath??ht.execPath,home:e.home??hv.homedir(),cwd:e.cwd??ht.cwd(),repoRoot:e.repoRoot??Uo,stateDir:(e.stateDir??Jm)(),processStartTime:e.processStartTime??O$,version:e.version??ht.version,arch:e.arch??ht.arch,nodeVersionOf:e.nodeVersionOf??N$,isGlobal:e.isGlobal??ei().node.isGlobal,nodeFs:e.nodeFs??ae,stableNode:null,stableNodeSidecar:null,bin:t}),ns="portless node",Tr="~/.infra-kit/node",ts=e=>({row:{name:ns,status:"fail",message:e},stableNode:null,sidecar:null}),fv=(e,t)=>{try{return e(t,{throwIfNoEntry:!1})}catch{return}},M$=e=>e.signal!==null?`killed by ${e.signal}`:e.status===null?"did not start":e.status!==0?`exit ${e.status}`:`printed ${e.version??"nothing"}`,j$=(e,t)=>e.status===0&&e.signal===null&&e.version===t.version,F$=e=>{let t=zm(e.home),r=fv(e.nodeFs.lstatSync,t);if(r===void 0)return ts(`${Tr} is missing and could not be written \u2014 run \`infra-kit setup\` and see the debug log`);if(!r.isFile())return ts(`${Tr} is not a regular file; infra-kit will not replace it \u2014 move it away and run \`infra-kit setup\``);let n=Xm(e.home,e.nodeFs);if(n===null)return ts(`${Tr} has no readable node.source.json and it could not be rewritten \u2014 run \`infra-kit setup\``);let o=fv(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 ts(`${Tr} is Node ${n.version} (${n.method} of ${w(n.source)}); infra-kit runs ${e.version} at ${w(e.execPath)}, a different file, and could not relink it \u2014 run \`infra-kit setup\``);if(!i){let c=e.nodeVersionOf(t);if(!j$(c,e))return ts(`${Tr} does not run as Node ${e.version} (${M$(c)}). Re-run through the current Node: \`${jt(e.bin,{...e,stableNode:null})}\`, then \`infra-kit setup\``)}return{row:{name:ns,status:"pass",message:`${Tr} is Node ${n.version} (${n.arch}, ${n.method} of ${w(n.source)})`},stableNode:t,sidecar:n}},L$=e=>{if(kv(e.platform)===null)return{row:{name:ns,status:"skip",message:"no portless OS service on this platform"},stableNode:null,sidecar:null};let t=F$(e);return e.isGlobal()?t:{...t,row:{name:ns,status:"skip",message:`not a global install; the global infra-kit keeps ${Tr} current`}}},bv=(e,t)=>{let r=_$(e,t),n=L$(r);return{seams:{...r,stableNode:n.stableNode,stableNodeSidecar:n.sidecar},node:n.row}},B$=(e,t)=>{let r=t.readFile(ve.join(e,"package.json"));try{let n=r===null?null:Ee.object({version:Ee.string()}).safeParse(JSON.parse(r));return n?.success===!0?n.data.version:"?"}catch{return"?"}},U$=e=>{let t=Number.parseInt(e.readFile(ve.join(e.stateDir,"proxy.pid"))?.trim()??"",10);return!Number.isInteger(t)||t<=0?null:e.processStartTime(t)},W$=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?null:t},V$=(e,t,r)=>{let n=U$(r),o=a=>n!==null&&a!==null&&n.getTime()<a.getTime(),s=r.stableNodeSidecar,i=[...s!==null&&o(W$(s.versionChangedAt))?[`Node ${s.version}`]:[],...o(r.mtime(ve.join(e,"package.json")))?[`portless ${t}`]:[]];return i.length===0?null:i.join(" and ")},G$=async(e,t)=>{let r=t.realpath(t.cwd);return r===t.realpath(t.home)?!1:zn(await t.repoRoot()??r,e,t.realpath)},Cr=e=>({state:"drifted",row:e}),J$=async(e,t,r)=>{let n=jt(r.bin,r);if(!r.exists(e))return Cr({name:Qt,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=ve.join(Pc(r.home),"dist","cli.js");if(t!==o)return Cr(rs(`The service points at \`${t}\`, a version-specific location. Re-run once to switch it to the stable link: \`${n}\``));if(Qs(r.home,r.exists)===null)return Cr({name:Qt,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(Pc(r.home));if(await G$(s,r))return Cr({name:Qt,status:"fail",message:`The service runs portless from a project checkout (${s}). Re-run \`service install\` from the global install: \`${n}\``});let i=K$(e,n,r);if(i!==null)return i;let a=B$(s,r),c=V$(s,a,r);return c!==null?{state:"converged",row:rs(`The running daemon predates ${c} that \`dev\` will talk to. Restart it: \`${$$(r.platform)}\` (or reboot).`)}:{state:"converged",row:{name:Qt,status:"pass",message:`service runs \`${e}\` (Node ${r.version}) + stable link \u2192 portless ${a}`}}},K$=(e,t,r)=>r.stableNode!==null?r.realpath(e)===r.realpath(r.stableNode)?null:Cr(rs(`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:Cr(rs(`The service runs \`${e}\`; infra-kit runs \`${r.execPath}\`. Works until the old Node is removed. Re-run when convenient: \`${t}\``)),Rv=async e=>{let t=kv(e.platform);if(t===null)return{state:"absent",row:{name:Qt,status:"skip",message:"no portless OS service file on this platform"}};let r=e.readServiceFile(t);if(r===null)return{state:"absent",row:{name:Qt,status:"skip",message:`the OS service is not installed (no ${t})`}};let[n,o]=wh(e.platform,r)??[];return n===void 0||o===void 0?Cr(rs(`could not parse ${t} \u2014 re-run \`${jt(e.bin,e)}\` to rewrite it.`)):J$(n,o,e)},Sv=async(e,t)=>{let{seams:r}=bv(e,t);return{state:(await Rv(r)).state,stableNode:r.stableNode}},H$=()=>[ns,Qt,wv(),"portless CA chain valid","portless CA trusted","portless routes"],q$=async(e={})=>{let t=e.resolveBin??Lm,r=e.isProxyServing??Gm,n=e.handshake??qm,o=e.caTrusted??Hm,s=e.routes??Zn,i=e.isListening??Xn,a=(e.caPath??Km)(),c=t();if(c===null)return[{name:"portless installed",status:"fail",message:"portless is not resolvable from node_modules \u2014 run `pnpm install`."},...H$().map(S=>({name:S,status:"skip",message:"portless not resolvable"}))];let l={name:"portless installed",status:"pass",message:"portless is resolvable from node_modules"},{seams:u,node:p}=bv(e,c),m=s(),f=await P$(r,c,u),h=f.status==="fail"?{name:"portless CA chain valid",status:"skip",message:"no daemon to handshake with"}:await x$(n,m,a,c,u);return[l,p,(await Rv(u)).row,f,h,T$(o(),a,c),await C$(m,i,c)]},Y$=async(e={})=>{let t="portless routes",r=e.routes??Zn,n=e.isListening??Xn,o=e.devSessionRunning??fh,s=r();if(s.length===0)return{name:t,status:"pass",message:"No portless routes registered"};let i=await Promise.all(s.map(async u=>({name:u.name,port:u.port,live:await n(u.port)}))),{prunable:a,withheld:c}=mh(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??Ym().removeAlias;for(let u of a)await l(u);return{name:t,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},da=async(e={})=>{let t=await KC(),r=UC(e.probeDeps??qo()),n=async(m,f)=>{let[h,S]=await Promise.all([f,r]),k=S.get(m);return k===void 0?h:{...h,detail:k}},o=await Promise.all([n("brew",It("brew installed",He("brew").probeArgv,"Homebrew is installed","Homebrew is not installed. Install from: https://brew.sh/")),n("git",It("git installed",He("git").probeArgv,"git is installed","git is not installed. Install with: brew install git")),n("gh",It("gh installed",He("gh").probeArgv,"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/")),It("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),n("doppler",It("doppler installed",He("doppler").probeArgv,"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli")),n("aws",It("aws installed",He("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")),It("package manager installed",["pnpm","--version"],"Installed: pnpm","pnpm is not installed. Install from: https://pnpm.io/installation"),It("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"),WC(),Promise.resolve(VC()),Promise.resolve(GC()),JC(),Promise.resolve(HC(t)),QC(),XC(t),e$(e.fix??!1),r$(),n$()]),s=await q$(e.portlessDeps);if(e.fix){let m=await Y$(),f=s.findIndex(h=>h.name===m.name);f>=0?s[f]=m:s.push(m)}let i=await a$(),a=await Uo(),c={projectDir:ht.env.CLAUDE_PROJECT_DIR||null,cwd:ht.cwd(),gitRoot:a},l=[await p$(),...h$(i,c),Wo(),w$({env:ht.env,stdinIsTTY:ht.stdin.isTTY===!0,flag:j.source==="flag"}),a===null?{name:"Agent allowlist",status:"skip",message:"no git root"}:b$(a)],u=[...o,await S$(a),...s,...await i$(),...l,y$(Sn(),L.version)],p={checks:u.map(m=>({name:m.name,status:m.status,message:m.message,fixable:ql.has(m.name),detail:m.detail})),allPassed:LC(u),cliVersion:L.version};return{content:b(JSON.stringify(p,null,2)),structuredContent:p}},qu=C({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:Ee.array(Ee.object({name:Ee.string().describe("Name of the check"),status:Ee.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:Ee.string().describe("Details about the check result"),fixable:Ee.boolean().describe("Whether `infra-kit doctor --fix` repairs this row"),detail:Ee.object({manager:Ee.string().describe("Which package manager owns this install, read from its resolved path"),version:Ee.string().nullable().describe("The version the tool reported, or null"),present:Ee.boolean().describe("The tool is installed somewhere findable \u2014 on PATH or not"),onPath:Ee.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:Ee.boolean().describe("Whether no check failed (warnings and skips do not count)"),cliVersion:Ee.string().describe("Version of the infra-kit CLI that produced this report")},handler:()=>da()});import{E2E_MODE_ENV as RA}from"@slip-stream-kit/config/internal";import rd from"node:fs";import SA from"node:os";import ss from"node:path";import fa from"node:process";import{z as P}from"zod";var yt=(e,t,r)=>new O({status:"refused",reason:e,...t},2,r);import{describeProxyRoutes as z$,loadDev as X$,readAppAliasName as Z$,readCloudOrigin as Q$,readLocalContext as Pv}from"@slip-stream-kit/config/internal";import Ev from"node:fs";import $r from"node:path";import pa from"node:process";import{z as Yu}from"zod";var eA=async e=>{let t=$r.join(e,"apps"),r=Ev.existsSync(t)?Ev.readdirSync(t).toSorted():[],n=[];for(let o of r){let s=$r.join(t,o,"tests"),a=(await lt(s))?.e2e;a?.target!==void 0&&n.push({app:o,testsDir:s,e2e:{target:a.target}})}return n},tA=(e,t)=>{let[r,n]=$r.relative(e,t).split($r.sep);return r==="apps"&&n?n:void 0},rA=(e,t,r,n)=>{let o=c=>e.find(l=>l.app===c),s=o(t)??(t===void 0?o(tA(n,r)):void 0);if(s)return s;if(t===void 0&&e.length===1)return e[0];let i=e.map(c=>c.app);if(i.length===0)throw new g(void 0,{operation:"find an e2e package",remediation:"declare `e2e: { target }` in `apps/<app>/tests/infra-kit.config.ts` (see the `InfraKitE2e` type)",stderrExcerpt:`no apps/*/tests package under ${n} declares an e2e block`});let a="app";throw new O({status:"argument_required",argument:a,choices:Yu.toJSONSchema(Yu.object({app:Yu.enum(i)})),agentMode:j.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(", ")}`})},nA=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}})),oA=e=>To(e).apps.find(t=>t.env!=="")?.env??null,zu=async(e,t={})=>{let r=t.cwd??pa.cwd(),n=t.projectRoot??await $(),o=(t.env??pa.env)[Lr]||null,s=t.healthProbe??Lc,i=rA(await eA(n),e,r,n),{target:a}=i.e2e,[c,l]=a.split("/"),u=$r.join(n,"apps",c,l),p=(await fr(u)).name,m=(await lt(u))?.deployedUrlEnv??null;if(!p)throw new g(void 0,{operation:`resolve e2e target ${a}`,remediation:`check \`e2e.target\` in ${$r.join(i.testsDir,"infra-kit.config.ts")}`,stderrExcerpt:`${u} has no package.json name`});let f=zf(u),h=Z$(p,u),S=`${h}.localhost`,k=`https://${S}`,A=0;if(l==="ui")A=(t.listRoutes??Zn)().find(R=>R.name===S||R.name===h)?.port??0;else{let R=Pv(u).info.get(p);A=R?.port??0,k=R?.origin??k}let M=A>0&&await s({tag:a,port:A,kind:l})==="ok",v=M?oA(u):null;return{app:i.app,testsDir:i.testsDir,target:a,kind:l,targetDir:u,packageName:p,deployedUrlEnv:m,release:f,env:o,servedEnv:v,localUrl:k,served:M}},xv=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}},Xu=async(e,t={})=>{let r=t.healthProbe??Lc,n=Pv(e.targetDir),o=e.kind==="ui"?await X$(e.targetDir):void 0,s=o?.proxy?z$({proxy:o.proxy,localContext:n,env:e.env??void 0,cloud:Q$(e.deployedUrlEnv??void 0,t.env??pa.env),getRelease:()=>e.release}):[],i=new Map([...n.info].map(([a,c])=>[a,c.port]));return{...xv(e),mode:"local",baseUrl:e.localUrl,routes:await nA(s,i,r)}},Zu=(e,t={})=>{let{env:r,deployedUrlEnv:n,target:o}=e;if(!n)throw yt("no_deployed_url_env",{target:o},{operation:`resolve the deployed app ${e.app}'s cloud e2e run targets`,remediation:`declare \`deployedUrlEnv: '<APP>_URL'\` in ${$r.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??pa.env)[n];if(!r||!s){let i=s?Lr:n;throw yt("env_not_loaded",{missing:i},{operation:`resolve the deployed app ${e.app}'s cloud e2e run targets`,remediation:"load an environment (`infra-kit env-load -c <env>`), or drop --cloud to run against this worktree",stderrExcerpt:`a cloud run of ${o} needs ${n} and ${Lr}, and ${i} is not set`})}return{...xv(e),mode:"cloud",baseUrl:s,routes:[]}};import sA from"node:fs";import iA from"node:path";import{stripVTControlCharacters as aA}from"node:util";import{z as I}from"zod";var Tv=2e3,Cv="--reporter=line,json",$v=e=>({PLAYWRIGHT_JSON_OUTPUT_FILE:e,PLAYWRIGHT_JSON_OUTPUT_NAME:e}),Av=e=>e.some(t=>t==="--reporter"||t.startsWith("--reporter=")),Qu=I.object({message:I.string().optional()}),Ov=I.object({type:I.string()}),cA=I.object({status:I.string(),retry:I.number(),error:Qu.optional(),errors:I.array(Qu).optional(),annotations:I.array(Ov).optional(),attachments:I.array(I.object({name:I.string(),path:I.string().optional()})).optional()}),lA=I.object({projectName:I.string(),status:I.string(),expectedStatus:I.string().optional(),annotations:I.array(Ov).optional(),results:I.array(cA)}),uA=I.object({title:I.string(),file:I.string(),line:I.number().optional(),tests:I.array(lA)}),Dv=I.lazy(()=>I.object({title:I.string(),specs:I.array(uA).optional(),suites:I.array(Dv).optional()})),dA=I.object({config:I.object({rootDir:I.string().optional()}).optional(),suites:I.array(Dv),errors:I.array(Qu).optional(),stats:I.object({expected:I.number(),unexpected:I.number(),flaky:I.number(),skipped:I.number()})}),Iv=e=>{let t=aA(e);return t.length>Tv?`${t.slice(0,Tv)}\u2026`:t},pA=e=>{let t=e.error?.message??e.errors?.[0]?.message;return t===void 0?null:Iv(t)},mA=e=>e.status==="unexpected"||e.status==="flaky",fA=e=>{let t=new Map;for(let r of e)t.set(r.projectName,[...t.get(r.projectName)??[],r]);return t},gA=e=>new Set([...e.annotations??[],...e.results.flatMap(t=>t.annotations??[])].map(t=>t.type)),hA=(e,t)=>{let r=e.filter(mA),n=r.at(-1);if(!n)return null;let o=n.results.findLast(i=>i.status!=="passed"&&i.status!=="skipped"),s=r.length===e.length&&n.status==="unexpected";return{...t,status:s?"unexpected":"flaky",retry:o?.retry??0,runs:e.length,failedRuns:r.length,error:o?pA(o):"Expected to fail, but passed.",tracePath:o?.attachments?.find(i=>i.name==="trace")?.path??null}},yA=e=>{let t=dA.safeParse(e);if(!t.success)return null;let{config:r,suites:n,errors:o,stats:s}=t.data,i=[],a=new Map,c=0,l=(p,m)=>{let f=new Set(m.flatMap(k=>[...gA(k)])),h=m.some(k=>k.expectedStatus==="failed");if(!h&&!f.has("fixme")&&!f.has("skip"))return;let S=a.get(p)??{file:p,fail:0,fixme:0,skip:0};h&&(S.fail+=1),f.has("fixme")?S.fixme+=1:f.has("skip")&&(S.skip+=1),a.set(p,S)},u=(p,m)=>{for(let f of p.specs??[]){let h=r?.rootDir?iA.resolve(r.rootDir,f.file):f.file,S=[...m,f.title].join(" \u203A ");l(h,f.tests);for(let[k,A]of fA(f.tests)){let M=hA(A,{title:S,file:h,line:f.line??null,project:k});M&&(M.runs>1&&M.failedRuns<M.runs&&(c+=1),i.push(M))}}for(let f of p.suites??[])u(f,[...m,f.title])};for(let p of n)u(p,[]);return{summary:{expected:s.expected,unexpected:s.unexpected,flaky:s.flaky,skipped:s.skipped,repeatFlaky:c},failures:i,annotated:[...a.values()],errors:(o??[]).flatMap(p=>p.message===void 0?[]:[Iv(p.message)])}},Nv=e=>{try{return yA(JSON.parse(sA.readFileSync(e,"utf8")))}catch{return null}};import os from"node:fs";import Mv from"node:path";import ma from"node:process";var vA=e=>Mv.join(e,"node_modules",".cache","infra-kit-e2e.lock"),wA=e=>{try{return ma.kill(e,0),!0}catch(t){return t.code==="EPERM"}},_v=e=>{try{return os.writeFileSync(e,String(ma.pid),{flag:"wx"}),!0}catch(t){if(t.code==="EEXIST")return!1;throw t}},ed=e=>{try{let t=Number.parseInt(os.readFileSync(e,"utf8"),10);return Number.isInteger(t)&&t>0?t:null}catch{return null}},jv=e=>{let t=vA(e);if(os.mkdirSync(Mv.dirname(t),{recursive:!0}),!_v(t)){let r=ed(t);if(r!==null&&r!==ma.pid&&wA(r))return{holder:r};if(os.rmSync(t,{force:!0}),!_v(t))return{holder:ed(t)??0}}return{release:()=>{ed(t)===ma.pid&&os.rmSync(t,{force:!0})}}};import{spawn as kA}from"node:child_process";import bA from"node:os";import td from"node:process";var Fv=(e,t,r)=>new Promise((n,o)=>{let s=kA(e,t,r),i=td.stdin.isTTY?["SIGTERM","SIGHUP"]:["SIGINT","SIGTERM","SIGHUP"],a=l=>{s.kill(l)},c=()=>{for(let l of i)td.off(l,a)};for(let l of i)td.on(l,a);s.once("error",l=>{c(),o(l)}),s.once("close",(l,u)=>{c(),n(l??(u?128+bA.constants.signals[u]:1))})});var EA=["playwright.config.ts","playwright.config.mts","playwright.config.js","playwright.config.mjs"],PA=e=>EA.some(t=>{try{return rd.readFileSync(ss.join(e,t),"utf8").includes("infraKitE2e")}catch{return!1}}),nd=e=>`infra-kit dev ${e.target.split("/")[0]} --no-watch --reuse`,xA=(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(`
374
- `)},TA=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 yt("dead_local_routes",{routes:r},{operation:`run ${e.app} e2e against the local dev server`,remediation:"check the backend rows in `infra-kit dev-status`, fix or restart it, then re-run",stderrExcerpt:`routes held local but their backend is not responding: ${r.join(", ")}`})},CA=async(e,t)=>{if(e.env===null||!qf(e.env))return;let r=await(t.protectedEnvAccess??it)();if(r.allowed)return;let n=`run ${e.app} e2e against "${e.env}"`;throw r.reason==="agent-blocked"?yt("protected_env",{env:e.env,humanMayRun:!0},{operation:n,remediation:'a human runs it from their own terminal \u2014 this project sets `protectedEnvs: "cli-only"`',stderrExcerpt:`"${e.env}" is withheld from agents in this project`}):yt("protected_env",{env:e.env,humanMayRun:!1},{operation:n,remediation:"load a non-protected env (`infra-kit env-load -c dev`), or set `protectedEnvs` in infra-kit.json",stderrExcerpt:`"${e.env}" is a protected environment`})},$A=e=>{if(!(e.servedEnv===null||e.servedEnv===e.env))throw yt("served_env_mismatch",{servedEnv:e.servedEnv,env:e.env},{operation:`run ${e.app} e2e against the local dev server`,remediation:`load the same env (\`infra-kit env-load -c ${e.servedEnv}\`), or restart \`infra-kit dev\` under "${e.env??"none"}"`,stderrExcerpt:`the dev server serving ${e.target} runs with env "${e.servedEnv}", this shell with "${e.env??"none"}"`})},AA=async(e,t)=>{if(e.served){$A(e);let p=await Xu(e,t);return TA(p),p}if(!PA(e.testsDir))throw yt("no_dev_server",{devCommand:nd(e)},{operation:`run ${e.app} e2e locally`,remediation:`start it (\`${nd(e)}\`), or wire \`infraKitE2e()\` from @slip-stream-kit/config/playwright into its playwright.config.ts`,stderrExcerpt:`nothing serves ${e.target} and ${e.testsDir}'s Playwright config does not start it`});let{app:r,testsDir:n,target:o,packageName:s,deployedUrlEnv:i,release:a,env:c,servedEnv:l,localUrl:u}=e;return{app:r,testsDir:n,target:o,packageName:s,deployedUrlEnv:i,release:a,env:c,servedEnv:l,localUrl:u,mode:"local",baseUrl:u,routes:[]}},OA=(e,t,r)=>Fv("pnpm",["exec","playwright","test",...t],{cwd:e.testsDir,env:{...fa.env,...r,[RA]:e.mode},stdio:["inherit",lr.enabled||X()?2:"inherit","inherit"]}),DA=(e,t)=>{let r=t.findIndex(s=>s==="--output"||s.startsWith("--output="));if(r!==-1){let s=t[r]==="--output"?t[r+1]??"":t[r].slice(9);return{args:t,outputDir:ss.resolve(e.testsDir,s)}}let n=new Date().toISOString().replace(/[:.]/g,"-"),o=ss.join(e.testsDir,"test-results",`ik-e2e-${n}-${fa.pid}`);return{args:[...t,`--output=${o}`],outputDir:o}},IA=e=>{if(e.mode==="cloud")return()=>{};let t=jv(e.testsDir);if("holder"in t)throw yt("run_in_progress",{pid:t.holder},{operation:`run ${e.app} e2e locally`,remediation:`wait for it to finish (or stop process ${t.holder}), then re-run`,stderrExcerpt:`another local e2e run of ${e.app} (pid ${t.holder}) is using its dev server`});return t.release},ga=async(e,t={})=>{let r=await zu(e.app,t),n=e.cloud?Zu(r,t):await AA(r,t);d.info(xA(n,r.served)),n.mode==="cloud"&&await CA(n,t);let o={...n,served:r.served,devCommand:n.mode==="local"&&!r.served?nd(r):null,playwrightArgs:e.playwrightArgs??[]};if(e.dryRun)return sd({...o,ran:!1,exitCode:null,...od});n.mode==="cloud"&&await J(e.yes,`Run ${n.app} e2e against ${n.baseUrl} ("${n.env}", shared)?`,{plan:o});let s=IA(n);try{return await NA(o,t.runPlaywright??OA)}finally{s()}},NA=async(e,t)=>{if(!X()||Av(e.playwrightArgs)){let i=await t(e,e.playwrightArgs,{});return i!==0&&(fa.exitCode=i),sd({...e,ran:!0,exitCode:i,...od,report:X()?"caller-reporter":"off"})}let{args:r,outputDir:n}=DA(e,e.playwrightArgs),o=rd.mkdtempSync(ss.join(SA.tmpdir(),"ik-e2e-report-")),s=ss.join(o,"report.json");try{let i=await t(e,[Cv,...r],$v(s));i!==0&&(fa.exitCode=i);let a=Nv(s);return sd({...e,ran:!0,exitCode:i,...a?{report:"collected",...a}:{...od,report:"unavailable"},outputDir:n})}finally{rd.rmSync(o,{recursive:!0,force:!0})}},od={report:"off",outputDir:null,summary:null,failures:[],annotated:[],errors:[]},sd=e=>({content:b(JSON.stringify(e,null,2)),structuredContent:e}),_A={app:P.string(),testsDir:P.string(),target:P.string().describe("The package under test, `<app>/ui` or `<app>/api`."),packageName:P.string(),mode:P.enum(["local","cloud"]).describe("local (default): this worktree\u2019s dev server. cloud (--cloud): the deployed app at env."),baseUrl:P.string().describe("The URL the run was pointed at: the local alias, or the deployed URL."),deployedUrlEnv:P.string().nullable().describe("The target\u2019s variable holding its deployed URL; a cloud run reads it. Null when it declares none."),release:P.string().describe("This worktree\u2019s release slug \u2014 the first label of every local alias."),env:P.string().nullable().describe("INFRA_KIT_ENV of this process; the env a cloud run targets."),servedEnv:P.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:P.string().describe("This worktree\u2019s address for the target, whether or not anything serves it."),served:P.boolean().describe("Whether this worktree\u2019s dev server already served the target when the run began."),devCommand:P.string().nullable().describe("Local runs with nothing served: the dev command the Playwright config starts, and stops after."),routes:P.array(P.object({path:P.string(),packageName:P.string(),source:P.enum(["local","cloud"]),target:P.string().nullable(),live:P.boolean().nullable()})).describe("Served local UI runs only: the dev proxy\u2019s route-by-route local/cloud split, local backends probed."),playwrightArgs:P.array(P.string()),ran:P.boolean().describe("False for --dry-run."),exitCode:P.number().nullable().describe("Playwright\u2019s exit code; null when it did not run."),report:P.enum(["off","caller-reporter","unavailable","collected"]).describe("Per-test results: collected from Playwright\u2019s JSON reporter under --json/agent mode; caller-reporter when playwrightArgs carried its own --reporter; unavailable when the run wrote no readable report; off otherwise."),outputDir:P.string().nullable().describe("Where this run\u2019s traces and attachments live \u2014 its own directory, so a later run cannot delete them. Null unless report is collected or unavailable."),summary:P.object({expected:P.number(),unexpected:P.number(),flaky:P.number(),skipped:P.number(),repeatFlaky:P.number()}).nullable().describe("Playwright\u2019s counts by outcome, one per run (each --repeat-each repeat counts), plus repeatFlaky: tests that passed in some repeats and failed in others. Null unless report is collected."),failures:P.array(P.object({title:P.string().describe("Describe path and test title, joined with \u203A."),file:P.string(),line:P.number().nullable(),project:P.string(),status:P.enum(["unexpected","flaky"]).describe("flaky: failed, then passed on a retry or in another --repeat-each repeat."),retry:P.number().describe("The retry index of the failed attempt reported here."),runs:P.number().describe("How many times the test ran in this project \u2014 its --repeat-each repeats."),failedRuns:P.number().describe("How many of those runs failed."),error:P.string().nullable().describe("The failure message, ANSI stripped, truncated to 2000 characters."),tracePath:P.string().nullable().describe("The failed attempt\u2019s trace.zip; open with `playwright show-trace`.")})).describe("One entry per test and project that failed, needed a retry, or failed in some repeat; empty unless report is collected."),annotated:P.array(P.object({file:P.string(),fail:P.number().describe("test.fail \u2014 green only while the bug it registers exists."),fixme:P.number().describe("test.fixme \u2014 skipped as unfinished."),skip:P.number().describe("test.skip, declared or called at runtime, conditional ones included.")})).describe("Per spec file, the tests that passed or skipped while asserting little, as Playwright ran them; empty unless report is collected."),errors:P.array(P.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.")},id=C({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:P.string().optional().describe("App folder with an apps/<app>/tests e2e package; inferred from cwd when omitted."),dryRun:P.boolean().optional(),yes:P.boolean().optional(),cloud:P.boolean().optional().describe("Run against the deployed app at INFRA_KIT_ENV instead of this worktree."),playwrightArgs:P.array(P.string()).optional().describe("Passed to `playwright test` verbatim \u2014 a spec path, `--grep <title>`, `--project=chromium`.")},outputSchema:_A,handler:e=>ga(e)});import ha from"node:fs";import ad from"node:path";import{z as is}from"zod";var MA=e=>[...e.map(t=>`unset ${t}`),`unset ${Lr}`,`unset ${Hs}`,`unset ${qs}`,`unset ${$m}`,`unset ${Ys}`],ya=async()=>{let e=Br(),t=ad.join(e,Fr);if(!ha.existsSync(t))throw new Error("No loaded environment found. Run `env-load` first.");let r=zs(t),n=MA(r),o=ad.resolve(e,Js);ha.mkdirSync(e,{recursive:!0,mode:448}),Mt(o,`${n.join(`
374
+ ${i}`:"")},Jy=()=>{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(`
375
+ `)},Ky=()=>`${xr}
376
+ ${Jy()}
377
+ ${Zt}`,Mu=()=>["# 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(`
378
+ `),ju=()=>`${xr}
379
+ ${Mu()}
380
+ ${Zt}`;import mC from"node:fs/promises";var Xo=async(e,t)=>{if(!t)return{hasOverrides:!1,overrideKeys:[],unreadable:!1};try{let r=await mC.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}}},Zo=e=>e.unreadable?"(unreadable \u2014 invalid JSON)":e.overrideKeys.length===0?"(empty \u2014 no overrides)":`(${e.overrideKeys.length} override(s): ${e.overrideKeys.join(", ")})`;import gC from"node:fs";import hC from"node:os";import Hy from"node:path";import yC from"node:process";import{$ as fC}from"zx";var _n=()=>fC({quiet:!0});var vC=()=>[Hy.join(hC.homedir(),".local","bin"),"/opt/homebrew/bin","/usr/local/bin"],wC=async e=>{try{return(await _n()`command -v ${e}`).stdout.trim()||null}catch{return null}},Qo=()=>({runCommand:async e=>{let t=await _n()`${e}`;return{stdout:`${t.stdout}
381
+ ${t.stderr}`}},resolveBinPath:async e=>{let t=await wC(e);return t!==null?t:vC().map(r=>Hy.join(r,e)).find(r=>gC.existsSync(r))??null},realpath:Ce,platform:yC.platform});var Qt=(...e)=>({steps:e,needsSudo:!1,fetchesNetworkScript:!1}),Mn=e=>/\d{1,10}\.\d{1,10}\.\d{1,10}/.exec(e)?.[0]??null,jn=["darwin","linux"],da=e=>t=>Tc(t,e)?"homebrew":"unknown",pa=(e,t)=>r=>r===null?null:t(e(r),r),Lu=e=>pa(da(e.kegName),t=>t==="homebrew"?Qt(["brew","upgrade",e.brewFormula]):null),qy=e=>ti(e,"Homebrew")||ti(e,"homebrew")?"homebrew":"unknown",kC={id:"brew",binName:"brew",probeArgv:["brew","--version"],versionFrom:Mn,platforms:jn,prerequisites:[],bootstrapInstall:{steps:[["/bin/bash","-c","$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"]],needsSudo:!0,fetchesNetworkScript:!0},identify:qy,updateFor:pa(qy,e=>e==="homebrew"?Qt(["brew","update"]):null)},Fu={brewFormula:"awscli",brewInstallSpec:"awscli",kegName:"awscli"},Xy="https://awscli.amazonaws.com/v2/install.sh",Zy={steps:[["/bin/bash","-c",`curl -fsSL ${Xy} | bash`]],needsSudo:!1,fetchesNetworkScript:!0},bC="/usr/local/aws-cli",RC=e=>ro(bC,e,Ce)?{steps:[["sudo","/bin/bash","-c",`curl -fsSL ${Xy} | bash -s -- --system`]],needsSudo:!0,fetchesNetworkScript:!0}:Zy,Yy=e=>Tc(e,Fu.kegName)?"homebrew":ti(e,"aws-cli")?"script":"unknown",SC={id:"aws",binName:"aws",...Fu,probeArgv:["aws","--version"],versionFrom:Mn,platforms:jn,prerequisites:[],bootstrapInstall:Zy,identify:Yy,updateFor:pa(Yy,(e,t)=>e==="homebrew"?Qt(["brew","upgrade",Fu.brewFormula]):e==="script"?RC(t):null)},ca={brewFormula:"git",brewInstallSpec:"git",kegName:"git"},EC={id:"git",binName:"git",...ca,probeArgv:["git","--version"],versionFrom:Mn,platforms:jn,prerequisites:["brew"],bootstrapInstall:Qt(["brew","install",ca.brewInstallSpec]),identify:da(ca.kegName),updateFor:Lu(ca)},la={brewFormula:"gh",brewInstallSpec:"gh",kegName:"gh"},PC={id:"gh",binName:"gh",...la,probeArgv:["gh","--version"],versionFrom:Mn,platforms:jn,prerequisites:["brew"],bootstrapInstall:Qt(["brew","install",la.brewInstallSpec]),identify:da(la.kegName),updateFor:Lu(la)},ua={brewFormula:"doppler",brewInstallSpec:"dopplerhq/cli/doppler",kegName:"doppler"},xC={id:"doppler",binName:"doppler",...ua,probeArgv:["doppler","--version"],versionFrom:Mn,platforms:jn,prerequisites:["brew"],bootstrapInstall:Qt(["brew","install","gnupg"],["brew","install",ua.brewInstallSpec]),identify:da(ua.kegName),updateFor:Lu(ua)},es="portless",zy=e=>Bm(e,es)===null?"unknown":"npm",TC={id:"portless",binName:es,npmPackage:es,probeArgv:["portless","--version"],versionFrom:Mn,platforms:[...jn,"win32"],prerequisites:[],bootstrapInstall:Qt(["npm","install","-g",es]),identify:zy,updateFor:pa(zy,e=>e==="npm"?Qt(["npm","install","-g",`${es}@latest`]):null)},Bu={brew:kC,git:EC,aws:SC,gh:PC,doppler:xC,portless:TC},Tr=Object.keys(Bu),Ye=e=>Bu[e],Uu=(e,t)=>e.platforms.includes(t),Wu=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 Ye(o).prerequisites)n(i,[...s,o]);t.push(o)}};for(let o of e)n(o,[]);return t};var Qy=e=>({id:e,present:!1,onPath:!1,binRealPath:null,version:null,manager:"unknown"}),ev=async(e,t)=>{try{return await e(t)}catch{return null}},CC=async(e,t)=>{try{let r=await e.resolveBinPath(t);return r==null?null:e.realpath(r)}catch{return null}},tv=async(e,t)=>{if(!Uu(e,t.platform))return Qy(e.id);let r=await ev(t.runCommand,e.probeArgv),n=await CC(t,e.binName);if(r==null&&n==null)return Qy(e.id);let o=r??(n==null?null:await ev(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)}},ts=async(e,t)=>Promise.all(e.map(r=>tv(Ye(r),t)));import{$ as NC}from"zx";import{z as rv}from"zod";var nv=/^\d{4}-\d{2}-\d{2}$/,rs=e=>{if(!nv.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},ov=e=>`Release date "${e}" is not a calendar date in yyyy-mm-dd form.`,Fn=class extends Error{constructor(t){super(ov(t)),this.name="InvalidReleaseDateError"}},Cr=e=>{let t=e.trim();if(!rs(t))throw new Fn(t);return t},ns=e=>{let t=e.trim();return t===""||rs(t)?!0:ov(t)},Gu=rv.string().refine(rs,{message:"Expected a calendar date in yyyy-mm-dd form."}),Vu=rv.string().refine(e=>e===""||rs(e),{message:'Expected a calendar date in yyyy-mm-dd form, or "" to clear.'});var er=e=>e.slice(1).split(".").map(Number),Ln=e=>[...e].sort((t,r)=>{let[n,o,s]=er(t),[i,a,c]=er(r);return n!==i?(n??0)-(i??0):o!==a?(o??0)-(a??0):(s??0)-(c??0)});var iv="next",$C=/^v?(\d+)\.(\d+)\.(\d+)$/,AC=e=>e.replace(/^.*release\//,""),Ju=e=>{let t=AC(e.trim()),r=$C.exec(t);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null},sv=e=>`${e[0]}.${e[1]}.${e[2]}`,Ku=e=>{let t=[...e.remoteBranches??[],...e.jiraVersions??[]],r=[],n=new Set;for(let o of t){let s=Ju(o);if(!s)continue;let i=sv(s);n.has(i)||(n.add(i),r.push(s))}return Ln(r.map(o=>sv(o))).map(o=>er(`v${o}`))},$r=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},Hu=(e,t)=>{if(e.length===0)throw new $r;let r=e[e.length-1];if(t==="hotfix"){let[s,i]=r,a=e.reduce((c,l)=>l[0]===s&&l[1]===i?Math.max(c,l[2]):c,0);return`${s}.${i}.${a+1}`}let[n,o]=r;return`${n}.${o+1}.0`},Bn=(e,t)=>{try{return Hu(e,t)}catch(r){if(r instanceof $r)return null;throw r}},qu=e=>e.trim().toLowerCase()===iv,fa=e=>qu(e)||Ju(e)!==null?{version:e}:{name:e},OC=e=>e==="regular"||e==="hotfix",av=e=>"name"in e,DC=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)}},Yu=e=>{let t=e.trim();if(t==="")throw new Error("Release spec is empty");let r=t.indexOf(":"),{token:n,releaseDate:o}=DC(r===-1?t:t.slice(0,r)),s="regular",i="";if(r!==-1){let a=t.slice(r+1),c=a.indexOf(":"),l=c===-1?a.trim():a.slice(0,c).trim();i=c===-1?"":a.slice(c+1).trim();let u=l.toLowerCase();if(!OC(u))throw new Error(`Invalid release type "${l}". Expected "regular" or "hotfix".`);s=u}return ma({...fa(n),type:s},{description:i,releaseDate:o})},zu=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},ma=(e,t)=>{let{description:r,releaseDate:n}=t;return{...e,...r!==void 0&&r!==""?{description:r}:{},...n===void 0?{}:{releaseDate:n}}},IC=e=>{let t=e.name.trim();return ii(t),ma({id:{kind:"name",name:t,raw:t},type:e.type},e)},Xu=(e,t)=>{let r=[...t];return e.map(n=>{if(av(n))return IC(n);let o=n.version.trim();if(o==="")throw new Error("Release entry has an empty version");if(qu(o)){let a=Hu(r,n.type);return r.push(er(`v${a}`)),ma({id:Re(a),type:n.type},n)}let s=Ju(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),ma({id:Re(i),type:n.type},n)})},Zu=e=>e.some(t=>!av(t)&&qu(t.version));var _C=e=>e.split(`
382
+ `).map(t=>{let r=t.indexOf(" ");return r===-1?null:ee(t.slice(r+1))}).filter(t=>t!==null&&t.kind==="version").map(t=>t.raw),MC=async()=>{let e=await NC({quiet:!0})`git ls-remote --heads origin 'release/v*'`;return _C(e.stdout)},jC=async()=>{let e=await Dt();return e?(await hn(e)).map(r=>r.name):[]},os=async()=>{let[e,t]=await Promise.allSettled([MC(),jC()]);return e.status==="rejected"&&d.warn({err:e.reason},"Failed to list remote release branches; continuing without them"),t.status==="rejected"&&d.warn({err:t.reason},"Failed to fetch Jira versions; continuing without them"),Ku({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:t.status==="fulfilled"?t.value:[]})};import FC from"node:fs";import LC from"node:path";var Qu=[".claude/settings.json",".claude/settings.local.json"],BC=["infra-kit","ik","pnpm exec infra-kit","pnpm exec ik","pnpm infra-kit"],UC=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),WC=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},GC=(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(UC).join(".*")}$`,"s").test(t)||n===t||n.startsWith(`${t} `)},VC=e=>{let t=e.groupPath.join(" ");return t===e.cliName?[t]:[t,e.cliName]},JC=()=>Ar.filter(e=>e.mutating),KC=e=>{let t=WC(e);return t===null?[]:JC().filter(r=>BC.some(n=>VC(r).some(o=>GC(t,`${n} ${o}`)))).map(r=>r.groupPath.join(" "))},HC=(e,t)=>{let r;try{r=FC.readFileSync(LC.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}},cv=e=>{let t={present:[],unreadable:[],hits:[]};for(let r of Qu){let n=HC(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=KC(o);s.length>0&&t.hits.push({file:r,pattern:o,commands:s})}}}return t};var qC=e=>e.every(t=>t.status!=="fail"),YC=["brew","git","gh","doppler","aws"],zC=async e=>{let t=await ts(YC,e);return new Map(t.map(r=>[r.id,{manager:r.manager,version:r.version,present:r.present,onPath:r.onPath}]))},_t=async(e,t,r,n)=>{try{return await _n()`${t}`,{name:e,status:"pass",message:r}}catch{return{name:e,status:"fail",message:n}}},XC=async()=>{let e="orca installed",t=await Vt();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)"}},Rv=(e,t,r,n)=>{let o=ke.join(bv.homedir(),t),s="Run: infra-kit setup --skip-tools";if(!ce.existsSync(o))return{name:e,status:"fail",message:`~/${t} not found. ${s}`};let i=ce.readFileSync(o,"utf-8"),a=i.indexOf(xr),c=i.indexOf(Zt);return a===-1||c===-1||c<a?{name:e,status:"fail",message:`infra-kit ${r} block missing from ~/${t}. ${s}`}:i.slice(a,c+Zt.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`}},ZC=()=>Rv("zshrc init block",".zshrc","shell",Ky()),QC=()=>Rv("zshenv session block",".zshenv","session-env",ju()),e$=async()=>{let e="pnpm enableGlobalVirtualStore";try{let t=await A(),r=ke.join(t,"pnpm-workspace.yaml");if(!ce.existsSync(r))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${r}`};let n=ce.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}`}}},t$=async()=>{try{return Ut(),{config:await J(),error:null}}catch(e){return{config:null,error:e}}},r$=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)"}},n$=384,ed=448,o$=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(", "),s$=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}}})),i$=async(e,t={})=>{let r="env tokens configured",n=t.readStore??tt,o=t.resolveToken??Jf;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 s$(await hi(),o);return{name:r,status:"pass",message:o$(s)}},a$=()=>vt.env[fr]||void 0,c$=async(e={})=>{let t="tokens.json present",r=e.readStore??tt,n=e.storePath??Gt;if((e.readEnvToken??a$)())return{name:t,status:"skip",message:`${fr} is set; that channel takes precedence over the store`};let s;try{s=w(await n())}catch{return{name:t,status:"skip",message:"the token store path could not be resolved"}}let i;try{i=await r()}catch{return{name:t,status:"skip",message:`The store at ${s} is unreadable (see env tokens configured)`}}let a=i===null?[]:Object.keys(i.envs);if(a.length===0){let c=i===null?`No token store at ${s}`:`${s} holds no tokens`;return{name:t,status:"fail",message:`${c} \u2014 every project needs one to authenticate. Fix: run \`infra-kit env-token-set <env>\`. CI / agents: set ${fr} instead.`}}return{name:t,status:"pass",message:`${s} holds ${a.length} token(s): ${a.join(", ")}`}},ss=(e,t)=>{let r=t(e);return r===null?null:r.mode&511},l$=async(e,t={})=>{let r="tokens.json perms",n=t.storePath??Gt,o=t.statPath??u$,s=t.chmodPath??ce.chmodSync,i;try{i=await n()}catch{return{name:r,status:"skip",message:"the token store path could not be resolved"}}if(ss(i,o)===null)return{name:r,status:"skip",message:`No store to protect at ${w(i)} (see tokens.json present)`};let a=ke.dirname(i),c=ke.dirname(a),l=ke.dirname(c),p=[{target:l,expected:ed,actual:ss(l,o)},{target:c,expected:ed,actual:ss(c,o)},{target:a,expected:ed,actual:ss(a,o)},{target:i,expected:n$,actual:ss(i,o)}].filter(f=>f.actual!==null&&f.actual!==f.expected);if(p.length===0)return{name:r,status:"pass",message:`${w(i)} is 0600 (0700 dirs)`};let m=p.map(f=>`${w(f.target)} is ${lv(f.actual)}, expected ${lv(f.expected)}`).join("; ");if(!e)return{name:r,status:"fail",message:`${m}. Fix: run \`infra-kit setup --skip-tools\` or \`infra-kit doctor --fix\`.`};for(let f of p)s(f.target,f.expected);return{name:r,status:"pass",message:`Tightened ${p.length} path(s): ${m}`}},lv=e=>`0${e.toString(8).padStart(3,"0")}`,u$=e=>{try{return ce.statSync(e)}catch{return null}},d$=async()=>{let e="user override path";try{let t=await Y(),r=ce.existsSync(t.userProject),n=await Xo(t.userProject,r),o=r?Zo(n):"(not created \u2014 seed failed?)";return{name:e,status:"pass",message:`${w(t.userProject)} ${o} \u2014 project: ${t.projectName}`}}catch(t){return{name:e,status:"fail",message:t.message}}},p$=async()=>{let e="legacy user-global config",t;try{t=await Y()}catch{return{name:e,status:"skip",message:"infra-kit config paths could not be resolved"}}let r=ke.join(ke.dirname(t.userGlobal),"config.json");return ce.existsSync(r)?ce.existsSync(t.userGlobal)?{name:e,status:"fail",message:`Stale legacy config.json found at ${w(r)} \u2014 ${w(t.userGlobal)} is active; remove the old file.`}:{name:e,status:"fail",message:`Legacy user-global config.json found at ${w(r)} \u2014 run \`infra-kit setup --skip-tools\` to migrate it (your overrides are not being applied).`}:{name:e,status:"pass",message:"No legacy user-global config.json"}},uv=/^\d+\.\d+\.\d+$/,dv=(e,t)=>e===t||!uv.test(e)||!uv.test(t)?!1:Ln([`v${e}`,`v${t}`])[0]===`v${e}`,m$=async e=>{let t;try{t=await Ee(e)}catch{return[]}return t.flatMap(r=>{let n=$t(pt(ke.join(r,"CLAUDE.md")));return n.state==="ok"&&n.version!==void 0?[n.version]:[]})},pv=e=>Ln(e.map(t=>`v${t}`)).map(t=>t.slice(1)),f$=async(e,t,r)=>{let n="Guidance version",o=yr(t,vr),s=await m$(e),a=(o===null?s:[o,...s]).filter(p=>Pt(p,r));if(a.length>0){let p=pv(a).at(-1);return{name:n,status:"warn",message:`${a.length} guidance ${a.length===1?"block was":"blocks were"} generated by a newer infra-kit (newest ${p}, current ${r}) \u2014 CLI behind the block, run: pnpm add -g infra-kit@${p}`}}let c=o!==null&&dv(o,r),l=s.filter(p=>dv(p,r));if(!c&&l.length===0)return{name:n,status:"pass",message:`guidance blocks match infra-kit ${r}`};let u=[...c?[`the root block is from infra-kit ${o} \u2014 run: infra-kit audit --fix --root`]:[],...l.length>0?[`${l.length} package guidance ${l.length===1?"block was":"blocks were"} generated by an older infra-kit (oldest ${pv(l)[0]}, current ${r}) \u2014 run: infra-kit audit --fix --all`]:[]];return{name:n,status:"warn",message:u.join("; ")}},g$=async()=>{let e=[{name:"CLAUDE.md block",status:"skip",message:"no infra-kit config in this repo"},{name:"Guidance version",status:"skip",message:"no infra-kit config in this repo"}],t;try{t=(await Y()).main}catch{return e}if(!ce.existsSync(t))return e;let r=ke.dirname(t),n=ke.join(r,"CLAUDE.md"),o=ce.existsSync(n)?ce.readFileSync(n,"utf-8"):"",s=Je(o,Pe,_e);return[{name:"CLAUDE.md block",status:s?"pass":"fail",message:s?"CLAUDE.md block present":"infra-kit block missing from CLAUDE.md. Run: infra-kit setup --skip-tools"},await f$(r,o,U.version)]},h$=async()=>{try{let e=(await Y()).main;return ce.existsSync(e)?ke.dirname(e):null}catch{return null}},y$=e=>{let t=Df();return t===null||!Pt(t,e)?"":` \u2014 plugin ${t} is fetched but not applied. Run: ${an}`},v$=e=>{let t=e.kind==="installed"?pi(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 ${z} version ${t}${y$(t)}`}},mv=3,fv=(e,t)=>Ce(e)===Ce(t),w$=e=>{if(e===void 0||e.gitRoot===null)return"";let t=w(e.gitRoot);if(e.projectDir!==null){if(fv(e.projectDir,e.gitRoot))return"";let r=ro(e.gitRoot,Ce(e.projectDir),Ce)?"below the repo root":"not this checkout";return` \u2014 this session was launched from ${w(e.projectDir)}, ${r}: the plugin and this repo's .claude/settings.json hooks load only from ${t} (measured); restart Claude Code there`}return fv(e.cwd,e.gitRoot)?"":` \u2014 if Claude Code was launched from ${w(e.cwd)} rather than ${t}, it loaded neither the plugin nor this repo's hooks; launch it at ${t}`},k$=(e,t)=>{let r="plugin installed",n=w$(t);if(e.kind==="installed"){let{scope:c,projectPath:l}=e.installation,u=l===null?"":`, ${w(l)}`;return{name:r,status:"pass",message:`Plugin ${z} installed (${c??"unknown"} scope${u})${n}`}}if(e.kind==="absent")return{name:r,status:"fail",message:`Plugin ${z} is not installed. Run: ${At}${n}`};let o=e.installations.map(c=>c.projectPath===null?"(unnamed project)":w(c.projectPath)),s=o.length-mv,i=s>0?` and ${s} more`:"",a=`${o.slice(0,mv).join(", ")}${i}`;return{name:r,status:"fail",message:`Plugin ${z} is installed for ${a} only, not this project. Run: ${At}${n}`}},b$=()=>_t("claude CLI",["claude","--version"],"Installed: claude","claude CLI not found on PATH \u2014 `infra-kit setup` cannot install the plugin; install Claude Code first");var R$=(e,...t)=>{try{return JSON.parse(ce.readFileSync(ke.join(e,...t),"utf-8"))}catch{return null}},S$=e=>{if(e.kind!=="installed")return{kind:"not-installed"};let t=pi(e.installation),{installPath:r}=e.installation;if(r===null)return{kind:"skills-only",version:t};let n=R$(r,He),o=n!==null&&typeof n=="object"?n[mt]:void 0;return o==null||typeof o!="object"?{kind:"skills-only",version:t}:{kind:"stale-server",version:t,keys:Object.keys(o)}},gv=e=>`Plugin ${z} ${e===null?"(version unreadable)":e}`,E$=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: ${At}`};if(e.kind==="stale-server"){let r=e.keys.length===0?"":` (under "${e.keys.join('", "')}")`;return{name:t,status:"pass",message:`${gv(e.version)} still carries an MCP server in its ${He}${r} \u2014 a copy from before the plugin went skills-only. Update it: infra-kit setup (or ${an}), then restart Claude Code`}}return{name:t,status:"pass",message:`${gv(e.version)} is skills-only \u2014 no ${He}, as shipped; the /infra-kit:* skills drive the infra-kit CLI`}},P$=(e,t)=>{let r=pr(e===null?{}:{projectPath:e}),n=co();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}`},k$(r,t),v$(r),E$(S$(r)),{name:"CLI version",status:"pass",message:`infra-kit CLI ${U.version}`}]},x$=(e,t)=>{let r="background setup";if(e===null)return{name:r,status:"skip",message:"not run yet \u2014 it runs after the next background update check"};if(e.version!==t)return{name:r,status:"skip",message:`last ran for ${e.version}; runs for ${t} after the next background update check`};if(e.finishedMs===null)return{name:r,status:"skip",message:`a pass for ${t} is running, or was interrupted and will be retried`};let n=e.runs.filter(o=>o.status!=="ok");return n.length===0?{name:r,status:"pass",message:`ran for ${t} on the machine and ${e.runs.length-1} project(s)`}:{name:r,status:"warn",message:`${n.length} run(s) left work for you (${n.map(o=>`${o.root??"machine"}: ${o.status}`).join(", ")}) \u2014 see ${w(Tn())}, or run: infra-kit setup`}},T$=({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(", ")},C$=e=>{let t="Agent mode",r=si(e),n=T$(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})`}},hv=4,$$=e=>{let t=e.slice(0,hv).join(", "),r=e.length-hv;return r>0?`${t} +${r} more`:t},A$=e=>{let t="Agent allowlist",{present:r,unreadable:n,hits:o}=cv(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"} (${$$(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 ${Qu.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`}},O$=(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`},D$=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 ty(e)}catch(i){return{name:r,status:"skip",message:`could not read the merge-dev state: ${i.message}`}}if(n.length===0)return{name:r,status:"pass",message:"no merge-dev hand-off in progress"};let o=n.map(i=>{let a=i.worktreeExists?w(i.worktreePath):"worktree missing";return`${i.branch} (${O$(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`}},Sv=e=>Cc(["trust"],{bin:e}),I$=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),yv="ERR_TLS_CERT_ALTNAME_INVALID",Ev=()=>`portless serving TLS on :${Bt}`,N$=async(e,t,r)=>{let n=Ev();return await e(Bt,!0)?{name:n,status:"pass",message:`portless is serving HTTPS on :${Bt}`}:{name:n,status:"fail",message:`No portless daemon is serving HTTPS on :${Bt}. Install it once (needs root): \`${Lt(t,r)}\`.`}},_$=async(e,t,r,n,o)=>{let s="portless CA chain valid",i=["localhost",...t.slice(0,1).map(u=>u.name)],c=(await Promise.all(i.map(async u=>({servername:u,result:await e(Bt,u)})))).filter(u=>!u.result.ok);if(c.length===0)return{name:s,status:"pass",message:`Served certificate chains to ${w(r)} (${i.join(", ")})`};let l=c.map(u=>u.result.ok?"":u.result.code);return l.includes(yv)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${yv} for servername(s) ${c.map(u=>u.servername).join(", ")} \u2014 doctor's probe is wrong, your trust store is not implicated. Please report this.`}:l.some(u=>I$.has(u))?{name:s,status:"fail",message:`The daemon is serving a certificate that does not chain to ${w(r)}. Its CA was regenerated \u2014 run \`${Sv(n)}\`, or reinstall: \`${Lt(n,o)}\`.`}:{name:s,status:"fail",message:`TLS handshake failed (${l.join(", ")})`}},M$=(e,t,r)=>{let n="portless CA trusted";return e?{name:n,status:"pass",message:`${w(t)} matches the recorded ca.trusted fingerprint`}:{name:n,status:"fail",message:`The portless CA is not trusted (or was regenerated). Run: \`${Sv(r)}\` (no sudo needed).`}},j$=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 \`${Cc(["alias","--remove","<name>"],{bin:r})}\`.`}},tr="portless service target",as=e=>({name:tr,status:"warn",message:e}),Pv=e=>e==="darwin"?qm:e==="linux"?Ym:null,F$=e=>e==="darwin"?`sudo launchctl kickstart -k system/${Hm}`:`sudo systemctl restart ${zm}`,L$="/bin/ps",B$=e=>{try{let t=kv(L$,["-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}},vv=e=>{try{return ce.readFileSync(e,"utf-8")}catch{return null}},U$=e=>{try{return ce.statSync(e).mtime}catch{return null}},W$=2e3,G$=e=>{try{let t=kv(e,["-p","process.version"],{encoding:"utf-8",timeout:W$}),r=t.stdout?.trim()??"";return{version:r===""?null:r,status:t.status,signal:t.signal}}catch{return{version:null,status:null,signal:null}}},V$=(e,t)=>({platform:e.platform??vt.platform,readServiceFile:e.readServiceFile??vv,readFile:e.readFile??vv,exists:e.exists??ce.existsSync,realpath:e.realpath??Ce,mtime:e.mtime??U$,execPath:e.execPath??vt.execPath,home:e.home??bv.homedir(),cwd:e.cwd??vt.cwd(),repoRoot:e.repoRoot??Ko,stateDir:(e.stateDir??Zm)(),processStartTime:e.processStartTime??B$,version:e.version??vt.version,arch:e.arch??vt.arch,nodeVersionOf:e.nodeVersionOf??G$,isGlobal:e.isGlobal??oi().node.isGlobal,nodeFs:e.nodeFs??ce,stableNode:null,stableNodeSidecar:null,bin:t}),cs="portless node",Or="~/.infra-kit/node",is=e=>({row:{name:cs,status:"fail",message:e},stableNode:null,sidecar:null}),wv=(e,t)=>{try{return e(t,{throwIfNoEntry:!1})}catch{return}},J$=e=>e.signal!==null?`killed by ${e.signal}`:e.status===null?"did not start":e.status!==0?`exit ${e.status}`:`printed ${e.version??"nothing"}`,K$=(e,t)=>e.status===0&&e.signal===null&&e.version===t.version,H$=e=>{let t=nf(e.home),r=wv(e.nodeFs.lstatSync,t);if(r===void 0)return is(`${Or} is missing and could not be written \u2014 run \`infra-kit setup\` and see the debug log`);if(!r.isFile())return is(`${Or} is not a regular file; infra-kit will not replace it \u2014 move it away and run \`infra-kit setup\``);let n=of(e.home,e.nodeFs);if(n===null)return is(`${Or} has no readable node.source.json and it could not be rewritten \u2014 run \`infra-kit setup\``);let o=wv(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 is(`${Or} is Node ${n.version} (${n.method} of ${w(n.source)}); infra-kit runs ${e.version} at ${w(e.execPath)}, a different file, and could not relink it \u2014 run \`infra-kit setup\``);if(!i){let c=e.nodeVersionOf(t);if(!K$(c,e))return is(`${Or} does not run as Node ${e.version} (${J$(c)}). Re-run through the current Node: \`${Lt(e.bin,{...e,stableNode:null})}\`, then \`infra-kit setup\``)}return{row:{name:cs,status:"pass",message:`${Or} is Node ${n.version} (${n.arch}, ${n.method} of ${w(n.source)})`},stableNode:t,sidecar:n}},q$=e=>{if(Pv(e.platform)===null)return{row:{name:cs,status:"skip",message:"no portless OS service on this platform"},stableNode:null,sidecar:null};let t=H$(e);return e.isGlobal()?t:{...t,row:{name:cs,status:"skip",message:`not a global install; the global infra-kit keeps ${Or} current`}}},xv=(e,t)=>{let r=V$(e,t),n=q$(r);return{seams:{...r,stableNode:n.stableNode,stableNodeSidecar:n.sidecar},node:n.row}},Y$=(e,t)=>{let r=t.readFile(ke.join(e,"package.json"));try{let n=r===null?null:xe.object({version:xe.string()}).safeParse(JSON.parse(r));return n?.success===!0?n.data.version:"?"}catch{return"?"}},z$=e=>{let t=Number.parseInt(e.readFile(ke.join(e.stateDir,"proxy.pid"))?.trim()??"",10);return!Number.isInteger(t)||t<=0?null:e.processStartTime(t)},X$=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?null:t},Z$=(e,t,r)=>{let n=z$(r),o=a=>n!==null&&a!==null&&n.getTime()<a.getTime(),s=r.stableNodeSidecar,i=[...s!==null&&o(X$(s.versionChangedAt))?[`Node ${s.version}`]:[],...o(r.mtime(ke.join(e,"package.json")))?[`portless ${t}`]:[]];return i.length===0?null:i.join(" and ")},Q$=async(e,t)=>{let r=t.realpath(t.cwd);return r===t.realpath(t.home)?!1:ro(await t.repoRoot()??r,e,t.realpath)},Dr=e=>({state:"drifted",row:e}),eA=async(e,t,r)=>{let n=Lt(r.bin,r);if(!r.exists(e))return Dr({name:tr,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=ke.join($c(r.home),"dist","cli.js");if(t!==o)return Dr(as(`The service points at \`${t}\`, a version-specific location. Re-run once to switch it to the stable link: \`${n}\``));if(ni(r.home,r.exists)===null)return Dr({name:tr,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($c(r.home));if(await Q$(s,r))return Dr({name:tr,status:"fail",message:`The service runs portless from a project checkout (${s}). Re-run \`service install\` from the global install: \`${n}\``});let i=tA(e,n,r);if(i!==null)return i;let a=Y$(s,r),c=Z$(s,a,r);return c!==null?{state:"converged",row:as(`The running daemon predates ${c} that \`dev\` will talk to. Restart it: \`${F$(r.platform)}\` (or reboot).`)}:{state:"converged",row:{name:tr,status:"pass",message:`service runs \`${e}\` (Node ${r.version}) + stable link \u2192 portless ${a}`}}},tA=(e,t,r)=>r.stableNode!==null?r.realpath(e)===r.realpath(r.stableNode)?null:Dr(as(`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:Dr(as(`The service runs \`${e}\`; infra-kit runs \`${r.execPath}\`. Works until the old Node is removed. Re-run when convenient: \`${t}\``)),Tv=async e=>{let t=Pv(e.platform);if(t===null)return{state:"absent",row:{name:tr,status:"skip",message:"no portless OS service file on this platform"}};let r=e.readServiceFile(t);if(r===null)return{state:"absent",row:{name:tr,status:"skip",message:`the OS service is not installed (no ${t})`}};let[n,o]=xh(e.platform,r)??[];return n===void 0||o===void 0?Dr(as(`could not parse ${t} \u2014 re-run \`${Lt(e.bin,e)}\` to rewrite it.`)):eA(n,o,e)},Cv=async(e,t)=>{let{seams:r}=xv(e,t);return{state:(await Tv(r)).state,stableNode:r.stableNode}},rA=()=>[cs,tr,Ev(),"portless CA chain valid","portless CA trusted","portless routes"],nA=async(e={})=>{let t=e.resolveBin??Km,r=e.isProxyServing??Xm,n=e.handshake??tf,o=e.caTrusted??ef,s=e.routes??oo,i=e.isListening??no,a=(e.caPath??Qm)(),c=t();if(c===null)return[{name:"portless installed",status:"fail",message:"portless is not resolvable from node_modules \u2014 run `pnpm install`."},...rA().map(b=>({name:b,status:"skip",message:"portless not resolvable"}))];let l={name:"portless installed",status:"pass",message:"portless is resolvable from node_modules"},{seams:u,node:p}=xv(e,c),m=s(),f=await N$(r,c,u),h=f.status==="fail"?{name:"portless CA chain valid",status:"skip",message:"no daemon to handshake with"}:await _$(n,m,a,c,u);return[l,p,(await Tv(u)).row,f,h,M$(o(),a,c),await j$(m,i,c)]},oA=async(e={})=>{let t="portless routes",r=e.routes??oo,n=e.isListening??no,o=e.devSessionRunning??bh,s=r();if(s.length===0)return{name:t,status:"pass",message:"No portless routes registered"};let i=await Promise.all(s.map(async u=>({name:u.name,port:u.port,live:await n(u.port)}))),{prunable:a,withheld:c}=kh(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??rf().removeAlias;for(let u of a)await l(u);return{name:t,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},ga=async(e={})=>{let t=await t$(),r=zC(e.probeDeps??Qo()),n=async(m,f)=>{let[h,b]=await Promise.all([f,r]),T=b.get(m);return T===void 0?h:{...h,detail:T}},o=await Promise.all([n("brew",_t("brew installed",Ye("brew").probeArgv,"Homebrew is installed","Homebrew is not installed. Install from: https://brew.sh/")),n("git",_t("git installed",Ye("git").probeArgv,"git is installed","git is not installed. Install with: brew install git")),n("gh",_t("gh installed",Ye("gh").probeArgv,"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/")),_t("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),n("doppler",_t("doppler installed",Ye("doppler").probeArgv,"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli")),n("aws",_t("aws installed",Ye("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")),_t("package manager installed",["pnpm","--version"],"Installed: pnpm","pnpm is not installed. Install from: https://pnpm.io/installation"),_t("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"),XC(),Promise.resolve(ZC()),Promise.resolve(QC()),e$(),Promise.resolve(r$(t)),c$(),i$(t),l$(e.fix??!1),d$(),p$()]),s=await nA(e.portlessDeps);if(e.fix){let m=await oA(),f=s.findIndex(h=>h.name===m.name);f>=0?s[f]=m:s.push(m)}let i=await h$(),a=await Ko(),c={projectDir:vt.env.CLAUDE_PROJECT_DIR||null,cwd:vt.cwd(),gitRoot:a},l=[await b$(),...P$(i,c),Ho(),C$({env:vt.env,stdinIsTTY:vt.stdin.isTTY===!0,flag:F.source==="flag"}),a===null?{name:"Agent allowlist",status:"skip",message:"no git root"}:A$(a)],u=[...o,await D$(a),...s,...await g$(),...l,x$(Cn(),U.version)],p={checks:u.map(m=>({name:m.name,status:m.status,message:m.message,fixable:Zl.has(m.name),detail:m.detail})),allPassed:qC(u),cliVersion:U.version};return{content:R(JSON.stringify(p,null,2)),structuredContent:p}},td=C({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:xe.array(xe.object({name:xe.string().describe("Name of the check"),status:xe.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:xe.string().describe("Details about the check result"),fixable:xe.boolean().describe("Whether `infra-kit doctor --fix` repairs this row"),detail:xe.object({manager:xe.string().describe("Which package manager owns this install, read from its resolved path"),version:xe.string().nullable().describe("The version the tool reported, or null"),present:xe.boolean().describe("The tool is installed somewhere findable \u2014 on PATH or not"),onPath:xe.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:xe.boolean().describe("Whether no check failed (warnings and skips do not count)"),cliVersion:xe.string().describe("Version of the infra-kit CLI that produced this report")},handler:()=>ga()});import{E2E_MODE_ENV as OA}from"@slip-stream-kit/config/internal";import ld from"node:fs";import DA from"node:os";import us from"node:path";import va from"node:process";import{z as E}from"zod";var wt=(e,t,r)=>new D({status:"refused",reason:e,...t},2,r);import{describeProxyRoutes as sA,loadDev as iA,readAppAliasName as aA,readCloudOrigin as cA,readLocalContext as Av}from"@slip-stream-kit/config/internal";import $v from"node:fs";import Ir from"node:path";import ha from"node:process";import{z as rd}from"zod";var lA=async e=>{let t=Ir.join(e,"apps"),r=$v.existsSync(t)?$v.readdirSync(t).toSorted():[],n=[];for(let o of r){let s=Ir.join(t,o,"tests"),a=(await dt(s))?.e2e;a?.target!==void 0&&n.push({app:o,testsDir:s,e2e:{target:a.target}})}return n},uA=(e,t)=>{let[r,n]=Ir.relative(e,t).split(Ir.sep);return r==="apps"&&n?n:void 0},dA=(e,t,r,n)=>{let o=c=>e.find(l=>l.app===c),s=o(t)??(t===void 0?o(uA(n,r)):void 0);if(s)return s;if(t===void 0&&e.length===1)return e[0];let i=e.map(c=>c.app);if(i.length===0)throw new g(void 0,{operation:"find an e2e package",remediation:"declare `e2e: { target }` in `apps/<app>/tests/infra-kit.config.ts` (see the `InfraKitE2e` type)",stderrExcerpt:`no apps/*/tests package under ${n} declares an e2e block`});let a="app";throw new D({status:"argument_required",argument:a,choices:rd.toJSONSchema(rd.object({app:rd.enum(i)})),agentMode:F.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(", ")}`})},pA=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}})),mA=e=>Io(e).apps.find(t=>t.env!=="")?.env??null,nd=async(e,t={})=>{let r=t.cwd??ha.cwd(),n=t.projectRoot??await A(),o=(t.env??ha.env)[Gr]||null,s=t.healthProbe??Gc,i=dA(await lA(n),e,r,n),{target:a}=i.e2e,[c,l]=a.split("/"),u=Ir.join(n,"apps",c,l),p=(await hr(u)).name,m=(await dt(u))?.deployedUrlEnv??null;if(!p)throw new g(void 0,{operation:`resolve e2e target ${a}`,remediation:`check \`e2e.target\` in ${Ir.join(i.testsDir,"infra-kit.config.ts")}`,stderrExcerpt:`${u} has no package.json name`});let f=ng(u),h=aA(p,u),b=`${h}.localhost`,T=`https://${b}`,k=0;if(l==="ui")k=(t.listRoutes??oo)().find(S=>S.name===b||S.name===h)?.port??0;else{let S=Av(u).info.get(p);k=S?.port??0,T=S?.origin??T}let j=k>0&&await s({tag:a,port:k,kind:l})==="ok",v=j?mA(u):null;return{app:i.app,testsDir:i.testsDir,target:a,kind:l,targetDir:u,packageName:p,deployedUrlEnv:m,release:f,env:o,servedEnv:v,localUrl:T,served:j}},Ov=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}},od=async(e,t={})=>{let r=t.healthProbe??Gc,n=Av(e.targetDir),o=e.kind==="ui"?await iA(e.targetDir):void 0,s=o?.proxy?sA({proxy:o.proxy,localContext:n,env:e.env??void 0,cloud:cA(e.deployedUrlEnv??void 0,t.env??ha.env),getRelease:()=>e.release}):[],i=new Map([...n.info].map(([a,c])=>[a,c.port]));return{...Ov(e),mode:"local",baseUrl:e.localUrl,routes:await pA(s,i,r)}},sd=(e,t={})=>{let{env:r,deployedUrlEnv:n,target:o}=e;if(!n)throw wt("no_deployed_url_env",{target:o},{operation:`resolve the deployed app ${e.app}'s cloud e2e run targets`,remediation:`declare \`deployedUrlEnv: '<APP>_URL'\` in ${Ir.join(e.targetDir,"infra-kit.config.ts")} and keep the URL per environment in Doppler`,stderrExcerpt:`${o} names no variable holding its deployed URL`});let s=(t.env??ha.env)[n];if(!r||!s){let i=s?Gr:n;throw wt("env_not_loaded",{missing:i},{operation:`resolve the deployed app ${e.app}'s cloud e2e run targets`,remediation:"load an environment (`infra-kit env-load -c <env>`), or drop --cloud to run against this worktree",stderrExcerpt:`a cloud run of ${o} needs ${n} and ${Gr}, and ${i} is not set`})}return{...Ov(e),mode:"cloud",baseUrl:s,routes:[]}};import fA from"node:fs";import gA from"node:path";import{stripVTControlCharacters as hA}from"node:util";import{z as N}from"zod";var Dv=2e3,Iv="--reporter=line,json",Nv=e=>({PLAYWRIGHT_JSON_OUTPUT_FILE:e,PLAYWRIGHT_JSON_OUTPUT_NAME:e}),_v=e=>e.some(t=>t==="--reporter"||t.startsWith("--reporter=")),id=N.object({message:N.string().optional()}),Mv=N.object({type:N.string()}),yA=N.object({status:N.string(),retry:N.number(),error:id.optional(),errors:N.array(id).optional(),annotations:N.array(Mv).optional(),attachments:N.array(N.object({name:N.string(),path:N.string().optional()})).optional()}),vA=N.object({projectName:N.string(),status:N.string(),expectedStatus:N.string().optional(),annotations:N.array(Mv).optional(),results:N.array(yA)}),wA=N.object({title:N.string(),file:N.string(),line:N.number().optional(),tests:N.array(vA)}),jv=N.lazy(()=>N.object({title:N.string(),specs:N.array(wA).optional(),suites:N.array(jv).optional()})),kA=N.object({config:N.object({rootDir:N.string().optional()}).optional(),suites:N.array(jv),errors:N.array(id).optional(),stats:N.object({expected:N.number(),unexpected:N.number(),flaky:N.number(),skipped:N.number()})}),Fv=e=>{let t=hA(e);return t.length>Dv?`${t.slice(0,Dv)}\u2026`:t},bA=e=>{let t=e.error?.message??e.errors?.[0]?.message;return t===void 0?null:Fv(t)},RA=e=>e.status==="unexpected"||e.status==="flaky",SA=e=>{let t=new Map;for(let r of e)t.set(r.projectName,[...t.get(r.projectName)??[],r]);return t},EA=e=>new Set([...e.annotations??[],...e.results.flatMap(t=>t.annotations??[])].map(t=>t.type)),PA=(e,t)=>{let r=e.filter(RA),n=r.at(-1);if(!n)return null;let o=n.results.findLast(i=>i.status!=="passed"&&i.status!=="skipped"),s=r.length===e.length&&n.status==="unexpected";return{...t,status:s?"unexpected":"flaky",retry:o?.retry??0,runs:e.length,failedRuns:r.length,error:o?bA(o):"Expected to fail, but passed.",tracePath:o?.attachments?.find(i=>i.name==="trace")?.path??null}},xA=e=>{let t=kA.safeParse(e);if(!t.success)return null;let{config:r,suites:n,errors:o,stats:s}=t.data,i=[],a=new Map,c=0,l=(p,m)=>{let f=new Set(m.flatMap(T=>[...EA(T)])),h=m.some(T=>T.expectedStatus==="failed");if(!h&&!f.has("fixme")&&!f.has("skip"))return;let b=a.get(p)??{file:p,fail:0,fixme:0,skip:0};h&&(b.fail+=1),f.has("fixme")?b.fixme+=1:f.has("skip")&&(b.skip+=1),a.set(p,b)},u=(p,m)=>{for(let f of p.specs??[]){let h=r?.rootDir?gA.resolve(r.rootDir,f.file):f.file,b=[...m,f.title].join(" \u203A ");l(h,f.tests);for(let[T,k]of SA(f.tests)){let j=PA(k,{title:b,file:h,line:f.line??null,project:T});j&&(j.runs>1&&j.failedRuns<j.runs&&(c+=1),i.push(j))}}for(let f of p.suites??[])u(f,[...m,f.title])};for(let p of n)u(p,[]);return{summary:{expected:s.expected,unexpected:s.unexpected,flaky:s.flaky,skipped:s.skipped,repeatFlaky:c},failures:i,annotated:[...a.values()],errors:(o??[]).flatMap(p=>p.message===void 0?[]:[Fv(p.message)])}},Lv=e=>{try{return xA(JSON.parse(fA.readFileSync(e,"utf8")))}catch{return null}};import ls from"node:fs";import Uv from"node:path";import ya from"node:process";var TA=e=>Uv.join(e,"node_modules",".cache","infra-kit-e2e.lock"),CA=e=>{try{return ya.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Bv=e=>{try{return ls.writeFileSync(e,String(ya.pid),{flag:"wx"}),!0}catch(t){if(t.code==="EEXIST")return!1;throw t}},ad=e=>{try{let t=Number.parseInt(ls.readFileSync(e,"utf8"),10);return Number.isInteger(t)&&t>0?t:null}catch{return null}},Wv=e=>{let t=TA(e);if(ls.mkdirSync(Uv.dirname(t),{recursive:!0}),!Bv(t)){let r=ad(t);if(r!==null&&r!==ya.pid&&CA(r))return{holder:r};if(ls.rmSync(t,{force:!0}),!Bv(t))return{holder:ad(t)??0}}return{release:()=>{ad(t)===ya.pid&&ls.rmSync(t,{force:!0})}}};import{spawn as $A}from"node:child_process";import AA from"node:os";import cd from"node:process";var Gv=(e,t,r)=>new Promise((n,o)=>{let s=$A(e,t,r),i=cd.stdin.isTTY?["SIGTERM","SIGHUP"]:["SIGINT","SIGTERM","SIGHUP"],a=l=>{s.kill(l)},c=()=>{for(let l of i)cd.off(l,a)};for(let l of i)cd.on(l,a);s.once("error",l=>{c(),o(l)}),s.once("close",(l,u)=>{c(),n(l??(u?128+AA.constants.signals[u]:1))})});var IA=["playwright.config.ts","playwright.config.mts","playwright.config.js","playwright.config.mjs"],NA=e=>IA.some(t=>{try{return ld.readFileSync(us.join(e,t),"utf8").includes("infraKitE2e")}catch{return!1}}),ud=e=>`infra-kit dev ${e.target.split("/")[0]} --no-watch --reuse`,_A=(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(`
383
+ `)},MA=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 wt("dead_local_routes",{routes:r},{operation:`run ${e.app} e2e against the local dev server`,remediation:"check the backend rows in `infra-kit dev-status`, fix or restart it, then re-run",stderrExcerpt:`routes held local but their backend is not responding: ${r.join(", ")}`})},jA=async(e,t)=>{if(e.env===null||!tg(e.env))return;let r=await(t.protectedEnvAccess??ct)();if(r.allowed)return;let n=`run ${e.app} e2e against "${e.env}"`;throw r.reason==="agent-blocked"?wt("protected_env",{env:e.env,humanMayRun:!0},{operation:n,remediation:'a human runs it from their own terminal \u2014 this project sets `protectedEnvs: "cli-only"`',stderrExcerpt:`"${e.env}" is withheld from agents in this project`}):wt("protected_env",{env:e.env,humanMayRun:!1},{operation:n,remediation:"load a non-protected env (`infra-kit env-load -c dev`), or set `protectedEnvs` in infra-kit.json",stderrExcerpt:`"${e.env}" is a protected environment`})},FA=e=>{if(!(e.servedEnv===null||e.servedEnv===e.env))throw wt("served_env_mismatch",{servedEnv:e.servedEnv,env:e.env},{operation:`run ${e.app} e2e against the local dev server`,remediation:`load the same env (\`infra-kit env-load -c ${e.servedEnv}\`), or restart \`infra-kit dev\` under "${e.env??"none"}"`,stderrExcerpt:`the dev server serving ${e.target} runs with env "${e.servedEnv}", this shell with "${e.env??"none"}"`})},LA=async(e,t)=>{if(e.served){FA(e);let p=await od(e,t);return MA(p),p}if(!NA(e.testsDir))throw wt("no_dev_server",{devCommand:ud(e)},{operation:`run ${e.app} e2e locally`,remediation:`start it (\`${ud(e)}\`), or wire \`infraKitE2e()\` from @slip-stream-kit/config/playwright into its playwright.config.ts`,stderrExcerpt:`nothing serves ${e.target} and ${e.testsDir}'s Playwright config does not start it`});let{app:r,testsDir:n,target:o,packageName:s,deployedUrlEnv:i,release:a,env:c,servedEnv:l,localUrl:u}=e;return{app:r,testsDir:n,target:o,packageName:s,deployedUrlEnv:i,release:a,env:c,servedEnv:l,localUrl:u,mode:"local",baseUrl:u,routes:[]}},BA=(e,t,r)=>Gv("pnpm",["exec","playwright","test",...t],{cwd:e.testsDir,env:{...va.env,...r,[OA]:e.mode},stdio:["inherit",dr.enabled||Q()?2:"inherit","inherit"]}),UA=(e,t)=>{let r=t.findIndex(s=>s==="--output"||s.startsWith("--output="));if(r!==-1){let s=t[r]==="--output"?t[r+1]??"":t[r].slice(9);return{args:t,outputDir:us.resolve(e.testsDir,s)}}let n=new Date().toISOString().replace(/[:.]/g,"-"),o=us.join(e.testsDir,"test-results",`ik-e2e-${n}-${va.pid}`);return{args:[...t,`--output=${o}`],outputDir:o}},WA=e=>{if(e.mode==="cloud")return()=>{};let t=Wv(e.testsDir);if("holder"in t)throw wt("run_in_progress",{pid:t.holder},{operation:`run ${e.app} e2e locally`,remediation:`wait for it to finish (or stop process ${t.holder}), then re-run`,stderrExcerpt:`another local e2e run of ${e.app} (pid ${t.holder}) is using its dev server`});return t.release},wa=async(e,t={})=>{let r=await nd(e.app,t),n=e.cloud?sd(r,t):await LA(r,t);d.info(_A(n,r.served)),n.mode==="cloud"&&await jA(n,t);let o={...n,served:r.served,devCommand:n.mode==="local"&&!r.served?ud(r):null,playwrightArgs:e.playwrightArgs??[]};if(e.dryRun)return pd({...o,ran:!1,exitCode:null,...dd});n.mode==="cloud"&&await H(e.yes,`Run ${n.app} e2e against ${n.baseUrl} ("${n.env}", shared)?`,{plan:o});let s=WA(n);try{return await GA(o,t.runPlaywright??BA)}finally{s()}},GA=async(e,t)=>{if(!Q()||_v(e.playwrightArgs)){let i=await t(e,e.playwrightArgs,{});return i!==0&&(va.exitCode=i),pd({...e,ran:!0,exitCode:i,...dd,report:Q()?"caller-reporter":"off"})}let{args:r,outputDir:n}=UA(e,e.playwrightArgs),o=ld.mkdtempSync(us.join(DA.tmpdir(),"ik-e2e-report-")),s=us.join(o,"report.json");try{let i=await t(e,[Iv,...r],Nv(s));i!==0&&(va.exitCode=i);let a=Lv(s);return pd({...e,ran:!0,exitCode:i,...a?{report:"collected",...a}:{...dd,report:"unavailable"},outputDir:n})}finally{ld.rmSync(o,{recursive:!0,force:!0})}},dd={report:"off",outputDir:null,summary:null,failures:[],annotated:[],errors:[]},pd=e=>({content:R(JSON.stringify(e,null,2)),structuredContent:e}),VA={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."),outputDir:E.string().nullable().describe("Where this run\u2019s traces and attachments live \u2014 its own directory, so a later run cannot delete them. Null unless report is collected or unavailable."),summary:E.object({expected:E.number(),unexpected:E.number(),flaky:E.number(),skipped:E.number(),repeatFlaky:E.number()}).nullable().describe("Playwright\u2019s counts by outcome, one per run (each --repeat-each repeat counts), plus repeatFlaky: tests that passed in some repeats and failed in others. Null unless report is collected."),failures: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 or in another --repeat-each repeat."),retry:E.number().describe("The retry index of the failed attempt reported here."),runs:E.number().describe("How many times the test ran in this project \u2014 its --repeat-each repeats."),failedRuns:E.number().describe("How many of those runs failed."),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("One entry per test and project that failed, needed a retry, or failed in some repeat; empty unless report is collected."),annotated:E.array(E.object({file:E.string(),fail:E.number().describe("test.fail \u2014 green only while the bug it registers exists."),fixme:E.number().describe("test.fixme \u2014 skipped as unfinished."),skip:E.number().describe("test.skip, declared or called at runtime, conditional ones included.")})).describe("Per spec file, the tests that passed or skipped while asserting little, as Playwright ran them; empty unless report is collected."),errors: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.")},md=C({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:VA,handler:e=>wa(e)});import ka from"node:fs";import fd from"node:path";import{z as ds}from"zod";var JA=e=>[...e.map(t=>`unset ${t}`),`unset ${Gr}`,`unset ${Xs}`,`unset ${Zs}`,`unset ${Mm}`,`unset ${Qs}`],ba=async()=>{let e=Vr(),t=fd.join(e,Wr);if(!ka.existsSync(t))throw new Error("No loaded environment found. Run `env-load` first.");let r=ei(t),n=JA(r),o=fd.resolve(e,Ys);ka.mkdirSync(e,{recursive:!0,mode:448}),Ft(o,`${n.join(`
375
384
  `)}
376
- `,384),ha.rmSync(t,{force:!0}),ha.rmSync(ad.join(e,Ks),{force:!0});let s={filePath:o,variableCount:r.length,unsetStatements:n};return{content:b(JSON.stringify(s,null,2)),structuredContent:s}},cd=C({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:is.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{filePath:is.string().describe("Path to the file that must be sourced to apply"),variableCount:is.number().describe("Number of variables cleared"),unsetStatements:is.array(is.string()).describe("Unset statements generated")},handler:()=>ya()});import jA from"node:path";import as from"node:process";import{z as Mn}from"zod";var va=async()=>{d.info("Environment session status:");let e=Br(),t=as.env[Yn],r=jA.join(e,Fr),n=0,o=0,s=as.env[Hs]??null,i=as.env[qs]??null,a=as.env[Ys]??null;if(s){let l=zs(r);l.length>0&&(o=l.length,n=l.filter(p=>p in as.env).length);let u=a?.replace(/\.\d{3}Z$/,"")??null;if(d.info(` ${s}: ${n} of ${o} vars loaded (project: ${i}, loadedAt: ${u}, session: ${t})
385
+ `,384),ka.rmSync(t,{force:!0}),ka.rmSync(fd.join(e,zs),{force:!0});let s={filePath:o,variableCount:r.length,unsetStatements:n};return{content:R(JSON.stringify(s,null,2)),structuredContent:s}},gd=C({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:ds.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{filePath:ds.string().describe("Path to the file that must be sourced to apply"),variableCount:ds.number().describe("Number of variables cleared"),unsetStatements:ds.array(ds.string()).describe("Unset statements generated")},handler:()=>ba()});import KA from"node:path";import ps from"node:process";import{z as Un}from"zod";var Ra=async()=>{d.info("Environment session status:");let e=Vr(),t=ps.env[to],r=KA.join(e,Wr),n=0,o=0,s=ps.env[Xs]??null,i=ps.env[Zs]??null,a=ps.env[Qs]??null;if(s){let l=ei(r);l.length>0&&(o=l.length,n=l.filter(p=>p in ps.env).length);let u=a?.replace(/\.\d{3}Z$/,"")??null;if(d.info(` ${s}: ${n} of ${o} vars loaded (project: ${i}, loadedAt: ${u}, session: ${t})
377
386
  `),o>0&&n<o){let p=o-n;d.warn(` ${p} cached var(s) are not present in the current process \u2014 env-load needs to be re-sourced, or vars were unset manually.`)}}else d.info(` Session ${t}: no env loaded
378
- `);let c={sessionId:t,sessionLoadedCount:n,sessionTotalCount:o,sessionConfig:s,sessionProject:i,sessionLoadedAt:a};return{content:b(JSON.stringify(c,null,2)),structuredContent:c}},ld=C({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:Mn.string().describe("Current terminal session ID"),sessionLoadedCount:Mn.number().describe("Number of cached vars active in the current session"),sessionTotalCount:Mn.number().describe("Total number of cached var names"),sessionConfig:Mn.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:Mn.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:Mn.string().nullable().describe("ISO 8601 timestamp of when the env was loaded")},handler:va});import FA from"node:process";import{z as er}from"zod";var Lv="****",$e=e=>typeof e!="string"||e.length<8?Lv:`${Lv}${e.slice(-4)}`;var Bv=(e,t,r)=>e.map(n=>{let o=r||t[n];return o?{env:n,source:r?`env:${pr}`:"store",redactedToken:$e(o),present:!0}:{env:n,source:"-",redactedToken:"-",present:!1}}),LA=["ENV","SOURCE","TOKEN","PRESENT"],Uv=(e,t)=>{let r=[...LA,...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())},wa=async({check:e}={})=>{let t=await pi(),r=await Qe(),n=FA.env[pr],o=Bv(t,r?.envs??{},n);if(e){let a=await dr();for(let c of o){if(!c.present)continue;let l=n||r.envs[c.env],u=await jf({childEnv:so(l),project:a,config:c.env});c.status=u.outcome}}for(let a of Uv(o,!!e))d.info(a);let s=o.filter(a=>!a.present);s.length>0&&d.info(`
379
- No token for: ${s.map(a=>a.env).join(", ")}. Add one with \`infra-kit env-token-set <env>\`.`);let i={tokens:o};return{content:b(JSON.stringify(i,null,2)),structuredContent:i}},ud=C({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:er.boolean().optional().describe("Probe Doppler for each token\u2019s validity and scope (one cheap call per environment).")},outputSchema:{tokens:er.array(er.object({env:er.string().describe("Environment / Doppler config name"),source:er.string().describe('"store", "env:INFRA_KIT_ENV_TOKEN", or "-" when absent'),redactedToken:er.string().describe("Redacted token \u2014 last 4 chars at most, never the raw value"),present:er.boolean().describe("Whether a token is configured for this environment"),status:er.string().optional().describe("Only with check=true: valid | revoked | mis-scoped | unreachable")})).describe("One row per declared environment")},handler:wa});import{z as x}from"zod";import{$ as BA}from"zx";var UA=(e,t)=>({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0,dryRun:e,atomicPush:{attempted:!1,aborted:!1},results:[],skipped:t}),WA=e=>e.dualBase?"open PRs to both dev and main":e.titleMismatch?"title/base mismatch":e.type==="hotfix"?"hotfix (targets main)":null,VA=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(", ")},pd=e=>({content:b(JSON.stringify(e,null,2)),structuredContent:e}),dd=new Set(["up-to-date","fast-forward","merged"]),GA=(e,t,r)=>{let n=(Array.isArray(e)?e:e.split(",")).map(a=>a.trim()).filter(a=>a.length>0),o=new Set(t),s=new Map(r.map(a=>[a.branch,a.reason])),i=new Set;for(let a of n){let c;try{c=Te(ke(a))}catch(l){throw new g(l,{operation:`resolve release selector "${a}"`,remediation:`pass one of: ${t.join(", ")}`})}if(!o.has(c)){let l=s.get(c);throw new g(void 0,{operation:`select release branch for "${a}"`,stderrExcerpt:l?`${c} is skipped: ${l}`:`${c} is not an open regular release branch`,remediation:`pass one of: ${t.join(", ")}`})}i.add(c)}return t.filter(a=>i.has(a))},JA={"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"},Vv=e=>{let t=JA[e.status];if(e.status==="conflict"){let r=e.conflictPaths?.length??0;return`${t}: ${r} file(s)`}return e.reason?`${t}: ${e.reason}`:t},KA=(e,t)=>{d.info(`
380
- \u{1F4CB} Merge plan:`);for(let r of e)d.info(` ${r.branch} \u2014 ${Vv(r)}`);for(let r of t)d.info(` ${r.branch} \u2014 skipped: ${r.reason}`)},HA=(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`},qA=async e=>{let{entries:t,toPlan:r,all:n,explicit:o}=e;if(o||n)return r;y.setInteractive();let s=new Map(t.flatMap(i=>{let a=Q(i.branch);return a?[[le(a),Vv(i)]]:[]}));return Yt(fe({branches:r,descriptions:s}),{required:!0})},YA=async e=>{let{cwd:t,worktreePath:r,entries:n,selected:o,verify:s}=e,i=n.filter(h=>o.includes(h.branch)),a=h=>{for(let S of h)d.info(`\u2139\uFE0F ${S} was merged by someone else while we planned \u2014 dropping it from the push`)},c=await Fo(t,Nh(i));a(c.nowUpToDate);let l=c.kept,u=new Map;if(s&&l.length>0){d.info(`
381
- \u{1F50E} Verifying ${l.length} merge(s) with: ${s}`);let h=await Mh({worktreePath:r,refs:l,command:s});u=h.failed;for(let[k,A]of h.failed)d.info(`\u2717 ${k} failed verification \u2014 not pushing it. ${A.split(`
382
- `)[0]??""}`);let S=await Fo(t,h.kept);a(S.nowUpToDate),l=S.kept}if(l.length===0)return{pushed:!1,pushAborted:!1,verifyFailed:u};d.info(`
383
- \u2B06\uFE0F Pushing atomically: ${l.map(h=>h.branch).join(", ")}`);let p=await si(t,l);if(p.pushed)return{pushed:!0,pushAborted:!1,verifyFailed:u};let f=(await Promise.all(l.map(async h=>({branch:h.branch,landed:await Gr(t,h.branch)===h.sha})))).filter(h=>h.landed);return f.length>0&&d.warn(`\u26A0\uFE0F The push reported failure, but origin already carries ${f.map(h=>h.branch).join(", ")} \u2014 re-run to reconcile.`),{pushed:!1,pushAborted:!0,verifyFailed:u,abortedBy:p.stderr?.split(`
384
- `)[0],observedLanded:f.map(h=>h.branch)}},zA=e=>{let t=["keepConflicts","continue","abort"].filter(n=>e[n]),r={keepConflicts:"--keep-conflicts",continue:"--continue",abort:"--abort"};if(t.length>1||t.length===1&&e.dryRun){let n=[...t.map(o=>r[o]),...e.dryRun?["--dry-run"]:[]];throw new g(void 0,{operation:"choose the merge-dev mode",stderrExcerpt:`${n.join(" and ")} cannot be combined`,remediation:"pass at most one of --keep-conflicts, --continue, --abort; --dry-run only on a plain run"})}if(e.tree!==void 0&&!e.continue)throw new g(void 0,{operation:"choose the merge-dev mode",stderrExcerpt:"--tree belongs to --continue",remediation:"run the rerun a --continue preview printed, unchanged"})},Wv=e=>{let{results:t,atomicPush:r,declined:n}=e;for(let i of t){let a=i.reason?.split(`
385
- `)[0];d.info(a?` ${i.branch} \u2014 ${i.status}: ${a}`:` ${i.branch} \u2014 ${i.status}`)}let o=n?[]:t.filter(i=>i.status!=="aborted"),s=o.filter(i=>!dd.has(i.status));return pd({successfulMerges:o.length-s.length,failedMerges:s.length,failedBranches:s.map(i=>i.branch),totalBranches:t.length,dryRun:!1,atomicPush:r,results:t,skipped:[]})},XA=async e=>{let{all:t,versions:r,verify:n,confirmedCommand:o}=e,s=await Ae();if(e.abort)return Wv(await cy({cwd:s,versions:r,all:t,confirmedCommand:o}));let i=typeof n=="string"&&n.length>0?n:void 0;return Wv(await iy({cwd:s,versions:r,all:t,verify:i,trees:ay(e.tree),confirmedCommand:o}))},ka=async e=>{let{all:t,versions:r,dryRun:n=!1,verify:o,keepConflicts:s=!1,confirmedCommand:i}=e;zA(e);let a=o===!0?_h:o||void 0;if(await zl({operation:"merge dev into release branches"}),e.continue||e.abort)return XA(e);let c=[],l=[];for(let E of await G()){let B=WA(E);B?l.push({branch:E.branch,reason:B}):c.push(E.branch)}if(c.length===0)return d.info(l.length===0?"\u2139\uFE0F No open release branches found":`\u2139\uFE0F No open regular release branches \u2014 ${l.length} skipped (${VA(l)})`),y.print(),pd(UA(n,l));let u=await Ae();try{await BA({cwd:u,quiet:!0})`git fetch origin --prune`}catch(E){throw new g(E,{operation:"fetch origin before planning the merges",remediation:"check network access and that `origin` is reachable"})}let p=r===void 0?c:GA(r,c,l),m=await ff({cwd:u},async E=>{let B=Ki(E.remove);try{return await ZA({cwd:u,worktree:E,toPlan:p,candidates:c,skipped:l,all:t,versions:r,dryRun:n,verify:a,keepConflicts:s,confirmedCommand:i})}finally{B()}}),{entries:f,selected:h,pushed:S,pushAborted:k,abortedBy:A,declined:M,verifyFailed:v,handOffs:R}=m,T=await st(u).catch(()=>[]);return rO({entries:f,selected:h,pushed:S,pushAborted:k,abortedBy:A,declined:M,verifyFailed:v,handOffs:R,dryRun:n,worktrees:T,skipped:l})},ZA=async e=>{let{cwd:t,worktree:r,toPlan:n,candidates:o,skipped:s,all:i,versions:a,dryRun:c,verify:l,keepConflicts:u,confirmedCommand:p}=e,m=u?await Ce(t,"origin/dev"):null,f=await Ih({cwd:t,worktreePath:r.path,branches:n}),h={entries:f,pushed:!1,pushAborted:!1,declined:!1};if(KA(f,s),c)return{...h,selected:n};let S=await qA({entries:f,toPlan:n,all:i,explicit:a!==void 0});S.length===o.length?y.addOption("--all",!0):y.addOption("--versions",S);let k=f.filter(E=>S.includes(E.branch)&&E.mergeSha).length;k>0&&d.info(`
386
- \u2139\uFE0F This will push ${k} branch(es), re-running CI on ${k} open PR(s). If the repo dismisses stale approvals on new commits, those PRs lose them.`);try{await J(p,`Are you sure you want to merge dev into these branches: ${S.join(", ")}?`,{throwOnDecline:!0,plan:QA(f,S,s)})}catch(E){if(!Et(E))throw E;return{...h,selected:S,declined:!0}}p||y.addOption("--yes",!0);let A=await YA({cwd:t,worktreePath:r.path,entries:f,selected:S,verify:l}),M=E=>f.filter(B=>S.includes(B.branch)&&E(B)).map(B=>B.branch),v=M(E=>E.status==="conflict"),R=M(E=>E.status==="merged"&&(A.verifyFailed?.has(E.branch)??!1)),T=u&&m&&v.length+R.length>0?await ny({cwd:t,conflicted:v,verifyFailed:R,devSha:m,verify:l}):void 0;return{entries:f,selected:S,declined:!1,...A,handOffs:T}},QA=(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:pu(n.conflictPaths)}:{},...n.reason?{reason:n.reason}:{}})),skipped:r}),eO=(e,t)=>e.resolution?`# ${e.branch} \u2014 ${e.status}, left to resolve in ${e.resolution.worktreePath} (then --continue)
387
+ `);let c={sessionId:t,sessionLoadedCount:n,sessionTotalCount:o,sessionConfig:s,sessionProject:i,sessionLoadedAt:a};return{content:R(JSON.stringify(c,null,2)),structuredContent:c}},hd=C({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:Un.string().describe("Current terminal session ID"),sessionLoadedCount:Un.number().describe("Number of cached vars active in the current session"),sessionTotalCount:Un.number().describe("Total number of cached var names"),sessionConfig:Un.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:Un.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:Un.string().nullable().describe("ISO 8601 timestamp of when the env was loaded")},handler:Ra});import HA from"node:process";import{z as rr}from"zod";var Vv="****",Oe=e=>typeof e!="string"||e.length<8?Vv:`${Vv}${e.slice(-4)}`;var Jv=(e,t,r)=>e.map(n=>{let o=r||t[n];return o?{env:n,source:r?`env:${fr}`:"store",redactedToken:Oe(o),present:!0}:{env:n,source:"-",redactedToken:"-",present:!1}}),qA=["ENV","SOURCE","TOKEN","PRESENT"],Kv=(e,t)=>{let r=[...qA,...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())},Sa=async({check:e}={})=>{let t=await hi(),r=await tt(),n=HA.env[fr],o=Jv(t,r?.envs??{},n);if(e){let a=await mr();for(let c of o){if(!c.present)continue;let l=n||r.envs[c.env],u=await Vf({childEnv:po(l),project:a,config:c.env});c.status=u.outcome}}for(let a of Kv(o,!!e))d.info(a);let s=o.filter(a=>!a.present);s.length>0&&d.info(`
388
+ No token for: ${s.map(a=>a.env).join(", ")}. Add one with \`infra-kit env-token-set <env>\`.`);let i={tokens:o};return{content:R(JSON.stringify(i,null,2)),structuredContent:i}},yd=C({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:rr.boolean().optional().describe("Probe Doppler for each token\u2019s validity and scope (one cheap call per environment).")},outputSchema:{tokens:rr.array(rr.object({env:rr.string().describe("Environment / Doppler config name"),source:rr.string().describe('"store", "env:INFRA_KIT_ENV_TOKEN", or "-" when absent'),redactedToken:rr.string().describe("Redacted token \u2014 last 4 chars at most, never the raw value"),present:rr.boolean().describe("Whether a token is configured for this environment"),status:rr.string().optional().describe("Only with check=true: valid | revoked | mis-scoped | unreachable")})).describe("One row per declared environment")},handler:Sa});import{z as x}from"zod";import{$ as YA}from"zx";var zA=(e,t)=>({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0,dryRun:e,atomicPush:{attempted:!1,aborted:!1},results:[],skipped:t}),XA=e=>e.dualBase?"open PRs to both dev and main":e.titleMismatch?"title/base mismatch":e.type==="hotfix"?"hotfix (targets main)":null,ZA=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(", ")},wd=e=>({content:R(JSON.stringify(e,null,2)),structuredContent:e}),vd=new Set(["up-to-date","fast-forward","merged"]),QA=(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=$e(Re(a))}catch(l){throw new g(l,{operation:`resolve release selector "${a}"`,remediation:`pass one of: ${t.join(", ")}`})}if(!o.has(c)){let l=s.get(c);throw new g(void 0,{operation:`select release branch for "${a}"`,stderrExcerpt:l?`${c} is skipped: ${l}`:`${c} is not an open regular release branch`,remediation:`pass one of: ${t.join(", ")}`})}i.add(c)}return t.filter(a=>i.has(a))},eO={"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"},qv=e=>{let t=eO[e.status];if(e.status==="conflict"){let r=e.conflictPaths?.length??0;return`${t}: ${r} file(s)`}return e.reason?`${t}: ${e.reason}`:t},tO=(e,t)=>{d.info(`
389
+ \u{1F4CB} Merge plan:`);for(let r of e)d.info(` ${r.branch} \u2014 ${qv(r)}`);for(let r of t)d.info(` ${r.branch} \u2014 skipped: ${r.reason}`)},rO=(e,t,r)=>{let n=t.find(o=>o.branch===e);return n?`git -C ${n.path} merge ${r}`:`git switch ${e} && git merge ${r}`},nO=async e=>{let{entries:t,toPlan:r,all:n,explicit:o}=e;if(o||n)return r;y.setInteractive();let s=new Map(t.flatMap(i=>{let a=ee(i.branch);return a?[[ue(a),qv(i)]]:[]}));return Xt(ge({branches:r,descriptions:s}),{required:!0})},oO=async e=>{let{cwd:t,worktreePath:r,entries:n,selected:o,verify:s,integrationRef:i}=e,a=n.filter(b=>o.includes(b.branch)),c=b=>{for(let T of b)d.info(`\u2139\uFE0F ${T} was merged by someone else while we planned \u2014 dropping it from the push`)},l=await Go(t,Lh(a),i);c(l.nowUpToDate);let u=l.kept,p=new Map;if(s&&u.length>0){d.info(`
390
+ \u{1F50E} Verifying ${u.length} merge(s) with: ${s}`);let b=await Uh({worktreePath:r,refs:u,command:s});p=b.failed;for(let[k,j]of b.failed)d.info(`\u2717 ${k} failed verification \u2014 not pushing it. ${j.split(`
391
+ `)[0]??""}`);let T=await Go(t,b.kept,i);c(T.nowUpToDate),u=T.kept}if(u.length===0)return{pushed:!1,pushAborted:!1,verifyFailed:p};d.info(`
392
+ \u2B06\uFE0F Pushing atomically: ${u.map(b=>b.branch).join(", ")}`);let m=await li(t,u);if(m.pushed)return{pushed:!0,pushAborted:!1,verifyFailed:p};let h=(await Promise.all(u.map(async b=>({branch:b.branch,landed:await qr(t,b.branch)===b.sha})))).filter(b=>b.landed);return h.length>0&&d.warn(`\u26A0\uFE0F The push reported failure, but origin already carries ${h.map(b=>b.branch).join(", ")} \u2014 re-run to reconcile.`),{pushed:!1,pushAborted:!0,verifyFailed:p,abortedBy:m.stderr?.split(`
393
+ `)[0],observedLanded:h.map(b=>b.branch)}},sO=e=>{let t=["keepConflicts","continue","abort"].filter(n=>e[n]),r={keepConflicts:"--keep-conflicts",continue:"--continue",abort:"--abort"};if(t.length>1||t.length===1&&e.dryRun){let n=[...t.map(o=>r[o]),...e.dryRun?["--dry-run"]:[]];throw new g(void 0,{operation:"choose the merge-dev mode",stderrExcerpt:`${n.join(" and ")} cannot be combined`,remediation:"pass at most one of --keep-conflicts, --continue, --abort; --dry-run only on a plain run"})}if(e.tree!==void 0&&!e.continue)throw new g(void 0,{operation:"choose the merge-dev mode",stderrExcerpt:"--tree belongs to --continue",remediation:"run the rerun a --continue preview printed, unchanged"})},Hv=e=>{let{results:t,atomicPush:r,declined:n}=e;for(let i of t){let a=i.reason?.split(`
394
+ `)[0];d.info(a?` ${i.branch} \u2014 ${i.status}: ${a}`:` ${i.branch} \u2014 ${i.status}`)}let o=n?[]:t.filter(i=>i.status!=="aborted"),s=o.filter(i=>!vd.has(i.status));return wd({successfulMerges:o.length-s.length,failedMerges:s.length,failedBranches:s.map(i=>i.branch),totalBranches:t.length,dryRun:!1,atomicPush:r,results:t,skipped:[]})},iO=async e=>{let{all:t,versions:r,verify:n,confirmedCommand:o}=e,s=await De();if(e.abort)return Hv(await my({cwd:s,versions:r,all:t,confirmedCommand:o}));let i=typeof n=="string"&&n.length>0?n:void 0;return Hv(await dy({cwd:s,versions:r,all:t,verify:i,trees:py(e.tree),confirmedCommand:o}))},Ea=async e=>{let{all:t,versions:r,dryRun:n=!1,verify:o,keepConflicts:s=!1,confirmedCommand:i}=e;sO(e);let a=o===!0?Bh:o||void 0;if(await tu({operation:"merge dev into release branches"}),e.continue||e.abort)return iO(e);let c=[],l=[];for(let O of await K()){let B=XA(O);B?l.push({branch:O.branch,reason:B}):c.push(O.branch)}if(c.length===0)return d.info(l.length===0?"\u2139\uFE0F No open release branches found":`\u2139\uFE0F No open regular release branches \u2014 ${l.length} skipped (${ZA(l)})`),y.print(),wd(zA(n,l));let u=await De();try{await YA({cwd:u,quiet:!0})`git fetch origin --prune`}catch(O){throw new g(O,{operation:"fetch origin before planning the merges",remediation:"check network access and that `origin` is reachable"})}let p=r===void 0?c:QA(r,c,l),m=`origin/${await br()}`,f=await bf({cwd:u,anchor:m},async O=>{let B=zi(O.remove);try{return await aO({cwd:u,worktree:O,toPlan:p,candidates:c,skipped:l,all:t,versions:r,dryRun:n,verify:a,keepConflicts:s,confirmedCommand:i,integrationRef:m})}finally{B()}}),{entries:h,selected:b,pushed:T,pushAborted:k,abortedBy:j,declined:v,verifyFailed:S,handOffs:P}=f,$=await at(u).catch(()=>[]);return dO({entries:h,selected:b,pushed:T,pushAborted:k,abortedBy:j,declined:v,verifyFailed:S,handOffs:P,dryRun:n,worktrees:$,skipped:l,integrationRef:m})},aO=async e=>{let{cwd:t,worktree:r,toPlan:n,candidates:o,skipped:s,all:i,versions:a,dryRun:c,verify:l,keepConflicts:u,confirmedCommand:p,integrationRef:m}=e,f=u?await Ae(t,m):null,h=await Fh({cwd:t,worktreePath:r.path,branches:n,integrationRef:m}),b={entries:h,pushed:!1,pushAborted:!1,declined:!1};if(tO(h,s),c)return{...b,selected:n};let T=await nO({entries:h,toPlan:n,all:i,explicit:a!==void 0});T.length===o.length?y.addOption("--all",!0):y.addOption("--versions",T);let k=h.filter(O=>T.includes(O.branch)&&O.mergeSha).length;k>0&&d.info(`
395
+ \u2139\uFE0F This will push ${k} branch(es), re-running CI on ${k} open PR(s). If the repo dismisses stale approvals on new commits, those PRs lose them.`);try{await H(p,`Are you sure you want to merge ${m} into these branches: ${T.join(", ")}?`,{throwOnDecline:!0,plan:cO(h,T,s)})}catch(O){if(!xt(O))throw O;return{...b,selected:T,declined:!0}}p||y.addOption("--yes",!0);let j=await oO({cwd:t,worktreePath:r.path,entries:h,selected:T,verify:l,integrationRef:m}),v=O=>h.filter(B=>T.includes(B.branch)&&O(B)).map(B=>B.branch),S=v(O=>O.status==="conflict"),P=v(O=>O.status==="merged"&&(j.verifyFailed?.has(O.branch)??!1)),$=u&&f&&S.length+P.length>0?await cy({cwd:t,conflicted:S,verifyFailed:P,devSha:f,integrationRef:m,verify:l}):void 0;return{entries:h,selected:T,declined:!1,...j,handOffs:$}},cO=(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:wu(n.conflictPaths)}:{},...n.reason?{reason:n.reason}:{}})),skipped:r}),lO=(e,t,r)=>e.resolution?`# ${e.branch} \u2014 ${e.status}, left to resolve in ${e.resolution.worktreePath} (then --continue)
387
396
  `:`# ${e.branch} \u2014 ${e.status}
388
- ${HA(e.branch,t)}
389
- `,tO=(e,t)=>e!==void 0&&t?`${e}
390
- hand-off: ${t}`:e??t,rO=e=>{let{entries:t,selected:r,pushed:n,pushAborted:o,abortedBy:s,declined:i,dryRun:a,worktrees:c,verifyFailed:l,handOffs:u,skipped:p}=e,m=new Set(n?t.filter(k=>r.includes(k.branch)&&k.mergeSha&&!l?.has(k.branch)).map(k=>k.branch):[]),f=t.filter(k=>r.includes(k.branch)).map(k=>{let A=!!k.mergeSha,M=l?.has(k.branch)??!1,v=l?.get(k.branch),R=o&&A?"push-aborted":k.status,T=M?"verify-failed":R,E=u?.get(k.branch);return{branch:k.branch,status:T,mergeSha:k.mergeSha,conflictPaths:k.conflictPaths,pushed:m.has(k.branch),reason:tO(v,E?.reason)??k.reason,...E?.resolution?{resolution:E.resolution}:{}}}),h=f.filter(k=>!dd.has(k.status));for(let k of f){let A=t.find(M=>M.branch===k.branch);d.info({branch:k.branch,status:k.status,mergeSha:k.mergeSha,conflictCount:k.conflictPaths?.length??0,durationMs:A?.durationMs,pushed:k.pushed,msg:"merge-dev branch result"})}if(i||a)d.info(i?`
397
+ ${rO(e.branch,t,r)}
398
+ `,uO=(e,t)=>e!==void 0&&t?`${e}
399
+ hand-off: ${t}`:e??t,dO=e=>{let{entries:t,selected:r,pushed:n,pushAborted:o,abortedBy:s,declined:i,dryRun:a,worktrees:c,verifyFailed:l,handOffs:u,skipped:p,integrationRef:m}=e,f=new Set(n?t.filter(k=>r.includes(k.branch)&&k.mergeSha&&!l?.has(k.branch)).map(k=>k.branch):[]),h=t.filter(k=>r.includes(k.branch)).map(k=>{let j=!!k.mergeSha,v=l?.has(k.branch)??!1,S=l?.get(k.branch),P=o&&j?"push-aborted":k.status,$=v?"verify-failed":P,O=u?.get(k.branch);return{branch:k.branch,status:$,mergeSha:k.mergeSha,conflictPaths:k.conflictPaths,pushed:f.has(k.branch),reason:uO(S,O?.reason)??k.reason,...O?.resolution?{resolution:O.resolution}:{}}}),b=h.filter(k=>!vd.has(k.status));for(let k of h){let j=t.find(v=>v.branch===k.branch);d.info({branch:k.branch,status:k.status,mergeSha:k.mergeSha,conflictCount:k.conflictPaths?.length??0,durationMs:j?.durationMs,pushed:k.pushed,msg:"merge-dev branch result"})}if(i||a)d.info(i?`
391
400
  Operation cancelled \u2014 nothing was pushed.
392
401
  `:`
393
402
  \u{1F50D} Dry run \u2014 nothing was pushed.
394
- `);else if(h.length>0){d.info(`
395
- \u26A0\uFE0F ${h.length} branch(es) did not merge.
396
- `);for(let k of h)d.info(eO(k,c))}else d.info(`\u2705 All merges completed successfully!
397
- `);y.print();let S=a||i;return pd({successfulMerges:S?0:f.filter(k=>dd.has(k.status)).length,failedMerges:S?0:h.length,failedBranches:S?[]:h.map(k=>k.branch),totalBranches:f.length,dryRun:a,atomicPush:{attempted:!a&&!i,aborted:o,abortedBy:s},results:f.map(k=>S?{...k,pushed:!1}:k),skipped:p})},md=C({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:x.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:x.union([x.string(),x.array(x.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:x.boolean().optional().describe("Compute and print the merge plan without pushing anything."),verify:x.union([x.boolean(),x.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:x.boolean().optional().describe("On the confirmed run, after the clean branches are pushed, leave each conflicted branch \u2014 and each clean merge that failed `verify` \u2014 mid-merge in a detached worktree under `<root>-worktrees/merge-dev/` for resolution. Excludes `continue`, `abort` and `dryRun`."),continue:x.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:x.boolean().optional().describe("Discard the selected resolution worktrees and their state. Excludes `keepConflicts`, `continue` and `dryRun`."),tree:x.union([x.string(),x.array(x.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:x.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{successfulMerges:x.number().describe("Number of branches that reached their desired state"),failedMerges:x.number().describe("Number of branches that did not"),failedBranches:x.array(x.string()).describe("List of branches that did not merge"),totalBranches:x.number().describe("Total number of branches processed"),dryRun:x.boolean().describe("True when nothing was pushed because this was a plan-only run"),atomicPush:x.object({attempted:x.boolean(),aborted:x.boolean(),abortedBy:x.string().optional()}).describe("Outcome of the single all-or-nothing push"),results:x.array(x.object({branch:x.string(),status:x.string(),mergeSha:x.string().optional(),conflictPaths:x.array(x.string()).optional(),pushed:x.boolean(),reason:x.string().optional(),resolution:x.object({worktreePath:x.string(),baseSha:x.string(),devSha:x.string(),conflictPaths:x.array(x.string()),editablePaths:x.array(x.string()).optional(),lockfileOnly:x.boolean(),rererePreResolved:x.array(x.string()),state:x.enum(["needs-agent","lockfile-only","verify-failed","exists"])}).optional().describe("The `keepConflicts` hand-off for a conflicted branch, or for a clean merge that failed verify (`verify-failed`: edit only `editablePaths`)"),blocked:x.object({code:x.enum(["unmerged-paths","markers-remaining","out-of-scope-edit","verify-failed","verify-mutated-tree","parents-mismatch","git-too-old","tree-changed"]),paths:x.array(x.string()).optional(),detail:x.string()}).optional().describe("Why a `continue` run did not commit this resolution")})).describe("Per-branch terminal state"),skipped:x.array(x.object({branch:x.string(),reason:x.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:ka});import{z as fs}from"zod";import{$ as qe}from"zx";var Gv=(e,t)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-t).trim()},Ar=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=Gv(t.stderr,500);o&&(r.stderr=o);let s=Gv(t.stdout,200);return s&&(r.stdout=s),r};var cs=e=>{let{removed:t,failed:r}=e;if(t.length>0){d.info("\u274C Removed worktrees:");for(let n of t)d.info(n);d.info("")}if(r.length>0){d.warn("\u26A0\uFE0F Not removed:");for(let{branch:n,reason:o}of r)d.warn(`${n} \u2014 ${o}`);d.warn("")}t.length===0&&r.length===0&&d.info("\u2139\uFE0F No worktrees to remove")};var ls=e=>{let{result:t,operation:r}=e,n={removedWorktrees:t.removed,failedWorktrees:t.failed.map(i=>i.branch),count:t.removed.length},o=b(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 he()?new O({status:"partial_failure",...n},1,s):new g(void 0,s)};import ba from"node:fs/promises";import{$ as gd}from"zx";var nO=new Set([".omc",".DS_Store"]),oO=new Set(["state","sessions"]),sO=2e3,qv="check 'git worktree list' for the path; uncommitted changes block removal",iO=e=>new Promise(t=>{setTimeout(t,e)}),fd=e=>typeof e=="object"&&e!==null?e.code:void 0,Jv=e=>{let t=e.length;for(;t>1&&e[t-1]==="/";)t-=1;return e.slice(0,t)},Kv=async e=>{try{return Jv(await ba.realpath(e))}catch{return Jv(e)}},aO=async e=>{let{projectRoot:t,worktreePath:r}=e;try{let n=await st(t),o=await Kv(r);for(let s of n)if(await Kv(s.path)===o)return!0;return!1}catch{return!0}},cO=async e=>{let t;try{t=await ba.readdir(e)}catch(n){return{kind:fd(n)==="ENOENT"?"gone":"not-sweepable",entries:[]}}if(!t.every(n=>nO.has(n)))return{kind:"not-sweepable",entries:t};if(!t.includes(".omc"))return{kind:"sweepable",entries:t};try{return{kind:(await ba.readdir(`${e}/.omc`)).every(s=>oO.has(s))?"sweepable":"not-sweepable",entries:t}}catch(n){return{kind:fd(n)==="ENOENT"?"sweepable":"not-sweepable",entries:t}}},Hv=async e=>{try{return await ba.rm(e,{recursive:!0,force:!0}),"removed"}catch(t){return fd(t)==="ENOTEMPTY"?"busy":"failed"}},lO=async e=>{let{worktreePath:t,sleep:r}=e,n=await Hv(t);return n!=="busy"?n==="removed":(await r(sO),await Hv(t)==="removed")},us=(e,t,r)=>{let n=new g(t,{operation:`remove worktree for ${e}`,remediation:r});return d.error({error:t,branch:e,msg:n.message}),{branch:e,status:"failed",reason:n.message}},uO=async e=>{let{branch:t,worktreePath:r,projectRoot:n,error:o,sleep:s}=e;if(await aO({projectRoot:n,worktreePath:r}))return us(t,o,qv);let i=await cO(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 lO({worktreePath:r,sleep:s})?us(t,o,a):(d.warn(`\u26A0\uFE0F swept leftover ${i.entries.join(", ")} from ${r}: a post-exit hook (e.g. oh-my-claudecode SessionEnd) wrote into the worktree while git was deleting it; set OMC_STATE_DIR to keep tool state out of worktrees`),{branch:t,status:"removed"})},dO=async e=>{try{return(await gd`git -C ${e} status --porcelain`).stdout.split(`
398
- `).filter(r=>r.trim().length>0)}catch{return[]}},pO=async e=>{let{branch:t,worktreeDir:r,projectRoot:n,orcaProbe:o,sleep:s}=e,i=`${r}/${t}`,a=await dO(i);if(a.length>0)return us(t,new Error(`uncommitted changes in ${i}: ${a.slice(0,5).join(", ")}`),qv);let c=await Uf(i,o);if(!c.closed&&"error"in c)return us(t,c.error,"close the Orca terminals of this worktree manually (orca terminal close --terminal <handle>) and re-run");try{return await gd`git worktree remove ${i}`,{branch:t,status:"removed"}}catch(l){return uO({branch:t,worktreePath:i,projectRoot:n,error:l,sleep:s})}},Or=async e=>{let{branches:t,worktreeDir:r,projectRoot:n,pruneFolder:o=!1,sleep:s=iO}=e,i=t.length>0?await Wt():"unreachable",a=await Promise.all(t.map(l=>pO({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 gd`git worktree prune`,c};var ds=async(e,t)=>{if(!(await be("release")).includes(e))return[];let n=await $(),o=`${n}${ge}`,{removed:s,failed:i}=await Or({branches:[e],worktreeDir:o,projectRoot:n});if(!s.includes(e)){let a=i.find(c=>c.branch===e);throw new g(void 0,{...t,stderrExcerpt:a?.reason})}return s};import{$ as hd}from"zx";var ps=async(e,t)=>{let r=await hd({quiet:!0,nothrow:!0})`git merge-tree --write-tree --name-only --no-messages ${e} ${t}`;if(r.exitCode!==0&&r.exitCode!==1)throw new g(new Error(r.stderr),{operation:`rehearse merging ${t} into ${e}`,remediation:"git merge-tree --write-tree needs git >= 2.38; check `git --version` and that both refs exist"});let[n="",...o]=r.stdout.trim().split(`
399
- `);return{tree:n,conflicts:r.exitCode===1?[...new Set(o.filter(Boolean))]:[]}},Yv=async(e,t)=>(await hd({quiet:!0})`git commit-tree ${e} -p ${t} -m ${"infra-kit deliver preflight"}`).stdout.trim(),ms=(e,t)=>{if(t.conflicts.length!==0)throw new g(void 0,{operation:`deliver: ${e} would conflict`,remediation:`resolve the conflicts in ${t.conflicts.join(", ")}, push, then re-run`})},zv=async e=>{let{releaseBranch:t,releaseType:r,releaseMerged:n,rcMerged:o}=e,s=`origin/${t}`;if(await hd({quiet:!0})`git fetch origin main dev ${n?[]:[t]}`,r==="hotfix"){let a="origin/main";if(!n){let c=await ps("origin/main",s);ms(`merging ${t} into main`,c),a=await Yv(c.tree,"origin/main")}ms("syncing main back into dev",await ps("origin/dev",a));return}let i="origin/dev";if(!n){let a=await ps("origin/dev",s);ms(`merging ${t} into dev`,a),i=await Yv(a.tree,"origin/dev")}o?ms("syncing main back into dev",await ps(i,"origin/main")):ms("merging dev into main (RC PR)",await ps("origin/main",i))};var jn=async(e,t,r)=>{try{return await r()}catch(n){throw d.debug({err:Ar(n)},`Failed to ${e}`),new g(n,{operation:e,remediation:t})}},Zv=async e=>{let t=xc(e),r=await qe`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},Xv=async()=>{let e=await qe`gh pr list --head dev --base main --state open --json number,state,title,baseRefName,headRefName --limit 5`;return JSON.parse(e.stdout)[0]??null},mO=async e=>{let t=Ot(e),r=await Ql(t);if(r.length>1){let s=r.map(i=>`#${i.number} \u2192 ${i.baseRefName}`).join(", ");throw new g(void 0,{operation:`deliver release ${t}`,remediation:`the branch has open PRs to both dev and main (${s}); close the one that should not be delivered`})}let n=r[0]??await ln(t);if(!n)throw d.error(`\u274C No PR found for branch ${t}.`),new g(void 0,{operation:`deliver release ${t}`,remediation:`confirm a PR exists ('gh pr list --head ${t} --state all')`});let o=Do(n.baseRefName);if(!o)throw new g(void 0,{operation:`deliver release ${t}`,remediation:`PR #${n.number} targets '${n.baseRefName}', which is neither dev nor main; retarget it ('gh pr edit ${n.number} --base <dev|main>')`});return{selectedReleaseBranch:t,releaseType:o,prNumber:n.number}},fO=async()=>{let e=await G(),t=e.map(i=>i.branch),r=new Map(e.map(i=>[i.branch,i.type]));y.setInteractive();let n=await me(),o=await qt(fe({branches:t,descriptions:n,types:r})),s=e.find(i=>i.branch===o);if(!s)throw d.error(`\u274C Release branch ${o} not found in open PRs.`),new g(void 0,{operation:`deliver release ${o}`,remediation:`confirm an open PR exists for ${o} ('gh pr list')`});if(s.dualBase)throw new g(void 0,{operation:`deliver release ${o}`,remediation:"the branch has open PRs to both dev and main; close the one that should not be delivered"});return{selectedReleaseBranch:o,releaseType:s.type,prNumber:s.number}},gO=async e=>{let{selectedReleaseBranch:t,releaseType:r,prNumber:n}=e,o=mt(r),s=await Ui(n);if(s.state==="MERGED"){d.info(`\u2713 Release PR ${t} already merged \u2014 skipping`);return}if(s.state==="CLOSED")throw new g(void 0,{operation:`merge release PR ${t} into ${o}`,remediation:"the PR is closed without merge; reopen it or create a new release"});if(s.baseRefName!==o||s.headRefName!==t)throw new g(void 0,{operation:`merge release PR #${n} ${t} into ${o}`,remediation:`PR #${n} now reads ${s.headRefName} \u2192 ${s.baseRefName}; it changed since it was resolved \u2014 re-run the command`});await jn(`merge release PR #${n} ${t} into ${o}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await qe`gh pr merge ${n} --squash --admin --delete-branch`})},hO=async e=>{let t=ne(e),r=xc(e),n=await Xv();if(n){let s=n.number;return n.title!==r&&(d.info(`Adopting open dev \u2192 main PR #${s} ("${n.title}") and retitling for ${t}`),await jn(`retitle dev \u2192 main PR #${s} to "${r}"`,`update manually: gh pr edit ${s} --title "${r}"`,async()=>{await qe`gh pr edit ${s} --title ${r}`})),s}await jn(`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 qe`gh pr create --base main --head dev --title ${r} --body ""`});let o=await Xv();if(!o)throw new g(void 0,{operation:`look up RC PR for ${t}`,remediation:"verify the RC PR was created ('gh pr list --head dev --base main')"});return o.number},yO=async e=>{let t=ne(e);if(await Zv(e)){d.info(`\u2713 RC PR for ${t} already merged into main \u2014 skipping`);return}let n=await hO(e);await jn(`merge RC PR #${n} (dev \u2192 main) for ${t}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await qe`gh pr merge ${n} --squash --admin`})},vO=async()=>{qe.quiet=!1,await jn("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await qe`gh workflow run deploy-all.yml --ref main -f environment=prod`}),qe.quiet=!0},wO=async()=>{await jn("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 qe`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},kO=async e=>{try{await ni(e)}catch(t){d.warn({err:Ar(t)},`Failed to delete local branch ${e} (non-blocking)`)}try{await oi(e)}catch(t){d.warn({err:Ar(t)},`Failed to delete remote branch ${e} (non-blocking)`)}},bO=async e=>{let t=await At();if(!t){d.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let r=le(e);await tu({versionName:r},t)}catch(r){let n=No(r)&&r.kind==="auth"?" \u2014 reissue the Atlassian API token and update JIRA_TOKEN":"";d.error({err:Ar(r)},`Failed to deliver Jira release (non-blocking)${n}`)}},Ra=async e=>{let{version:t,confirmedCommand:r}=e;await _e({operation:"deliver release"});let{selectedReleaseBranch:n,releaseType:o,prNumber:s}=t?await mO(t):await fO(),i=Q(n);if(!i)throw new g(void 0,{operation:`deliver release ${n}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let a=ne(i);if(y.addOption("--version",a),d.info(`Delivering ${i.kind==="name"?"named release":"version"} ${n}`),he())throw new O({status:"refused",agentMode:j.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 zv({releaseBranch:n,releaseType:o,releaseMerged:(await Ui(s)).state==="MERGED",rcMerged:o!=="hotfix"&&await Zv(i)!==null}),await J(r,`Are you sure you want to deliver version ${n} to production?`),y.addOption("--yes",!0),qe.quiet=!0;let l=`${await $()}${ge}`;await ds(n,{operation:`remove worktree for ${n} before merge`,remediation:`run manually: git worktree remove ${l}/${n} (use --force if uncommitted changes)`}),await gO({selectedReleaseBranch:n,releaseType:o,prNumber:s}),o!=="hotfix"&&await yO(i),await vO(),await wO(),await kO(n),qe.quiet=!1,await bO(i),d.info(`Successfully delivered ${n} to production!`),y.print();let u={releaseBranch:n,version:a,type:o,success:!0};return{content:b(JSON.stringify(u,null,2)),structuredContent:u}},yd=C({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:fs.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:fs.string().describe("The release branch that was delivered"),version:fs.string().describe("The version that was delivered"),type:fs.enum(["regular","hotfix"]).describe("Release type"),success:fs.boolean().describe("Whether the delivery was successful")},handler:Ra});import{z as Nt}from"zod";import{$ as Id}from"zx";import{z as ws}from"zod";import cw from"node:fs/promises";import Pd from"node:path";import{DEPLOY_CONFIG_FILE as Sa,deployConfigSchema as RO}from"@slip-stream-kit/config/internal";import SO from"node:fs/promises";import EO from"node:path";import{pathToFileURL as PO}from"node:url";import{z as xO}from"zod";var vt=async e=>{let t=EO.join(e,Sa);try{await SO.access(t)}catch{return}let r=await import(PO(t).href);if(r.default===void 0)throw new Error(`${Sa} at ${t} has no default export`);let n=RO.safeParse(r.default);if(!n.success)throw new Error(`Invalid ${Sa} at ${t}:
400
- ${xO.prettifyError(n.error)}`);let o=[...CO(n.data),...TO(n.data)];if(o.length>0)throw new Error(`Invalid ${Sa} at ${t}:
403
+ `);else if(b.length>0){d.info(`
404
+ \u26A0\uFE0F ${b.length} branch(es) did not merge.
405
+ `);for(let k of b)d.info(lO(k,c,m))}else d.info(`\u2705 All merges completed successfully!
406
+ `);y.print();let T=a||i;return wd({successfulMerges:T?0:h.filter(k=>vd.has(k.status)).length,failedMerges:T?0:b.length,failedBranches:T?[]:b.map(k=>k.branch),totalBranches:h.length,dryRun:a,atomicPush:{attempted:!a&&!i,aborted:o,abortedBy:s},results:h.map(k=>T?{...k,pushed:!1}:k),skipped:p})},kd=C({name:"gh-merge-dev",description:'Merge origin/dev (origin/main in a repo with "gitFlow": "main") 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:x.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:x.union([x.string(),x.array(x.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:x.boolean().optional().describe("Compute and print the merge plan without pushing anything."),verify:x.union([x.boolean(),x.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:x.boolean().optional().describe("On the confirmed run, after the clean branches are pushed, leave each conflicted branch \u2014 and each clean merge that failed `verify` \u2014 mid-merge in a detached worktree under `<root>-worktrees/merge-dev/` for resolution. Excludes `continue`, `abort` and `dryRun`."),continue:x.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:x.boolean().optional().describe("Discard the selected resolution worktrees and their state. Excludes `keepConflicts`, `continue` and `dryRun`."),tree:x.union([x.string(),x.array(x.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:x.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{successfulMerges:x.number().describe("Number of branches that reached their desired state"),failedMerges:x.number().describe("Number of branches that did not"),failedBranches:x.array(x.string()).describe("List of branches that did not merge"),totalBranches:x.number().describe("Total number of branches processed"),dryRun:x.boolean().describe("True when nothing was pushed because this was a plan-only run"),atomicPush:x.object({attempted:x.boolean(),aborted:x.boolean(),abortedBy:x.string().optional()}).describe("Outcome of the single all-or-nothing push"),results:x.array(x.object({branch:x.string(),status:x.string(),mergeSha:x.string().optional(),conflictPaths:x.array(x.string()).optional(),pushed:x.boolean(),reason:x.string().optional(),resolution:x.object({worktreePath:x.string(),baseSha:x.string(),devSha:x.string(),conflictPaths:x.array(x.string()),editablePaths:x.array(x.string()).optional(),lockfileOnly:x.boolean(),rererePreResolved:x.array(x.string()),state:x.enum(["needs-agent","lockfile-only","verify-failed","exists"])}).optional().describe("The `keepConflicts` hand-off for a conflicted branch, or for a clean merge that failed verify (`verify-failed`: edit only `editablePaths`)"),blocked:x.object({code:x.enum(["unmerged-paths","markers-remaining","out-of-scope-edit","verify-failed","verify-mutated-tree","parents-mismatch","git-too-old","tree-changed"]),paths:x.array(x.string()).optional(),detail:x.string()}).optional().describe("Why a `continue` run did not commit this resolution")})).describe("Per-branch terminal state"),skipped:x.array(x.object({branch:x.string(),reason:x.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:Ea});import{z as ws}from"zod";import{$ as ze}from"zx";var Yv=(e,t)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-t).trim()},Nr=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=Yv(t.stderr,500);o&&(r.stderr=o);let s=Yv(t.stdout,200);return s&&(r.stdout=s),r};var ms=e=>{let{removed:t,failed:r}=e;if(t.length>0){d.info("\u274C Removed worktrees:");for(let n of t)d.info(n);d.info("")}if(r.length>0){d.warn("\u26A0\uFE0F Not removed:");for(let{branch:n,reason:o}of r)d.warn(`${n} \u2014 ${o}`);d.warn("")}t.length===0&&r.length===0&&d.info("\u2139\uFE0F No worktrees to remove")};var fs=e=>{let{result:t,operation:r}=e,n={removedWorktrees:t.removed,failedWorktrees:t.failed.map(i=>i.branch),count:t.removed.length},o=R(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 D({status:"partial_failure",...n},1,s):new g(void 0,s)};import Pa from"node:fs/promises";import{$ as Rd}from"zx";var pO=new Set([".omc",".DS_Store"]),mO=new Set(["state","sessions"]),fO=2e3,Qv="check 'git worktree list' for the path; uncommitted changes block removal",gO=e=>new Promise(t=>{setTimeout(t,e)}),bd=e=>typeof e=="object"&&e!==null?e.code:void 0,zv=e=>{let t=e.length;for(;t>1&&e[t-1]==="/";)t-=1;return e.slice(0,t)},Xv=async e=>{try{return zv(await Pa.realpath(e))}catch{return zv(e)}},hO=async e=>{let{projectRoot:t,worktreePath:r}=e;try{let n=await at(t),o=await Xv(r);for(let s of n)if(await Xv(s.path)===o)return!0;return!1}catch{return!0}},yO=async e=>{let t;try{t=await Pa.readdir(e)}catch(n){return{kind:bd(n)==="ENOENT"?"gone":"not-sweepable",entries:[]}}if(!t.every(n=>pO.has(n)))return{kind:"not-sweepable",entries:t};if(!t.includes(".omc"))return{kind:"sweepable",entries:t};try{return{kind:(await Pa.readdir(`${e}/.omc`)).every(s=>mO.has(s))?"sweepable":"not-sweepable",entries:t}}catch(n){return{kind:bd(n)==="ENOENT"?"sweepable":"not-sweepable",entries:t}}},Zv=async e=>{try{return await Pa.rm(e,{recursive:!0,force:!0}),"removed"}catch(t){return bd(t)==="ENOTEMPTY"?"busy":"failed"}},vO=async e=>{let{worktreePath:t,sleep:r}=e,n=await Zv(t);return n!=="busy"?n==="removed":(await r(fO),await Zv(t)==="removed")},gs=(e,t,r)=>{let n=new g(t,{operation:`remove worktree for ${e}`,remediation:r});return d.error({error:t,branch:e,msg:n.message}),{branch:e,status:"failed",reason:n.message}},wO=async e=>{let{branch:t,worktreePath:r,projectRoot:n,error:o,sleep:s}=e;if(await hO({projectRoot:n,worktreePath:r}))return gs(t,o,Qv);let i=await yO(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 vO({worktreePath:r,sleep:s})?gs(t,o,a):(d.warn(`\u26A0\uFE0F swept leftover ${i.entries.join(", ")} from ${r}: a post-exit hook (e.g. oh-my-claudecode SessionEnd) wrote into the worktree while git was deleting it; set OMC_STATE_DIR to keep tool state out of worktrees`),{branch:t,status:"removed"})},kO=async e=>{try{return(await Rd`git -C ${e} status --porcelain`).stdout.split(`
407
+ `).filter(r=>r.trim().length>0)}catch{return[]}},bO=async e=>{let{branch:t,worktreeDir:r,projectRoot:n,orcaProbe:o,sleep:s}=e,i=`${r}/${t}`,a=await kO(i);if(a.length>0)return gs(t,new Error(`uncommitted changes in ${i}: ${a.slice(0,5).join(", ")}`),Qv);let c=await qf(i,o);if(!c.closed&&"error"in c)return gs(t,c.error,"close the Orca terminals of this worktree manually (orca terminal close --terminal <handle>) and re-run");try{return await Rd`git worktree remove ${i}`,{branch:t,status:"removed"}}catch(l){return wO({branch:t,worktreePath:i,projectRoot:n,error:l,sleep:s})}},_r=async e=>{let{branches:t,worktreeDir:r,projectRoot:n,pruneFolder:o=!1,sleep:s=gO}=e,i=t.length>0?await Vt():"unreachable",a=await Promise.all(t.map(l=>bO({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 Rd`git worktree prune`,c};var hs=async(e,t)=>{if(!(await Se("release")).includes(e))return[];let n=await A(),o=`${n}${he}`,{removed:s,failed:i}=await _r({branches:[e],worktreeDir:o,projectRoot:n});if(!s.includes(e)){let a=i.find(c=>c.branch===e);throw new g(void 0,{...t,stderrExcerpt:a?.reason})}return s};import{$ as Sd}from"zx";var ys=async(e,t)=>{let r=await Sd({quiet:!0,nothrow:!0})`git merge-tree --write-tree --name-only --no-messages ${e} ${t}`;if(r.exitCode!==0&&r.exitCode!==1)throw new g(new Error(r.stderr),{operation:`rehearse merging ${t} into ${e}`,remediation:"git merge-tree --write-tree needs git >= 2.38; check `git --version` and that both refs exist"});let[n="",...o]=r.stdout.trim().split(`
408
+ `);return{tree:n,conflicts:r.exitCode===1?[...new Set(o.filter(Boolean))]:[]}},ew=async(e,t)=>(await Sd({quiet:!0})`git commit-tree ${e} -p ${t} -m ${"infra-kit deliver preflight"}`).stdout.trim(),vs=(e,t)=>{if(t.conflicts.length!==0)throw new g(void 0,{operation:`deliver: ${e} would conflict`,remediation:`resolve the conflicts in ${t.conflicts.join(", ")}, push, then re-run`})},tw=async e=>{let{releaseBranch:t,viaIntegration:r,syncsDev:n,releaseMerged:o,rcMerged:s}=e,i=`origin/${t}`;if(await Sd({quiet:!0})`git fetch origin main ${n?["dev"]:[]} ${o?[]:[t]}`,!r){let c="origin/main";if(!o){let l=await ys("origin/main",i);vs(`merging ${t} into main`,l),c=await ew(l.tree,"origin/main")}n&&vs("syncing main back into dev",await ys("origin/dev",c));return}let a="origin/dev";if(!o){let c=await ys("origin/dev",i);vs(`merging ${t} into dev`,c),a=await ew(c.tree,"origin/dev")}s?vs("syncing main back into dev",await ys(a,"origin/main")):vs("merging dev into main (RC PR)",await ys("origin/main",a))};var Wn=async(e,t,r)=>{try{return await r()}catch(n){throw d.debug({err:Nr(n)},`Failed to ${e}`),new g(n,{operation:e,remediation:t})}},nw=async e=>{let t=Ac(e),r=await ze`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},rw=async()=>{let e=await ze`gh pr list --head dev --base main --state open --json number,state,title,baseRefName,headRefName --limit 5`;return JSON.parse(e.stdout)[0]??null},RO=async(e,t)=>{let r=It(e),n=await su(r);if(n.length>1){let i=n.map(a=>`#${a.number} \u2192 ${a.baseRefName}`).join(", ");throw new g(void 0,{operation:`deliver release ${r}`,remediation:`the branch has open PRs to both dev and main (${i}); close the one that should not be delivered`})}let o=n[0]??await mn(r);if(!o)throw d.error(`\u274C No PR found for branch ${r}.`),new g(void 0,{operation:`deliver release ${r}`,remediation:`confirm a PR exists ('gh pr list --head ${r} --state all')`});let s=jo(o.baseRefName,t);if(!s){let i=t==="dev"?"dev nor main":`${ve} (this repo's "gitFlow": "main")`,a=t==="dev"?"<dev|main>":ve;throw new g(void 0,{operation:`deliver release ${r}`,remediation:`PR #${o.number} targets '${o.baseRefName}', which is ${t==="dev"?"neither":"not"} ${i}; retarget it ('gh pr edit ${o.number} --base ${a}')`})}return{selectedReleaseBranch:r,releaseType:s,prNumber:o.number}},SO=async()=>{let e=await K(),t=e.map(i=>i.branch),r=new Map(e.map(i=>[i.branch,i.type]));y.setInteractive();let n=await fe(),o=await zt(ge({branches:t,descriptions:n,types:r})),s=e.find(i=>i.branch===o);if(!s)throw d.error(`\u274C Release branch ${o} not found in open PRs.`),new g(void 0,{operation:`deliver release ${o}`,remediation:`confirm an open PR exists for ${o} ('gh pr list')`});if(s.dualBase)throw new g(void 0,{operation:`deliver release ${o}`,remediation:"the branch has open PRs to both dev and main; close the one that should not be delivered"});return{selectedReleaseBranch:o,releaseType:s.type,prNumber:s.number}},EO=async e=>{let{selectedReleaseBranch:t,releaseType:r,prNumber:n,flow:o}=e,s=gt(r,o),i=await Ji(n);if(i.state==="MERGED"){d.info(`\u2713 Release PR ${t} already merged \u2014 skipping`);return}if(i.state==="CLOSED")throw new g(void 0,{operation:`merge release PR ${t} into ${s}`,remediation:"the PR is closed without merge; reopen it or create a new release"});if(i.baseRefName!==s||i.headRefName!==t)throw new g(void 0,{operation:`merge release PR #${n} ${t} into ${s}`,remediation:`PR #${n} now reads ${i.headRefName} \u2192 ${i.baseRefName}; it changed since it was resolved \u2014 re-run the command`});await Wn(`merge release PR #${n} ${t} into ${s}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await ze`gh pr merge ${n} --squash --admin --delete-branch`})},PO=async e=>{let t=oe(e),r=Ac(e),n=await rw();if(n){let s=n.number;return n.title!==r&&(d.info(`Adopting open dev \u2192 main PR #${s} ("${n.title}") and retitling for ${t}`),await Wn(`retitle dev \u2192 main PR #${s} to "${r}"`,`update manually: gh pr edit ${s} --title "${r}"`,async()=>{await ze`gh pr edit ${s} --title ${r}`})),s}await Wn(`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 ze`gh pr create --base main --head dev --title ${r} --body ""`});let o=await rw();if(!o)throw new g(void 0,{operation:`look up RC PR for ${t}`,remediation:"verify the RC PR was created ('gh pr list --head dev --base main')"});return o.number},xO=async e=>{let t=oe(e);if(await nw(e)){d.info(`\u2713 RC PR for ${t} already merged into main \u2014 skipping`);return}let n=await PO(e);await Wn(`merge RC PR #${n} (dev \u2192 main) for ${t}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await ze`gh pr merge ${n} --squash --admin`})},TO=async()=>{ze.quiet=!1,await Wn("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await ze`gh workflow run deploy-all.yml --ref main -f environment=prod`}),ze.quiet=!0},CO=async()=>{await Wn("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 ze`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},$O=async e=>{try{await ai(e)}catch(t){d.warn({err:Nr(t)},`Failed to delete local branch ${e} (non-blocking)`)}try{await ci(e)}catch(t){d.warn({err:Nr(t)},`Failed to delete remote branch ${e} (non-blocking)`)}},AO=async e=>{let t=await Dt();if(!t){d.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let r=ue(e);await au({versionName:r},t)}catch(r){let n=Lo(r)&&r.kind==="auth"?" \u2014 reissue the Atlassian API token and update JIRA_TOKEN":"";d.error({err:Nr(r)},`Failed to deliver Jira release (non-blocking)${n}`)}},xa=async e=>{let{version:t,confirmedCommand:r}=e;await je({operation:"deliver release"});let n=await te(),{selectedReleaseBranch:o,releaseType:s,prNumber:i}=t?await RO(t,n):await SO(),a=n==="dev"&&s!=="hotfix",c=ee(o);if(!c)throw new g(void 0,{operation:`deliver release ${o}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let l=oe(c);if(y.addOption("--version",l),d.info(`Delivering ${c.kind==="name"?"named release":"version"} ${o}`),ye())throw new D({status:"refused",agentMode:F.source},2,{operation:`deliver release ${o}`,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 tw({releaseBranch:o,viaIntegration:a,syncsDev:n==="dev",releaseMerged:(await Ji(i)).state==="MERGED",rcMerged:a&&await nw(c)!==null}),await H(r,`Are you sure you want to deliver version ${o} to production?`),y.addOption("--yes",!0),ze.quiet=!0;let p=`${await A()}${he}`;await hs(o,{operation:`remove worktree for ${o} before merge`,remediation:`run manually: git worktree remove ${p}/${o} (use --force if uncommitted changes)`}),await EO({selectedReleaseBranch:o,releaseType:s,prNumber:i,flow:n}),a&&await xO(c),await TO(),n==="dev"&&await CO(),await $O(o),ze.quiet=!1,await AO(c),d.info(`Successfully delivered ${o} to production!`),y.print();let m={releaseBranch:o,version:l,type:s,success:!0};return{content:R(JSON.stringify(m,null,2)),structuredContent:m}},Ed=C({name:"gh-release-deliver",description:'Deliver a release to production. For hotfixes, and for every release in a repo with "gitFlow": "main" (no dev branch, no RC PR, no back-sync): 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:ws.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:ws.string().describe("The release branch that was delivered"),version:ws.string().describe("The version that was delivered"),type:ws.enum(["regular","hotfix"]).describe("Release type"),success:ws.boolean().describe("Whether the delivery was successful")},handler:xa});import{z as Mt}from"zod";import{$ as Bd}from"zx";import{z as Es}from"zod";import mw from"node:fs/promises";import Dd from"node:path";import{DEPLOY_CONFIG_FILE as Ta,deployConfigSchema as OO}from"@slip-stream-kit/config/internal";import DO from"node:fs/promises";import IO from"node:path";import{pathToFileURL as NO}from"node:url";import{z as _O}from"zod";var kt=async e=>{let t=IO.join(e,Ta);try{await DO.access(t)}catch{return}let r=await import(NO(t).href);if(r.default===void 0)throw new Error(`${Ta} at ${t} has no default export`);let n=OO.safeParse(r.default);if(!n.success)throw new Error(`Invalid ${Ta} at ${t}:
409
+ ${_O.prettifyError(n.error)}`);let o=[...jO(n.data),...MO(n.data)];if(o.length>0)throw new Error(`Invalid ${Ta} at ${t}:
401
410
  ${o.join(`
402
- `)}`);return n.data},TO=e=>e.replaceV1!==!0?[]:Fc.filter(t=>!e.environments.includes(t)).map(t=>`\u2716 replaceV1: environments must include '${t}', which delivery dispatches deploy-all.yml with`),CO=e=>{let t=new Set([...e.environments,...Fc]);return Object.entries(e.services).flatMap(([r,n])=>["envs","skipEnvs"].flatMap(o=>(n[o]??[]).filter(s=>!t.has(s)).map(s=>`\u2716 services.${r}.${o}: unknown environment '${s}' (known: ${[...t].join(", ")})`)))};var gs=e=>{let t=new Map;for(let[r,n]of Object.entries(e.services)){if(n.envs!==void 0){t.set(r,[...n.envs]);continue}let o=n.skipEnvs??[],s=e.environments.filter(i=>!o.includes(i));s.length<e.environments.length&&t.set(r,s)}return t};import{serviceDependencies as $O}from"@slip-stream-kit/config/internal";var rw="28aac6de980c6073d37a872c78309134bf62c47c",nw=`ArthurSaenz/infra-kit/.github/workflows/ik-deploy-service.yml@${rw}`,AO=`ArthurSaenz/infra-kit/.github/workflows/ik-install-deps.yml@${rw}`,Ta="install-deps",Qv=25,Fn="# Generated by `infra-kit deploy-sync` from infra-kit.deploy.ts",Ca="skip_terraform_deploy",ow={pilot:{all:{file:"deploy-all-v2.yml",title:"91 \u{1F9EA} Deploy all (v2)",concurrency:"deploy-all"},selected:{file:"deploy-selected-v2.yml",title:"92 \u{1F9EA} Deploy selected (v2)",concurrency:"deploy-selected"}},v1:{all:{file:"deploy-all.yml",title:"01 \u2699\uFE0F Deploy all",concurrency:"deploy-all"},selected:{file:"deploy-selected-services.yml",title:"02 \u2699\uFE0F Deploy selected services",concurrency:"deploy-selected"}}},sw=(e,t)=>ow[e.replaceV1===!0?"v1":"pilot"][t],iw=e=>Object.values(ow[e]).map(({file:t})=>`.github/workflows/${t}`),vd=iw("pilot"),wd=iw("v1"),Pa=e=>e.replace(/^_/,"").replace(/(?:-jobs)?\.ya?ml$/,""),OO=(e,t)=>{let r=Object.entries(e.services).flatMap(([o,s])=>{if(t==="all"&&s.deployAll===!1)return[];let i=t==="all"&&Array.isArray(s.deployAll)?s.deployAll:void 0,a=e.environments.filter(c=>(s.envs?.includes(c)??!0)&&!(s.skipEnvs?.includes(c)??!1)&&(i?.includes(c)??!0));return a.length===0?[]:[{name:o,service:s,gate:a.length===e.environments.length?void 0:a,triggers:void 0}]}),n=new Set(r.map(o=>o.name));return r.flatMap(o=>{if(o.service.runsBefore===void 0)return[o];let s=o.service.runsBefore.filter(i=>n.has(i));return s.length===0?[]:[{...o,triggers:s}]})},kd=e=>e.filter(t=>t.triggers===void 0),Y=e=>`\${{ ${e} }}`,Ea=e=>Y(`secrets[format('{0}_${e}', inputs.environment)]`),DO=e=>[Ta,...e.terraform,...e.preDeploy],bd=e=>e.map(t=>`(needs.${t}.result == 'success' || needs.${t}.result == 'skipped')`),IO=e=>[`needs.${Ta}.result == 'success'`,...bd(e.terraform),...e.preDeploy.map(t=>`needs.${t}.result == 'success'`)],NO=(e,t,r,n)=>{let o=[];return t==="selected"&&o.push(e.triggers===void 0?`inputs.${e.name}`:`(${e.triggers.map(s=>`inputs.${s}`).join(" || ")})`),e.gate!==void 0&&o.push(`contains(fromJSON('${JSON.stringify(e.gate)}'), inputs.environment)`),o.push("!cancelled()",...IO(r),...bd(n.map(xa))),Y(o.join(" && "))},xa=e=>`deploy-${e}`,Rd=e=>e.length===0?[]:[` needs: [ ${e.join(", ")} ]`],aw=e=>e===void 0?[]:[` if: ${e}`],Sd=e=>[` uses: ./.github/workflows/${e}`," with:",` branch: ${Y("github.ref")}`,` environment: ${Y("inputs.environment")}`," secrets: inherit"],_O=(e,t)=>{let r=t.extraEnv??[],n=e.service.runner===void 0?[]:[` runner: ${e.service.runner}`],o=t.deployTimeoutMinutes===void 0?[]:[` timeout-minutes: ${t.deployTimeoutMinutes}`],s=r.length===0?[]:[" extra-env: |",...r.map(i=>{let a=Y(`secrets.${i}`);return` ${i}=${a}`})];return[` uses: ${nw}`," with:",` environment: ${Y("inputs.environment")}`,` ref: ${Y("github.ref")}`,` sha: ${Y("github.sha")}`,` service: ${e.name}`,` infra-kit-version: ${L.version}`,...n,...o,...t.doppler===void 0?[]:[` doppler-project: ${t.doppler.project}`]," secrets:",...t.doppler===void 0?[` aws-access-key-id: ${Ea("AWS_ACCESS_KEY_ID")}`,` aws-secret-access-key: ${Ea("AWS_SECRET_ACCESS_KEY")}`,` aws-region: ${Ea("AWS_REGION")}`]:[` doppler-token: ${Ea("DOPPLER_TOKEN")}`],` serverless-access-key: ${Y("secrets.SERVERLESS_ACCESS_KEY")}`,` slack-token: ${Y("secrets.SLACK_TOKEN")}`,` slack-channel: ${Y("secrets.SLACK_CHANNEL")}`,...s]},MO=(e,t,r,n,o)=>{let s=e.service.workflow===void 0?_O(e,n):Sd(e.service.workflow);return["",` ${xa(e.name)}:`,...Rd([...DO(r),...o.map(xa)]),...aw(NO(e,t,r,o)),...s]},ew=(e,t)=>["",` ${e}:`," type: boolean",` description: '${t}'`," required: false"," default: false"],jO=(e,t,r)=>{let n=[" environment:"," type: choice"," description: 'Environment for deploy'"," required: true",` default: '${e.defaultEnvironment??e.environments[0]}'`," options:",...e.environments.map(i=>` - ${i}`)],o=(e.terraform??[]).length>0?ew(Ca,"Skip terraform deployment"):[],s=t==="all"?[]:kd(r).flatMap(i=>{let a=i.gate===void 0?"":` (${i.gate.join(", ")} only)`;return ew(i.name,`Deploy ${i.name}${a}`)});return["on:"," workflow_dispatch:"," inputs:",...n,...o,...s]},FO=e=>kd(e).map(t=>Y(`inputs.${t.name} && ''${t.name} '' || ''''`)).join(""),LO=(e,t,r)=>{let{title:n,concurrency:o}=sw(e,t),s=(e.terraform??[]).length>0?Y(`inputs.${Ca} && '' \u2014 skip TF'' || ''''`):"",i=t==="selected"?` \u2014 ${FO(r)}`:"";return[`${Fn}: edit that file and re-run the command,`,"# a hand edit here is overwritten.",`name: '${n}'`,`run-name: '${n} [${Y("inputs.environment")}]${s}${i}'`,"",`# The v1 ${t==="all"?"deploy-all":"deploy-selected"} group: two runs of this kind, v1 or v2, never deploy into one`,"# environment at once.","concurrency:",` group: ${o}-${Y("inputs.environment")}`," # false: a cancelled run would also kill an in-flight terraform apply."," cancel-in-progress: false",""]},BO=e=>{let t=Y(`!inputs.${Ca}`);return["",` ${Pa(e)}:`,` if: ${t}`,...Sd(e)]},UO=(e,t)=>{let r=t.length===0?void 0:Y(["!cancelled()",...bd(t)].join(" && "));return["",` ${Pa(e)}:`,...Rd(t),...aw(r),...Sd(e)]},WO=()=>["",` ${Ta}:`,` uses: ${AO}`," with:",` ref: ${Y("github.ref")}`,` sha: ${Y("github.sha")}`," secrets:",` slack-token: ${Y("secrets.SLACK_TOKEN")}`,` slack-channel: ${Y("secrets.SLACK_CHANNEL")}`],VO=(e,t)=>{let r=new Set;for(let n of e){if(r.has(n))throw new Error(`${t} would declare job \`${n}\` twice; rename one of the workflows`);r.add(n)}},GO=(e,t)=>[""," notify-success:",...Rd(t),` if: ${Y("!cancelled() && contains(needs.*.result, 'success') && !contains(needs.*.result, 'failure')")}`,` uses: ./.github/workflows/${e}`," secrets: inherit"],tw=(e,t)=>{let r=OO(e,t),n=e.terraform??[],o=e.preDeploy??[],s={terraform:n.map(Pa),preDeploy:o.map(Pa)},{file:i}=sw(e,t),a=1+(n.length>0?1:0)+(t==="selected"?kd(r).length:0);if(a>Qv){let h=n.length>0?`environment, ${Ca}`:"environment";throw new Error(`${i} would need ${a} dispatch inputs (${h} and one checkbox per service); GitHub allows ${Qv}. Fold services that always deploy together into one deploy script.`)}let c=r.map(h=>xa(h.name)),l=new Set(r.map(h=>h.name)),u=$O(e.services),p=h=>(u.get(h)??[]).filter(S=>l.has(S));VO([Ta,...s.terraform,...s.preDeploy,...c,...e.notifySuccess===void 0?[]:["notify-success"]],i);let f=`${[...LO(e,t,r),...jO(e,t,r),"","permissions:"," contents: read","","jobs:",...WO(),...n.flatMap(BO),...o.flatMap(h=>UO(h,s.terraform)),...r.flatMap(h=>MO(h,t,s,e,p(h.name))),...e.notifySuccess===void 0?[]:GO(e.notifySuccess,c)].join(`
411
+ `)}`);return n.data},MO=e=>e.replaceV1!==!0?[]:Wc.filter(t=>!e.environments.includes(t)).map(t=>`\u2716 replaceV1: environments must include '${t}', which delivery dispatches deploy-all.yml with`),jO=e=>{let t=new Set([...e.environments,...Wc]);return Object.entries(e.services).flatMap(([r,n])=>["envs","skipEnvs"].flatMap(o=>(n[o]??[]).filter(s=>!t.has(s)).map(s=>`\u2716 services.${r}.${o}: unknown environment '${s}' (known: ${[...t].join(", ")})`)))};var ks=e=>{let t=new Map;for(let[r,n]of Object.entries(e.services)){if(n.envs!==void 0){t.set(r,[...n.envs]);continue}let o=n.skipEnvs??[],s=e.environments.filter(i=>!o.includes(i));s.length<e.environments.length&&t.set(r,s)}return t};import{serviceDependencies as FO}from"@slip-stream-kit/config/internal";var aw="28aac6de980c6073d37a872c78309134bf62c47c",cw=`ArthurSaenz/infra-kit/.github/workflows/ik-deploy-service.yml@${aw}`,LO=`ArthurSaenz/infra-kit/.github/workflows/ik-install-deps.yml@${aw}`,Oa="install-deps",ow=25,Gn="# Generated by `infra-kit deploy-sync` from infra-kit.deploy.ts",Da="skip_terraform_deploy",lw={pilot:{all:{file:"deploy-all-v2.yml",title:"91 \u{1F9EA} Deploy all (v2)",concurrency:"deploy-all"},selected:{file:"deploy-selected-v2.yml",title:"92 \u{1F9EA} Deploy selected (v2)",concurrency:"deploy-selected"}},v1:{all:{file:"deploy-all.yml",title:"01 \u2699\uFE0F Deploy all",concurrency:"deploy-all"},selected:{file:"deploy-selected-services.yml",title:"02 \u2699\uFE0F Deploy selected services",concurrency:"deploy-selected"}}},uw=(e,t)=>lw[e.replaceV1===!0?"v1":"pilot"][t],dw=e=>Object.values(lw[e]).map(({file:t})=>`.github/workflows/${t}`),Pd=dw("pilot"),xd=dw("v1"),$a=e=>e.replace(/^_/,"").replace(/(?:-jobs)?\.ya?ml$/,""),BO=(e,t)=>{let r=Object.entries(e.services).flatMap(([o,s])=>{if(t==="all"&&s.deployAll===!1)return[];let i=t==="all"&&Array.isArray(s.deployAll)?s.deployAll:void 0,a=e.environments.filter(c=>(s.envs?.includes(c)??!0)&&!(s.skipEnvs?.includes(c)??!1)&&(i?.includes(c)??!0));return a.length===0?[]:[{name:o,service:s,gate:a.length===e.environments.length?void 0:a,triggers:void 0}]}),n=new Set(r.map(o=>o.name));return r.flatMap(o=>{if(o.service.runsBefore===void 0)return[o];let s=o.service.runsBefore.filter(i=>n.has(i));return s.length===0?[]:[{...o,triggers:s}]})},Td=e=>e.filter(t=>t.triggers===void 0),X=e=>`\${{ ${e} }}`,Ca=e=>X(`secrets[format('{0}_${e}', inputs.environment)]`),UO=e=>[Oa,...e.terraform,...e.preDeploy],Cd=e=>e.map(t=>`(needs.${t}.result == 'success' || needs.${t}.result == 'skipped')`),WO=e=>[`needs.${Oa}.result == 'success'`,...Cd(e.terraform),...e.preDeploy.map(t=>`needs.${t}.result == 'success'`)],GO=(e,t,r,n)=>{let o=[];return t==="selected"&&o.push(e.triggers===void 0?`inputs.${e.name}`:`(${e.triggers.map(s=>`inputs.${s}`).join(" || ")})`),e.gate!==void 0&&o.push(`contains(fromJSON('${JSON.stringify(e.gate)}'), inputs.environment)`),o.push("!cancelled()",...WO(r),...Cd(n.map(Aa))),X(o.join(" && "))},Aa=e=>`deploy-${e}`,$d=e=>e.length===0?[]:[` needs: [ ${e.join(", ")} ]`],pw=e=>e===void 0?[]:[` if: ${e}`],Ad=e=>[` uses: ./.github/workflows/${e}`," with:",` branch: ${X("github.ref")}`,` environment: ${X("inputs.environment")}`," secrets: inherit"],VO=(e,t)=>{let r=t.extraEnv??[],n=e.service.runner===void 0?[]:[` runner: ${e.service.runner}`],o=t.deployTimeoutMinutes===void 0?[]:[` timeout-minutes: ${t.deployTimeoutMinutes}`],s=r.length===0?[]:[" extra-env: |",...r.map(i=>{let a=X(`secrets.${i}`);return` ${i}=${a}`})];return[` uses: ${cw}`," with:",` environment: ${X("inputs.environment")}`,` ref: ${X("github.ref")}`,` sha: ${X("github.sha")}`,` service: ${e.name}`,` infra-kit-version: ${U.version}`,...n,...o,...t.doppler===void 0?[]:[` doppler-project: ${t.doppler.project}`]," secrets:",...t.doppler===void 0?[` aws-access-key-id: ${Ca("AWS_ACCESS_KEY_ID")}`,` aws-secret-access-key: ${Ca("AWS_SECRET_ACCESS_KEY")}`,` aws-region: ${Ca("AWS_REGION")}`]:[` doppler-token: ${Ca("DOPPLER_TOKEN")}`],` serverless-access-key: ${X("secrets.SERVERLESS_ACCESS_KEY")}`,` slack-token: ${X("secrets.SLACK_TOKEN")}`,` slack-channel: ${X("secrets.SLACK_CHANNEL")}`,...s]},JO=(e,t,r,n,o)=>{let s=e.service.workflow===void 0?VO(e,n):Ad(e.service.workflow);return["",` ${Aa(e.name)}:`,...$d([...UO(r),...o.map(Aa)]),...pw(GO(e,t,r,o)),...s]},sw=(e,t)=>["",` ${e}:`," type: boolean",` description: '${t}'`," required: false"," default: false"],KO=(e,t,r)=>{let n=[" environment:"," type: choice"," description: 'Environment for deploy'"," required: true",` default: '${e.defaultEnvironment??e.environments[0]}'`," options:",...e.environments.map(i=>` - ${i}`)],o=(e.terraform??[]).length>0?sw(Da,"Skip terraform deployment"):[],s=t==="all"?[]:Td(r).flatMap(i=>{let a=i.gate===void 0?"":` (${i.gate.join(", ")} only)`;return sw(i.name,`Deploy ${i.name}${a}`)});return["on:"," workflow_dispatch:"," inputs:",...n,...o,...s]},HO=e=>Td(e).map(t=>X(`inputs.${t.name} && ''${t.name} '' || ''''`)).join(""),qO=(e,t,r)=>{let{title:n,concurrency:o}=uw(e,t),s=(e.terraform??[]).length>0?X(`inputs.${Da} && '' \u2014 skip TF'' || ''''`):"",i=t==="selected"?` \u2014 ${HO(r)}`:"";return[`${Gn}: edit that file and re-run the command,`,"# a hand edit here is overwritten.",`name: '${n}'`,`run-name: '${n} [${X("inputs.environment")}]${s}${i}'`,"",`# The v1 ${t==="all"?"deploy-all":"deploy-selected"} group: two runs of this kind, v1 or v2, never deploy into one`,"# environment at once.","concurrency:",` group: ${o}-${X("inputs.environment")}`," # false: a cancelled run would also kill an in-flight terraform apply."," cancel-in-progress: false",""]},YO=e=>{let t=X(`!inputs.${Da}`);return["",` ${$a(e)}:`,` if: ${t}`,...Ad(e)]},zO=(e,t)=>{let r=t.length===0?void 0:X(["!cancelled()",...Cd(t)].join(" && "));return["",` ${$a(e)}:`,...$d(t),...pw(r),...Ad(e)]},XO=()=>["",` ${Oa}:`,` uses: ${LO}`," with:",` ref: ${X("github.ref")}`,` sha: ${X("github.sha")}`," secrets:",` slack-token: ${X("secrets.SLACK_TOKEN")}`,` slack-channel: ${X("secrets.SLACK_CHANNEL")}`],ZO=(e,t)=>{let r=new Set;for(let n of e){if(r.has(n))throw new Error(`${t} would declare job \`${n}\` twice; rename one of the workflows`);r.add(n)}},QO=(e,t)=>[""," notify-success:",...$d(t),` if: ${X("!cancelled() && contains(needs.*.result, 'success') && !contains(needs.*.result, 'failure')")}`,` uses: ./.github/workflows/${e}`," secrets: inherit"],iw=(e,t)=>{let r=BO(e,t),n=e.terraform??[],o=e.preDeploy??[],s={terraform:n.map($a),preDeploy:o.map($a)},{file:i}=uw(e,t),a=1+(n.length>0?1:0)+(t==="selected"?Td(r).length:0);if(a>ow){let h=n.length>0?`environment, ${Da}`:"environment";throw new Error(`${i} would need ${a} dispatch inputs (${h} and one checkbox per service); GitHub allows ${ow}. Fold services that always deploy together into one deploy script.`)}let c=r.map(h=>Aa(h.name)),l=new Set(r.map(h=>h.name)),u=FO(e.services),p=h=>(u.get(h)??[]).filter(b=>l.has(b));ZO([Oa,...s.terraform,...s.preDeploy,...c,...e.notifySuccess===void 0?[]:["notify-success"]],i);let f=`${[...qO(e,t,r),...KO(e,t,r),"","permissions:"," contents: read","","jobs:",...XO(),...n.flatMap(YO),...o.flatMap(h=>zO(h,s.terraform)),...r.flatMap(h=>JO(h,t,s,e,p(h.name))),...e.notifySuccess===void 0?[]:QO(e.notifySuccess,c)].join(`
403
412
  `).replace(`jobs:
404
413
 
405
414
  `,`jobs:
406
415
  `)}
407
- `;return{path:`.github/workflows/${i}`,content:f}},Ed=e=>[tw(e,"all"),tw(e,"selected")];var lw=".github/workflows",JO=/script_name:\s*(?<service>[a-z0-9-]+)/,KO=/uses:\s*\.\/\.github\/workflows\/_deploy-(?<service>[a-z0-9-]+)-jobs\.ya?ml/,HO=/inputs\.environment\s*==\s*'(?<env>[a-z0-9-]+)'/g,xd=async e=>{let t=Pd.resolve(e,lw),r;try{r=await cw.readdir(t)}catch{return new Map}return uw(e,r.filter(n=>n.endsWith(".yml")||n.endsWith(".yaml")))},hs=async(e,t)=>uw(e,[t]),uw=async(e,t)=>{let r=Pd.resolve(e,lw),n=new Map,o=!1;for(let s of t){let i;try{i=await cw.readFile(Pd.resolve(r,s),"utf-8")}catch{continue}i.startsWith(Fn)?o=!0:YO(i,n)}return o&&dw(n,await qO(e)),n},qO=async e=>{try{let t=await vt(e);return t?.replaceV1===!0?gs(t):new Map}catch(t){return d.warn(`Deploy gates unavailable, nothing is refused before dispatch: ${t.message}`),new Map}},dw=(e,t)=>{for(let[r,n]of t)e.set(r,[...new Set([...e.get(r)??[],...n])])},YO=(e,t)=>{for(let r of e.split(/\n(?= {2}[\w-]+:)/i)){let n=JO.exec(r)?.groups?.service??KO.exec(r)?.groups?.service;if(n===void 0||r.trimStart().startsWith("#"))continue;let o=[...r.matchAll(HO)].map(s=>s.groups?.env??"");o.length!==0&&dw(t,new Map([[n,o]]))}},ys=(e,t)=>e===null?t??null:t===void 0?e:e.filter(r=>t.includes(r));import zO from"node:fs/promises";import XO from"node:path";import ZO from"yaml";var QO=".github/workflows",eD="skip_terraform_deploy",vs=async(e,t)=>{let r=XO.resolve(e,QO,t),n;try{n=ZO.parse(await zO.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!==eD).map(([i])=>i)};var pw="dev",Td=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),mw=(e,t)=>e[t]===void 0,fw=(e,t)=>{let r=e[t];return typeof r=="string"&&r.length>0?r:void 0},Cd=async e=>{try{return await e}catch{return[]}},tD=async()=>{let e=await G();return Dt(e.map(t=>t.branch))},rD=(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},Dr=e=>{let{workflowFile:t,fields:r,toolName:n}=e,o=c=>(d.info({msg:`Tool execution form options empty (${t}): ${n}`,emptyList:c}),null),s=async c=>{let l=await Cd(tD());if(l.length===0)return null;let u=fw(c,"version");return ws.enum([...new Set([...l,pw])]).optional().describe(`Which release to deploy from. "${pw}" deploys from the dev branch instead of a release branch. ${u===void 0?"Leaving it blank sends no version, and the tool will refuse rather than guess one.":`Leave it blank to keep the caller's "${u}".`}`)},i=async c=>{let l=Vt(await Cd(Gt(t)),await it());if(l.length===0)return null;let u=l.filter(oo),p=l.filter(f=>!oo(f)),m=fw(c,"env");return ws.enum(l).optional().describe(`Target environment. Shared with the whole team: ${u.length>0?u.join(", "):"none"}. Personal accounts: ${p.length>0?p.join(", "):"none"}. This list is read from .github/workflows/${t} in the WORKING TREE, not from the branch being deployed or from GitHub. ${m===void 0?"Leaving it blank sends no environment at all.":`Leave it blank to keep the caller's "${m}" \u2014 including when this tree does not declare it.`}`)},a=async()=>{let c=await $(),l=await Cd(vs(c,t));if(l.length===0)return null;let u=await hs(c,t);return ws.array(ws.enum(l)).optional().describe(`Services to deploy. Environment gates declared by ${t} \u2014 ${rD(l,u)} A service the chosen environment gates out is REFUSED before dispatch, not skipped in silence. Selecting none discards the form and falls back to the caller's arguments.`)};return{message:`Choose the arguments for ${n}. Anything left blank keeps what the caller sent.`,isFormable:c=>Td(c)?r.some(l=>mw(c,l)):!1,buildRequestedSchema:async c=>{let l=Td(c)?c:{},u={};if(r.includes("version")){let p=await s(l);if(p===null)return o("releases");u.version=p}if(r.includes("env")){let p=await i(l);if(p===null)return o("envs");u.env=p}if(r.includes("services")&&mw(l,"services")){let p=await a();if(p===null)return o("services");u.services=p}return Object.keys(u).length===0?o("fields"):ws.object(u)},toArgs:(c,l)=>{let u={...Td(l)?l:{}};for(let p of r){let m=c[p];if(m!==void 0){if(p==="services"&&(!Array.isArray(m)||m.length===0))return null;u[p]=m}}return u}}};import nD from"@inquirer/select";var Ln=async(e,t)=>{if(e.length===0)throw new g(void 0,{operation:t,remediation:"pass --env <name> explicitly",stderrExcerpt:"the workflow declares no `environment` choices to pick from"});return _(r=>nD({message:"\u{1F9EA} Select environment",choices:e.map(n=>({name:n,value:n}))},r),{whenHeadless:"refuse"})};import oD from"@inquirer/confirm";var ks=async e=>{let{confirmedCommand:t,branch:r,env:n}=e;if(t)return!0;let o=`Deploy ${r} \u2192 ${n} via GitHub Actions?`;X()&&li(o,{branch:r,env:n}),y.setInteractive();let s=await _(i=>oD({message:o,default:!1},i),{whenHeadless:"refuse"});return s&&y.addOption("--yes",!0),s};import sD from"@inquirer/select";import iD from"node:process";var $d=()=>!X()&&iD.stdin.isTTY===!0,aD={ci:"Dispatch the GitHub workflow for a release ref",local:"Run devops/scripts/deploy-*.sh here, against your current checkout"},Ad=async()=>_(e=>sD({message:"\u{1F680} Where should this deploy run?",choices:tr.filter(t=>t!=="local").map(t=>({name:t,value:t,description:aD[t]}))},e),{whenHeadless:"refuse"});var tr=["ci","local"],cD={ci:["--version","--skip-terraform"],local:["--dry-run","--print-env"]},gw=e=>{if(!e){let r={operation:"resolve the deploy source",remediation:`pass --from with one of: ${tr.join(", ")}`,stderrExcerpt:"--from is required \u2014 it decides whether this deploy runs in CI or on this machine"};throw X()?new O({status:"argument_required",argument:"from",agentMode:j.source},2,r):new g(void 0,r)}let t=tr.find(r=>r===e);if(!t)throw new g(void 0,{operation:"resolve the deploy source",remediation:`use one of: ${tr.join(", ")}`,stderrExcerpt:`unknown --from value "${e}"`});return t},Od=(e,t)=>{let n=cD[e==="ci"?"local":"ci"].filter(o=>{let s=t[o];return s!==void 0&&s!==!1});if(n.length!==0)throw new g(void 0,{operation:`deploy --from ${e}`,remediation:e==="ci"?"drop the flag, or use --from local to deploy from this machine":"drop the flag, or use --from ci to dispatch the release workflow",stderrExcerpt:`${n.join(", ")} ${n.length===1?"is":"are"} not valid with --from ${e}`})},Dd=async e=>e||!$d()?gw(e):Ad();var bs=async e=>{if(e)return e==="dev"?"dev":Ot(e);y.setInteractive();let t=await G(),r=t.map(s=>s.branch),n=new Map(t.map(s=>[s.branch,s.type])),o=await me();return qt([{value:"dev",label:"dev"},...fe({branches:r,descriptions:o,types:n})])};var hw="deploy-all.yml",yw=Dr({workflowFile:hw,fields:["version","env"],toolName:"gh-release-deploy-all"}),$a=async e=>{let{version:t,env:r,skipTerraform:n,confirmedCommand:o}=e;await at({provider:yw,params:e,operation:"launch deploy-all workflow",argument:p=>p[0]??"version"});let s=await bs(t),i=jo(s);y.addOption("--version",i);let a=await it(),c=Vt(await Gt(hw),a),l="";r?l=r:(y.setInteractive(),l=await Ln(c,"launch deploy-all workflow")),y.addOption("--env",l),Kr(l,"launch deploy-all workflow",a),di({env:l,branch:s});let u=n??!1;if(u&&y.addOption("--skip-terraform",!0),!await ks({confirmedCommand:o,branch:s,env:l})){d.info("Deployment cancelled");let p={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:u,success:!1};return{content:b(JSON.stringify(p,null,2)),structuredContent:p}}try{Id.quiet=!0,await Id`gh workflow run deploy-all.yml --ref ${s} -f environment=${l} ${u?["-f","skip_terraform_deploy=true"]:[]}`,Id.quiet=!1,d.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${s} and environment: ${l}`),y.print();let m={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:u,success:!0};return{content:b(JSON.stringify(m,null,2)),structuredContent:m}}catch(p){throw d.error({error:p},"\u274C Error launching workflow"),new g(p,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},Nd=C({name:"gh-release-deploy-all",formProvider:yw,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:Nt.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:Nt.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:Nt.boolean().optional().describe("Skip the terraform deployment stage."),confirm:Nt.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:Nt.string().describe("The release branch that was deployed"),version:Nt.string().describe("The version that was deployed"),environment:Nt.string().describe("The environment deployed to"),skipTerraformDeploy:Nt.boolean().describe("Whether terraform deployment was skipped"),success:Nt.boolean().describe("Whether the deployment was successful")},handler:$a});import lD from"@inquirer/checkbox";import{z as je}from"zod";import{$ as _d}from"zx";var Ir="deploy-selected-services.yml",vw=Dr({workflowFile:Ir,fields:["version","env","services"],toolName:"gh-release-deploy-selected"}),Aa=async e=>{let{version:t,env:r,services:n,skipTerraform:o,confirmedCommand:s}=e;await at({provider:vw,params:e,operation:"launch deploy-selected workflow",argument:v=>v[0]??"version"});let i=await bs(t),a=jo(i);y.addOption("--version",a);let c=await it(),l=Vt(await Gt(Ir),c),u="";r?u=r:(y.setInteractive(),u=await Ln(l,"launch deploy-selected workflow")),y.addOption("--env",u),Kr(u,"launch deploy-selected workflow",c),di({env:u,branch:i});let p=await $(),m=await vs(p,Ir);if(m.length===0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${Ir}`,stderrExcerpt:`no services found in .github/workflows/${Ir}`});let f=[];if(n&&n.length>0?f=n:(y.setInteractive(),f=await _(v=>lD({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:m.map(R=>({name:R,value:R}))},v),{whenHeadless:"refuse"})),y.addOption("--services",f),f.length===0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${m.join(", ")}`,stderrExcerpt:"no services selected"});let h=f.filter(v=>!m.includes(v));if(h.length>0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${m.join(", ")}`,stderrExcerpt:`invalid services: ${h.join(", ")}`});let S=await hs(p,Ir),k=f.filter(v=>{let R=S.get(v);return R!==void 0&&!R.includes(u)});if(k.length>0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:k.map(v=>`${v} deploys only to: ${(S.get(v)??[]).join(", ")}`).join("; "),stderrExcerpt:`${Ir} gates these services out of ${u}: ${k.join(", ")}`});let A=o??!1;A&&y.addOption("--skip-terraform",!0);let M=v=>{let R={releaseBranch:i,version:a,environment:u,services:f,skipTerraformDeploy:A,success:v};return{content:b(JSON.stringify(R,null,2)),structuredContent:R}};if(!await ks({confirmedCommand:s,branch:i,env:u}))return d.info("Deployment cancelled"),M(!1);try{_d.quiet=!0;let v=f.flatMap(T=>["-f",`${T}=true`]);return await _d`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${u} ${v} ${A?["-f","skip_terraform_deploy=true"]:[]}`,_d.quiet=!1,d.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${u}, services: ${f.join(", ")}`),y.print(),M(!0)}catch(v){throw d.error({error:v},"\u274C Error launching workflow"),new g(v,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},Md=C({name:"gh-release-deploy-selected",requiresHumanConfirm:!0,formProvider:vw,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:je.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:je.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:je.array(je.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:je.boolean().optional().describe("Skip the terraform deployment stage."),confirm:je.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:je.string().describe("The release branch that was deployed"),version:je.string().describe("The version that was deployed"),environment:je.string().describe("The environment deployed to"),services:je.array(je.string()).describe("The services that were deployed"),skipTerraformDeploy:je.boolean().describe("Whether terraform deployment was skipped"),success:je.boolean().describe("Whether the deployment was successful")},handler:Aa});import{z as rr}from"zod";var Oa=async()=>{let t=(await G()).flatMap(i=>{let a=Q(i.branch);return a?[{version:ne(a),jiraKey:le(a),type:i.type,titleMismatch:i.titleMismatch}]:[]}),r=await Vi(),n=Math.max(...t.map(i=>i.version.length)),o=t.map(i=>{let a=Mo(i.version,i.type,n),c=r.get(i.jiraKey),l=c?.description?` ${c.description}`:"",u=c?.releaseDate?` \xB7 ships ${c.releaseDate}`:"",p=i.titleMismatch?" \u26A0 title/base mismatch":"";return`${a}${l}${u}${p}`});d.info(`All release branches:
416
+ `;return{path:`.github/workflows/${i}`,content:f}},Od=e=>[iw(e,"all"),iw(e,"selected")];var fw=".github/workflows",eD=/script_name:\s*(?<service>[a-z0-9-]+)/,tD=/uses:\s*\.\/\.github\/workflows\/_deploy-(?<service>[a-z0-9-]+)-jobs\.ya?ml/,rD=/inputs\.environment\s*==\s*'(?<env>[a-z0-9-]+)'/g,Id=async e=>{let t=Dd.resolve(e,fw),r;try{r=await mw.readdir(t)}catch{return new Map}return gw(e,r.filter(n=>n.endsWith(".yml")||n.endsWith(".yaml")))},bs=async(e,t)=>gw(e,[t]),gw=async(e,t)=>{let r=Dd.resolve(e,fw),n=new Map,o=!1;for(let s of t){let i;try{i=await mw.readFile(Dd.resolve(r,s),"utf-8")}catch{continue}i.startsWith(Gn)?o=!0:oD(i,n)}return o&&hw(n,await nD(e)),n},nD=async e=>{try{let t=await kt(e);return t?.replaceV1===!0?ks(t):new Map}catch(t){return d.warn(`Deploy gates unavailable, nothing is refused before dispatch: ${t.message}`),new Map}},hw=(e,t)=>{for(let[r,n]of t)e.set(r,[...new Set([...e.get(r)??[],...n])])},oD=(e,t)=>{for(let r of e.split(/\n(?= {2}[\w-]+:)/i)){let n=eD.exec(r)?.groups?.service??tD.exec(r)?.groups?.service;if(n===void 0||r.trimStart().startsWith("#"))continue;let o=[...r.matchAll(rD)].map(s=>s.groups?.env??"");o.length!==0&&hw(t,new Map([[n,o]]))}},Rs=(e,t)=>e===null?t??null:t===void 0?e:e.filter(r=>t.includes(r));import sD from"node:fs/promises";import iD from"node:path";import aD from"yaml";var cD=".github/workflows",lD="skip_terraform_deploy",Ss=async(e,t)=>{let r=iD.resolve(e,cD,t),n;try{n=aD.parse(await sD.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!==lD).map(([i])=>i)};var Nd=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),yw=(e,t)=>e[t]===void 0,vw=(e,t)=>{let r=e[t];return typeof r=="string"&&r.length>0?r:void 0},_d=async e=>{try{return await e}catch{return[]}},uD=async()=>{let e=await K();return Nt(e.map(t=>t.branch))},dD=(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},Mr=e=>{let{workflowFile:t,fields:r,toolName:n}=e,o=c=>(d.info({msg:`Tool execution form options empty (${t}): ${n}`,emptyList:c}),null),s=async c=>{let l=await _d(uD());if(l.length===0)return null;let u=vw(c,"version"),p=await br();return Es.enum([...new Set([...l,p])]).optional().describe(`Which release to deploy from. "${p}" deploys from the ${p} branch instead of a release branch. ${u===void 0?"Leaving it blank sends no version, and the tool will refuse rather than guess one.":`Leave it blank to keep the caller's "${u}".`}`)},i=async c=>{let l=Jt(await _d(Kt(t)),await ct());if(l.length===0)return null;let u=l.filter(uo),p=l.filter(f=>!uo(f)),m=vw(c,"env");return Es.enum(l).optional().describe(`Target environment. Shared with the whole team: ${u.length>0?u.join(", "):"none"}. Personal accounts: ${p.length>0?p.join(", "):"none"}. This list is read from .github/workflows/${t} in the WORKING TREE, not from the branch being deployed or from GitHub. ${m===void 0?"Leaving it blank sends no environment at all.":`Leave it blank to keep the caller's "${m}" \u2014 including when this tree does not declare it.`}`)},a=async()=>{let c=await A(),l=await _d(Ss(c,t));if(l.length===0)return null;let u=await bs(c,t);return Es.array(Es.enum(l)).optional().describe(`Services to deploy. Environment gates declared by ${t} \u2014 ${dD(l,u)} A service the chosen environment gates out is REFUSED before dispatch, not skipped in silence. Selecting none discards the form and falls back to the caller's arguments.`)};return{message:`Choose the arguments for ${n}. Anything left blank keeps what the caller sent.`,isFormable:c=>Nd(c)?r.some(l=>yw(c,l)):!1,buildRequestedSchema:async c=>{let l=Nd(c)?c:{},u={};if(r.includes("version")){let p=await s(l);if(p===null)return o("releases");u.version=p}if(r.includes("env")){let p=await i(l);if(p===null)return o("envs");u.env=p}if(r.includes("services")&&yw(l,"services")){let p=await a();if(p===null)return o("services");u.services=p}return Object.keys(u).length===0?o("fields"):Es.object(u)},toArgs:(c,l)=>{let u={...Nd(l)?l:{}};for(let p of r){let m=c[p];if(m!==void 0){if(p==="services"&&(!Array.isArray(m)||m.length===0))return null;u[p]=m}}return u}}};import pD from"@inquirer/select";var Vn=async(e,t)=>{if(e.length===0)throw new g(void 0,{operation:t,remediation:"pass --env <name> explicitly",stderrExcerpt:"the workflow declares no `environment` choices to pick from"});return M(r=>pD({message:"\u{1F9EA} Select environment",choices:e.map(n=>({name:n,value:n}))},r),{whenHeadless:"refuse"})};import mD from"@inquirer/confirm";var Ps=async e=>{let{confirmedCommand:t,branch:r,env:n}=e;if(t)return!0;let o=`Deploy ${r} \u2192 ${n} via GitHub Actions?`;Q()&&mi(o,{branch:r,env:n}),y.setInteractive();let s=await M(i=>mD({message:o,default:!1},i),{whenHeadless:"refuse"});return s&&y.addOption("--yes",!0),s};import fD from"@inquirer/select";import gD from"node:process";var Md=()=>!Q()&&gD.stdin.isTTY===!0,hD={ci:"Dispatch the GitHub workflow for a release ref",local:"Run devops/scripts/deploy-*.sh here, against your current checkout"},jd=async()=>M(e=>fD({message:"\u{1F680} Where should this deploy run?",choices:nr.filter(t=>t!=="local").map(t=>({name:t,value:t,description:hD[t]}))},e),{whenHeadless:"refuse"});var nr=["ci","local"],yD={ci:["--version","--skip-terraform"],local:["--dry-run","--print-env"]},ww=e=>{if(!e){let r={operation:"resolve the deploy source",remediation:`pass --from with one of: ${nr.join(", ")}`,stderrExcerpt:"--from is required \u2014 it decides whether this deploy runs in CI or on this machine"};throw Q()?new D({status:"argument_required",argument:"from",agentMode:F.source},2,r):new g(void 0,r)}let t=nr.find(r=>r===e);if(!t)throw new g(void 0,{operation:"resolve the deploy source",remediation:`use one of: ${nr.join(", ")}`,stderrExcerpt:`unknown --from value "${e}"`});return t},Fd=(e,t)=>{let n=yD[e==="ci"?"local":"ci"].filter(o=>{let s=t[o];return s!==void 0&&s!==!1});if(n.length!==0)throw new g(void 0,{operation:`deploy --from ${e}`,remediation:e==="ci"?"drop the flag, or use --from local to deploy from this machine":"drop the flag, or use --from ci to dispatch the release workflow",stderrExcerpt:`${n.join(", ")} ${n.length===1?"is":"are"} not valid with --from ${e}`})},Ld=async e=>e||!Md()?ww(e):jd();var xs=async e=>{let t=await br();if(e==="dev"&&t!=="dev")throw new g(void 0,{operation:"resolve the deploy branch",remediation:`this repo sets "gitFlow": "${t}" in infra-kit.json and has no dev branch to deploy \u2014 pass --version ${t}, or a release`});if(e)return e===t?t:It(e);y.setInteractive();let r=await K(),n=r.map(i=>i.branch),o=new Map(r.map(i=>[i.branch,i.type])),s=await fe();return zt([{value:t,label:t},...ge({branches:n,descriptions:s,types:o})])};var kw="deploy-all.yml",bw=Mr({workflowFile:kw,fields:["version","env"],toolName:"gh-release-deploy-all"}),Ia=async e=>{let{version:t,env:r,skipTerraform:n,confirmedCommand:o}=e;await lt({provider:bw,params:e,operation:"launch deploy-all workflow",argument:p=>p[0]??"version"});let s=await xs(t),i=Wo(s);y.addOption("--version",i);let a=await ct(),c=Jt(await Kt(kw),a),l="";r?l=r:(y.setInteractive(),l=await Vn(c,"launch deploy-all workflow")),y.addOption("--env",l),zr(l,"launch deploy-all workflow",a),gi({env:l,branch:s});let u=n??!1;if(u&&y.addOption("--skip-terraform",!0),!await Ps({confirmedCommand:o,branch:s,env:l})){d.info("Deployment cancelled");let p={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:u,success:!1};return{content:R(JSON.stringify(p,null,2)),structuredContent:p}}try{Bd.quiet=!0,await Bd`gh workflow run deploy-all.yml --ref ${s} -f environment=${l} ${u?["-f","skip_terraform_deploy=true"]:[]}`,Bd.quiet=!1,d.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${s} and environment: ${l}`),y.print();let m={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:u,success:!0};return{content:R(JSON.stringify(m,null,2)),structuredContent:m}}catch(p){throw d.error({error:p},"\u274C Error launching workflow"),new g(p,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},Ud=C({name:"gh-release-deploy-all",formProvider:bw,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:Mt.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 ("main" in a repo with "gitFlow": "main"). Omit it to be offered the open releases.'),env:Mt.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:Mt.boolean().optional().describe("Skip the terraform deployment stage."),confirm:Mt.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:Mt.string().describe("The release branch that was deployed"),version:Mt.string().describe("The version that was deployed"),environment:Mt.string().describe("The environment deployed to"),skipTerraformDeploy:Mt.boolean().describe("Whether terraform deployment was skipped"),success:Mt.boolean().describe("Whether the deployment was successful")},handler:Ia});import vD from"@inquirer/checkbox";import{z as Le}from"zod";import{$ as Wd}from"zx";var jr="deploy-selected-services.yml",Rw=Mr({workflowFile:jr,fields:["version","env","services"],toolName:"gh-release-deploy-selected"}),Na=async e=>{let{version:t,env:r,services:n,skipTerraform:o,confirmedCommand:s}=e;await lt({provider:Rw,params:e,operation:"launch deploy-selected workflow",argument:v=>v[0]??"version"});let i=await xs(t),a=Wo(i);y.addOption("--version",a);let c=await ct(),l=Jt(await Kt(jr),c),u="";r?u=r:(y.setInteractive(),u=await Vn(l,"launch deploy-selected workflow")),y.addOption("--env",u),zr(u,"launch deploy-selected workflow",c),gi({env:u,branch:i});let p=await A(),m=await Ss(p,jr);if(m.length===0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${jr}`,stderrExcerpt:`no services found in .github/workflows/${jr}`});let f=[];if(n&&n.length>0?f=n:(y.setInteractive(),f=await M(v=>vD({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:m.map(S=>({name:S,value:S}))},v),{whenHeadless:"refuse"})),y.addOption("--services",f),f.length===0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${m.join(", ")}`,stderrExcerpt:"no services selected"});let h=f.filter(v=>!m.includes(v));if(h.length>0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${m.join(", ")}`,stderrExcerpt:`invalid services: ${h.join(", ")}`});let b=await bs(p,jr),T=f.filter(v=>{let S=b.get(v);return S!==void 0&&!S.includes(u)});if(T.length>0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:T.map(v=>`${v} deploys only to: ${(b.get(v)??[]).join(", ")}`).join("; "),stderrExcerpt:`${jr} gates these services out of ${u}: ${T.join(", ")}`});let k=o??!1;k&&y.addOption("--skip-terraform",!0);let j=v=>{let S={releaseBranch:i,version:a,environment:u,services:f,skipTerraformDeploy:k,success:v};return{content:R(JSON.stringify(S,null,2)),structuredContent:S}};if(!await Ps({confirmedCommand:s,branch:i,env:u}))return d.info("Deployment cancelled"),j(!1);try{Wd.quiet=!0;let v=f.flatMap(P=>["-f",`${P}=true`]);return await Wd`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${u} ${v} ${k?["-f","skip_terraform_deploy=true"]:[]}`,Wd.quiet=!1,d.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${u}, services: ${f.join(", ")}`),y.print(),j(!0)}catch(v){throw d.error({error:v},"\u274C Error launching workflow"),new g(v,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},Gd=C({name:"gh-release-deploy-selected",requiresHumanConfirm:!0,formProvider:Rw,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:Le.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 ("main" in a repo with "gitFlow": "main"). Omit it to be offered the open releases.'),env:Le.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:Le.array(Le.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:Le.boolean().optional().describe("Skip the terraform deployment stage."),confirm:Le.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:Le.string().describe("The release branch that was deployed"),version:Le.string().describe("The version that was deployed"),environment:Le.string().describe("The environment deployed to"),services:Le.array(Le.string()).describe("The services that were deployed"),skipTerraformDeploy:Le.boolean().describe("Whether terraform deployment was skipped"),success:Le.boolean().describe("Whether the deployment was successful")},handler:Na});import{z as or}from"zod";var _a=async()=>{let t=(await K()).flatMap(i=>{let a=ee(i.branch);return a?[{version:oe(a),jiraKey:ue(a),type:i.type,titleMismatch:i.titleMismatch}]:[]}),r=await Hi(),n=Math.max(...t.map(i=>i.version.length)),o=t.map(i=>{let a=Uo(i.version,i.type,n),c=r.get(i.jiraKey),l=c?.description?` ${c.description}`:"",u=c?.releaseDate?` \xB7 ships ${c.releaseDate}`:"",p=i.titleMismatch?" \u26A0 title/base mismatch":"";return`${a}${l}${u}${p}`});d.info(`All release branches:
408
417
  `),d.info(`
409
418
  ${o.join(`
410
419
  `)}
411
- `);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:b(JSON.stringify(s,null,2)),structuredContent:s}},jd=C({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:rr.array(rr.object({version:rr.string().describe("Release version"),type:rr.enum(["regular","hotfix"]).describe("Release type"),description:rr.string().nullable().describe("Jira version description"),releaseDate:rr.string().nullable().describe("Planned release date of the Jira version (yyyy-mm-dd)"),titleMismatch:rr.boolean().describe("The PR title names a different release type than its base branch")})).describe("List of all release branches"),count:rr.number().describe("Number of release branches")},handler:Oa});import uD from"node:process";var Rs="local-deploy";var Fd=e=>({...e}),Ld=e=>{let{env:t,branch:r,sha:n,isClean:o,ambient:s=uD.env}=e,i={VITE_DOMAIN_ENV:t,VITE_BRANCH_NAME:r,VITE_COMMIT_HASH:o?n:`${n}-dirty`},a={},c=[];for(let[l,u]of Object.entries(s)){if(l.startsWith("VITE_")){c.push(l);continue}a[l]=u}return c.sort(),{childEnv:{...a,...i,DEPLOY_ENV:t,DEPLOY_BRANCH:r,DEPLOY_SHA:n,DEPLOY_SHA_LABEL:i.VITE_COMMIT_HASH,TURBO_TELEMETRY_DISABLED:"1",INFRA_KIT_DEPLOY_VIA:Rs},contract:i,stripped:c}},Da=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(`
412
- `)};import TD from"@inquirer/checkbox";import CD from"@inquirer/confirm";import $D from"@inquirer/select";import{spawn as AD}from"node:child_process";import Jd from"node:process";import{z as te}from"zod";import{$ as xs}from"zx";import{$ as Ss}from"zx";var dD=async e=>{let t=Ss.quiet;Ss.quiet=!0;try{let r=`/${e}/environment`,n=await Ss`aws sts get-caller-identity --query Account --output text`,o=await Ss`aws ssm get-parameter --name ${r} --query Parameter.Value --output text`;return{accountId:n.stdout.trim(),stage:o.stdout.trim()}}catch(r){throw new g(r,{operation:"resolve the AWS account for this deploy",remediation:`check that credentials are loaded and that \`/${e}/environment\` exists in the account they point at \u2014 run \`aws sts get-caller-identity\` to see which account that is`})}finally{Ss.quiet=t}},ww=(e,t)=>{if(t.stage!==e)throw new g(void 0,{operation:"verify the target environment",remediation:"switch AWS_PROFILE to the account for this environment, or pass the env this account is",stderrExcerpt:`you asked for "${e}", but AWS account ${t.accountId} reports "${t.stage}" \u2014 refusing to deploy to an environment you did not name`})},kw=e=>{let{env:t,isShared:r,isClean:n}=e;if(!(!r||n))throw new g(void 0,{operation:`deploy to shared environment "${t}"`,remediation:"commit, or `git stash -u` (plain stash leaves untracked files), or deploy to a personal environment",stderrExcerpt:"the working tree has uncommitted or untracked changes and this environment is shared"})},bw=(e,t)=>{if(t.includes(e))throw new g(void 0,{operation:`deploy to "${e}"`,remediation:"wait for the CI run to finish, or watch it with `gh run watch`",stderrExcerpt:`a CI deploy to "${e}" is already in flight \u2014 running both would interleave`})},Bd=async e=>{let{env:t,project:r,isShared:n,isClean:o,runningEnvs:s,protectedEnvAccess:i}=e;Kr(t,`deploy to "${t}"`,i),bw(t,s),kw({env:t,isShared:n,isClean:o});let a=await dD(r);return ww(t,a),{identity:a}};import{serviceDependencies as pD}from"@slip-stream-kit/config/internal";import Ud from"node:fs/promises";import Es from"node:path";var Ew="devops/scripts",mD=/^deploy-(?<service>[a-z0-9-]+)\.sh$/,fD=/skip_unless_env_enabled\s+"[^"]*"\s+"[^"]*"\s+"(?<envs>[^"]*)"/,gD=/aws\s+ssm\s+get-parameter\s+--name[=\s]+(?<arg>[^\s)]+)/,hD=/aws\s+ssm\s+get-parameter\s+--name[=\s]+["']?\/(?<prefix>[\w.-]+)\/environment["']?(?![\w./-])/,yD=/(["'`])\/(?<prefix>[\w.-]+)\/environment\1/,vD=/`[^`]*\$\{[^`]*\/environment[^`]*`/,Rw={commentPrefixes:["#"],literalPrefix:e=>hD.exec(e)?.groups?.prefix,isUnparseable:e=>{let t=gD.exec(e)?.groups?.arg;return t!==void 0&&SD(t)}},Sw={commentPrefixes:["//","/*","*"],literalPrefix:e=>yD.exec(e)?.groups?.prefix,isUnparseable:e=>vD.test(e)},Wd=async e=>{let t=await vt(e),r=await xd(e);return(t===void 0?await wD(e,r):await kD(e,t,r)).sort((o,s)=>o.name.localeCompare(s.name))},wD=async(e,t)=>{let r=Es.resolve(e,Ew),n;try{n=await Ud.readdir(r)}catch{return[]}return Promise.all(n.flatMap(o=>{let s=mD.exec(o)?.groups?.service;return s===void 0?[]:[Pw(s,Es.resolve(r,o),t)]}))},Pw=async(e,t,r)=>{let n=Tw(await xw(t),Rw);return{name:e,scriptPath:t,runner:"sh",allowedEnvs:ys(RD(n),r.get(e)),ssmPrefix:Cw(n,Rw)}},kD=async(e,t,r)=>{let n=gs(t),o=pD(t.services),s=(a,c)=>({...(o.get(a)??[]).length===0?{}:{dependsOn:o.get(a)},...c.runsBefore===void 0?{}:{runsBefore:[...c.runsBefore]}});return(await Promise.all(Object.entries(t.services).map(async([a,c])=>{if(c.deploy===void 0){let p=Es.resolve(e,Ew,`deploy-${a}.sh`);if(!await bD(p))return null;let m=await Pw(a,p,r);return{...m,allowedEnvs:ys(m.allowedEnvs,n.get(a)),...s(a,c)}}let l=Es.resolve(e,c.deploy),u=Tw(await xw(l),Sw);return{name:a,scriptPath:l,runner:"deploy-run",allowedEnvs:ys(n.get(a)??null,r.get(a)),ssmPrefix:Cw(u,Sw),...s(a,c)}}))).filter(a=>a!==null)},bD=async e=>{try{return await Ud.access(e),!0}catch{return!1}},xw=async e=>{try{return await Ud.readFile(e,"utf-8")}catch{return""}},Tw=(e,t)=>e.split(`
413
- `).map((r,n)=>({line:n+1,text:r})).filter(({text:r})=>{let n=r.trimStart();return!t.commentPrefixes.some(o=>n.startsWith(o))}),RD=e=>{let t=e.reduce((n,{text:o})=>n??fD.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},SD=e=>{let t=e.replaceAll(/["']/g,"");return t.includes("$")&&(t.includes("/environment")||t.startsWith("$"))},Cw=(e,t)=>{for(let{line:r,text:n}of e){let o=t.literalPrefix(n);if(o!==void 0)return o;if(t.isUnparseable(n))return{unparseable:{line:r,text:n.trim()}}}return null},$w=e=>{let t=Es.basename(e.scriptPath);return e.runner==="sh"?t:`${e.name} (${t})`},ED=e=>{let t=new Map;for(let r of e)typeof r.ssmPrefix=="string"&&t.set(r.ssmPrefix,[...t.get(r.ssmPrefix)??[],$w(r)]);return t},PD=e=>{let t=e.flatMap(r=>{if(r.ssmPrefix===null||typeof r.ssmPrefix=="string")return[];let{line:n,text:o}=r.ssmPrefix.unparseable;return[`${$w(r)}:${n}: ${o}`]});if(t.length!==0)throw new g(void 0,{operation:"resolve the SSM project prefix",remediation:"write the parameter name as a literal `/<project>/environment` so infra-kit can preflight it",stderrExcerpt:t.join("; ")})},xD=e=>{PD(e);let t=ED(e),[r,...n]=t.keys();if(r===void 0)throw new g(void 0,{operation:"resolve the SSM project prefix",remediation:'read the literal "/<project>/environment" in at least one deploy script: a deploy.ts in infra-kit.deploy.ts, or `aws ssm get-parameter --name "/<project>/environment"` in a devops/scripts/deploy-*.sh',stderrExcerpt:`none of ${e.length} deploy scripts reads /<project>/environment`});if(n.length>0){let o=[...t.entries()].sort(([,s],[,i])=>s.length-i.length).map(([s,i])=>`${s}: ${i.join(", ")}`).join("; ");throw new g(void 0,{operation:"resolve the SSM project prefix",remediation:"make every deploy script read the same /<project>/environment parameter",stderrExcerpt:`${t.size} different prefixes across ${e.length} deploy scripts \u2014 ${o}`})}return r},Aw=async(e,t)=>(await vt(e))?.project??xD(t),Ps=(e,t)=>e.allowedEnvs===null||e.allowedEnvs.includes(t),Vd=(e,t)=>e.filter(r=>r.runsBefore===void 0&&Ps(r,t)),Ow=(e,t,r)=>{let n=new Set(e.map(l=>l.name)),o=t.filter(l=>!n.has(l.name)&&Ps(l,r)&&(l.runsBefore??[]).some(u=>n.has(u))),s=new Map([...o,...e].map(l=>[l.name,l])),i=[],a=new Set,c=l=>{if(!a.has(l.name)){a.add(l.name);for(let u of l.dependsOn??[]){let p=s.get(u);p!==void 0&&c(p)}i.push(l)}};for(let l of e)c(l);return i};var Kd="deploy-all.yml",OD="/bin/sh",DD=async()=>{let e=xs.quiet;xs.quiet=!0;try{let t=await xs`gh run list --workflow=${Kd} --status=in_progress --json displayTitle`;return JSON.parse(t.stdout).flatMap(n=>/\[(?<env>[a-z0-9-]+)\]/.exec(n.displayTitle??"")?.groups?.env??[])}catch{return[]}finally{xs.quiet=e}},ID=async(e,t)=>{let r=e.map(o=>({name:o.name,value:o.name})),n=await _(o=>TD({message:`Deploy which services to ${t}?`,choices:r,pageSize:20},o),{whenHeadless:{refuse:"service"}});if(n.length===0)throw new g(void 0,{operation:"select services",remediation:"pick at least one service, or use `local deploy-all`",stderrExcerpt:"no services selected"});return n},ND=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 X()&&li(i,{env:t,services:n,accountId:o,shared:r}),r?_(a=>$D({message:i,choices:[{name:"No, cancel",value:!1},{name:`Yes, deploy to ${t}`,value:!0}]},a),{whenHeadless:"refuse"}):_(a=>CD({message:i,default:!1},a),{whenHeadless:"refuse"})},Iw=e=>e.runner==="sh"?[OD,[e.scriptPath]]:[Jd.execPath,[Jd.argv[1]??"","deploy-run",e.name]],_D=(e,t,r)=>new Promise((n,o)=>{let[s,i]=Iw(e),a=AD(s,i,{cwd:r,env:t,stdio:"inherit"});a.on("error",o),a.on("close",c=>{n(c??1)})}),MD=async e=>{let{chosen:t,childEnv:r,cwd:n,env:o}=e,s=[],i=[];for(let a of t){d.info(`\u2192 ${a.name} \u2192 ${o}`);let c=await _D(a,r,n);if(c!==0){i.push(a.name),d.error(`\u2717 ${a.name} failed (exit ${c})`);break}s.push(a.name),d.info(`\u2713 ${a.name}`)}return{deployed:s,failed:i}},jD=e=>{let{names:t,services:r,env:n}=e,o=new Map(r.map(a=>[a.name,a])),s=t.filter(a=>!o.has(a));if(s.length>0)throw new g(void 0,{operation:"resolve the requested services",remediation:`known services: ${r.map(a=>a.name).join(", ")}`,stderrExcerpt:`no deploy script for: ${s.join(", ")}`});let i=t.filter(a=>{let c=o.get(a);return c!==void 0&&!Ps(c,n)});if(i.length>0)throw new g(void 0,{operation:`deploy to "${n}"`,remediation:"drop those services, or deploy them to an environment they allow",stderrExcerpt:`not enabled for "${n}": ${i.join(", ")} (the scripts would skip them)`});return t.map(a=>o.get(a))},Gd=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:Fd(o.contract),strippedVars:o.stripped,dryRun:a,success:c};return{content:b(JSON.stringify(l,null,2)),structuredContent:l}},FD=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:(y.setInteractive(),ID(r,o))},Nw=async(e,t)=>{let{env:r,service:n,confirmedCommand:o,dryRun:s,printEnv:i}=e,a=await $(),c=await Wd(a);if(c.length===0)throw new g(void 0,{operation:"discover deployable services",remediation:"run this from a repo that has infra-kit.deploy.ts or devops/scripts/deploy-*.sh",stderrExcerpt:`no deployable services found under ${a}`});let l=await Aw(a,c);await at({provider:Hd[t],params:e,operation:"deploy locally",argument:"env"});let u=await it(),p=Vt(await Gt(Kd),u),m=r??"";m||(y.setInteractive(),m=await Ln(p,"deploy locally")),y.addOption("--env",m);let f=Vd(c,m);if(f.length===0)throw new g(void 0,{operation:`deploy to "${m}"`,remediation:"pick an environment these services allow",stderrExcerpt:`no service on disk is enabled for "${m}"`});let h=await FD({selection:t,eligible:f,service:n,env:m}),S=Ow(jD({names:h,services:c,env:m}),c,m);if(t==="selected")for(let we of h)y.addOption("--service",we);let k=oo(m),A=await Vr(),M=(await xs`git rev-parse HEAD`.quiet()).stdout.trim(),v=await cf(),R=Ld({env:m,branch:A,sha:M,isClean:v});i&&d.info(`Deploy contract for ${m}:
414
- ${Da(R)}`);let E=(await Bd({env:m,project:l,isShared:k,isClean:v,runningEnvs:await DD(),protectedEnvAccess:u})).identity.accountId;if(s)return d.info([`Would deploy to "${m}" (AWS account ${E}) from this machine`,`Preflight parameter: /${l}/environment`,Da(R),"Commands:",...S.map(we=>` ${Iw(we).flat().join(" ")}`),"","Dry run: preflight and contract only \u2014 says nothing about whether the deploy would succeed."].join(`
415
- `)),Gd({env:m,accountId:E,names:h,built:R,deployed:[],failed:[],dryRun:!0,success:!0});if(!o&&!await ND({env:m,isShared:k,names:h,accountId:E}))return d.info("Deployment cancelled"),Gd({env:m,accountId:E,names:h,built:R,deployed:[],failed:[],dryRun:!1,success:!1});R.stripped.length>0&&d.info(`Stripped ambient VITE_* from the build env: ${R.stripped.join(", ")}`);let{deployed:B,failed:Z}=await MD({chosen:S,childEnv:R.childEnv,cwd:a,env:m});return Z.length>0&&(d.error(`Partial deploy to "${m}": succeeded [${B.join(", ")||"none"}], failed [${Z.join(", ")}]. There is no rollback \u2014 redeploy the previous commit to restore it.`),Jd.exitCode=1),y.print(),Gd({env:m,accountId:E,names:h,built:R,deployed:B,failed:Z,dryRun:!1,success:Z.length===0})},_w=async e=>Nw(e,"all"),Mw=async e=>Nw(e,"selected"),jw='Runs the repo\'s own deploys (infra-kit.deploy.ts via deploy-run, else 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.',Fw={env:te.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:te.boolean().optional().describe("Resolve target, contract and commands without deploying."),confirm:te.boolean().optional().describe("Set true to execute; omit for a dry-run gate.")},Lw={environment:te.string().describe("Environment deployed to"),accountId:te.string().describe("AWS account the deploy targeted"),services:te.array(te.string()).describe("Services requested"),deployed:te.array(te.string()).describe("Services that completed successfully"),failed:te.array(te.string()).describe("Services that failed"),contract:te.record(te.string(),te.string()).describe("Build contract passed to the scripts"),strippedVars:te.array(te.string()).describe("Ambient VITE_* names removed from the build env"),dryRun:te.boolean().describe("Whether this was a dry run"),success:te.boolean().describe("Whether every requested service deployed")},Dw=e=>Dr({workflowFile:Kd,fields:["env"],toolName:e}),Hd={all:Dw("local-deploy-all"),selected:Dw("local-deploy-selected")},qd=C({name:"local-deploy-all",description:`Deploy EVERY service enabled for an environment, from this machine. ${jw}`,requiresHumanConfirm:!0,formProvider:Hd.all,inputSchema:Fw,outputSchema:Lw,handler:_w}),Yd=C({name:"local-deploy-selected",description:`Deploy a NAMED SUBSET of services from this machine. ${jw}`,requiresHumanConfirm:!0,formProvider:Hd.selected,inputSchema:{...Fw,service:te.array(te.string()).min(1).describe('Service names as in infra-kit.deploy.ts or devops/scripts/deploy-<name>.sh, e.g. ["client-be"]. Required for MCP.')},outputSchema:Lw,handler:Mw});import UD from"@inquirer/confirm";import Ia from"@inquirer/input";import Vw from"@inquirer/select";import Xd from"node:process";import{z as H}from"zod";import{z as Ts}from"zod";var Bn=async(e,t)=>new Promise(r=>{let n=setTimeout(()=>{r(null)},t);e.then(o=>{clearTimeout(n),r(o)},()=>{clearTimeout(n),r(null)})});var Ww=2500,Bw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Uw=e=>typeof e=="string"&&e.trim()!==""?e.trim():void 0,LD=async()=>{let e=await Qo();return{regular:_n(e,"regular"),hotfix:_n(e,"hotfix")}},BD=(e,t)=>e===null?(d.info({msg:"Tool execution form hint unavailable (timeout): release-create"}),`The "next" hint could not be computed within ${t/1e3} s \u2014 "next" still works and is resolved at execution.`):e.regular===null&&e.hotfix===null?(d.info({msg:"Tool execution form hint unavailable (no prior versions): release-create"}),'No prior version is known from origin release/v* branches or Jira, so "next" will be REFUSED \u2014 pass an explicit semver.'):`"next" resolves to ${e.regular} for a regular release or ${e.hotfix} for a hotfix (computed now from origin release/v* branches and Jira fix versions; recomputed at execution).`,zd=(e={})=>{let t=e.hintBudgetMs??Ww;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=>Bw(r)&&(r.releases===void 0||Array.isArray(r.releases)&&r.releases.length===0),buildRequestedSchema:async()=>{let r=await Bn(LD(),t);return Ts.object({type:Ts.enum(["regular","hotfix"]).describe('Release type. "regular" branches off dev and bumps the minor; "hotfix" branches off main and bumps the patch.'),release:Ts.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. ${BD(r,t)}`),description:Ts.string().optional().describe("Optional. Becomes the Jira fix version description and feeds the PR body. Blank means none."),releaseDate:Ts.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=Uw(r.description),a=Uw(r.releaseDate),c=ua(o);return{...Bw(n)?n:{},releases:[{...c,type:s,...i===void 0?{}:{description:i},...a===void 0?{}:{releaseDate:a}}]}}}};var WD='"1.2.5" or "next"',Zd=(e,t)=>{try{return Gu(e,t)}catch(r){throw r instanceof Pr?new g(r,{operation:"resolve release version",remediation:'pass an explicit version (e.g. "1.2.5") instead of "next" when there are no prior versions'}):r instanceof nf?new g(r,{operation:"validate release name",remediation:'use a kebab-case name like "checkout-redesign" (lowercase, digits, single hyphens, not a reserved word)'}):r}},VD=async(e,t)=>{let r=_n(e,t),n=r?` [${r}]`:"",o=(await _(i=>Ia({message:` Version (e.g. ${WD})${n}: `},i),{whenHeadless:"refuse"})).trim(),s=o===""?r??"":o;return s===""&&(d.error("No version provided. Exiting..."),Xd.exit(1)),s},GD=async()=>{let e=(await _(t=>Ia({message:' Name (kebab-case, e.g. "checkout-redesign"): '},t),{whenHeadless:"refuse"})).trim();e===""&&(d.error("No name provided. Exiting..."),Xd.exit(1));try{ri(e)}catch(t){let r=t instanceof Error?t.message:String(t);d.error(`${r} Exiting...`),Xd.exit(1)}return e},JD=async()=>(await _(e=>Ia({message:" Release date (yyyy-mm-dd, optional, press Enter to skip): ",validate:Zo},e),{whenHeadless:"refuse"})).trim(),KD=async e=>{y.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 _(m=>Vw({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 _(m=>Vw({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 GD();l=Zd([{name:m,type:c}],[])[0]}else{let m=await VD(await n(),c);l=Zd([{version:m,type:c}],r)[0],l.id.kind==="version"&&r.push(Zt(`v${l.id.raw}`))}let u=(await _(m=>Ia({message:" Description (optional, press Enter to skip): "},m),{whenHeadless:"refuse"})).trim(),p=await JD();o.push({...l,...u!==""?{description:u}:{},...p!==""?{releaseDate:p}:{}}),s=await _(m=>UD({message:"Add another release?",default:!1},m),{whenHeadless:"refuse"})}return o},HD=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 ")},Gw=e=>{for(let t of e)y.addOption("--release",Vu(t))},qD=async(e,t)=>{if(e&&e.length>0){let n=Ju(e)?await t():[],o=Zd(e,n);return Gw(o),o}if(he())throw new O({status:"argument_required",argument:"release",agentMode:j.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 KD(t);return Gw(r),r},YD=e=>{if(new Set(e.map(r=>r.type)).size>1)throw new g(void 0,{operation:"create release",remediation:"create regular and hotfix releases in separate invocations",stderrExcerpt:"mixed regular and hotfix releases in one batch are not supported"})},zD=async(e,t)=>{let r=e.map(HD).join(`
416
- - `);await J(t,`Create the following ${e.length} release(s)?
420
+ `);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:R(JSON.stringify(s,null,2)),structuredContent:s}},Vd=C({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:or.array(or.object({version:or.string().describe("Release version"),type:or.enum(["regular","hotfix"]).describe("Release type"),description:or.string().nullable().describe("Jira version description"),releaseDate:or.string().nullable().describe("Planned release date of the Jira version (yyyy-mm-dd)"),titleMismatch:or.boolean().describe("The PR title names a different release type than its base branch")})).describe("List of all release branches"),count:or.number().describe("Number of release branches")},handler:_a});import wD from"node:process";var Ts="local-deploy";var Jd=e=>({...e}),Kd=e=>{let{env:t,branch:r,sha:n,isClean:o,ambient:s=wD.env}=e,i={VITE_DOMAIN_ENV:t,VITE_BRANCH_NAME:r,VITE_COMMIT_HASH:o?n:`${n}-dirty`},a={},c=[];for(let[l,u]of Object.entries(s)){if(l.startsWith("VITE_")){c.push(l);continue}a[l]=u}return c.sort(),{childEnv:{...a,...i,DEPLOY_ENV:t,DEPLOY_BRANCH:r,DEPLOY_SHA:n,DEPLOY_SHA_LABEL:i.VITE_COMMIT_HASH,TURBO_TELEMETRY_DISABLED:"1",INFRA_KIT_DEPLOY_VIA:Ts},contract:i,stripped:c}},Ma=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(`
421
+ `)};import MD from"@inquirer/checkbox";import jD from"@inquirer/confirm";import FD from"@inquirer/select";import{spawn as LD}from"node:child_process";import Zd from"node:process";import{z as re}from"zod";import{$ as Os}from"zx";import{$ as Cs}from"zx";var kD=async e=>{let t=Cs.quiet;Cs.quiet=!0;try{let r=`/${e}/environment`,n=await Cs`aws sts get-caller-identity --query Account --output text`,o=await Cs`aws ssm get-parameter --name ${r} --query Parameter.Value --output text`;return{accountId:n.stdout.trim(),stage:o.stdout.trim()}}catch(r){throw new g(r,{operation:"resolve the AWS account for this deploy",remediation:`check that credentials are loaded and that \`/${e}/environment\` exists in the account they point at \u2014 run \`aws sts get-caller-identity\` to see which account that is`})}finally{Cs.quiet=t}},Sw=(e,t)=>{if(t.stage!==e)throw new g(void 0,{operation:"verify the target environment",remediation:"switch AWS_PROFILE to the account for this environment, or pass the env this account is",stderrExcerpt:`you asked for "${e}", but AWS account ${t.accountId} reports "${t.stage}" \u2014 refusing to deploy to an environment you did not name`})},Ew=e=>{let{env:t,isShared:r,isClean:n}=e;if(!(!r||n))throw new g(void 0,{operation:`deploy to shared environment "${t}"`,remediation:"commit, or `git stash -u` (plain stash leaves untracked files), or deploy to a personal environment",stderrExcerpt:"the working tree has uncommitted or untracked changes and this environment is shared"})},Pw=(e,t)=>{if(t.includes(e))throw new g(void 0,{operation:`deploy to "${e}"`,remediation:"wait for the CI run to finish, or watch it with `gh run watch`",stderrExcerpt:`a CI deploy to "${e}" is already in flight \u2014 running both would interleave`})},Hd=async e=>{let{env:t,project:r,isShared:n,isClean:o,runningEnvs:s,protectedEnvAccess:i}=e;zr(t,`deploy to "${t}"`,i),Pw(t,s),Ew({env:t,isShared:n,isClean:o});let a=await kD(r);return Sw(t,a),{identity:a}};import{serviceDependencies as bD}from"@slip-stream-kit/config/internal";import qd from"node:fs/promises";import $s from"node:path";var Cw="devops/scripts",RD=/^deploy-(?<service>[a-z0-9-]+)\.sh$/,SD=/skip_unless_env_enabled\s+"[^"]*"\s+"[^"]*"\s+"(?<envs>[^"]*)"/,ED=/aws\s+ssm\s+get-parameter\s+--name[=\s]+(?<arg>[^\s)]+)/,PD=/aws\s+ssm\s+get-parameter\s+--name[=\s]+["']?\/(?<prefix>[\w.-]+)\/environment["']?(?![\w./-])/,xD=/(["'`])\/(?<prefix>[\w.-]+)\/environment\1/,TD=/`[^`]*\$\{[^`]*\/environment[^`]*`/,xw={commentPrefixes:["#"],literalPrefix:e=>PD.exec(e)?.groups?.prefix,isUnparseable:e=>{let t=ED.exec(e)?.groups?.arg;return t!==void 0&&DD(t)}},Tw={commentPrefixes:["//","/*","*"],literalPrefix:e=>xD.exec(e)?.groups?.prefix,isUnparseable:e=>TD.test(e)},Yd=async e=>{let t=await kt(e),r=await Id(e);return(t===void 0?await CD(e,r):await $D(e,t,r)).sort((o,s)=>o.name.localeCompare(s.name))},CD=async(e,t)=>{let r=$s.resolve(e,Cw),n;try{n=await qd.readdir(r)}catch{return[]}return Promise.all(n.flatMap(o=>{let s=RD.exec(o)?.groups?.service;return s===void 0?[]:[$w(s,$s.resolve(r,o),t)]}))},$w=async(e,t,r)=>{let n=Ow(await Aw(t),xw);return{name:e,scriptPath:t,runner:"sh",allowedEnvs:Rs(OD(n),r.get(e)),ssmPrefix:Dw(n,xw)}},$D=async(e,t,r)=>{let n=ks(t),o=bD(t.services),s=(a,c)=>({...(o.get(a)??[]).length===0?{}:{dependsOn:o.get(a)},...c.runsBefore===void 0?{}:{runsBefore:[...c.runsBefore]}});return(await Promise.all(Object.entries(t.services).map(async([a,c])=>{if(c.deploy===void 0){let p=$s.resolve(e,Cw,`deploy-${a}.sh`);if(!await AD(p))return null;let m=await $w(a,p,r);return{...m,allowedEnvs:Rs(m.allowedEnvs,n.get(a)),...s(a,c)}}let l=$s.resolve(e,c.deploy),u=Ow(await Aw(l),Tw);return{name:a,scriptPath:l,runner:"deploy-run",allowedEnvs:Rs(n.get(a)??null,r.get(a)),ssmPrefix:Dw(u,Tw),...s(a,c)}}))).filter(a=>a!==null)},AD=async e=>{try{return await qd.access(e),!0}catch{return!1}},Aw=async e=>{try{return await qd.readFile(e,"utf-8")}catch{return""}},Ow=(e,t)=>e.split(`
422
+ `).map((r,n)=>({line:n+1,text:r})).filter(({text:r})=>{let n=r.trimStart();return!t.commentPrefixes.some(o=>n.startsWith(o))}),OD=e=>{let t=e.reduce((n,{text:o})=>n??SD.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},DD=e=>{let t=e.replaceAll(/["']/g,"");return t.includes("$")&&(t.includes("/environment")||t.startsWith("$"))},Dw=(e,t)=>{for(let{line:r,text:n}of e){let o=t.literalPrefix(n);if(o!==void 0)return o;if(t.isUnparseable(n))return{unparseable:{line:r,text:n.trim()}}}return null},Iw=e=>{let t=$s.basename(e.scriptPath);return e.runner==="sh"?t:`${e.name} (${t})`},ID=e=>{let t=new Map;for(let r of e)typeof r.ssmPrefix=="string"&&t.set(r.ssmPrefix,[...t.get(r.ssmPrefix)??[],Iw(r)]);return t},ND=e=>{let t=e.flatMap(r=>{if(r.ssmPrefix===null||typeof r.ssmPrefix=="string")return[];let{line:n,text:o}=r.ssmPrefix.unparseable;return[`${Iw(r)}:${n}: ${o}`]});if(t.length!==0)throw new g(void 0,{operation:"resolve the SSM project prefix",remediation:"write the parameter name as a literal `/<project>/environment` so infra-kit can preflight it",stderrExcerpt:t.join("; ")})},_D=e=>{ND(e);let t=ID(e),[r,...n]=t.keys();if(r===void 0)throw new g(void 0,{operation:"resolve the SSM project prefix",remediation:'read the literal "/<project>/environment" in at least one deploy script: a deploy.ts in infra-kit.deploy.ts, or `aws ssm get-parameter --name "/<project>/environment"` in a devops/scripts/deploy-*.sh',stderrExcerpt:`none of ${e.length} deploy scripts reads /<project>/environment`});if(n.length>0){let o=[...t.entries()].sort(([,s],[,i])=>s.length-i.length).map(([s,i])=>`${s}: ${i.join(", ")}`).join("; ");throw new g(void 0,{operation:"resolve the SSM project prefix",remediation:"make every deploy script read the same /<project>/environment parameter",stderrExcerpt:`${t.size} different prefixes across ${e.length} deploy scripts \u2014 ${o}`})}return r},Nw=async(e,t)=>(await kt(e))?.project??_D(t),As=(e,t)=>e.allowedEnvs===null||e.allowedEnvs.includes(t),zd=(e,t)=>e.filter(r=>r.runsBefore===void 0&&As(r,t)),_w=(e,t,r)=>{let n=new Set(e.map(l=>l.name)),o=t.filter(l=>!n.has(l.name)&&As(l,r)&&(l.runsBefore??[]).some(u=>n.has(u))),s=new Map([...o,...e].map(l=>[l.name,l])),i=[],a=new Set,c=l=>{if(!a.has(l.name)){a.add(l.name);for(let u of l.dependsOn??[]){let p=s.get(u);p!==void 0&&c(p)}i.push(l)}};for(let l of e)c(l);return i};var Qd="deploy-all.yml",BD="/bin/sh",UD=async()=>{let e=Os.quiet;Os.quiet=!0;try{let t=await Os`gh run list --workflow=${Qd} --status=in_progress --json displayTitle`;return JSON.parse(t.stdout).flatMap(n=>/\[(?<env>[a-z0-9-]+)\]/.exec(n.displayTitle??"")?.groups?.env??[])}catch{return[]}finally{Os.quiet=e}},WD=async(e,t)=>{let r=e.map(o=>({name:o.name,value:o.name})),n=await M(o=>MD({message:`Deploy which services to ${t}?`,choices:r,pageSize:20},o),{whenHeadless:{refuse:"service"}});if(n.length===0)throw new g(void 0,{operation:"select services",remediation:"pick at least one service, or use `local deploy-all`",stderrExcerpt:"no services selected"});return n},GD=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 Q()&&mi(i,{env:t,services:n,accountId:o,shared:r}),r?M(a=>FD({message:i,choices:[{name:"No, cancel",value:!1},{name:`Yes, deploy to ${t}`,value:!0}]},a),{whenHeadless:"refuse"}):M(a=>jD({message:i,default:!1},a),{whenHeadless:"refuse"})},jw=e=>e.runner==="sh"?[BD,[e.scriptPath]]:[Zd.execPath,[Zd.argv[1]??"","deploy-run",e.name]],VD=(e,t,r)=>new Promise((n,o)=>{let[s,i]=jw(e),a=LD(s,i,{cwd:r,env:t,stdio:"inherit"});a.on("error",o),a.on("close",c=>{n(c??1)})}),JD=async e=>{let{chosen:t,childEnv:r,cwd:n,env:o}=e,s=[],i=[];for(let a of t){d.info(`\u2192 ${a.name} \u2192 ${o}`);let c=await VD(a,r,n);if(c!==0){i.push(a.name),d.error(`\u2717 ${a.name} failed (exit ${c})`);break}s.push(a.name),d.info(`\u2713 ${a.name}`)}return{deployed:s,failed:i}},KD=e=>{let{names:t,services:r,env:n}=e,o=new Map(r.map(a=>[a.name,a])),s=t.filter(a=>!o.has(a));if(s.length>0)throw new g(void 0,{operation:"resolve the requested services",remediation:`known services: ${r.map(a=>a.name).join(", ")}`,stderrExcerpt:`no deploy script for: ${s.join(", ")}`});let i=t.filter(a=>{let c=o.get(a);return c!==void 0&&!As(c,n)});if(i.length>0)throw new g(void 0,{operation:`deploy to "${n}"`,remediation:"drop those services, or deploy them to an environment they allow",stderrExcerpt:`not enabled for "${n}": ${i.join(", ")} (the scripts would skip them)`});return t.map(a=>o.get(a))},Xd=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:Jd(o.contract),strippedVars:o.stripped,dryRun:a,success:c};return{content:R(JSON.stringify(l,null,2)),structuredContent:l}},HD=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:(y.setInteractive(),WD(r,o))},Fw=async(e,t)=>{let{env:r,service:n,confirmedCommand:o,dryRun:s,printEnv:i}=e,a=await A(),c=await Yd(a);if(c.length===0)throw new g(void 0,{operation:"discover deployable services",remediation:"run this from a repo that has infra-kit.deploy.ts or devops/scripts/deploy-*.sh",stderrExcerpt:`no deployable services found under ${a}`});let l=await Nw(a,c);await lt({provider:ep[t],params:e,operation:"deploy locally",argument:"env"});let u=await ct(),p=Jt(await Kt(Qd),u),m=r??"";m||(y.setInteractive(),m=await Vn(p,"deploy locally")),y.addOption("--env",m);let f=zd(c,m);if(f.length===0)throw new g(void 0,{operation:`deploy to "${m}"`,remediation:"pick an environment these services allow",stderrExcerpt:`no service on disk is enabled for "${m}"`});let h=await HD({selection:t,eligible:f,service:n,env:m}),b=_w(KD({names:h,services:c,env:m}),c,m);if(t==="selected")for(let be of h)y.addOption("--service",be);let T=uo(m),k=await Hr(),j=(await Os`git rev-parse HEAD`.quiet()).stdout.trim(),v=await gf(),S=Kd({env:m,branch:k,sha:j,isClean:v});i&&d.info(`Deploy contract for ${m}:
423
+ ${Ma(S)}`);let $=(await Hd({env:m,project:l,isShared:T,isClean:v,runningEnvs:await UD(),protectedEnvAccess:u})).identity.accountId;if(s)return d.info([`Would deploy to "${m}" (AWS account ${$}) from this machine`,`Preflight parameter: /${l}/environment`,Ma(S),"Commands:",...b.map(be=>` ${jw(be).flat().join(" ")}`),"","Dry run: preflight and contract only \u2014 says nothing about whether the deploy would succeed."].join(`
424
+ `)),Xd({env:m,accountId:$,names:h,built:S,deployed:[],failed:[],dryRun:!0,success:!0});if(!o&&!await GD({env:m,isShared:T,names:h,accountId:$}))return d.info("Deployment cancelled"),Xd({env:m,accountId:$,names:h,built:S,deployed:[],failed:[],dryRun:!1,success:!1});S.stripped.length>0&&d.info(`Stripped ambient VITE_* from the build env: ${S.stripped.join(", ")}`);let{deployed:O,failed:B}=await JD({chosen:b,childEnv:S.childEnv,cwd:a,env:m});return B.length>0&&(d.error(`Partial deploy to "${m}": succeeded [${O.join(", ")||"none"}], failed [${B.join(", ")}]. There is no rollback \u2014 redeploy the previous commit to restore it.`),Zd.exitCode=1),y.print(),Xd({env:m,accountId:$,names:h,built:S,deployed:O,failed:B,dryRun:!1,success:B.length===0})},Lw=async e=>Fw(e,"all"),Bw=async e=>Fw(e,"selected"),Uw='Runs the repo\'s own deploys (infra-kit.deploy.ts via deploy-run, else 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.',Ww={env:re.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:re.boolean().optional().describe("Resolve target, contract and commands without deploying."),confirm:re.boolean().optional().describe("Set true to execute; omit for a dry-run gate.")},Gw={environment:re.string().describe("Environment deployed to"),accountId:re.string().describe("AWS account the deploy targeted"),services:re.array(re.string()).describe("Services requested"),deployed:re.array(re.string()).describe("Services that completed successfully"),failed:re.array(re.string()).describe("Services that failed"),contract:re.record(re.string(),re.string()).describe("Build contract passed to the scripts"),strippedVars:re.array(re.string()).describe("Ambient VITE_* names removed from the build env"),dryRun:re.boolean().describe("Whether this was a dry run"),success:re.boolean().describe("Whether every requested service deployed")},Mw=e=>Mr({workflowFile:Qd,fields:["env"],toolName:e}),ep={all:Mw("local-deploy-all"),selected:Mw("local-deploy-selected")},tp=C({name:"local-deploy-all",description:`Deploy EVERY service enabled for an environment, from this machine. ${Uw}`,requiresHumanConfirm:!0,formProvider:ep.all,inputSchema:Ww,outputSchema:Gw,handler:Lw}),rp=C({name:"local-deploy-selected",description:`Deploy a NAMED SUBSET of services from this machine. ${Uw}`,requiresHumanConfirm:!0,formProvider:ep.selected,inputSchema:{...Ww,service:re.array(re.string()).min(1).describe('Service names as in infra-kit.deploy.ts or devops/scripts/deploy-<name>.sh, e.g. ["client-be"]. Required for MCP.')},outputSchema:Gw,handler:Bw});import zD from"@inquirer/confirm";import ja from"@inquirer/input";import Hw from"@inquirer/select";import op from"node:process";import{z as q}from"zod";import{z as Ds}from"zod";var Jn=async(e,t)=>new Promise(r=>{let n=setTimeout(()=>{r(null)},t);e.then(o=>{clearTimeout(n),r(o)},()=>{clearTimeout(n),r(null)})});var Kw=2500,Vw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Jw=e=>typeof e=="string"&&e.trim()!==""?e.trim():void 0,qD=async()=>{let e=await os();return{regular:Bn(e,"regular"),hotfix:Bn(e,"hotfix")}},YD=(e,t)=>e===null?(d.info({msg:"Tool execution form hint unavailable (timeout): release-create"}),`The "next" hint could not be computed within ${t/1e3} s \u2014 "next" still works and is resolved at execution.`):e.regular===null&&e.hotfix===null?(d.info({msg:"Tool execution form hint unavailable (no prior versions): release-create"}),'No prior version is known from origin release/v* branches or Jira, so "next" will be REFUSED \u2014 pass an explicit semver.'):`"next" resolves to ${e.regular} for a regular release or ${e.hotfix} for a hotfix (computed now from origin release/v* branches and Jira fix versions; recomputed at execution).`,np=(e={})=>{let t=e.hintBudgetMs??Kw;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=>Vw(r)&&(r.releases===void 0||Array.isArray(r.releases)&&r.releases.length===0),buildRequestedSchema:async()=>{let r=await Jn(qD(),t),n=await te(),[o,...s]=wn(n);return Ds.object({type:Ds.enum([o,...s]).describe(n==="main"?'Release type. This repo sets "gitFlow": "main", so every release is "regular": it branches off main and bumps the minor.':'Release type. "regular" branches off dev and bumps the minor; "hotfix" branches off main and bumps the patch.'),release:Ds.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. ${YD(r,t)}`),description:Ds.string().optional().describe("Optional. Becomes the Jira fix version description and feeds the PR body. Blank means none."),releaseDate:Ds.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=Jw(r.description),a=Jw(r.releaseDate),c=fa(o);return{...Vw(n)?n:{},releases:[{...c,type:s,...i===void 0?{}:{description:i},...a===void 0?{}:{releaseDate:a}}]}}}};var XD='"1.2.5" or "next"',sp=(e,t)=>{try{return Xu(e,t)}catch(r){throw r instanceof $r?new g(r,{operation:"resolve release version",remediation:'pass an explicit version (e.g. "1.2.5") instead of "next" when there are no prior versions'}):r instanceof df?new g(r,{operation:"validate release name",remediation:'use a kebab-case name like "checkout-redesign" (lowercase, digits, single hyphens, not a reserved word)'}):r}},ZD=async(e,t)=>{let r=Bn(e,t),n=r?` [${r}]`:"",o=(await M(i=>ja({message:` Version (e.g. ${XD})${n}: `},i),{whenHeadless:"refuse"})).trim(),s=o===""?r??"":o;return s===""&&(d.error("No version provided. Exiting..."),op.exit(1)),s},QD=async()=>{let e=(await M(t=>ja({message:' Name (kebab-case, e.g. "checkout-redesign"): '},t),{whenHeadless:"refuse"})).trim();e===""&&(d.error("No name provided. Exiting..."),op.exit(1));try{ii(e)}catch(t){let r=t instanceof Error?t.message:String(t);d.error(`${r} Exiting...`),op.exit(1)}return e},eI=async()=>(await M(e=>ja({message:" Release date (yyyy-mm-dd, optional, press Enter to skip): ",validate:ns},e),{whenHeadless:"refuse"})).trim(),tI=async e=>{y.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 M(f=>Hw({message:`Release #${i} \u2014 version or name?`,choices:[{name:"version (semver / next)",value:"version"},{name:"name (free-form)",value:"name"}],default:"version"},f),{whenHeadless:"refuse"}),c=wn(await te()),l=c.length===1?c[0]:await M(f=>Hw({message:`Release #${i} \u2014 select type:`,choices:c.map(h=>({name:h,value:h})),default:"regular"},f),{whenHeadless:"refuse"}),u;if(a==="name"){let f=await QD();u=sp([{name:f,type:l}],[])[0]}else{let f=await ZD(await n(),l);u=sp([{version:f,type:l}],r)[0],u.id.kind==="version"&&r.push(er(`v${u.id.raw}`))}let p=(await M(f=>ja({message:" Description (optional, press Enter to skip): "},f),{whenHeadless:"refuse"})).trim(),m=await eI();o.push({...u,...p!==""?{description:p}:{},...m!==""?{releaseDate:m}:{}}),s=await M(f=>zD({message:"Add another release?",default:!1},f),{whenHeadless:"refuse"})}return o},rI=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 ")},qw=e=>{for(let t of e)y.addOption("--release",zu(t))},nI=async(e,t)=>{if(e&&e.length>0){let n=Zu(e)?await t():[],o=sp(e,n);return qw(o),o}if(ye())throw new D({status:"argument_required",argument:"release",agentMode:F.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 tI(t);return qw(r),r},oI=e=>{if(new Set(e.map(r=>r.type)).size>1)throw new g(void 0,{operation:"create release",remediation:"create regular and hotfix releases in separate invocations",stderrExcerpt:"mixed regular and hotfix releases in one batch are not supported"})},sI=async(e,t)=>{let r=e.map(rI).join(`
425
+ - `);await H(t,`Create the following ${e.length} release(s)?
417
426
  - ${r}
418
- `),y.addOption("--yes",!0)},XD=async e=>{let{entry:t,jiraConfig:r}=e,n=ne(t.id),o=t.id.kind==="version"?`v${t.id.raw}`:t.id.name;try{await an({operation:`create release ${o}`});let s=await nu(t.type),i=await ou({id:t.id,jiraConfig:r,description:t.description,...t.releaseDate===void 0?{}:{releaseDate:t.releaseDate},type:t.type,baseSha:s});return d.info(`\u2705 Successfully created release: ${o} (${t.type})`),d.info(`\u{1F517} GitHub PR: ${i.prUrl}`),d.info(`\u{1F517} Jira Version: ${i.jiraVersionUrl}
419
- `),{result:i}}catch(s){let i=No(s)?s:void 0,a=new g(s,{operation:`create release ${o} (${t.type})`,remediation:i?.kind==="auth"?"reissue the Atlassian API token and update JIRA_TOKEN":"verify the version or name is unique and the base branch is clean",stderrExcerpt:i?.message});return d.error(`\u274C ${a.message}
420
- `),{failure:{version:n,error:a.message}}}},ZD=(e,t,r)=>{t===e?d.info(`\u2705 All ${e} release branch(es) were created successfully.`):t>0?(d.warn(`\u26A0\uFE0F ${t} of ${e} release branches were created successfully.`),d.warn(`\u274C ${r} release(s) failed.`)):d.error(`\u274C All ${e} release branch(es) failed to create.`)},Jw=zd(),Na=async e=>{let{releases:t,confirmedCommand:r}=e;await _e({operation:"create release"}),await at({provider:Jw,params:e,operation:"create release",argument:"release"});let n=await fn(),o=null,i=await qD(t,async()=>(o===null&&(o=await Qo()),o));if(i.length===0)throw new g(void 0,{operation:"create release",remediation:'pass at least one entry in "releases" (e.g. [{ version: "1.2.5", type: "regular" }])',stderrExcerpt:"no releases provided"});YD(i),await $o({operation:"create release",base:mt(i[0].type)}),await zD(i,!!r);let a=[],c=[];for(let u of i){let{result:p,failure:m}=await XD({entry:u,jiraConfig:n});p&&a.push(p),m&&c.push(m)}ZD(i.length,a.length,c.length),y.print();let l={createdBranches:a.map(u=>u.branchName),successCount:a.length,failureCount:c.length,releases:a,failedReleases:c};return{content:b(JSON.stringify(l,null,2)),structuredContent:l}},Qd=C({name:"release-create",requiresHumanConfirm:!0,formProvider:Jw,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:H.array(H.object({version:H.string().optional().describe('Version to create (e.g., "1.2.5") or the literal token "next" for auto-increment. Mutually exclusive with "name".'),name:H.string().optional().describe('Free-form kebab-case release name (e.g., "checkout-redesign"). Mutually exclusive with "version". Named releases never auto-bump.'),type:H.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" (branches off dev) or "hotfix" (branches off main).'),description:H.string().optional().describe("Optional description for the Jira version."),releaseDate:Mu.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:H.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{createdBranches:H.array(H.string()).describe("List of created release branch names"),successCount:H.number().describe("Number of releases created successfully"),failureCount:H.number().describe("Number of releases that failed"),releases:H.array(H.object({version:H.string().describe("Version number"),type:H.enum(["regular","hotfix"]).describe("Release type"),branchName:H.string().describe("Release branch name"),prUrl:H.string().describe("GitHub PR URL"),jiraVersionUrl:H.string().describe("Jira version URL"),releaseDate:H.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:H.array(H.object({version:H.string().describe("Version number that failed"),error:H.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:Na});import Kw from"@inquirer/input";import{z as Ye}from"zod";var Hw=["description","releaseDate"],QD=async()=>{let e=await G(),t=e.map(s=>s.branch),r=new Map(e.map(s=>[s.branch,s.type])),n=await me(),o=await qt(fe({branches:t,descriptions:n,types:r}));return{branch:o,type:r.get(o)||"regular"}},eI=async e=>{let r=(await G()).find(n=>n.branch===e);if(!r)throw new g(void 0,{operation:`edit release ${e}`,remediation:`confirm an open PR exists for ${e} ('gh pr list')`});return r.type},tI=async e=>{let t=e===""?"(no current description)":`current: "${e}"`,n=(await _(o=>Kw({message:` New description ${t} (press Enter to keep current): `},o),{whenHeadless:{refuse:"description"}})).trim();return n===""?e:n},rI=async e=>{let t=e===null?"(no current date)":`current: ${e}`,n=(await _(o=>Kw({message:` Release date yyyy-mm-dd ${t} (press Enter to keep current): `,validate:Zo},o),{whenHeadless:{refuse:"releaseDate"}})).trim();return n===""?e:Er(n)},nI=e=>{if(e!==void 0)return e===""?null:e},oI=async e=>(y.setInteractive(),{description:await tI(e.description),releaseDate:await rI(e.releaseDate)}),ep=e=>e??"(none)",sI=(e,t,r)=>e==="description"?` description: "${t.description}" \u2192 "${r.description}"`:` release date: ${ep(t.releaseDate)} \u2192 ${ep(r.releaseDate)}`,_a=async e=>{let{version:t,description:r,releaseDate:n,confirmedCommand:o}=e,s=nI(n),i=await fn(),a;t?(a=Ot(t),await eI(a)):(y.setInteractive(),a=(await QD()).branch);let c=Q(a);if(!c)throw new g(void 0,{operation:`edit release ${a}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let l=ne(c);y.addOption("--version",l);let u=le(c),p=await $t(u,i);if(!p)throw new g(void 0,{operation:`edit release ${u}`,remediation:`create the Jira fix version "${u}" first or pick a different release`});let m={description:p.description??"",releaseDate:p.releaseDate||null},f=r!==void 0||s!==void 0;if(!f&&X())throw new O({status:"argument_required",argument:"description",agentMode:j.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 h=f?{description:r??m.description,releaseDate:s===void 0?m.releaseDate:s}:await oI(m),S=Hw.filter(T=>h[T]!==m[T]),k=S.includes("description"),A=S.includes("releaseDate"),M=wr(i,p),v=T=>{let E={version:l,branch:a,jiraVersionUrl:M,previousDescription:m.description,newDescription:h.description,previousReleaseDate:m.releaseDate,newReleaseDate:h.releaseDate,changedFields:S,changed:T};return{content:b(JSON.stringify(E,null,2)),structuredContent:E}};if(S.length===0)return d.info(`No change \u2014 ${u} already has description "${m.description}" and release date ${ep(m.releaseDate)}`),y.print(),v(!1);k&&y.addOption("--description",h.description),A&&y.addOption("--release-date",h.releaseDate??"");let R=S.map(T=>sI(T,m,h));return await J(o,`Update ${u}?
421
- ${R.join(`
427
+ `),y.addOption("--yes",!0)},iI=async e=>{let{entry:t,jiraConfig:r}=e,n=oe(t.id),o=t.id.kind==="version"?`v${t.id.raw}`:t.id.name;try{await dn({operation:`create release ${o}`});let s=await uu(t.type),i=await du({id:t.id,jiraConfig:r,description:t.description,...t.releaseDate===void 0?{}:{releaseDate:t.releaseDate},type:t.type,baseSha:s});return d.info(`\u2705 Successfully created release: ${o} (${t.type})`),d.info(`\u{1F517} GitHub PR: ${i.prUrl}`),d.info(`\u{1F517} Jira Version: ${i.jiraVersionUrl}
428
+ `),{result:i}}catch(s){let i=Lo(s)?s:void 0,a=new g(s,{operation:`create release ${o} (${t.type})`,remediation:i?.kind==="auth"?"reissue the Atlassian API token and update JIRA_TOKEN":"verify the version or name is unique and the base branch is clean",stderrExcerpt:i?.message});return d.error(`\u274C ${a.message}
429
+ `),{failure:{version:n,error:a.message}}}},aI=(e,t,r)=>{t===e?d.info(`\u2705 All ${e} release branch(es) were created successfully.`):t>0?(d.warn(`\u26A0\uFE0F ${t} of ${e} release branches were created successfully.`),d.warn(`\u274C ${r} release(s) failed.`)):d.error(`\u274C All ${e} release branch(es) failed to create.`)},Yw=np(),Fa=async e=>{let{releases:t,confirmedCommand:r}=e;await je({operation:"create release"}),await lt({provider:Yw,params:e,operation:"create release",argument:"release"});let n=await vn(),o=null,i=await nI(t,async()=>(o===null&&(o=await os()),o));if(i.length===0)throw new g(void 0,{operation:"create release",remediation:'pass at least one entry in "releases" (e.g. [{ version: "1.2.5", type: "regular" }])',stderrExcerpt:"no releases provided"});oI(i),await _o({operation:"create release",base:gt(i[0].type,await te())}),await sI(i,!!r);let a=[],c=[];for(let u of i){let{result:p,failure:m}=await iI({entry:u,jiraConfig:n});p&&a.push(p),m&&c.push(m)}aI(i.length,a.length,c.length),y.print();let l={createdBranches:a.map(u=>u.branchName),successCount:a.length,failureCount:c.length,releases:a,failedReleases:c};return{content:R(JSON.stringify(l,null,2)),structuredContent:l}},ip=C({name:"release-create",requiresHumanConfirm:!0,formProvider:Yw,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; main for every release in a repo with "gitFlow": "main", which has no hotfix type), 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:q.array(q.object({version:q.string().optional().describe('Version to create (e.g., "1.2.5") or the literal token "next" for auto-increment. Mutually exclusive with "name".'),name:q.string().optional().describe('Free-form kebab-case release name (e.g., "checkout-redesign"). Mutually exclusive with "version". Named releases never auto-bump.'),type:q.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" (branches off dev) or "hotfix" (branches off main).'),description:q.string().optional().describe("Optional description for the Jira version."),releaseDate:Gu.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:q.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{createdBranches:q.array(q.string()).describe("List of created release branch names"),successCount:q.number().describe("Number of releases created successfully"),failureCount:q.number().describe("Number of releases that failed"),releases:q.array(q.object({version:q.string().describe("Version number"),type:q.enum(["regular","hotfix"]).describe("Release type"),branchName:q.string().describe("Release branch name"),prUrl:q.string().describe("GitHub PR URL"),jiraVersionUrl:q.string().describe("Jira version URL"),releaseDate:q.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:q.array(q.object({version:q.string().describe("Version number that failed"),error:q.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:Fa});import zw from"@inquirer/input";import{z as Xe}from"zod";var Xw=["description","releaseDate"],cI=async()=>{let e=await K(),t=e.map(s=>s.branch),r=new Map(e.map(s=>[s.branch,s.type])),n=await fe(),o=await zt(ge({branches:t,descriptions:n,types:r}));return{branch:o,type:r.get(o)||"regular"}},lI=async e=>{let r=(await K()).find(n=>n.branch===e);if(!r)throw new g(void 0,{operation:`edit release ${e}`,remediation:`confirm an open PR exists for ${e} ('gh pr list')`});return r.type},uI=async e=>{let t=e===""?"(no current description)":`current: "${e}"`,n=(await M(o=>zw({message:` New description ${t} (press Enter to keep current): `},o),{whenHeadless:{refuse:"description"}})).trim();return n===""?e:n},dI=async e=>{let t=e===null?"(no current date)":`current: ${e}`,n=(await M(o=>zw({message:` Release date yyyy-mm-dd ${t} (press Enter to keep current): `,validate:ns},o),{whenHeadless:{refuse:"releaseDate"}})).trim();return n===""?e:Cr(n)},pI=e=>{if(e!==void 0)return e===""?null:e},mI=async e=>(y.setInteractive(),{description:await uI(e.description),releaseDate:await dI(e.releaseDate)}),ap=e=>e??"(none)",fI=(e,t,r)=>e==="description"?` description: "${t.description}" \u2192 "${r.description}"`:` release date: ${ap(t.releaseDate)} \u2192 ${ap(r.releaseDate)}`,La=async e=>{let{version:t,description:r,releaseDate:n,confirmedCommand:o}=e,s=pI(n),i=await vn(),a;t?(a=It(t),await lI(a)):(y.setInteractive(),a=(await cI()).branch);let c=ee(a);if(!c)throw new g(void 0,{operation:`edit release ${a}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let l=oe(c);y.addOption("--version",l);let u=ue(c),p=await Ot(u,i);if(!p)throw new g(void 0,{operation:`edit release ${u}`,remediation:`create the Jira fix version "${u}" first or pick a different release`});let m={description:p.description??"",releaseDate:p.releaseDate||null},f=r!==void 0||s!==void 0;if(!f&&Q())throw new D({status:"argument_required",argument:"description",agentMode:F.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 h=f?{description:r??m.description,releaseDate:s===void 0?m.releaseDate:s}:await mI(m),b=Xw.filter(P=>h[P]!==m[P]),T=b.includes("description"),k=b.includes("releaseDate"),j=Sr(i,p),v=P=>{let $={version:l,branch:a,jiraVersionUrl:j,previousDescription:m.description,newDescription:h.description,previousReleaseDate:m.releaseDate,newReleaseDate:h.releaseDate,changedFields:b,changed:P};return{content:R(JSON.stringify($,null,2)),structuredContent:$}};if(b.length===0)return d.info(`No change \u2014 ${u} already has description "${m.description}" and release date ${ap(m.releaseDate)}`),y.print(),v(!1);T&&y.addOption("--description",h.description),k&&y.addOption("--release-date",h.releaseDate??"");let S=b.map(P=>fI(P,m,h));return await H(o,`Update ${u}?
430
+ ${S.join(`
422
431
  `)}
423
- `),y.addOption("--yes",!0),await mn({versionId:p.id,...k?{description:h.description}:{},...A?{releaseDate:h.releaseDate}:{}},i),k&&await Li({branch:a,body:Io(M,h.description)}),d.info(`\u2705 Updated ${S.join(" and ")} for ${u}`),d.info(`\u{1F517} Jira Version: ${M}`),d.info(`\u{1F517} PR branch: ${a}
424
- `),y.print(),v(!0)},tp=C({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:Ye.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:Ye.string().optional().describe("New description. Empty string clears the description."),releaseDate:ju.optional().describe("New planned release date (yyyy-mm-dd). Empty string clears the date.")},outputSchema:{version:Ye.string().describe("Release version"),branch:Ye.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:Ye.string().describe("Jira fix version URL"),previousDescription:Ye.string().describe("The description before the update"),newDescription:Ye.string().describe("The description after the update"),previousReleaseDate:Ye.string().nullable().describe("The planned release date before the update, or null"),newReleaseDate:Ye.string().nullable().describe("The planned release date after the update, or null"),changedFields:Ye.array(Ye.enum(Hw)).describe("The fields whose value actually changed"),changed:Ye.boolean().describe("Whether anything actually changed")},handler:_a});import{z as ce}from"zod";import{$ as np}from"zx";import{z as qw}from"zod";var Xw=2500,Ma="release-remove",Yw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),iI=e=>e.version===void 0||e.version==="",aI=async()=>{try{return{outcome:"listed",prs:await G()}}catch(e){return e instanceof g&&e.operation===Oo?{outcome:"empty"}:{outcome:"failed"}}},zw=(e,t)=>(e===null?d.info({msg:`Tool execution form enumeration timed out (gh pr list, ${t/1e3} s): ${Ma}`}):e.outcome==="failed"?d.info({msg:`Tool execution form enumeration failed (gh pr list): ${Ma}`}):d.info({msg:`Tool execution form options empty (open release PRs): ${Ma}`}),null),cI=(e,t)=>{let r=new Map(e.map(n=>[n.branch,n.type]));return Gi(e.map(n=>n.branch)).map(({branch:n,id:o,label:s})=>{let i=t?.get(le(o)),a=i===void 0?"":` \u2014 ${i}`;return{label:s,prose:`${s} [${r.get(n)??"regular"}]${a}`}})},lI=(e,t,r)=>{let n=e.map(o=>o.prose).join("; ");return t!==null?`Open release PRs right now: ${n}. `:(d.info({msg:`Tool execution form descriptions unavailable (timeout): ${Ma}`}),`Open release PRs right now: ${n}. Jira descriptions could not be fetched within ${r/1e3} s. `)},rp=(e={})=>{let t=e.fetchBudgetMs??Xw;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=>Yw(r)&&iI(r),buildRequestedSchema:async()=>{let[r,n]=await Promise.all([Bn(aI(),t),Bn(me(),t)]);if(r===null||r.outcome!=="listed")return zw(r,t);let o=cI(r.prs,n);return o.length===0?zw({outcome:"empty"},t):qw.object({version:qw.enum(o.map(s=>s.label)).describe(`The ONE release to tear down. ${lI(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:{...Yw(n)?n:{},version:r.version}}};var Zw=["worktree","pr","local-branch","remote-branch","jira"],tk={worktree:"remove the worktree",pr:"close the PR","local-branch":"delete the local branch","remote-branch":"delete the remote branch",jira:"remove the Jira fix version"},Nr="remove a release",rt=e=>{throw d.warn({operation:e.operation},`\u26D4 ${e.stderrExcerpt??e.operation}`),new g(void 0,e)},Qw=(e,t)=>{throw d.warn({operation:t.operation},`\u26D4 ${t.stderrExcerpt??t.operation}`),new O({...e,agentMode:j.source},2,t)},uI=e=>{he()&&(e.version||Qw({status:"argument_required",argument:"version"},{operation:Nr,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&&Qw({status:"refused"},{operation:Nr,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"}))},rk=e=>{e.pr?.state==="MERGED"&&rt({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`})},dI=(e,t)=>{if(t.skipJira||(e.jiraConfig||rt({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)&&rt({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||rt({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)`}))},pI=e=>{if(e.worktreePresent||e.pr!==null||e.localTipSha!==null||e.remoteTipSha!==null||e.jira)return;rt({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"})},mI=e=>{!e.worktreeDirty||e.worktreeDirty.length===0||rt({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(", ")}`})},fI=async e=>(await np`git -C ${e} status --porcelain`).stdout.split(`
425
- `).map(r=>r.trimEnd()).filter(r=>r.length>0),gI=async e=>{try{let{terminals:t}=await Bf(e);return t.filter(r=>r.connected).length}catch(t){return d.debug({error:t,worktreePath:e},"release remove: orca terminal probe failed"),0}},hI=async e=>{let t=await ui([e]);if(t!==null)throw d.warn({operation:Nr},`\u26D4 this command runs inside an Orca terminal of ${t}`),new O({status:"refused",reason:"orca_caller_inside_target",agentMode:j.source},2,{operation:Nr,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`})},yI=async(e,t)=>{let r={jiraConfig:null,jira:null,moveIssuesTo:null};if(t.skipJira)return r;let n=await At();if(!n)return r;let o=await $t(le(e),n),s=t.moveIssuesTo?await vI(t.moveIssuesTo,n):null;if(!o)return{jiraConfig:n,jira:null,moveIssuesTo:s};let i=await Wi(o.id,n);return{jiraConfig:n,moveIssuesTo:s,jira:{version:o,fixCount:i.issuesFixedCount,affectsCount:i.issuesAffectedCount,url:wr(n,o)}}},vI=async(e,t)=>{let r=await $t(e,t);return r||rt({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}"`})},wI=async(e,t)=>{let r=Q(e);r||rt({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 $(),s=`${`${n}${ge}`}/${e}`,[i,a,c,l]=await Promise.all([be("release"),ln(e),Ce(n,`refs/heads/${e}`),Gr(n,e)]),u=i.includes(e);return u&&await hI(s),{...await yI(r,t),branch:e,id:r,label:ne(r),baseBranch:a?.baseRefName??mt("regular"),worktreePath:s,worktreePresent:u,orcaTerminalCount:u?await gI(s):0,worktreeDirty:u?await fI(s):null,localTipSha:c,remoteTipSha:l,pr:a}},ek=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}),kI=(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}`},bI=(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: ${kI(e,t)}`];return e.orcaTerminalCount>0&&n.push(` \u2022 ${e.orcaTerminalCount} Orca terminal(s) in ${e.worktreePath} will be closed`),n.join(`
426
- `)},ja=class extends Error{constructor(r,n){super(`step ${r} failed`,{cause:n});this.step=r;this.reason=n;this.name="StepFailure"}step;reason},RI=e=>typeof e=="string"?e:e.outcome;async function Cs(e,t,r){try{let n=await r(),o=RI(n);return t.push({step:e}),d.info({step:e,outcome:o},`\u2705 ${tk[e]} \u2014 ${o}`),n}catch(n){throw new ja(e,n)}}var SI=(e,t)=>t.step==="local-branch"&&e.localTipSha?`local-branch (was ${e.localTipSha.slice(0,7)})`:t.step,EI=e=>{let{plan:t,step:r,done:n,cause:o}=e,s=n.map(p=>SI(t,p)).join(", ")||"nothing",i=t.jira?`The Jira fix version ${t.jira.version.name} was NOT removed. `:"",a=t.localTipSha?`Restore the branch with \`git branch ${t.branch} ${t.localTipSha}\`. `:"",c=`Re-run \`infra-kit release remove --version ${t.label}\` to finish; completed steps are skipped.`,l=`completed: ${s}. ${i}${a}${c}`,u=o instanceof g?o.remediation:void 0;return new g(o,{operation:`remove release ${t.label} \u2014 step ${Zw.indexOf(r)+1} of ${Zw.length} (${tk[r]})`,remediation:u?`${u} \u2014 ${l}`:l})},PI=async e=>(await ds(e.branch,{operation:`remove the worktree for ${e.branch}`,remediation:`commit or discard the changes inside ${e.worktreePath} (\`git -C ${e.worktreePath} stash -u\`), then re-run`})).includes(e.branch)?"removed":"absent",xI=async e=>{let t=await ln(e.branch);if(rk({...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 np`gh pr close ${String(t.number)} --comment ${r}`,{outcome:"closed",number:t.number}},TI=async e=>(await Vr()===e.branch&&await np`git switch ${e.baseBranch}`,await ni(e.branch),await uf(e.branch)?rt({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"),CI=async e=>(await oi(e.branch),e.remoteTipSha?"deleted":"absent"),$I=async(e,t,r)=>{let n=await Wi(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}\``;rt({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}`})},AI=async(e,t)=>t.skipJira?"skipped":!e.jira||!e.jiraConfig?"absent":(await $I(e,e.jira,e.jiraConfig),d.info({jiraVersionId:e.jira.version.id,jiraVersionName:e.jira.version.name},"\u{1F5D1}\uFE0F removing Jira fix version"),await ru({versionId:e.jira.version.id,moveFixIssuesTo:e.moveIssuesTo?.id,moveAffectedIssuesTo:e.moveIssuesTo?.id},e.jiraConfig),"removed"),OI=(e,t)=>({branch:e.branch,version:e.label,baseBranch:e.baseBranch,worktree:t.worktree,pr:t.pr.outcome,prNumber:t.pr.number,localBranch:t.localBranch,localTipSha:e.localTipSha,remoteBranch:t.remoteBranch,remoteTipSha:e.remoteTipSha,jira:t.jira,jiraVersion:e.jira?{id:e.jira.version.id,name:e.jira.version.name,url:e.jira.url}:null}),DI=async(e,t,r)=>{let n=await Cs("worktree",r,()=>PI(e)),o=await Cs("pr",r,()=>xI(e));d.info({branch:e.branch,localTipSha:e.localTipSha,remoteTipSha:e.remoteTipSha},"\u{1F516} branch tips before deletion");let s=await Cs("local-branch",r,()=>TI(e)),i=await Cs("remote-branch",r,()=>CI(e)),a=await Cs("jira",r,()=>AI(e,t));return{worktree:n,pr:o,localBranch:s,remoteBranch:i,jira:a}},II=async(e,t)=>{let r=[];try{return OI(e,await DI(e,t,r))}catch(n){throw n instanceof ja?EI({plan:e,step:n.step,done:r,cause:n.reason}):n}},NI=async e=>{if(e)return Ot(e);y.setInteractive();let[t,r]=await Promise.all([me(),G()]),n=r.map(s=>s.branch);n.length===0&&rt({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 qt(fe({branches:n,descriptions:t,types:o}))}catch(s){throw Oe(s)?s:new g(s,{operation:"select a release to remove",remediation:"pass `--version <ref>` (e.g. `--version 1.2.5`); the picker needs an interactive terminal"})}},nk=rp(),Fa=async e=>{let{confirmedCommand:t,version:r,moveIssuesTo:n,skipJira:o}=e;await _e({operation:Nr}),await K(),await at({provider:nk,params:e,operation:Nr,argument:"version"}),uI(e);try{let s=await wI(await NI(r),e);d.debug({plan:ek(s)},"release remove: resolved plan"),rk(s),dI(s,e),pI(s),await $o({operation:`remove release ${s.label}`,base:s.baseBranch}),mI(s),y.addOption("--version",s.label),n&&y.addOption("--move-issues-to",n),o&&y.addOption("--skip-jira",!0),await J(t,bI(s,!!o),{throwOnDecline:!0,plan:{...ek(s),skipJira:!!o}}),t||y.addOption("--yes",!0);let i=await II(s,e);return y.print(),{content:b(JSON.stringify(i,null,2)),structuredContent:i}}catch(s){throw Oe(s)||Et(s)||s instanceof g?s:(d.error({err:Ar(s)},"\u274C Error removing release"),new g(s,{operation:Nr,remediation:"check `gh auth status`, `git worktree list` and the Jira credentials, then re-run"}))}},op=C({name:"release-remove",description:'Tear down ONE release created by release-create: removes its git worktree (closing every Orca terminal open in it first \u2014 a call made from an Orca terminal inside that worktree is refused as orca_caller_inside_target before anything is touched), closes its pull request with a comment, deletes the release branch locally and on origin, and REMOVES ITS JIRA FIX VERSION \u2014 the one irreversible step (new id, new URL, lost issue links), which is why every call is gated behind human confirmation. Omit "version" and this server offers the human a form listing the open release PRs; the accepted choice feeds the confirm gate. A client that cannot render a form gets a gate with no version \u2014 confirming it is refused, never guessed. Pass "version" when the human already named the release. One release per call \u2014 repeat the call for another; there is no "versions" field. Refuses before any mutation when the PR is MERGED (the release has shipped), when the fix version is released/archived, when the fix version still carries issues (pass "moveIssuesTo" to reassign them), or when nothing named that version exists. skipJira is CLI-only and has no field here: it would leave a live fix version behind with nothing in the result pointing at it. Resumable: every step is a verified no-op when its artefact is already gone, so a re-run finishes a partial teardown. What is lost with the worktree directory: gitignored contents including a hydrated .env of Doppler secrets (re-fetch with env-load) and node_modules/dist.',requiresHumanConfirm:!0,formProvider:nk,inputSchema:{version:ce.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:ce.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:ce.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{branch:ce.string().describe("The release branch that was targeted"),version:ce.string().describe('The release label (e.g. "1.2.5")'),baseBranch:ce.string().describe("The branch HEAD was moved to before the local delete"),worktree:ce.enum(["removed","absent"]).describe("Whether a git worktree was removed or none existed"),pr:ce.enum(["closed","already-closed","absent"]).describe("What happened to the release pull request"),prNumber:ce.number().nullable().describe("The pull request number, or null when none exists"),localBranch:ce.enum(["deleted","absent"]).describe("Whether a local branch was deleted or none existed"),localTipSha:ce.string().nullable().describe("The local tip before deletion \u2014 the handle that restores the branch"),remoteBranch:ce.enum(["deleted","absent"]).describe("Whether the origin branch was deleted or none existed"),remoteTipSha:ce.string().nullable().describe("The origin tip before deletion"),jira:ce.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:ce.object({id:ce.string(),name:ce.string(),url:ce.string()}).nullable().describe("The fix version this release owned, captured before removal \u2014 the id is the only handle that survives it")},handler:Fa});import{spawn as FI}from"node:child_process";import LI from"node:fs";import{homedir as BI}from"node:os";import Ba from"node:process";import La from"node:fs";import Un from"node:path";var _I=e=>{try{return La.statSync(e).isFile()?La.readFileSync(e,"utf8"):null}catch{return null}},MI=e=>{try{return La.realpathSync(e)}catch{return e}},jI=(e,t)=>{let o=t(Un.join(e,".git"))?.split(`
427
- `).map(c=>c.trim()).find(c=>c.startsWith("gitdir:"))?.slice(7).trim();if(!o)return e;let s=Un.resolve(e,o),i=`${Un.sep}.git${Un.sep}worktrees${Un.sep}`,a=s.lastIndexOf(i);return a===-1?e:s.slice(0,a)},ok=(e={})=>{let t=e.listInstallations??Dc,r=e.exists??La.existsSync,n=e.readGitFile??_I,o=e.realpath??MI,s=new Map;for(let i of t()){if(i.projectPath===null)continue;let a=jI(i.projectPath,n);if(!r(Un.join(a,"infra-kit.json")))continue;let c=o(a);s.has(c)||s.set(c,a)}return[...s.values()].sort()};var UI=180*1e3,WI=900*1e3,VI=4*1024*1024,GI=2e3,JI=e=>new Promise(t=>{let r={stdout:"",stderr:""},n=!1,o=!1,s,i=(u,p)=>{n||(n=!0,clearTimeout(s),t({status:u,stdout:r.stdout,stderr:r.stderr,error:p}))},a=FI(e.command,[...e.args],{cwd:e.cwd,env:e.env,stdio:["ignore","pipe","pipe"],detached:!0,windowsHide:!0});s=setTimeout(()=>{o=!0;try{a.pid!==void 0&&Ba.kill(-a.pid,"SIGKILL")}catch{}i(null,`timed out after ${Math.round(e.timeoutMs/1e3)}s`)},e.timeoutMs);let c=u=>p=>{r[u].length<VI&&(r[u]+=p.toString("utf8"))};a.stdout.on("data",c("stdout")),a.stderr.on("data",c("stderr")),a.on("error",u=>{i(null,u.message)});let l=(u,p)=>{i(u,o||p===null?null:`killed by ${p}`)};a.on("close",l),a.on("exit",(u,p)=>{setTimeout(()=>{l(u,p)},GI).unref()})}),KI=({cwd:e,timeoutMs:t})=>JI({command:Ba.execPath,args:[Ba.argv[1]??"","setup","--unattended","--json"],cwd:e,env:Nf(Ba.env),timeoutMs:t}),HI=e=>{LI.writeFileSync(Rn(),e,{mode:384})},qI=e=>{try{let t=JSON.parse(e);return!Array.isArray(t?.init)||!Array.isArray(t.tools)||typeof t.portlessService!="object"?null:t}catch{return null}},YI=new RegExp("\x1B\\[[0-9;]*m","g"),zI=e=>{if(e.error!==null)return e.error;try{let n=JSON.parse(e.stdout),o=n?.message??n?.error;if(typeof o=="string"&&o!=="")return o}catch{}let t=e.stderr.replace(YI,"").split(`
428
- `).map(n=>n.trim()).filter(Boolean).at(-1),r=`no setup report (exit ${String(e.status)})`;return t?`${r}: ${t.slice(0,300)}`:r},XI=(e,t)=>{let r=[],n=[];for(let a of e.init)a.outcome==="failed"?r.push(a.message):(a.outcome==="manual"||a.outcome==="warned")&&n.push(a.message);for(let a of e.tools)a.action==="failed"?r.push(`${a.id}: ${a.detail}`):a.before.present||n.push(`${a.id} is not installed \u2014 run: infra-kit setup --tools ${a.id}`);let{link:o,node:s,command:i}=e.portlessService;return(o==="failed"||s==="failed")&&r.push(`portless: link ${o}, node ${s}`),i!==null&&n.push(i),r.length===0&&t!==0&&r.push(`setup exited ${String(t)}`),r.length>0?{status:"failed",notes:[...r,...n]}:{status:n.length>0?"attention":"ok",notes:n}},sk=async(e,t,r,n)=>{let o=n-r.clock(),s=e===null?"infra-kit setup":na(e);if(o<=0)return{root:e,status:"failed",notes:[`out of time budget \u2014 run: ${s}`]};try{let i=await r.runSetupChild({cwd:t,timeoutMs:Math.min(UI,o)}),a=i.error===null?qI(i.stdout):null;return a===null?{root:e,status:"failed",notes:[`${zI(i)} \u2014 run: ${s}`]}:{root:e,...XI(a,i.status)}}catch(i){return{root:e,status:"failed",notes:[`${i instanceof Error?i.message:String(i)} \u2014 run: ${s}`]}}},ZI=e=>{let t=e.find(n=>n.root===null),r=new Set(t?.notes??[]);return e.map(n=>{if(n.root===null||n.status==="failed")return n;let o=n.notes.filter(s=>!r.has(s));return{...n,notes:o,status:n.status==="attention"&&o.length===0?"ok":n.status}})},QI=e=>{let t=[`infra-kit ${e.version} unattended setup \u2014 ${new Date(e.finishedMs??e.startedMs).toISOString()} (attempt ${e.attempts})`];for(let r of e.runs){t.push("",`${r.status.padEnd(9)} ${r.root??"machine"}`);for(let n of r.notes)t.push(` ${n}`)}return`${t.join(`
432
+ `),y.addOption("--yes",!0),await yn({versionId:p.id,...T?{description:h.description}:{},...k?{releaseDate:h.releaseDate}:{}},i),T&&await Gi({branch:a,body:Fo(j,h.description)}),d.info(`\u2705 Updated ${b.join(" and ")} for ${u}`),d.info(`\u{1F517} Jira Version: ${j}`),d.info(`\u{1F517} PR branch: ${a}
433
+ `),y.print(),v(!0)},cp=C({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:Xe.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:Xe.string().optional().describe("New description. Empty string clears the description."),releaseDate:Vu.optional().describe("New planned release date (yyyy-mm-dd). Empty string clears the date.")},outputSchema:{version:Xe.string().describe("Release version"),branch:Xe.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:Xe.string().describe("Jira fix version URL"),previousDescription:Xe.string().describe("The description before the update"),newDescription:Xe.string().describe("The description after the update"),previousReleaseDate:Xe.string().nullable().describe("The planned release date before the update, or null"),newReleaseDate:Xe.string().nullable().describe("The planned release date after the update, or null"),changedFields:Xe.array(Xe.enum(Xw)).describe("The fields whose value actually changed"),changed:Xe.boolean().describe("Whether anything actually changed")},handler:La});import{z as le}from"zod";import{$ as up}from"zx";import{z as Zw}from"zod";var tk=2500,Ba="release-remove",Qw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),gI=e=>e.version===void 0||e.version==="",hI=async()=>{try{return{outcome:"listed",prs:await K()}}catch(e){return e instanceof g&&e.operation===Mo?{outcome:"empty"}:{outcome:"failed"}}},ek=(e,t)=>(e===null?d.info({msg:`Tool execution form enumeration timed out (gh pr list, ${t/1e3} s): ${Ba}`}):e.outcome==="failed"?d.info({msg:`Tool execution form enumeration failed (gh pr list): ${Ba}`}):d.info({msg:`Tool execution form options empty (open release PRs): ${Ba}`}),null),yI=(e,t)=>{let r=new Map(e.map(n=>[n.branch,n.type]));return qi(e.map(n=>n.branch)).map(({branch:n,id:o,label:s})=>{let i=t?.get(ue(o)),a=i===void 0?"":` \u2014 ${i}`;return{label:s,prose:`${s} [${r.get(n)??"regular"}]${a}`}})},vI=(e,t,r)=>{let n=e.map(o=>o.prose).join("; ");return t!==null?`Open release PRs right now: ${n}. `:(d.info({msg:`Tool execution form descriptions unavailable (timeout): ${Ba}`}),`Open release PRs right now: ${n}. Jira descriptions could not be fetched within ${r/1e3} s. `)},lp=(e={})=>{let t=e.fetchBudgetMs??tk;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=>Qw(r)&&gI(r),buildRequestedSchema:async()=>{let[r,n]=await Promise.all([Jn(hI(),t),Jn(fe(),t)]);if(r===null||r.outcome!=="listed")return ek(r,t);let o=yI(r.prs,n);return o.length===0?ek({outcome:"empty"},t):Zw.object({version:Zw.enum(o.map(s=>s.label)).describe(`The ONE release to tear down. ${vI(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:{...Qw(n)?n:{},version:r.version}}};var rk=["worktree","pr","local-branch","remote-branch","jira"],sk={worktree:"remove the worktree",pr:"close the PR","local-branch":"delete the local branch","remote-branch":"delete the remote branch",jira:"remove the Jira fix version"},Fr="remove a release",ot=e=>{throw d.warn({operation:e.operation},`\u26D4 ${e.stderrExcerpt??e.operation}`),new g(void 0,e)},nk=(e,t)=>{throw d.warn({operation:t.operation},`\u26D4 ${t.stderrExcerpt??t.operation}`),new D({...e,agentMode:F.source},2,t)},wI=e=>{ye()&&(e.version||nk({status:"argument_required",argument:"version"},{operation:Fr,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&&nk({status:"refused"},{operation:Fr,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"}))},ik=e=>{e.pr?.state==="MERGED"&&ot({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`})},kI=(e,t)=>{if(t.skipJira||(e.jiraConfig||ot({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)&&ot({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||ot({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)`}))},bI=e=>{if(e.worktreePresent||e.pr!==null||e.localTipSha!==null||e.remoteTipSha!==null||e.jira)return;ot({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"})},RI=e=>{!e.worktreeDirty||e.worktreeDirty.length===0||ot({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(", ")}`})},SI=async e=>(await up`git -C ${e} status --porcelain`).stdout.split(`
434
+ `).map(r=>r.trimEnd()).filter(r=>r.length>0),EI=async e=>{try{let{terminals:t}=await Hf(e);return t.filter(r=>r.connected).length}catch(t){return d.debug({error:t,worktreePath:e},"release remove: orca terminal probe failed"),0}},PI=async e=>{let t=await fi([e]);if(t!==null)throw d.warn({operation:Fr},`\u26D4 this command runs inside an Orca terminal of ${t}`),new D({status:"refused",reason:"orca_caller_inside_target",agentMode:F.source},2,{operation:Fr,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`})},xI=async(e,t)=>{let r={jiraConfig:null,jira:null,moveIssuesTo:null};if(t.skipJira)return r;let n=await Dt();if(!n)return r;let o=await Ot(ue(e),n),s=t.moveIssuesTo?await TI(t.moveIssuesTo,n):null;if(!o)return{jiraConfig:n,jira:null,moveIssuesTo:s};let i=await Ki(o.id,n);return{jiraConfig:n,moveIssuesTo:s,jira:{version:o,fixCount:i.issuesFixedCount,affectsCount:i.issuesAffectedCount,url:Sr(n,o)}}},TI=async(e,t)=>{let r=await Ot(e,t);return r||ot({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}"`})},CI=async(e,t)=>{let r=ee(e);r||ot({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 A(),s=`${`${n}${he}`}/${e}`,[i,a,c,l]=await Promise.all([Se("release"),mn(e),Ae(n,`refs/heads/${e}`),qr(n,e)]),u=i.includes(e);return u&&await PI(s),{...await xI(r,t),branch:e,id:r,label:oe(r),baseBranch:a?.baseRefName??gt("regular",await te()),worktreePath:s,worktreePresent:u,orcaTerminalCount:u?await EI(s):0,worktreeDirty:u?await SI(s):null,localTipSha:c,remoteTipSha:l,pr:a}},ok=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}),$I=(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}`},AI=(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: ${$I(e,t)}`];return e.orcaTerminalCount>0&&n.push(` \u2022 ${e.orcaTerminalCount} Orca terminal(s) in ${e.worktreePath} will be closed`),n.join(`
435
+ `)},Ua=class extends Error{constructor(r,n){super(`step ${r} failed`,{cause:n});this.step=r;this.reason=n;this.name="StepFailure"}step;reason},OI=e=>typeof e=="string"?e:e.outcome;async function Is(e,t,r){try{let n=await r(),o=OI(n);return t.push({step:e}),d.info({step:e,outcome:o},`\u2705 ${sk[e]} \u2014 ${o}`),n}catch(n){throw new Ua(e,n)}}var DI=(e,t)=>t.step==="local-branch"&&e.localTipSha?`local-branch (was ${e.localTipSha.slice(0,7)})`:t.step,II=e=>{let{plan:t,step:r,done:n,cause:o}=e,s=n.map(p=>DI(t,p)).join(", ")||"nothing",i=t.jira?`The Jira fix version ${t.jira.version.name} was NOT removed. `:"",a=t.localTipSha?`Restore the branch with \`git branch ${t.branch} ${t.localTipSha}\`. `:"",c=`Re-run \`infra-kit release remove --version ${t.label}\` to finish; completed steps are skipped.`,l=`completed: ${s}. ${i}${a}${c}`,u=o instanceof g?o.remediation:void 0;return new g(o,{operation:`remove release ${t.label} \u2014 step ${rk.indexOf(r)+1} of ${rk.length} (${sk[r]})`,remediation:u?`${u} \u2014 ${l}`:l})},NI=async e=>(await hs(e.branch,{operation:`remove the worktree for ${e.branch}`,remediation:`commit or discard the changes inside ${e.worktreePath} (\`git -C ${e.worktreePath} stash -u\`), then re-run`})).includes(e.branch)?"removed":"absent",_I=async e=>{let t=await mn(e.branch);if(ik({...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 up`gh pr close ${String(t.number)} --comment ${r}`,{outcome:"closed",number:t.number}},MI=async e=>(await Hr()===e.branch&&await up`git switch ${e.baseBranch}`,await ai(e.branch),await yf(e.branch)?ot({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"),jI=async e=>(await ci(e.branch),e.remoteTipSha?"deleted":"absent"),FI=async(e,t,r)=>{let n=await Ki(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}\``;ot({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}`})},LI=async(e,t)=>t.skipJira?"skipped":!e.jira||!e.jiraConfig?"absent":(await FI(e,e.jira,e.jiraConfig),d.info({jiraVersionId:e.jira.version.id,jiraVersionName:e.jira.version.name},"\u{1F5D1}\uFE0F removing Jira fix version"),await cu({versionId:e.jira.version.id,moveFixIssuesTo:e.moveIssuesTo?.id,moveAffectedIssuesTo:e.moveIssuesTo?.id},e.jiraConfig),"removed"),BI=(e,t)=>({branch:e.branch,version:e.label,baseBranch:e.baseBranch,worktree:t.worktree,pr:t.pr.outcome,prNumber:t.pr.number,localBranch:t.localBranch,localTipSha:e.localTipSha,remoteBranch:t.remoteBranch,remoteTipSha:e.remoteTipSha,jira:t.jira,jiraVersion:e.jira?{id:e.jira.version.id,name:e.jira.version.name,url:e.jira.url}:null}),UI=async(e,t,r)=>{let n=await Is("worktree",r,()=>NI(e)),o=await Is("pr",r,()=>_I(e));d.info({branch:e.branch,localTipSha:e.localTipSha,remoteTipSha:e.remoteTipSha},"\u{1F516} branch tips before deletion");let s=await Is("local-branch",r,()=>MI(e)),i=await Is("remote-branch",r,()=>jI(e)),a=await Is("jira",r,()=>LI(e,t));return{worktree:n,pr:o,localBranch:s,remoteBranch:i,jira:a}},WI=async(e,t)=>{let r=[];try{return BI(e,await UI(e,t,r))}catch(n){throw n instanceof Ua?II({plan:e,step:n.step,done:r,cause:n.reason}):n}},GI=async e=>{if(e)return It(e);y.setInteractive();let[t,r]=await Promise.all([fe(),K()]),n=r.map(s=>s.branch);n.length===0&&ot({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 zt(ge({branches:n,descriptions:t,types:o}))}catch(s){throw Ie(s)?s:new g(s,{operation:"select a release to remove",remediation:"pass `--version <ref>` (e.g. `--version 1.2.5`); the picker needs an interactive terminal"})}},ak=lp(),Wa=async e=>{let{confirmedCommand:t,version:r,moveIssuesTo:n,skipJira:o}=e;await je({operation:Fr}),await J(),await lt({provider:ak,params:e,operation:Fr,argument:"version"}),wI(e);try{let s=await CI(await GI(r),e);d.debug({plan:ok(s)},"release remove: resolved plan"),ik(s),kI(s,e),bI(s),await _o({operation:`remove release ${s.label}`,base:s.baseBranch}),RI(s),y.addOption("--version",s.label),n&&y.addOption("--move-issues-to",n),o&&y.addOption("--skip-jira",!0),await H(t,AI(s,!!o),{throwOnDecline:!0,plan:{...ok(s),skipJira:!!o}}),t||y.addOption("--yes",!0);let i=await WI(s,e);return y.print(),{content:R(JSON.stringify(i,null,2)),structuredContent:i}}catch(s){throw Ie(s)||xt(s)||s instanceof g?s:(d.error({err:Nr(s)},"\u274C Error removing release"),new g(s,{operation:Fr,remediation:"check `gh auth status`, `git worktree list` and the Jira credentials, then re-run"}))}},dp=C({name:"release-remove",description:'Tear down ONE release created by release-create: removes its git worktree (closing every Orca terminal open in it first \u2014 a call made from an Orca terminal inside that worktree is refused as orca_caller_inside_target before anything is touched), closes its pull request with a comment, deletes the release branch locally and on origin, and REMOVES ITS JIRA FIX VERSION \u2014 the one irreversible step (new id, new URL, lost issue links), which is why every call is gated behind human confirmation. Omit "version" and this server offers the human a form listing the open release PRs; the accepted choice feeds the confirm gate. A client that cannot render a form gets a gate with no version \u2014 confirming it is refused, never guessed. Pass "version" when the human already named the release. One release per call \u2014 repeat the call for another; there is no "versions" field. Refuses before any mutation when the PR is MERGED (the release has shipped), when the fix version is released/archived, when the fix version still carries issues (pass "moveIssuesTo" to reassign them), or when nothing named that version exists. skipJira is CLI-only and has no field here: it would leave a live fix version behind with nothing in the result pointing at it. Resumable: every step is a verified no-op when its artefact is already gone, so a re-run finishes a partial teardown. What is lost with the worktree directory: gitignored contents including a hydrated .env of Doppler secrets (re-fetch with env-load) and node_modules/dist.',requiresHumanConfirm:!0,formProvider:ak,inputSchema:{version:le.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:le.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:le.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{branch:le.string().describe("The release branch that was targeted"),version:le.string().describe('The release label (e.g. "1.2.5")'),baseBranch:le.string().describe("The branch HEAD was moved to before the local delete"),worktree:le.enum(["removed","absent"]).describe("Whether a git worktree was removed or none existed"),pr:le.enum(["closed","already-closed","absent"]).describe("What happened to the release pull request"),prNumber:le.number().nullable().describe("The pull request number, or null when none exists"),localBranch:le.enum(["deleted","absent"]).describe("Whether a local branch was deleted or none existed"),localTipSha:le.string().nullable().describe("The local tip before deletion \u2014 the handle that restores the branch"),remoteBranch:le.enum(["deleted","absent"]).describe("Whether the origin branch was deleted or none existed"),remoteTipSha:le.string().nullable().describe("The origin tip before deletion"),jira:le.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:le.object({id:le.string(),name:le.string(),url:le.string()}).nullable().describe("The fix version this release owned, captured before removal \u2014 the id is the only handle that survives it")},handler:Wa});import{spawn as HI}from"node:child_process";import qI from"node:fs";import{homedir as YI}from"node:os";import Va from"node:process";import Ga from"node:fs";import Kn from"node:path";var VI=e=>{try{return Ga.statSync(e).isFile()?Ga.readFileSync(e,"utf8"):null}catch{return null}},JI=e=>{try{return Ga.realpathSync(e)}catch{return e}},KI=(e,t)=>{let o=t(Kn.join(e,".git"))?.split(`
436
+ `).map(c=>c.trim()).find(c=>c.startsWith("gitdir:"))?.slice(7).trim();if(!o)return e;let s=Kn.resolve(e,o),i=`${Kn.sep}.git${Kn.sep}worktrees${Kn.sep}`,a=s.lastIndexOf(i);return a===-1?e:s.slice(0,a)},ck=(e={})=>{let t=e.listInstallations??Mc,r=e.exists??Ga.existsSync,n=e.readGitFile??VI,o=e.realpath??JI,s=new Map;for(let i of t()){if(i.projectPath===null)continue;let a=KI(i.projectPath,n);if(!r(Kn.join(a,"infra-kit.json")))continue;let c=o(a);s.has(c)||s.set(c,a)}return[...s.values()].sort()};var zI=180*1e3,XI=900*1e3,ZI=4*1024*1024,QI=2e3,eN=e=>new Promise(t=>{let r={stdout:"",stderr:""},n=!1,o=!1,s,i=(u,p)=>{n||(n=!0,clearTimeout(s),t({status:u,stdout:r.stdout,stderr:r.stderr,error:p}))},a=HI(e.command,[...e.args],{cwd:e.cwd,env:e.env,stdio:["ignore","pipe","pipe"],detached:!0,windowsHide:!0});s=setTimeout(()=>{o=!0;try{a.pid!==void 0&&Va.kill(-a.pid,"SIGKILL")}catch{}i(null,`timed out after ${Math.round(e.timeoutMs/1e3)}s`)},e.timeoutMs);let c=u=>p=>{r[u].length<ZI&&(r[u]+=p.toString("utf8"))};a.stdout.on("data",c("stdout")),a.stderr.on("data",c("stderr")),a.on("error",u=>{i(null,u.message)});let l=(u,p)=>{i(u,o||p===null?null:`killed by ${p}`)};a.on("close",l),a.on("exit",(u,p)=>{setTimeout(()=>{l(u,p)},QI).unref()})}),tN=({cwd:e,timeoutMs:t})=>eN({command:Va.execPath,args:[Va.argv[1]??"","setup","--unattended","--json"],cwd:e,env:Uf(Va.env),timeoutMs:t}),rN=e=>{qI.writeFileSync(Tn(),e,{mode:384})},nN=e=>{try{let t=JSON.parse(e);return!Array.isArray(t?.init)||!Array.isArray(t.tools)||typeof t.portlessService!="object"?null:t}catch{return null}},oN=new RegExp("\x1B\\[[0-9;]*m","g"),sN=e=>{if(e.error!==null)return e.error;try{let n=JSON.parse(e.stdout),o=n?.message??n?.error;if(typeof o=="string"&&o!=="")return o}catch{}let t=e.stderr.replace(oN,"").split(`
437
+ `).map(n=>n.trim()).filter(Boolean).at(-1),r=`no setup report (exit ${String(e.status)})`;return t?`${r}: ${t.slice(0,300)}`:r},iN=(e,t)=>{let r=[],n=[];for(let a of e.init)a.outcome==="failed"?r.push(a.message):(a.outcome==="manual"||a.outcome==="warned")&&n.push(a.message);for(let a of e.tools)a.action==="failed"?r.push(`${a.id}: ${a.detail}`):a.before.present||n.push(`${a.id} is not installed \u2014 run: infra-kit setup --tools ${a.id}`);let{link:o,node:s,command:i}=e.portlessService;return(o==="failed"||s==="failed")&&r.push(`portless: link ${o}, node ${s}`),i!==null&&n.push(i),r.length===0&&t!==0&&r.push(`setup exited ${String(t)}`),r.length>0?{status:"failed",notes:[...r,...n]}:{status:n.length>0?"attention":"ok",notes:n}},lk=async(e,t,r,n)=>{let o=n-r.clock(),s=e===null?"infra-kit setup":aa(e);if(o<=0)return{root:e,status:"failed",notes:[`out of time budget \u2014 run: ${s}`]};try{let i=await r.runSetupChild({cwd:t,timeoutMs:Math.min(zI,o)}),a=i.error===null?nN(i.stdout):null;return a===null?{root:e,status:"failed",notes:[`${sN(i)} \u2014 run: ${s}`]}:{root:e,...iN(a,i.status)}}catch(i){return{root:e,status:"failed",notes:[`${i instanceof Error?i.message:String(i)} \u2014 run: ${s}`]}}},aN=e=>{let t=e.find(n=>n.root===null),r=new Set(t?.notes??[]);return e.map(n=>{if(n.root===null||n.status==="failed")return n;let o=n.notes.filter(s=>!r.has(s));return{...n,notes:o,status:n.status==="attention"&&o.length===0?"ok":n.status}})},cN=e=>{let t=[`infra-kit ${e.version} unattended setup \u2014 ${new Date(e.finishedMs??e.startedMs).toISOString()} (attempt ${e.attempts})`];for(let r of e.runs){t.push("",`${r.status.padEnd(9)} ${r.root??"machine"}`);for(let n of r.notes)t.push(` ${n}`)}return`${t.join(`
429
438
  `)}
430
- `},eN=e=>({version:e.version??L.version,home:e.home??BI(),clock:e.clock??Date.now,acquireLock:e.acquireLock??(()=>_c({lockPath:wy()})),readRecord:e.readRecord??Sn,writeRecord:e.writeRecord??ky,discoverProjects:e.discoverProjects??(()=>ok()),runSetupChild:e.runSetupChild??KI,writeLog:e.writeLog??HI}),tN=e=>{try{return{projects:e.discoverProjects(),error:null}}catch(t){return{projects:[],error:t instanceof Error?t.message:String(t)}}},rN=async e=>{let t=e.readRecord(),r=e.clock();if(!Sy(t,e.version,r))return"not-due";let n=t?.version===e.version?t.attempts+1:1;e.writeRecord({version:e.version,attempts:n,startedMs:r,finishedMs:null,runs:[]});let o=r+WI,s=await sk(null,e.home,e,o),i=tN(e),a=[i.error===null?s:{root:null,status:"failed",notes:[...s.notes,`could not list projects: ${i.error}`]}];for(let l of i.projects)a.push(await sk(l,l,e,o));let c={version:e.version,attempts:n,startedMs:r,finishedMs:e.clock(),runs:ZI(a)};e.writeRecord(c);try{e.writeLog(QI(c))}catch{}return"ran"},ik=async(e={})=>{try{let t=eN(e),r=t.acquireLock();if(r===null)return"already-running";try{return await rN(t)}finally{r()}}catch{return"not-due"}},sp=async(e={})=>{let t=await ik(e);return{content:b(JSON.stringify({outcome:t})),structuredContent:{outcome:t}}};import{spawnSync as iN}from"node:child_process";import{homedir as aN}from"node:os";import cN from"node:process";var nN=e=>{let t=new Set(e.steps.map(r=>r[0]));return t.has("brew")?"homebrew":t.has("npm")?"npm":null},oN=e=>{let t=[];return e.needsSudo&&t.push("needs-sudo"),e.fetchesNetworkScript&&t.push("fetches-network-script"),t},sN=(e,t)=>{let r=nN(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},$s=(e,t)=>{let r=[...oN(e),...sN(e,t)];return r.length===0?{executable:!0}:{executable:!1,reasons:r}},As=e=>e.steps.map(Ue);var lN=["NONINTERACTIVE","CI","INTERACTIVE","HAVE_SUDO_ACCESS","SUDO_ASKPASS"],uN=e=>{let t={...jm(e)};for(let r of lN)delete t[r];return t},ip=(e,t,r={})=>{let n=r.spawnSync??iN,o=r.env??cN.env,s=(r.agentMode??he)(),i=As(e),a=$s(e,t);return a.executable?s?{ran:!1,commands:i,refusedBecause:["agent-mode"]}:mN({recipe:e,spawn:n,env:o,commands:i,notify:r.notify??dN}):{ran:!1,commands:i,refusedBecause:a.reasons}},dN=e=>{d.info(e)},ck=64,pN=ck*1024*1024,mN=({recipe:e,spawn:t,env:r,commands:n,notify:o})=>{let s=uN(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:pN,cwd:aN(),env:s}),l=wN(c);if(l!==null)return{ran:!0,ok:!1,commands:n,failedStep:n[i],detail:l}}return{ran:!0,ok:!0,commands:n}},fN=5,gN=/^(?:error|fatal|warning: failed|[a-z-]{0,20} ERR!)[:\s]/i,ak=e=>e==null?[]:String(e).split(`
431
- `).map(t=>t.trim()).filter(t=>t.length>0),hN=e=>{let t=ak(e.stderr),r=ak(e.stdout),n=[...t,...r].filter(s=>gN.test(s)),o=t.length>0?t:r;return(n.length>0?n:o).slice(-fN).join(" / ")},yN="ENOBUFS",vN=e=>e.error?.code===yN,wN=e=>{if(vN(e))return`terminated after exceeding the ${ck} 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=hN(e),r=t===""?"":`: ${t}`;return`exited ${e.status??"unknown"}${r}`};var kN=e=>{let t=[];return e.some(n=>n.id==="brew"&&n.present)&&t.push("homebrew"),t.push("npm"),t},bN=e=>{let t=He(e.id);return e.present?t.updateFor(e.binRealPath):t.bootstrapInstall},RN=(e,t)=>{let r=bN(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=$s(r,n);return{state:e,action:e.present?"update":"install",recipe:r,executable:o.executable,refusedBecause:o.executable?[]:o.reasons,commands:As(r),context:n}},Ua=async(e=Sr,t=qo())=>{let r=await zo(Sr,t),n={owner:null,present:kN(r)},o=_u(e),s=new Map(r.map(a=>[a.id,a]));return{plans:o.filter(a=>e.includes(a)).map(a=>RN(s.get(a),n)),context:n}};var ap=(e,t)=>({...Os(e),action:"skipped",commands:e.commands,detail:t}),Os=e=>({id:e.state.id,before:{present:e.state.present,onPath:e.state.onPath,version:e.state.version,manager:e.state.manager}}),lk=(e,t)=>e.action==="none"?ap(e,`nothing to do: ${e.state.manager} installs are not managed from here`):t==="update"&&e.action==="install"?ap(e,"not installed, and --update only updates \u2014 drop the flag to install it"):e.executable?null:{...Os(e),action:"refused",commands:e.commands,detail:`refused (${e.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},SN=(e,t)=>t.ran?t.ok?{...Os(e),action:e.action==="install"?"installed":"updated",commands:t.commands,detail:e.action==="install"?"installed":"updated"}:{...Os(e),action:"failed",commands:t.commands,detail:`${t.failedStep??"a step"} ${t.detail??"failed"}`}:{...Os(e),action:"refused",commands:t.commands,detail:`refused (${t.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},cp=async e=>{let t=e.run??ip,{plans:r}=await Ua(e.ids,e.probeDeps),n=[];for(let o of r){let s=lk(o,e.mode);if(s!==null){n.push(s);continue}n.push(SN(o,t(o.recipe,o.context)))}return n},lp=async(e,t)=>{let{plans:r}=await Ua(e,t);return r.map(n=>lk(n,"converge")??ap(n,`would ${n.action} \u2014 nothing was run (--skip-tools)`))};import LN from"node:process";import{z as N}from"zod";var up={zshrc:0,zshenv:1,migrations:2,"user-config":3,guidance:4,worktrees:5,"plugin-pointer":6,"mcp-server":7,"mcp-proxies":8,"project-config":9,"token-perms":10,chrome:11,shell:12},EN=Object.keys(up).sort((e,t)=>up[e]-up[t]),uk={skipped:0,ok:1,changed:2,manual:3,warn:4,fail:5},dk=new Set(["manual","warn","fail"]),dp=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 We(e)}},PN=e=>e.reduce((t,r)=>uk[r]>uk[t]?r:t,"skipped"),mk=e=>e.message.trim(),xN=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 "),pk=e=>e.message===$n,TN=(e,t)=>{let[r]=e;return e.length===1&&r!==void 0?mk(r):e.length>1?xN(e):t?"activate with the last line below":"see below"},CN=(e,t)=>{if(t.length===0)return{name:e,status:"skipped",message:"did not run"};let r=t.map(i=>dp(i.outcome)),n=t.filter(i=>dk.has(dp(i.outcome))).map(mk),o=t.filter(i=>!dk.has(dp(i.outcome))&&!pk(i)),s={name:e,status:PN(r),message:TN(o,t.some(pk))};return n.length>0?{...s,notes:n}:s},$N=e=>({label:"Local setup",rows:EN.map(t=>CN(t,e.filter(r=>r.step===t)))}),AN=(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 We(e.action)}},ON=(e,t)=>{let r=AN(e,t),n={name:e.id,status:r,message:e.detail};return r==="manual"&&e.commands.length>0?{...n,notes:[...e.commands]}:n},DN=(e,t)=>({label:t.skipTools?"Tools (probe: nothing installed)":"Tools",rows:e.map(r=>ON(r,t))}),IN=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 We(e)}},NN=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 We(e)}},_N=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 We(e)}},MN=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 We(e.outcome)}},jN=(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 We(e)}},FN=e=>({label:"Portless service",rows:[{name:"link",status:IN(e.link),message:_N(e.link)},{name:"node",status:NN(e.node.outcome),message:MN(e.node)},jN(e.service,e.command)]}),fk=(e,t)=>[$N(e.init),DN(e.tools,t),FN(e.portless)],gk=e=>e.some(t=>t.rows.some(r=>r.status==="fail"));var BN=()=>{let{link:e,node:t}=ei();return{link:e,node:t,target:{home:e.home,isGlobal:e.isGlobal,processStartTime:()=>null}}},UN=async e=>{let t=Qm(e.link).outcome,r=Zm(e.node),n=Qs(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 Sv(e.target,n);if(o==="converged")return{link:t,node:r,service:o,command:null};let i=jt(n,{home:e.link.home,exists:e.target.exists,execPath:e.target.execPath,stableNode:s});return{link:t,node:r,service:o,command:i}},yk="--unattended cannot be combined with --tools or --update: an unattended run installs and updates nothing (it implies --skip-tools).",vk="--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.",WN=e=>{let t=Array.isArray(e.update)?e.update:void 0,r=e.update===!0||t!==void 0,n=e.unattended===!0,o=e.skipTools===!0||n;if(n&&(e.tools!==void 0||r))throw new Error(yk);if(o&&(e.tools!==void 0||r))throw new Error(vk);return{ids:e.tools??t??Sr,mode:r?"update":"converge",skipTools:o}},hk=(e,t)=>e instanceof Cn?e.step:t.at(-1)?.step??"zshrc",VN=async()=>{let e=[];try{await Cu(t=>{e.push(t)})}catch(t){e.push({step:hk(t,e),outcome:"failed",message:`The ${hk(t,e)} step failed: ${t instanceof Error?t.message:String(t)}`,level:"warn"})}return e},GN=(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}`}))},JN=async(e,t)=>{try{return e.skipTools?await lp(e.ids,t.probeDeps):await cp({ids:e.ids,mode:e.mode,probeDeps:t.probeDeps,run:t.run})}catch(r){return GN(e.ids,r)}},KN=e=>({step:e.step,outcome:e.outcome,message:e.message}),Wa=async(e={})=>{let t=WN(e);Ze.withheld=e.unattended===!0;let r=await VN(),n=await JN(t,e),o=await UN(e.portlessDeps??BN()),s=fk({init:r,tools:n,portless:o},{skipTools:t.skipTools});pt({title:"infra-kit setup",sections:s},{ascii:e.ascii}),d.info($n),gk(s)&&(LN.exitCode=1);let i={init:r.map(KN),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:b(JSON.stringify(i,null,2)),structuredContent:i}},HN=N.object({step:N.enum(["zshrc","zshenv","migrations","user-config","guidance","worktrees","plugin-pointer","mcp-server","mcp-proxies","project-config","token-perms","chrome","shell"]).describe("Which init step this reports on"),outcome:N.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:N.string().describe("The same line a human running this would have read")}),qN=N.object({id:N.string().describe("Dependency id"),action:N.enum(["installed","updated","skipped","refused","failed"]).describe("What happened"),before:N.object({present:N.boolean(),onPath:N.boolean(),version:N.string().nullable(),manager:N.string()}).describe("The tool\u2019s state before this run"),commands:N.array(N.string()).describe("The exact commands, one per step \u2014 printed even when refused"),detail:N.string().describe("Why, in one line")}),YN=N.object({link:N.enum(["created","repointed","unchanged","skipped-local","skipped-unresolved","failed"]).describe("What the ~/.infra-kit/portless link step did"),node:N.enum(["created","refreshed","unchanged","skipped-local","skipped-platform","failed"]).describe("What the ~/.infra-kit/node step did"),service:N.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:N.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")}),zN={init:N.array(HN).describe("One entry per init step, in the order they ran"),tools:N.array(qN).describe("One result per requested dependency"),portlessService:YN.describe("The portless link, node, and system-service step \u2014 run on every setup, never gated on the tool options"),converged:N.boolean().describe("Whether the dependency step could act at all (false under skipTools)"),changed:N.boolean().describe("Whether anything was installed or updated"),report:N.array(N.object({label:N.string().describe("Section heading"),rows:N.array(N.object({name:N.string().describe("Init step, tool id, or portless part"),status:N.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:N.string().describe("The row message, as printed"),notes:N.array(N.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:N.boolean().describe("Whether no tool failed (a refusal is not a failure)")},XN={tools:N.array(N.enum(Sr)).optional().describe("Which tools to act on. Omit for all six."),mode:N.enum(["converge","update"]).optional().describe("converge (default): install what is missing and update the rest. update: never install."),skipTools:N.boolean().optional().describe("Read-only: run the init half, then REPORT what each tool needs without installing anything.")},pp=C({name:"setup",description:'Set this machine up in one call: inject the shell integration into .zshrc and the session-env block into .zshenv, run the config migrations, seed the user-global config, check the agent-instruction files (never rewritten here: drift is reported with the `audit --fix` command that refreshes them), register the Claude Code plugin pointer and install or update the skills plugin (the `/infra-kit:*` skills drive the infra-kit CLI on PATH; a leftover .mcp.json entry is reported, never written), then bring brew, git, aws, gh, doppler and portless to a working state \u2014 installing what is missing and updating what is present. Pass mode:"update" to update only and never install, or skipTools:true to do the local setup and then REPORT what each tool needs without installing anything. Recipes that need sudo or pipe a script fetched over the network \u2014 the Homebrew bootstrap and the first AWS CLI install \u2014 are never run; they are reported with the exact commands for you to run yourself. Use `doctor` first to see the state of this machine without changing it.',inputSchema:XN,outputSchema:zN,requiresHumanConfirm:!0,handler:e=>Wa({tools:e.tools,update:e.mode==="update",skipTools:e.skipTools})});import{existsSync as kk}from"node:fs";import bk from"node:path";import c_ from"node:process";import{z as _t}from"zod";import{createHash as ZN}from"node:crypto";import{readFileSync as QN}from"node:fs";var _r=e=>ZN("sha256").update(QN(e)).digest("hex");import{readFileSync as s_,writeFileSync as i_}from"node:fs";import Ka from"node:path";import{z as wt}from"zod";var se="vendor",e_=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".vitest",".output",".source",".nitro",".tanstack"]),t_=new Set([".sync-manifest.json",".eslintcache","log.txt","routeTree.gen.ts"]),r_=[".tsbuildinfo"],mp=e=>e_.has(e),fp=e=>t_.has(e)?!0:r_.some(t=>e.endsWith(t)),Va=e=>{let t=e.split("/"),r=t.pop()??"";return t.some(o=>mp(o))||fp(r)};import{readdirSync as n_}from"node:fs";import gp from"node:path";var o_=e=>e.split(gp.sep).join("/"),Ga=e=>{let t=[],r=n=>{for(let o of n_(n,{withFileTypes:!0})){let s=gp.join(n,o.name);if(o.isDirectory()){if(mp(o.name))continue;r(s);continue}fp(o.name)||t.push(o_(gp.relative(e,s)))}};return r(e),t.sort()};var ze=".sync-manifest.json",Ja=1,a_=wt.object({schemaVersion:wt.number().optional(),source:wt.string(),commit:wt.string(),syncedAt:wt.string(),fileCount:wt.number(),files:wt.record(wt.string(),wt.string())}),hp=e=>(e.schemaVersion??Ja)>Ja,wk=(e,t)=>{let r={},n=t?[...new Set(t)].sort():Ga(e);for(let o of n)try{r[o]=_r(Ka.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},Ds=e=>{let t=Ka.join(e,ze),r;try{r=s_(t,"utf8")}catch{throw new Error(`Missing ${ze} at ${t}`)}let n=a_.safeParse(JSON.parse(r));if(!n.success)throw new Error(`Invalid ${ze} at ${t}: ${wt.prettifyError(n.error)}`);return n.data},yp=(e,t,r)=>{let n=wk(e,r),o={schemaVersion:Ja,source:t.source,commit:t.commit,syncedAt:new Date().toISOString(),fileCount:Object.keys(n).length,files:n};return i_(Ka.join(e,ze),`${JSON.stringify(o,null,2)}
432
- `),o},vp=(e,t)=>{let r=Object.fromEntries(Object.entries(t.files).filter(([c])=>!Va(c))),n=Ga(e),o=[],s=[];for(let c of n){if(!(c in r)){s.push(c);continue}_r(Ka.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 wp=30,kp=(e,t)=>{if(t.length!==0){d.info(`
433
- ${e} (${t.length}):`);for(let r of t.slice(0,wp))d.info(` ${r}`);t.length>wp&&d.info(` \u2026and ${t.length-wp} more`)}},Ha=async(e={})=>{let t=e.cwd??await $(),r=bk.join(t,se),n={modified:[],added:[],removed:[],fileCount:0};if(!kk(r)){d.info(`\u2139\uFE0F No ${se}/ folder found \u2014 nothing to check.`);let u={status:"skipped",ok:!0,...n};return{content:b(JSON.stringify(u,null,2)),structuredContent:u}}if(!kk(bk.join(r,ze))){d.error(`\u274C Missing ${se}/${ze}. Re-run the vendor sync to generate it.`);let u={status:"missing-manifest",ok:!1,...n};return{content:b(JSON.stringify(u,null,2)),structuredContent:u}}let o=Ds(r);if(hp(o)){d.error(`\u274C ${se}/${ze} has a newer schemaVersion (${String(o.schemaVersion)}) than this CLI supports. Upgrade infra-kit.`);let u={status:"unknown-schema",ok:!1,...n};return{content:b(JSON.stringify(u,null,2)),structuredContent:u}}let{modified:s,added:i,removed:a}=vp(r,o),c=s.length>0||i.length>0||a.length>0;c?(d.error(`\u274C ${se}/ has drifted from ${se}/${ze}.`),d.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),kp("Modified",s),kp("Added (not in manifest)",i),kp("Removed (in manifest, now missing)",a)):d.info(`\u2705 ${se}/ matches manifest (${o.fileCount} files).`);let l={status:c?"drift":"clean",ok:!c,fileCount:o.fileCount,modified:s,added:i,removed:a};return{content:b(JSON.stringify(l,null,2)),structuredContent:l}},l_={status:_t.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:_t.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:_t.number(),modified:_t.array(_t.string()),added:_t.array(_t.string()),removed:_t.array(_t.string())},bp=C({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:l_,handler:()=>Ha({cwd:c_.cwd()})});import Rk from"node:process";import{z as Is}from"zod";var Sk=async e=>{try{return await e()}catch{return null}},qa=async()=>{let e=L.version;d.info(e);let t=await Sk($),r=t===null?null:await Sk(()=>Ae(t)),n={version:e,cwd:Rk.cwd(),repoRoot:t,mainRepoRoot:r,projectDir:Rk.env.CLAUDE_PROJECT_DIR||null};return{content:b(JSON.stringify(n,null,2)),structuredContent:n}},Rp=C({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:Is.string().describe("Installed infra-kit CLI version (from package.json)"),cwd:Is.string().describe("The working directory of this process"),repoRoot:Is.string().nullable().describe("git toplevel of cwd \u2014 the worktree itself in a linked worktree; null when git cannot answer"),mainRepoRoot:Is.string().nullable().describe("The main checkout a linked worktree belongs to (equals repoRoot outside worktrees); null with repoRoot"),projectDir:Is.string().nullable().describe("CLAUDE_PROJECT_DIR as Claude Code set it for this process, or null")},handler:qa});import Mk from"@inquirer/confirm";import g_ from"node:path";import{z as W}from"zod";import{$ as _s}from"zx";import u_ from"@inquirer/input";import Pk from"@inquirer/select";import{$ as nr}from"zx";var Ns="dev",d_="main",Sp="feature/",xk=["new","local","remote"],Ya=e=>{let t=e.trim().replace(/^feature\//,"").toLowerCase().replaceAll(/\s+/g,"-");return`${Sp}${t}`},Tk=async()=>{let e=await nr({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},p_=2,Ep=async()=>{let e=await nr({nothrow:!0,quiet:!0})`git ls-remote --exit-code origin refs/heads/${Ns}`;if(e.exitCode===0)return Ns;if(e.exitCode!==p_)throw new g(void 0,{operation:"create feature worktree",remediation:"check the network and your access to origin, or pass --base explicitly",stderrExcerpt:e.stderr.trim()||`could not ask origin whether ${Ns} exists`});return await Tk()??Ns},Ck=async e=>{let t=e?.trim();return t?t===Ns||t===d_||t===await Tk()?t:Te(ke(t)):Ep()},$k=async()=>_(e=>Pk({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"}}),Ak=async()=>_(e=>u_({message:"Feature name (becomes feature/<name>):",required:!0,validate:t=>Ya(t)===Sp?"Enter a name":!0},e),{whenHeadless:{refuse:"feature"}}),Ok=async(e,t)=>e.length===0?t:_(r=>Pk({message:"Base branch:",default:t,choices:[t,...e].map(n=>({name:n,value:n}))},r),{whenHeadless:{value:t}}),m_=async e=>{let t=await nr({nothrow:!0,quiet:!0})`git check-ref-format --branch ${e}`;if(e===Sp||t.exitCode!==0)throw new g(void 0,{operation:"create feature worktree",remediation:"pass a feature name made of letters, digits, `-`, `_`, `.` or `/`, e.g. --feature checkout-v2",stderrExcerpt:`"${e}" is not a valid branch name`})},Ek=async e=>(await nr({nothrow:!0,quiet:!0})`git fetch origin ${e}`).exitCode===0,f_=async e=>(await nr({nothrow:!0,quiet:!0})`git show-ref --verify --quiet refs/heads/${e}`).exitCode===0,Dk=async e=>{let{names:t,base:r}=e,n=[...new Set(t.map(Ya))];for(let s of n)await m_(s);if(!await Ek(r))throw new g(void 0,{operation:"create feature worktree",remediation:"pass --base dev, --base main or an existing release branch (`infra-kit release list` lists them); a repo with neither dev nor a recorded default branch needs `git remote set-head origin --auto`",stderrExcerpt:`base branch origin/${r} not found`});let o=[];for(let s of n)await f_(s)?o.push({branch:s,base:r,source:"local"}):await Ek(s)?o.push({branch:s,base:r,source:"remote"}):o.push({branch:s,base:r,source:"new"});return o},Ik=async(e,t)=>{let{branch:r,base:n,source:o}=e;o==="local"?await nr`git worktree add ${t} ${r}`:o==="remote"?await nr`git worktree add --track -b ${r} ${t} origin/${r}`:await nr`git worktree add --no-track -b ${r} ${t} origin/${n}`},Nk=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 Ms="create worktrees",h_=["already_open","orca_unreachable","orca_absent","orca_worktree_not_selectable","orca_error"],Pp=()=>({orcaOpened:[],orcaSkipped:[],orcaHidden:[]}),za=async e=>{let{confirmedCommand:t,githubDesktop:r,orca:n}=e;await _e({operation:Ms}),y_(e);try{let o=await $(),s=`${o}${ge}`;await _k(`${s}/${Ur.release}`),await _k(`${s}/${Ur.feature}`);let i=await v_(e),a=i==="feature"?await k_(e):await w_(e);if(a===null){d.info("\u2139\uFE0F No open release branches found"),y.print();let M={kind:i,createdWorktrees:[],count:0,features:[],...Pp()};return{content:b(JSON.stringify(M,null,2)),structuredContent:M}}let c=await K(),l=await b_(r,c),u=await R_(n,c),p=await Ae(o),m=g_.basename(p),f=u?await S_({explicit:n!==void 0,mainRepoRoot:p}):null;await J(t,E_(f,m,a.previewLines)),t||y.addOption("--yes",!0);let h=f?await P_(f,p):null,S=await A_(a.targets,s);if(O_(S),l)for(let M of S)await _s`github ${s}/${M}`,await _s`sleep 5`;let k=h?await T_({registration:h,createdWorktrees:S,worktreeDir:s,mainRepoRoot:p,repoName:m,config:c}):Pp();C_(k),y.print();let A={kind:i,createdWorktrees:S,count:S.length,features:a.features.filter(M=>S.includes(M.branch)),...k};return{content:b(JSON.stringify(A,null,2)),structuredContent:A}}catch(o){throw Oe(o)||o instanceof O?o:(d.debug({err:o},"Error managing worktrees"),new g(o,{operation:Ms,remediation:o instanceof g&&o.remediation||"verify branches don't already exist as worktrees: 'git worktree list'"}))}},y_=e=>{let t=e.all||e.versions!==void 0,r=e.feature!==void 0||e.base!==void 0;if(t&&r)throw new g(void 0,{operation:Ms,remediation:"pass either --versions/--all (release worktrees) or --feature [--base] (feature worktrees)",stderrExcerpt:"--feature/--base cannot be combined with --versions/--all"})},v_=async e=>e.feature!==void 0||e.base!==void 0?"feature":e.all||e.versions!==void 0?"release":(y.setInteractive(),$k()),w_=async e=>{let{all:t,versions:r}=e,n=await be("release"),o=[];if(r)o=r.split(",").map(a=>Te(ke(a.trim())));else{let a=await G(),c=a.map(l=>l.branch);if(c.length===0)return null;if(t)o=c;else{y.setInteractive();let l=new Map(a.map(p=>[p.branch,p.type])),u=await me();o=await Yt(fe({branches:c,descriptions:u,types:l}),{required:!0})}}t?y.addOption("--all",!0):y.addOption("--versions",Dt(o));let{branchesToCreate:s}=$_({selectedReleaseBranches:o,currentWorktrees:n});return{targets:s.map(a=>({branch:a,add:c=>_s`git worktree add ${c} ${a}`})),features:[],previewLines:[]}},k_=async e=>{let r=e.feature?.split(",").filter(l=>l.trim()!=="")??[],n=e.base;if(r.length===0&&(y.setInteractive(),r=[await Ak()],n===void 0)){let l=(await G()).map(u=>u.branch);n=await Ok(l,await Ep())}let o=await Ck(n),s=await Dk({names:r,base:o});y.addOption("--feature",s.map(l=>l.branch.replace(/^feature\//,"")).join(",")),y.addOption("--base",o);let i=await be("feature"),a=s.filter(l=>i.includes(l.branch)?(d.info(`\u2139\uFE0F ${l.branch} is already checked out in a worktree`),!1):!0);return{targets:a.map(l=>({branch:l.branch,add:u=>Ik(l,u)})),features:a,previewLines:a.map(Nk)}},b_=async(e,t)=>{let r=t.worktrees?.openInGithubDesktop,n=e??r??await _(o=>Mk({message:"Open created worktrees in GitHub Desktop?"},o),{whenHeadless:{value:!1}});return e===void 0&&r===void 0&&y.setInteractive(),y.addOption(n?"--github-desktop":"--no-github-desktop",!0),n},R_=async(e,t)=>{let r=t.worktrees?.openInOrca,n=e??r??await _(o=>Mk({message:"Open created worktrees in Orca?",default:!0},o),{whenHeadless:{value:!1}});return e===void 0&&r===void 0&&y.setInteractive(),y.addOption(n?"--orca":"--no-orca",!0),n},jk=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"},S_=async e=>{let{explicit:t,mainRepoRoot:r}=e,n=await Wt();if(n!=="ready"){let{reason:s,text:i}=jk(n);if(t)throw d.warn({operation:Ms},`\u26D4 --orca was passed but ${i}`),new O({status:"refused",reason:s,agentMode:j.source},2,{operation:Ms,remediation:n==="absent"?"install Orca (brew install --cask stablyai/orca/orca) and register its CLI from Settings \u2192 Experimental \u2192 CLI, or re-run with --no-orca":"open Orca (`orca open`) and re-run, or re-run with --no-orca",stderrExcerpt:`--orca was passed but ${i}; no worktree was created`});return d.warn(`\u26A0\uFE0F ${i} \u2014 worktrees will be created but not opened in Orca`),{probe:n,registered:!1,visibility:void 0}}let o=await Wf(r);return{probe:n,registered:o.registered,visibility:o.visibility}},E_=(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(`
434
- `)},P_=async(e,t)=>{if(e.probe!=="ready")return{kind:"skip",reason:jk(e.probe).reason};if(e.registered)return{kind:"ready",visibility:e.visibility};try{let{visibility:r}=await Vf(t);return{kind:"ready",visibility:r}}catch(r){return d.warn({error:r},"\u26A0\uFE0F orca repo add failed \u2014 worktrees will be created but not opened in Orca"),{kind:"skip",reason:"orca_error",code:r instanceof Jr?r.code:void 0}}},x_=e=>`Orca \u2192 ${e} \u2192 "hidden worktrees" card \u2192 Show, or Settings \u2192 General \u2192 Workspace \u2192 external-worktree sources`,T_=async e=>{let{registration:t,createdWorktrees:r,worktreeDir:n,mainRepoRoot:o,repoName:s,config:i}=e,a=Pp();if(t.kind==="skip"){for(let p of r)a.orcaSkipped.push({branch:p,reason:t.reason,code:t.code});return a}let c=Sf(i),l=r.length===1&&t.visibility!=="hide",u=Jf();for(let p of r){let m=`${n}/${p}`;try{let{layout:f}=await Kf({cwd:m,title:Hf({branch:p}),focus:l,layout:"full",panes:c,poll:u});await Gf(o,m)?a.orcaOpened.push({branch:p,layout:f}):a.orcaHidden.push({branch:p,path:m,fix:x_(s)})}catch(f){d.warn({error:f,branch:p},`\u26A0\uFE0F Failed to open Orca terminals for ${p}`),f instanceof Jr&&f.code==="orca_worktree_not_selectable"?a.orcaSkipped.push({branch:p,reason:"orca_worktree_not_selectable"}):a.orcaSkipped.push({branch:p,reason:"orca_error",code:f instanceof Jr?f.code:void 0})}}return a},C_=e=>{for(let t of e.orcaOpened)d.info(`\u{1FA9F} Opened ${t.branch} in Orca (${t.layout})`);for(let t of e.orcaHidden)d.info(`\u{1F648} ${t.branch} opened in Orca but its row is hidden (${t.path}) \u2014 ${t.fix}`);for(let t of e.orcaSkipped){let r=t.code?` (${t.code})`:"";d.info(`\u21A9\uFE0F ${t.branch} not opened in Orca: ${t.reason}${r}`)}},_k=async e=>{await _s`mkdir -p ${e}`},$_=e=>{let{selectedReleaseBranches:t,currentWorktrees:r}=e,n=r.filter(s=>Wr(s));return{branchesToCreate:t.filter(s=>!n.includes(s))}},A_=async(e,t)=>{let r=await Promise.allSettled(e.map(async o=>{let s=`${t}/${o.branch}`;return await o.add(s),await _s({cwd:s})`pnpm install`,o.branch})),n=[];for(let[o,s]of r.entries())if(s.status==="fulfilled")n.push(s.value);else{let i=e[o]?.branch,a=new g(s.reason,{operation:`git worktree add for ${i}`,remediation:"check the branch name and that the parent dir is writable"});d.error({error:s.reason,msg:a.message})}return n},O_=e=>{if(e.length>0){d.info("\u2705 Created git worktrees:");for(let t of e)d.info(t);d.info("")}else d.info("\u2139\uFE0F No new git worktrees to create")},xp=C({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:W.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:W.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:W.boolean().optional().describe('Add worktrees for every open release branch. Either "all" or "versions" must be provided for MCP calls (the interactive picker is unavailable without a TTY). Ignored if "versions" is provided.'),versions:W.string().optional().describe('Comma-separated release versions or names to target (e.g. "1.2.5, 1.2.6" or "checkout-redesign, 1.2.5"). Either "versions" or all=true must be provided for MCP calls. Overrides "all" when set.'),githubDesktop:W.boolean().optional().describe('Open each created worktree in GitHub Desktop. Resolution order: this flag \u2192 "worktrees.openInGithubDesktop" from infra-kit config \u2192 interactive prompt (CLI) / false (MCP, no TTY).'),orca:W.boolean().optional().describe('Open each created worktree in Orca: one terminal tab per worktree, laid out per "worktrees.orca.layout" (default "two-columns": left | right; or "three-pane": left split top/bottom + full-height right). Resolution order: this flag \u2192 "worktrees.openInOrca" from infra-kit config \u2192 interactive prompt (CLI, default yes) / false (MCP, no TTY). Passed explicitly, an Orca that is absent or not running is refused before any worktree is created (orca_absent / orca_unreachable); resolved from config it degrades to orcaSkipped with that reason.')},outputSchema:{kind:W.enum(["release","feature"]).describe("Which kind of worktree the run created"),features:W.array(W.object({branch:W.string(),base:W.string(),source:W.enum(xk)})).describe('Created feature worktrees: source "new" = cut from origin/<base>; "local" / "remote" = an existing branch checked out as-is (base not applied)'),createdWorktrees:W.array(W.string()).describe("List of created git worktree branches"),count:W.number().describe("Number of git worktrees created"),orcaOpened:W.array(W.object({branch:W.string(),layout:W.enum(["full","single-pane"])})).describe("Created worktrees that got an Orca terminal tab on a row the sidebar shows, with the layout applied"),orcaSkipped:W.array(W.object({branch:W.string(),reason:W.enum(h_),code:W.string().optional()})).describe("Created worktrees NOT opened in Orca and why: orca_absent / orca_unreachable (config-derived ask, Orca down), orca_worktree_not_selectable (Orca had not scanned the fresh worktree yet), orca_error (code carries the Orca error code)"),orcaHidden:W.array(W.object({branch:W.string(),path:W.string(),fix:W.string()})).describe("Created worktrees whose Orca terminals opened on a row the sidebar HIDES (the repo hides external worktrees); fix names the in-app steps to reveal it")},handler:za});import{z as or}from"zod";var Xa=async()=>{await K();let[e,t]=await Promise.all([be("release"),be("feature")]);if(e.length===0&&t.length===0){d.info("\u2139\uFE0F No active worktrees found");let s={worktrees:[],count:0,features:[]};return{content:b(JSON.stringify(s,null,2)),structuredContent:s}}let r=e.length>0?await D_(e):[],n=[];r.length>0&&n.push(`\u{1F33F} Active worktrees:
439
+ `},lN=e=>({version:e.version??U.version,home:e.home??YI(),clock:e.clock??Date.now,acquireLock:e.acquireLock??(()=>Lc({lockPath:Ey()})),readRecord:e.readRecord??Cn,writeRecord:e.writeRecord??Py,discoverProjects:e.discoverProjects??(()=>ck()),runSetupChild:e.runSetupChild??tN,writeLog:e.writeLog??rN}),uN=e=>{try{return{projects:e.discoverProjects(),error:null}}catch(t){return{projects:[],error:t instanceof Error?t.message:String(t)}}},dN=async e=>{let t=e.readRecord(),r=e.clock();if(!Cy(t,e.version,r))return"not-due";let n=t?.version===e.version?t.attempts+1:1;e.writeRecord({version:e.version,attempts:n,startedMs:r,finishedMs:null,runs:[]});let o=r+XI,s=await lk(null,e.home,e,o),i=uN(e),a=[i.error===null?s:{root:null,status:"failed",notes:[...s.notes,`could not list projects: ${i.error}`]}];for(let l of i.projects)a.push(await lk(l,l,e,o));let c={version:e.version,attempts:n,startedMs:r,finishedMs:e.clock(),runs:aN(a)};e.writeRecord(c);try{e.writeLog(cN(c))}catch{}return"ran"},uk=async(e={})=>{try{let t=lN(e),r=t.acquireLock();if(r===null)return"already-running";try{return await dN(t)}finally{r()}}catch{return"not-due"}},pp=async(e={})=>{let t=await uk(e);return{content:R(JSON.stringify({outcome:t})),structuredContent:{outcome:t}}};import{spawnSync as gN}from"node:child_process";import{homedir as hN}from"node:os";import yN from"node:process";var pN=e=>{let t=new Set(e.steps.map(r=>r[0]));return t.has("brew")?"homebrew":t.has("npm")?"npm":null},mN=e=>{let t=[];return e.needsSudo&&t.push("needs-sudo"),e.fetchesNetworkScript&&t.push("fetches-network-script"),t},fN=(e,t)=>{let r=pN(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},Ns=(e,t)=>{let r=[...mN(e),...fN(e,t)];return r.length===0?{executable:!0}:{executable:!1,reasons:r}},_s=e=>e.steps.map(Ge);var vN=["NONINTERACTIVE","CI","INTERACTIVE","HAVE_SUDO_ACCESS","SUDO_ASKPASS"],wN=e=>{let t={...Vm(e)};for(let r of vN)delete t[r];return t},mp=(e,t,r={})=>{let n=r.spawnSync??gN,o=r.env??yN.env,s=(r.agentMode??ye)(),i=_s(e),a=Ns(e,t);return a.executable?s?{ran:!1,commands:i,refusedBecause:["agent-mode"]}:RN({recipe:e,spawn:n,env:o,commands:i,notify:r.notify??kN}):{ran:!1,commands:i,refusedBecause:a.reasons}},kN=e=>{d.info(e)},pk=64,bN=pk*1024*1024,RN=({recipe:e,spawn:t,env:r,commands:n,notify:o})=>{let s=wN(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:bN,cwd:hN(),env:s}),l=CN(c);if(l!==null)return{ran:!0,ok:!1,commands:n,failedStep:n[i],detail:l}}return{ran:!0,ok:!0,commands:n}},SN=5,EN=/^(?:error|fatal|warning: failed|[a-z-]{0,20} ERR!)[:\s]/i,dk=e=>e==null?[]:String(e).split(`
440
+ `).map(t=>t.trim()).filter(t=>t.length>0),PN=e=>{let t=dk(e.stderr),r=dk(e.stdout),n=[...t,...r].filter(s=>EN.test(s)),o=t.length>0?t:r;return(n.length>0?n:o).slice(-SN).join(" / ")},xN="ENOBUFS",TN=e=>e.error?.code===xN,CN=e=>{if(TN(e))return`terminated after exceeding the ${pk} 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=PN(e),r=t===""?"":`: ${t}`;return`exited ${e.status??"unknown"}${r}`};var $N=e=>{let t=[];return e.some(n=>n.id==="brew"&&n.present)&&t.push("homebrew"),t.push("npm"),t},AN=e=>{let t=Ye(e.id);return e.present?t.updateFor(e.binRealPath):t.bootstrapInstall},ON=(e,t)=>{let r=AN(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=Ns(r,n);return{state:e,action:e.present?"update":"install",recipe:r,executable:o.executable,refusedBecause:o.executable?[]:o.reasons,commands:_s(r),context:n}},Ja=async(e=Tr,t=Qo())=>{let r=await ts(Tr,t),n={owner:null,present:$N(r)},o=Wu(e),s=new Map(r.map(a=>[a.id,a]));return{plans:o.filter(a=>e.includes(a)).map(a=>ON(s.get(a),n)),context:n}};var fp=(e,t)=>({...Ms(e),action:"skipped",commands:e.commands,detail:t}),Ms=e=>({id:e.state.id,before:{present:e.state.present,onPath:e.state.onPath,version:e.state.version,manager:e.state.manager}}),mk=(e,t)=>e.action==="none"?fp(e,`nothing to do: ${e.state.manager} installs are not managed from here`):t==="update"&&e.action==="install"?fp(e,"not installed, and --update only updates \u2014 drop the flag to install it"):e.executable?null:{...Ms(e),action:"refused",commands:e.commands,detail:`refused (${e.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},DN=(e,t)=>t.ran?t.ok?{...Ms(e),action:e.action==="install"?"installed":"updated",commands:t.commands,detail:e.action==="install"?"installed":"updated"}:{...Ms(e),action:"failed",commands:t.commands,detail:`${t.failedStep??"a step"} ${t.detail??"failed"}`}:{...Ms(e),action:"refused",commands:t.commands,detail:`refused (${t.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},gp=async e=>{let t=e.run??mp,{plans:r}=await Ja(e.ids,e.probeDeps),n=[];for(let o of r){let s=mk(o,e.mode);if(s!==null){n.push(s);continue}n.push(DN(o,t(o.recipe,o.context)))}return n},hp=async(e,t)=>{let{plans:r}=await Ja(e,t);return r.map(n=>mk(n,"converge")??fp(n,`would ${n.action} \u2014 nothing was run (--skip-tools)`))};import qN from"node:process";import{z as _}from"zod";var yp={zshrc:0,zshenv:1,migrations:2,"user-config":3,guidance:4,worktrees:5,"plugin-pointer":6,"mcp-server":7,"mcp-proxies":8,"project-config":9,"token-perms":10,chrome:11,shell:12},IN=Object.keys(yp).sort((e,t)=>yp[e]-yp[t]),fk={skipped:0,ok:1,changed:2,manual:3,warn:4,fail:5},gk=new Set(["manual","warn","fail"]),vp=e=>{switch(e){case"written":return"changed";case"unchanged":return"ok";case"skipped":return"skipped";case"manual":return"manual";case"warned":return"warn";case"failed":return"fail";default:return Ve(e)}},NN=e=>e.reduce((t,r)=>fk[r]>fk[t]?r:t,"skipped"),yk=e=>e.message.trim(),_N=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 "),hk=e=>e.message===Nn,MN=(e,t)=>{let[r]=e;return e.length===1&&r!==void 0?yk(r):e.length>1?_N(e):t?"activate with the last line below":"see below"},jN=(e,t)=>{if(t.length===0)return{name:e,status:"skipped",message:"did not run"};let r=t.map(i=>vp(i.outcome)),n=t.filter(i=>gk.has(vp(i.outcome))).map(yk),o=t.filter(i=>!gk.has(vp(i.outcome))&&!hk(i)),s={name:e,status:NN(r),message:MN(o,t.some(hk))};return n.length>0?{...s,notes:n}:s},FN=e=>({label:"Local setup",rows:IN.map(t=>jN(t,e.filter(r=>r.step===t)))}),LN=(e,t)=>{switch(e.action){case"installed":case"updated":return"changed";case"skipped":return t.skipTools&&e.commands.length>0?"manual":"skipped";case"refused":return"manual";case"failed":return"fail";default:return Ve(e.action)}},BN=(e,t)=>{let r=LN(e,t),n={name:e.id,status:r,message:e.detail};return r==="manual"&&e.commands.length>0?{...n,notes:[...e.commands]}:n},UN=(e,t)=>({label:t.skipTools?"Tools (probe: nothing installed)":"Tools",rows:e.map(r=>BN(r,t))}),WN=e=>{switch(e){case"created":case"repointed":return"changed";case"unchanged":return"ok";case"skipped-local":case"skipped-unresolved":return"skipped";case"failed":return"fail";default:return Ve(e)}},GN=e=>{switch(e){case"created":case"refreshed":return"changed";case"unchanged":return"ok";case"skipped-local":case"skipped-platform":return"skipped";case"failed":return"fail";default:return Ve(e)}},VN=e=>{switch(e){case"created":return"linked ~/.infra-kit/portless to the running portless";case"repointed":return"re-pointed ~/.infra-kit/portless to the running portless";case"unchanged":return"already linked to the running portless";case"skipped-local":return"skipped \u2014 this install is not global";case"skipped-unresolved":return"skipped \u2014 portless is not installed";case"failed":return"could not update the link \u2014 see the debug log";default:return Ve(e)}},JN=e=>{let t=e.method==="copy"?"copied":"linked";switch(e.outcome){case"created":return`${t} Node ${e.version} to ~/.infra-kit/node`;case"refreshed":return`re-${t} Node ${e.version} to ~/.infra-kit/node`;case"unchanged":return`~/.infra-kit/node is already Node ${e.version}`;case"skipped-local":return"skipped \u2014 this install is not global";case"skipped-platform":return"skipped \u2014 no portless OS service on this platform";case"failed":return"could not write ~/.infra-kit/node \u2014 see the debug log";default:return Ve(e.outcome)}},KN=(e,t)=>{let r="service";switch(e){case"converged":return{name:r,status:"ok",message:"installed service runs through the link and the node"};case"absent":return{name:r,status:"manual",message:"no service installed",notes:t===null?[]:[t]};case"drifted":return{name:r,status:"manual",message:"installed service is out of date",notes:t===null?[]:[t]};case"skipped":return{name:r,status:"skipped",message:"not judged \u2014 portless is not installed"};default:return Ve(e)}},HN=e=>({label:"Portless service",rows:[{name:"link",status:WN(e.link),message:VN(e.link)},{name:"node",status:GN(e.node.outcome),message:JN(e.node)},KN(e.service,e.command)]}),vk=(e,t)=>[FN(e.init),UN(e.tools,t),HN(e.portless)],wk=e=>e.some(t=>t.rows.some(r=>r.status==="fail"));var YN=()=>{let{link:e,node:t}=oi();return{link:e,node:t,target:{home:e.home,isGlobal:e.isGlobal,processStartTime:()=>null}}},zN=async e=>{let t=af(e.link).outcome,r=sf(e.node),n=ni(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 Cv(e.target,n);if(o==="converged")return{link:t,node:r,service:o,command:null};let i=Lt(n,{home:e.link.home,exists:e.target.exists,execPath:e.target.execPath,stableNode:s});return{link:t,node:r,service:o,command:i}},bk="--unattended cannot be combined with --tools or --update: an unattended run installs and updates nothing (it implies --skip-tools).",Rk="--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.",XN=e=>{let t=Array.isArray(e.update)?e.update:void 0,r=e.update===!0||t!==void 0,n=e.unattended===!0,o=e.skipTools===!0||n;if(n&&(e.tools!==void 0||r))throw new Error(bk);if(o&&(e.tools!==void 0||r))throw new Error(Rk);return{ids:e.tools??t??Tr,mode:r?"update":"converge",skipTools:o}},kk=(e,t)=>e instanceof In?e.step:t.at(-1)?.step??"zshrc",ZN=async()=>{let e=[];try{await _u(t=>{e.push(t)})}catch(t){e.push({step:kk(t,e),outcome:"failed",message:`The ${kk(t,e)} step failed: ${t instanceof Error?t.message:String(t)}`,level:"warn"})}return e},QN=(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}`}))},e_=async(e,t)=>{try{return e.skipTools?await hp(e.ids,t.probeDeps):await gp({ids:e.ids,mode:e.mode,probeDeps:t.probeDeps,run:t.run})}catch(r){return QN(e.ids,r)}},t_=e=>({step:e.step,outcome:e.outcome,message:e.message}),Ka=async(e={})=>{let t=XN(e);et.withheld=e.unattended===!0;let r=await ZN(),n=await e_(t,e),o=await zN(e.portlessDeps??YN()),s=vk({init:r,tools:n,portless:o},{skipTools:t.skipTools});ft({title:"infra-kit setup",sections:s},{ascii:e.ascii}),d.info(Nn),wk(s)&&(qN.exitCode=1);let i={init:r.map(t_),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:R(JSON.stringify(i,null,2)),structuredContent:i}},r_=_.object({step:_.enum(["zshrc","zshenv","migrations","user-config","guidance","worktrees","plugin-pointer","mcp-server","mcp-proxies","project-config","token-perms","chrome","shell"]).describe("Which init step this reports on"),outcome:_.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")}),n_=_.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")}),o_=_.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")}),s_={init:_.array(r_).describe("One entry per init step, in the order they ran"),tools:_.array(n_).describe("One result per requested dependency"),portlessService:o_.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)")},i_={tools:_.array(_.enum(Tr)).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.")},wp=C({name:"setup",description:'Set this machine up in one call: inject the shell integration into .zshrc and the session-env block into .zshenv, run the config migrations, seed the user-global config, check the agent-instruction files (never rewritten here: drift is reported with the `audit --fix` command that refreshes them), register the Claude Code plugin pointer and install or update the skills plugin (the `/infra-kit:*` skills drive the infra-kit CLI on PATH; a leftover .mcp.json entry is reported, never written), then bring brew, git, aws, gh, doppler and portless to a working state \u2014 installing what is missing and updating what is present. Pass mode:"update" to update only and never install, or skipTools:true to do the local setup and then REPORT what each tool needs without installing anything. Recipes that need sudo or pipe a script fetched over the network \u2014 the Homebrew bootstrap and the first AWS CLI install \u2014 are never run; they are reported with the exact commands for you to run yourself. Use `doctor` first to see the state of this machine without changing it.',inputSchema:i_,outputSchema:s_,requiresHumanConfirm:!0,handler:e=>Ka({tools:e.tools,update:e.mode==="update",skipTools:e.skipTools})});import{existsSync as Ek}from"node:fs";import Pk from"node:path";import y_ from"node:process";import{z as jt}from"zod";import{createHash as a_}from"node:crypto";import{readFileSync as c_}from"node:fs";var Lr=e=>a_("sha256").update(c_(e)).digest("hex");import{readFileSync as f_,writeFileSync as g_}from"node:fs";import za from"node:path";import{z as bt}from"zod";var ie="vendor",l_=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".vitest",".output",".source",".nitro",".tanstack"]),u_=new Set([".sync-manifest.json",".eslintcache","log.txt","routeTree.gen.ts"]),d_=[".tsbuildinfo"],kp=e=>l_.has(e),bp=e=>u_.has(e)?!0:d_.some(t=>e.endsWith(t)),Ha=e=>{let t=e.split("/"),r=t.pop()??"";return t.some(o=>kp(o))||bp(r)};import{readdirSync as p_}from"node:fs";import Rp from"node:path";var m_=e=>e.split(Rp.sep).join("/"),qa=e=>{let t=[],r=n=>{for(let o of p_(n,{withFileTypes:!0})){let s=Rp.join(n,o.name);if(o.isDirectory()){if(kp(o.name))continue;r(s);continue}bp(o.name)||t.push(m_(Rp.relative(e,s)))}};return r(e),t.sort()};var Ze=".sync-manifest.json",Ya=1,h_=bt.object({schemaVersion:bt.number().optional(),source:bt.string(),commit:bt.string(),syncedAt:bt.string(),fileCount:bt.number(),files:bt.record(bt.string(),bt.string())}),Sp=e=>(e.schemaVersion??Ya)>Ya,Sk=(e,t)=>{let r={},n=t?[...new Set(t)].sort():qa(e);for(let o of n)try{r[o]=Lr(za.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},js=e=>{let t=za.join(e,Ze),r;try{r=f_(t,"utf8")}catch{throw new Error(`Missing ${Ze} at ${t}`)}let n=h_.safeParse(JSON.parse(r));if(!n.success)throw new Error(`Invalid ${Ze} at ${t}: ${bt.prettifyError(n.error)}`);return n.data},Ep=(e,t,r)=>{let n=Sk(e,r),o={schemaVersion:Ya,source:t.source,commit:t.commit,syncedAt:new Date().toISOString(),fileCount:Object.keys(n).length,files:n};return g_(za.join(e,Ze),`${JSON.stringify(o,null,2)}
441
+ `),o},Pp=(e,t)=>{let r=Object.fromEntries(Object.entries(t.files).filter(([c])=>!Ha(c))),n=qa(e),o=[],s=[];for(let c of n){if(!(c in r)){s.push(c);continue}Lr(za.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 xp=30,Tp=(e,t)=>{if(t.length!==0){d.info(`
442
+ ${e} (${t.length}):`);for(let r of t.slice(0,xp))d.info(` ${r}`);t.length>xp&&d.info(` \u2026and ${t.length-xp} more`)}},Xa=async(e={})=>{let t=e.cwd??await A(),r=Pk.join(t,ie),n={modified:[],added:[],removed:[],fileCount:0};if(!Ek(r)){d.info(`\u2139\uFE0F No ${ie}/ folder found \u2014 nothing to check.`);let u={status:"skipped",ok:!0,...n};return{content:R(JSON.stringify(u,null,2)),structuredContent:u}}if(!Ek(Pk.join(r,Ze))){d.error(`\u274C Missing ${ie}/${Ze}. Re-run the vendor sync to generate it.`);let u={status:"missing-manifest",ok:!1,...n};return{content:R(JSON.stringify(u,null,2)),structuredContent:u}}let o=js(r);if(Sp(o)){d.error(`\u274C ${ie}/${Ze} has a newer schemaVersion (${String(o.schemaVersion)}) than this CLI supports. Upgrade infra-kit.`);let u={status:"unknown-schema",ok:!1,...n};return{content:R(JSON.stringify(u,null,2)),structuredContent:u}}let{modified:s,added:i,removed:a}=Pp(r,o),c=s.length>0||i.length>0||a.length>0;c?(d.error(`\u274C ${ie}/ has drifted from ${ie}/${Ze}.`),d.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),Tp("Modified",s),Tp("Added (not in manifest)",i),Tp("Removed (in manifest, now missing)",a)):d.info(`\u2705 ${ie}/ matches manifest (${o.fileCount} files).`);let l={status:c?"drift":"clean",ok:!c,fileCount:o.fileCount,modified:s,added:i,removed:a};return{content:R(JSON.stringify(l,null,2)),structuredContent:l}},v_={status:jt.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:jt.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:jt.number(),modified:jt.array(jt.string()),added:jt.array(jt.string()),removed:jt.array(jt.string())},Cp=C({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:v_,handler:()=>Xa({cwd:y_.cwd()})});import xk from"node:process";import{z as Fs}from"zod";var Tk=async e=>{try{return await e()}catch{return null}},Za=async()=>{let e=U.version;d.info(e);let t=await Tk(A),r=t===null?null:await Tk(()=>De(t)),n={version:e,cwd:xk.cwd(),repoRoot:t,mainRepoRoot:r,projectDir:xk.env.CLAUDE_PROJECT_DIR||null};return{content:R(JSON.stringify(n,null,2)),structuredContent:n}},$p=C({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:Fs.string().describe("Installed infra-kit CLI version (from package.json)"),cwd:Fs.string().describe("The working directory of this process"),repoRoot:Fs.string().nullable().describe("git toplevel of cwd \u2014 the worktree itself in a linked worktree; null when git cannot answer"),mainRepoRoot:Fs.string().nullable().describe("The main checkout a linked worktree belongs to (equals repoRoot outside worktrees); null with repoRoot"),projectDir:Fs.string().nullable().describe("CLAUDE_PROJECT_DIR as Claude Code set it for this process, or null")},handler:Za});import Bk from"@inquirer/confirm";import E_ from"node:path";import{z as G}from"zod";import{$ as Ls}from"zx";import w_ from"@inquirer/input";import $k from"@inquirer/select";import{$ as sr}from"zx";var Hn="dev",k_="main",Ap="feature/",Ak=["new","local","remote"],Qa=e=>{let t=e.trim().replace(/^feature\//,"").toLowerCase().replaceAll(/\s+/g,"-");return`${Ap}${t}`},Ok=async()=>{let e=await sr({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},b_=2,Op=async()=>{if(await te()==="main")return ve;let e=await sr({nothrow:!0,quiet:!0})`git ls-remote --exit-code origin refs/heads/${Hn}`;if(e.exitCode===0)return Hn;if(e.exitCode!==b_)throw new g(void 0,{operation:"create feature worktree",remediation:"check the network and your access to origin, or pass --base explicitly",stderrExcerpt:e.stderr.trim()||`could not ask origin whether ${Hn} exists`});return await Ok()??Hn},Dk=async e=>{let t=e?.trim();if(!t)return Op();if(t===Hn&&await te()==="main")throw new g(void 0,{operation:"create feature worktree",remediation:'this repo sets "gitFlow": "main" in infra-kit.json, so features branch off main \u2014 drop --base or pass --base main'});return t===Hn||t===k_||t===await Ok()?t:$e(Re(t))},Ik=async()=>M(e=>$k({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"}}),Nk=async()=>M(e=>w_({message:"Feature name (becomes feature/<name>):",required:!0,validate:t=>Qa(t)===Ap?"Enter a name":!0},e),{whenHeadless:{refuse:"feature"}}),_k=async(e,t)=>e.length===0?t:M(r=>$k({message:"Base branch:",default:t,choices:[t,...e].map(n=>({name:n,value:n}))},r),{whenHeadless:{value:t}}),R_=async e=>{let t=await sr({nothrow:!0,quiet:!0})`git check-ref-format --branch ${e}`;if(e===Ap||t.exitCode!==0)throw new g(void 0,{operation:"create feature worktree",remediation:"pass a feature name made of letters, digits, `-`, `_`, `.` or `/`, e.g. --feature checkout-v2",stderrExcerpt:`"${e}" is not a valid branch name`})},Ck=async e=>(await sr({nothrow:!0,quiet:!0})`git fetch origin ${e}`).exitCode===0,S_=async e=>(await sr({nothrow:!0,quiet:!0})`git show-ref --verify --quiet refs/heads/${e}`).exitCode===0,Mk=async e=>{let{names:t,base:r}=e,n=[...new Set(t.map(Qa))];for(let s of n)await R_(s);if(!await Ck(r))throw new g(void 0,{operation:"create feature worktree",remediation:"pass --base dev, --base main or an existing release branch (`infra-kit release list` lists them); a repo with neither dev nor a recorded default branch needs `git remote set-head origin --auto`",stderrExcerpt:`base branch origin/${r} not found`});let o=[];for(let s of n)await S_(s)?o.push({branch:s,base:r,source:"local"}):await Ck(s)?o.push({branch:s,base:r,source:"remote"}):o.push({branch:s,base:r,source:"new"});return o},jk=async(e,t)=>{let{branch:r,base:n,source:o}=e;o==="local"?await sr`git worktree add ${t} ${r}`:o==="remote"?await sr`git worktree add --track -b ${r} ${t} origin/${r}`:await sr`git worktree add --no-track -b ${r} ${t} origin/${n}`},Fk=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 Bs="create worktrees",P_=["already_open","orca_unreachable","orca_absent","orca_worktree_not_selectable","orca_error"],Dp=()=>({orcaOpened:[],orcaSkipped:[],orcaHidden:[]}),ec=async e=>{let{confirmedCommand:t,githubDesktop:r,orca:n}=e;await je({operation:Bs}),x_(e);try{let o=await A(),s=`${o}${he}`;await Lk(`${s}/${Jr.release}`),await Lk(`${s}/${Jr.feature}`);let i=await T_(e),a=i==="feature"?await $_(e):await C_(e);if(a===null){d.info("\u2139\uFE0F No open release branches found"),y.print();let j={kind:i,createdWorktrees:[],count:0,features:[],...Dp()};return{content:R(JSON.stringify(j,null,2)),structuredContent:j}}let c=await J(),l=await A_(r,c),u=await O_(n,c),p=await De(o),m=E_.basename(p),f=u?await D_({explicit:n!==void 0,mainRepoRoot:p}):null;await H(t,I_(f,m,a.previewLines)),t||y.addOption("--yes",!0);let h=f?await N_(f,p):null,b=await L_(a.targets,s);if(B_(b),l)for(let j of b)await Ls`github ${s}/${j}`,await Ls`sleep 5`;let T=h?await M_({registration:h,createdWorktrees:b,worktreeDir:s,mainRepoRoot:p,repoName:m,config:c}):Dp();j_(T),y.print();let k={kind:i,createdWorktrees:b,count:b.length,features:a.features.filter(j=>b.includes(j.branch)),...T};return{content:R(JSON.stringify(k,null,2)),structuredContent:k}}catch(o){throw Ie(o)||o instanceof D?o:(d.debug({err:o},"Error managing worktrees"),new g(o,{operation:Bs,remediation:o instanceof g&&o.remediation||"verify branches don't already exist as worktrees: 'git worktree list'"}))}},x_=e=>{let t=e.all||e.versions!==void 0,r=e.feature!==void 0||e.base!==void 0;if(t&&r)throw new g(void 0,{operation:Bs,remediation:"pass either --versions/--all (release worktrees) or --feature [--base] (feature worktrees)",stderrExcerpt:"--feature/--base cannot be combined with --versions/--all"})},T_=async e=>e.feature!==void 0||e.base!==void 0?"feature":e.all||e.versions!==void 0?"release":(y.setInteractive(),Ik()),C_=async e=>{let{all:t,versions:r}=e,n=await Se("release"),o=[];if(r)o=r.split(",").map(a=>$e(Re(a.trim())));else{let a=await K(),c=a.map(l=>l.branch);if(c.length===0)return null;if(t)o=c;else{y.setInteractive();let l=new Map(a.map(p=>[p.branch,p.type])),u=await fe();o=await Xt(ge({branches:c,descriptions:u,types:l}),{required:!0})}}t?y.addOption("--all",!0):y.addOption("--versions",Nt(o));let{branchesToCreate:s}=F_({selectedReleaseBranches:o,currentWorktrees:n});return{targets:s.map(a=>({branch:a,add:c=>Ls`git worktree add ${c} ${a}`})),features:[],previewLines:[]}},$_=async e=>{let r=e.feature?.split(",").filter(l=>l.trim()!=="")??[],n=e.base;if(r.length===0&&(y.setInteractive(),r=[await Nk()],n===void 0)){let l=(await K()).map(u=>u.branch);n=await _k(l,await Op())}let o=await Dk(n),s=await Mk({names:r,base:o});y.addOption("--feature",s.map(l=>l.branch.replace(/^feature\//,"")).join(",")),y.addOption("--base",o);let i=await Se("feature"),a=s.filter(l=>i.includes(l.branch)?(d.info(`\u2139\uFE0F ${l.branch} is already checked out in a worktree`),!1):!0);return{targets:a.map(l=>({branch:l.branch,add:u=>jk(l,u)})),features:a,previewLines:a.map(Fk)}},A_=async(e,t)=>{let r=t.worktrees?.openInGithubDesktop,n=e??r??await M(o=>Bk({message:"Open created worktrees in GitHub Desktop?"},o),{whenHeadless:{value:!1}});return e===void 0&&r===void 0&&y.setInteractive(),y.addOption(n?"--github-desktop":"--no-github-desktop",!0),n},O_=async(e,t)=>{let r=t.worktrees?.openInOrca,n=e??r??await M(o=>Bk({message:"Open created worktrees in Orca?",default:!0},o),{whenHeadless:{value:!1}});return e===void 0&&r===void 0&&y.setInteractive(),y.addOption(n?"--orca":"--no-orca",!0),n},Uk=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"},D_=async e=>{let{explicit:t,mainRepoRoot:r}=e,n=await Vt();if(n!=="ready"){let{reason:s,text:i}=Uk(n);if(t)throw d.warn({operation:Bs},`\u26D4 --orca was passed but ${i}`),new D({status:"refused",reason:s,agentMode:F.source},2,{operation:Bs,remediation:n==="absent"?"install Orca (brew install --cask stablyai/orca/orca) and register its CLI from Settings \u2192 Experimental \u2192 CLI, or re-run with --no-orca":"open Orca (`orca open`) and re-run, or re-run with --no-orca",stderrExcerpt:`--orca was passed but ${i}; no worktree was created`});return d.warn(`\u26A0\uFE0F ${i} \u2014 worktrees will be created but not opened in Orca`),{probe:n,registered:!1,visibility:void 0}}let o=await Yf(r);return{probe:n,registered:o.registered,visibility:o.visibility}},I_=(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(`
443
+ `)},N_=async(e,t)=>{if(e.probe!=="ready")return{kind:"skip",reason:Uk(e.probe).reason};if(e.registered)return{kind:"ready",visibility:e.visibility};try{let{visibility:r}=await zf(t);return{kind:"ready",visibility:r}}catch(r){return d.warn({error:r},"\u26A0\uFE0F orca repo add failed \u2014 worktrees will be created but not opened in Orca"),{kind:"skip",reason:"orca_error",code:r instanceof Yr?r.code:void 0}}},__=e=>`Orca \u2192 ${e} \u2192 "hidden worktrees" card \u2192 Show, or Settings \u2192 General \u2192 Workspace \u2192 external-worktree sources`,M_=async e=>{let{registration:t,createdWorktrees:r,worktreeDir:n,mainRepoRoot:o,repoName:s,config:i}=e,a=Dp();if(t.kind==="skip"){for(let p of r)a.orcaSkipped.push({branch:p,reason:t.reason,code:t.code});return a}let c=Af(i),l=r.length===1&&t.visibility!=="hide",u=Zf();for(let p of r){let m=`${n}/${p}`;try{let{layout:f}=await Qf({cwd:m,title:eg({branch:p}),focus:l,layout:"full",panes:c,poll:u});await Xf(o,m)?a.orcaOpened.push({branch:p,layout:f}):a.orcaHidden.push({branch:p,path:m,fix:__(s)})}catch(f){d.warn({error:f,branch:p},`\u26A0\uFE0F Failed to open Orca terminals for ${p}`),f instanceof Yr&&f.code==="orca_worktree_not_selectable"?a.orcaSkipped.push({branch:p,reason:"orca_worktree_not_selectable"}):a.orcaSkipped.push({branch:p,reason:"orca_error",code:f instanceof Yr?f.code:void 0})}}return a},j_=e=>{for(let t of e.orcaOpened)d.info(`\u{1FA9F} Opened ${t.branch} in Orca (${t.layout})`);for(let t of e.orcaHidden)d.info(`\u{1F648} ${t.branch} opened in Orca but its row is hidden (${t.path}) \u2014 ${t.fix}`);for(let t of e.orcaSkipped){let r=t.code?` (${t.code})`:"";d.info(`\u21A9\uFE0F ${t.branch} not opened in Orca: ${t.reason}${r}`)}},Lk=async e=>{await Ls`mkdir -p ${e}`},F_=e=>{let{selectedReleaseBranches:t,currentWorktrees:r}=e,n=r.filter(s=>Kr(s));return{branchesToCreate:t.filter(s=>!n.includes(s))}},L_=async(e,t)=>{let r=await Promise.allSettled(e.map(async o=>{let s=`${t}/${o.branch}`;return await o.add(s),await Ls({cwd:s})`pnpm install`,o.branch})),n=[];for(let[o,s]of r.entries())if(s.status==="fulfilled")n.push(s.value);else{let i=e[o]?.branch,a=new g(s.reason,{operation:`git worktree add for ${i}`,remediation:"check the branch name and that the parent dir is writable"});d.error({error:s.reason,msg:a.message})}return n},B_=e=>{if(e.length>0){d.info("\u2705 Created git worktrees:");for(let t of e)d.info(t);d.info("")}else d.info("\u2139\uFE0F No new git worktrees to create")},Ip=C({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:G.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:G.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:G.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:G.string().optional().describe('Comma-separated release versions or names to target (e.g. "1.2.5, 1.2.6" or "checkout-redesign, 1.2.5"). Either "versions" or all=true must be provided for MCP calls. Overrides "all" when set.'),githubDesktop:G.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:G.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:G.enum(["release","feature"]).describe("Which kind of worktree the run created"),features:G.array(G.object({branch:G.string(),base:G.string(),source:G.enum(Ak)})).describe('Created feature worktrees: source "new" = cut from origin/<base>; "local" / "remote" = an existing branch checked out as-is (base not applied)'),createdWorktrees:G.array(G.string()).describe("List of created git worktree branches"),count:G.number().describe("Number of git worktrees created"),orcaOpened:G.array(G.object({branch:G.string(),layout:G.enum(["full","single-pane"])})).describe("Created worktrees that got an Orca terminal tab on a row the sidebar shows, with the layout applied"),orcaSkipped:G.array(G.object({branch:G.string(),reason:G.enum(P_),code:G.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:G.array(G.object({branch:G.string(),path:G.string(),fix:G.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:ec});import{z as ir}from"zod";var tc=async()=>{await J();let[e,t]=await Promise.all([Se("release"),Se("feature")]);if(e.length===0&&t.length===0){d.info("\u2139\uFE0F No active worktrees found");let s={worktrees:[],count:0,features:[]};return{content:R(JSON.stringify(s,null,2)),structuredContent:s}}let r=e.length>0?await U_(e):[],n=[];r.length>0&&n.push(`\u{1F33F} Active worktrees:
435
444
 
436
- ${I_(r).join(`
445
+ ${W_(r).join(`
437
446
  `)}`),t.length>0&&n.push(`\u{1F9EA} Feature worktrees:
438
447
 
439
448
  ${t.join(`
440
449
  `)}`),d.info(n.join(`
441
450
 
442
- `));let o={worktrees:r,count:r.length,features:t};return{content:b(JSON.stringify(o,null,2)),structuredContent:o}},D_=async e=>{let[t,r]=await Promise.all([G(),me()]),n=new Map(t.map(o=>[o.branch,o.type]));return e.flatMap(o=>{let s=Q(o);if(!s)return[];let i=ne(s),a=n.get(o)||"regular",c=r.get(le(s))||null;return[{version:i,type:a,description:c}]})},I_=e=>{let t=Math.max(...e.map(r=>r.version.length));return e.map(r=>{let n=Mo(r.version,r.type,t);return r.description?`${n} ${r.description}`:n})},Tp=C({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:or.array(or.object({version:or.string().describe("Release version"),type:or.enum(["regular","hotfix"]).describe("Release type"),description:or.string().nullable().describe("Jira version description")})).describe("Release worktrees with details"),count:or.number().describe("Number of release worktrees"),features:or.array(or.string()).describe("Branches of feature worktrees (feature/<name>)")},handler:Xa});import{z as Xe}from"zod";import N_ from"node:fs/promises";import{$ as __}from"zx";var Lk="remove this worktree",M_=2,j_=3,Za=async e=>{try{return await N_.realpath(e)}catch{return e}},Mr=(e,t)=>{throw new g(void 0,{operation:Lk,remediation:e,stderrExcerpt:t})},F_=e=>{if(e.startsWith("feature/"))return["--feature",e.slice(8)];let[t]=Dt([e]);return Wr(e)&&t?["--versions",t]:Mr("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`)},L_=async()=>{let e=await Za(await $()),t=await Za(await Ae(e));e===t&&Mr("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 st(t))await Za(o.path)===e&&(r=o.branch);if(!r)return Mr("check out a branch in this worktree first",`no branch is checked out at ${e}`);let n=await Za(`${t}${ge}/${r}`);return n!==e&&Mr("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:F_(r)}},Fk=async e=>(await __({quiet:!0})`git -C ${e} status --porcelain`).stdout.split(`
443
- `).filter(r=>r.trim().length>0),B_=async e=>{let[t,r]=await Promise.all([Fk(e.worktreePath),Fk(e.mainRoot)]);t.length>0&&Mr("commit or stash your changes (`git stash -u`), then retry",`uncommitted changes: ${t.join(", ")}`),r.length>0&&Mr(`commit or stash the changes in the main checkout ${e.mainRoot}, then retry`,`the main checkout has uncommitted changes: ${r.join(", ")}`);let n=await Wt();n!=="ready"&&Mr(`run \`infra-kit worktrees remove ${Ue(e.targetArgs)}\` from the main checkout ${e.mainRoot}`,`--self hands the removal to an Orca terminal, and Orca is ${n}`)},U_=async e=>{let t=Ue(["infra-kit","worktrees","remove",...e.targetArgs,"--yes"]),r=`sleep ${M_}; ${t} && { sleep ${j_}; exit; }`;try{return(await Lf(["terminal","create","--worktree",`path:${e.mainRoot}`,"--title",`ik: remove ${e.branch}`,"--command",r])).terminal.handle}catch(n){throw n instanceof Jr?new g(n,{operation:Lk,remediation:`run \`infra-kit worktrees remove ${Ue(e.targetArgs)}\` from the main checkout ${e.mainRoot}`,stderrExcerpt:n.message}):n}},Bk=async e=>{let t=await L_();await B_(t),y.addOption("--self",!0),await J(e,`Remove ${t.branch} at ${t.worktreePath} and close every Orca tab in it (this terminal included)?`),e||y.addOption("--yes",!0);let r=await U_(t);d.info(`\u27A1\uFE0F Removal of ${t.branch} handed off to Orca (main checkout tab "ik: remove ${t.branch}")`),y.print();let n={branch:t.branch,worktreePath:t.worktreePath,terminal:r};return{content:b(JSON.stringify({status:"handed_off",...n},null,2)),structuredContent:{removedWorktrees:[],failedWorktrees:[],count:0,handedOff:n}}};var W_=e=>{if(he()){if(e.all)throw new O({status:"refused",agentMode:j.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 O({status:"argument_required",argument:"versions",agentMode:j.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"})}},V_=(e,t)=>{let r=e.filter(n=>!t.includes(n));if(r.length>0)throw new g(void 0,{operation:"remove worktrees",remediation:`no active worktree for: ${r.join(", ")}. Run 'infra-kit worktrees list' to see current worktrees`,stderrExcerpt:`unmatched worktree target(s): ${r.join(", ")}`})},G_=async(e,t)=>{let r=await ui(t.map(n=>`${e}/${n}`));if(r!==null)throw new O({status:"refused",reason:"orca_caller_inside_target",agentMode:j.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`})},J_=e=>e?e.split(",").map(t=>Te(ke(t.trim()))):[],K_=e=>e?e.split(",").filter(t=>t.trim()!=="").map(Ya):[],H_=e=>{let t=e.filter(n=>n.startsWith("feature/")),r=e.filter(n=>!t.includes(n));r.length>0&&y.addOption("--versions",Dt(r)),t.length>0&&y.addOption("--feature",t.map(n=>n.replace(/^feature\//,"")).join(","))},Qa=async e=>{let{confirmedCommand:t,all:r,versions:n,feature:o,self:s}=e;if(s){if(r||n||o)throw new g(void 0,{operation:"remove worktrees",remediation:"pass --self alone, or name targets with --versions / --feature",stderrExcerpt:"--self cannot be combined with --all, --versions or --feature"});return Bk(t)}await _e({operation:"remove worktrees"}),await K(),W_({all:r,versions:n,feature:o});try{let[i,a]=await Promise.all([be("release"),be("feature")]),c=[...i,...a];if(c.length===0){d.info("\u2139\uFE0F No active worktrees to remove"),y.print();let h={removedWorktrees:[],failedWorktrees:[],count:0};return{content:b(JSON.stringify(h,null,2)),structuredContent:h}}let l=await $(),u=`${l}${ge}`,p=[];if(r)p=c;else if(n||o)p=[...J_(n),...K_(o)];else{y.setInteractive();let[h,S]=await Promise.all([me(),G()]),k=new Map(S.map(A=>[A.branch,A.type]));p=await Yt([...fe({branches:i,descriptions:h,types:k}),...a.map(A=>({value:A,label:A,type:"feature"}))],{required:!0})}V_(p,c);let m=p.length===c.length;m?y.addOption("--all",!0):H_(p),await G_(u,p),await J(t,"Are you sure you want to proceed with these worktree changes?"),t||y.addOption("--yes",!0);let f=await Or({branches:p,worktreeDir:u,projectRoot:l,pruneFolder:m});return cs(f),y.print(),ls({result:f,operation:"remove worktrees"})}catch(i){throw Oe(i)||i instanceof g?i:(d.error({error:i},"\u274C Error managing worktrees"),new g(i,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"}))}},Cp=C({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:Xe.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:Xe.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:Xe.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{removedWorktrees:Xe.array(Xe.string()).describe("List of removed git worktree branches"),failedWorktrees:Xe.array(Xe.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:Xe.number().describe("Number of git worktrees removed"),handedOff:Xe.object({branch:Xe.string(),worktreePath:Xe.string(),terminal:Xe.string()}).optional().describe("--self only: the worktree whose removal now runs in an Orca tab of the main checkout")},handler:Qa});import{z as js}from"zod";var ec=async e=>{let{confirmedCommand:t}=e;await _e({operation:"sync worktrees"}),await K();try{let r=await be("release"),n=await $(),o=`${n}${ge}`,s=await Fi();await J(t,"Are you sure you want to proceed with these worktree changes?"),t||y.addOption("--yes",!0);let{branchesToRemove:i}=q_({releasePRsList:s,currentWorktrees:r}),a=await Or({branches:i,worktreeDir:o,projectRoot:n});return cs(a),y.print(),ls({result:a,operation:"sync worktrees"})}catch(r){throw Oe(r)||r instanceof g?r:(d.error({error:r},"\u274C Error managing worktrees"),new g(r,{operation:"sync worktrees with remote",remediation:"ensure 'gh auth status' is ok and you can reach origin"}))}},q_=e=>{let{releasePRsList:t,currentWorktrees:r}=e;return{branchesToRemove:r.filter(s=>Wr(s)).filter(s=>!t.includes(s))}},$p=C({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:js.array(js.string()).describe("List of removed worktree branches"),failedWorktrees:js.array(js.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:js.number().describe("Number of worktrees removed during sync")},handler:ec});var Ap=[{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"}],xr=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["dev"],longRunning:!0},{cliName:"dev-status",menuGroup:"develop",mcpTool:Wl,mcpExposed:!0,mutating:!1,groupPath:["dev-status"]},{cliName:"e2e",menuGroup:"develop",mcpTool:id,mcpExposed:!1,mutating:!0,groupPath:["e2e"]},{cliName:"merge-dev",menuGroup:"release",mcpTool:md,mcpExposed:!0,mutating:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:jd,mcpExposed:!0,mutating:!1,groupPath:["release","list"]},{cliName:"release-create",menuGroup:"release",mcpTool:Qd,mcpExposed:!0,mutating:!0,groupPath:["release","create"]},{cliName:"release-edit",menuGroup:"release",mcpTool:tp,mcpExposed:!0,mutating:!0,groupPath:["release","edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:Nd,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:Md,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:yd,mcpExposed:!1,mutating:!0,humanOnly:!0,groupPath:["release","deliver"]},{cliName:"release-remove",menuGroup:"release",mcpTool:op,mcpExposed:!0,mutating:!0,groupPath:["release","remove"]},{cliName:"local-deploy-all",menuGroup:null,mcpTool:qd,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:xp,mcpExposed:!0,mutating:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:Tp,mcpExposed:!0,mutating:!1,groupPath:["worktrees","list"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:Cp,mcpExposed:!0,mutating:!0,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:$p,mcpExposed:!0,mutating:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:ld,mcpExposed:!0,mutating:!1,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:Zf,mcpExposed:!0,mutating:!1,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:Vc,mcpExposed:!0,mutating:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:cd,mcpExposed:!0,mutating:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:ud,mcpExposed:!0,mutating:!1,groupPath:["env-token-list"]},{cliName:"config-get",menuGroup:"configuration",mcpTool:Bl,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:bp,mcpExposed:!0,mutating:!1,groupPath:["vendor","check"]},{cliName:"vendor-config",menuGroup:"vendor",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["vendor","config"]},{cliName:"vendor-sync",menuGroup:"vendor",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["vendor","sync"]},{cliName:"deploy-run",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,humanOnly:!0,groupPath:["deploy-run"]},{cliName:"deploy-sync",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["deploy-sync"]},{cliName:"setup",menuGroup:"setup",mcpTool:pp,mcpExposed:!0,mutating:!0,groupPath:["setup"]},{cliName:"doctor",menuGroup:"setup",mcpTool:qu,mcpExposed:!0,mutating:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:$l,mcpExposed:!0,mutating:!1,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:Rp,mcpExposed:!0,mutating:!1,groupPath:["version"]},{cliName:"change-stats",menuGroup:null,mcpTool:jl,mcpExposed:!1,mutating:!1,groupPath:["change-stats"]},{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 Op=e=>xr.filter(t=>t.menuGroup===e),Dp=e=>xr.some(t=>t.longRunning===!0&&t.groupPath.join(" ")===e);var Y_=(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},Uk=e=>Ap.flatMap(({key:t,label:r})=>Op(t).flatMap(n=>{let o=Y_(e,n.groupPath);return o?[{name:n.groupPath.join(" "),description:o.description(),group:r}]:[]}));import Ip from"node:process";var z_="MODULE_TYPELESS_PACKAGE_JSON",X_=(e,t)=>typeof e=="object"&&e!==null?e.code:t,Wk=!1,Np=()=>{if(Wk)return;Wk=!0;let e=Ip.emitWarning.bind(Ip);Ip.emitWarning=((t,...r)=>{X_(r[0],r[1])!==z_&&e(t,...r)})};import{Command as lF,InvalidArgumentError as Kb,Option as Gb}from"commander";import{resolve as uF}from"node:path";import Fe from"node:process";import{cd as dF}from"zx";import Vk from"node:process";import{$ as Z_}from"zx";var _p=async()=>{let e=await ee(),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 oe(i.path)}))),r=t.at(-1)?.exists===!0,n=await Ko(e.userProject,r),o=r?Ho(n):"";d.info(`Project name: ${e.projectName}
451
+ `));let o={worktrees:r,count:r.length,features:t};return{content:R(JSON.stringify(o,null,2)),structuredContent:o}},U_=async e=>{let[t,r]=await Promise.all([K(),fe()]),n=new Map(t.map(o=>[o.branch,o.type]));return e.flatMap(o=>{let s=ee(o);if(!s)return[];let i=oe(s),a=n.get(o)||"regular",c=r.get(ue(s))||null;return[{version:i,type:a,description:c}]})},W_=e=>{let t=Math.max(...e.map(r=>r.version.length));return e.map(r=>{let n=Uo(r.version,r.type,t);return r.description?`${n} ${r.description}`:n})},Np=C({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:ir.array(ir.object({version:ir.string().describe("Release version"),type:ir.enum(["regular","hotfix"]).describe("Release type"),description:ir.string().nullable().describe("Jira version description")})).describe("Release worktrees with details"),count:ir.number().describe("Number of release worktrees"),features:ir.array(ir.string()).describe("Branches of feature worktrees (feature/<name>)")},handler:tc});import{z as Qe}from"zod";import G_ from"node:fs/promises";import{$ as V_}from"zx";var Gk="remove this worktree",J_=2,K_=3,rc=async e=>{try{return await G_.realpath(e)}catch{return e}},Br=(e,t)=>{throw new g(void 0,{operation:Gk,remediation:e,stderrExcerpt:t})},H_=e=>{if(e.startsWith("feature/"))return["--feature",e.slice(8)];let[t]=Nt([e]);return Kr(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`)},q_=async()=>{let e=await rc(await A()),t=await rc(await De(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 at(t))await rc(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 rc(`${t}${he}/${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:H_(r)}},Wk=async e=>(await V_({quiet:!0})`git -C ${e} status --porcelain`).stdout.split(`
452
+ `).filter(r=>r.trim().length>0),Y_=async e=>{let[t,r]=await Promise.all([Wk(e.worktreePath),Wk(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 Vt();n!=="ready"&&Br(`run \`infra-kit worktrees remove ${Ge(e.targetArgs)}\` from the main checkout ${e.mainRoot}`,`--self hands the removal to an Orca terminal, and Orca is ${n}`)},z_=async e=>{let t=Ge(["infra-kit","worktrees","remove",...e.targetArgs,"--yes"]),r=`sleep ${J_}; ${t} && { sleep ${K_}; exit; }`;try{return(await Kf(["terminal","create","--worktree",`path:${e.mainRoot}`,"--title",`ik: remove ${e.branch}`,"--command",r])).terminal.handle}catch(n){throw n instanceof Yr?new g(n,{operation:Gk,remediation:`run \`infra-kit worktrees remove ${Ge(e.targetArgs)}\` from the main checkout ${e.mainRoot}`,stderrExcerpt:n.message}):n}},Vk=async e=>{let t=await q_();await Y_(t),y.addOption("--self",!0),await H(e,`Remove ${t.branch} at ${t.worktreePath} and close every Orca tab in it (this terminal included)?`),e||y.addOption("--yes",!0);let r=await z_(t);d.info(`\u27A1\uFE0F Removal of ${t.branch} handed off to Orca (main checkout tab "ik: remove ${t.branch}")`),y.print();let n={branch:t.branch,worktreePath:t.worktreePath,terminal:r};return{content:R(JSON.stringify({status:"handed_off",...n},null,2)),structuredContent:{removedWorktrees:[],failedWorktrees:[],count:0,handedOff:n}}};var X_=e=>{if(ye()){if(e.all)throw new D({status:"refused",agentMode:F.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 D({status:"argument_required",argument:"versions",agentMode:F.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"})}},Z_=(e,t)=>{let r=e.filter(n=>!t.includes(n));if(r.length>0)throw new g(void 0,{operation:"remove worktrees",remediation:`no active worktree for: ${r.join(", ")}. Run 'infra-kit worktrees list' to see current worktrees`,stderrExcerpt:`unmatched worktree target(s): ${r.join(", ")}`})},Q_=async(e,t)=>{let r=await fi(t.map(n=>`${e}/${n}`));if(r!==null)throw new D({status:"refused",reason:"orca_caller_inside_target",agentMode:F.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`})},eM=e=>e?e.split(",").map(t=>$e(Re(t.trim()))):[],tM=e=>e?e.split(",").filter(t=>t.trim()!=="").map(Qa):[],rM=e=>{let t=e.filter(n=>n.startsWith("feature/")),r=e.filter(n=>!t.includes(n));r.length>0&&y.addOption("--versions",Nt(r)),t.length>0&&y.addOption("--feature",t.map(n=>n.replace(/^feature\//,"")).join(","))},nc=async e=>{let{confirmedCommand:t,all:r,versions:n,feature:o,self:s}=e;if(s){if(r||n||o)throw new g(void 0,{operation:"remove worktrees",remediation:"pass --self alone, or name targets with --versions / --feature",stderrExcerpt:"--self cannot be combined with --all, --versions or --feature"});return Vk(t)}await je({operation:"remove worktrees"}),await J(),X_({all:r,versions:n,feature:o});try{let[i,a]=await Promise.all([Se("release"),Se("feature")]),c=[...i,...a];if(c.length===0){d.info("\u2139\uFE0F No active worktrees to remove"),y.print();let h={removedWorktrees:[],failedWorktrees:[],count:0};return{content:R(JSON.stringify(h,null,2)),structuredContent:h}}let l=await A(),u=`${l}${he}`,p=[];if(r)p=c;else if(n||o)p=[...eM(n),...tM(o)];else{y.setInteractive();let[h,b]=await Promise.all([fe(),K()]),T=new Map(b.map(k=>[k.branch,k.type]));p=await Xt([...ge({branches:i,descriptions:h,types:T}),...a.map(k=>({value:k,label:k,type:"feature"}))],{required:!0})}Z_(p,c);let m=p.length===c.length;m?y.addOption("--all",!0):rM(p),await Q_(u,p),await H(t,"Are you sure you want to proceed with these worktree changes?"),t||y.addOption("--yes",!0);let f=await _r({branches:p,worktreeDir:u,projectRoot:l,pruneFolder:m});return ms(f),y.print(),fs({result:f,operation:"remove worktrees"})}catch(i){throw Ie(i)||i instanceof g?i:(d.error({error:i},"\u274C Error managing worktrees"),new g(i,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"}))}},_p=C({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:Qe.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:Qe.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:Qe.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{removedWorktrees:Qe.array(Qe.string()).describe("List of removed git worktree branches"),failedWorktrees:Qe.array(Qe.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:Qe.number().describe("Number of git worktrees removed"),handedOff:Qe.object({branch:Qe.string(),worktreePath:Qe.string(),terminal:Qe.string()}).optional().describe("--self only: the worktree whose removal now runs in an Orca tab of the main checkout")},handler:nc});import{z as Us}from"zod";var oc=async e=>{let{confirmedCommand:t}=e;await je({operation:"sync worktrees"}),await J();try{let r=await Se("release"),n=await A(),o=`${n}${he}`,s=await Wi();await H(t,"Are you sure you want to proceed with these worktree changes?"),t||y.addOption("--yes",!0);let{branchesToRemove:i}=nM({releasePRsList:s,currentWorktrees:r}),a=await _r({branches:i,worktreeDir:o,projectRoot:n});return ms(a),y.print(),fs({result:a,operation:"sync worktrees"})}catch(r){throw Ie(r)||r instanceof g?r:(d.error({error:r},"\u274C Error managing worktrees"),new g(r,{operation:"sync worktrees with remote",remediation:"ensure 'gh auth status' is ok and you can reach origin"}))}},nM=e=>{let{releasePRsList:t,currentWorktrees:r}=e;return{branchesToRemove:r.filter(s=>Kr(s)).filter(s=>!t.includes(s))}},Mp=C({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:Us.array(Us.string()).describe("List of removed worktree branches"),failedWorktrees:Us.array(Us.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:Us.number().describe("Number of worktrees removed during sync")},handler:oc});var jp=[{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"}],Ar=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["dev"],longRunning:!0},{cliName:"dev-status",menuGroup:"develop",mcpTool:Kl,mcpExposed:!0,mutating:!1,groupPath:["dev-status"]},{cliName:"e2e",menuGroup:"develop",mcpTool:md,mcpExposed:!1,mutating:!0,groupPath:["e2e"]},{cliName:"merge-dev",menuGroup:"release",mcpTool:kd,mcpExposed:!0,mutating:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:Vd,mcpExposed:!0,mutating:!1,groupPath:["release","list"]},{cliName:"release-create",menuGroup:"release",mcpTool:ip,mcpExposed:!0,mutating:!0,groupPath:["release","create"]},{cliName:"release-edit",menuGroup:"release",mcpTool:cp,mcpExposed:!0,mutating:!0,groupPath:["release","edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:Ud,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:Gd,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:Ed,mcpExposed:!1,mutating:!0,humanOnly:!0,groupPath:["release","deliver"]},{cliName:"release-remove",menuGroup:"release",mcpTool:dp,mcpExposed:!0,mutating:!0,groupPath:["release","remove"]},{cliName:"local-deploy-all",menuGroup:null,mcpTool:tp,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-all"]},{cliName:"local-deploy-selected",menuGroup:null,mcpTool:rp,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-selected"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:Ip,mcpExposed:!0,mutating:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:Np,mcpExposed:!0,mutating:!1,groupPath:["worktrees","list"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:_p,mcpExposed:!0,mutating:!0,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:Mp,mcpExposed:!0,mutating:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:hd,mcpExposed:!0,mutating:!1,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:sg,mcpExposed:!0,mutating:!1,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:Hc,mcpExposed:!0,mutating:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:gd,mcpExposed:!0,mutating:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:yd,mcpExposed:!0,mutating:!1,groupPath:["env-token-list"]},{cliName:"config-get",menuGroup:"configuration",mcpTool:Vl,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:Cp,mcpExposed:!0,mutating:!1,groupPath:["vendor","check"]},{cliName:"vendor-config",menuGroup:"vendor",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["vendor","config"]},{cliName:"vendor-sync",menuGroup:"vendor",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["vendor","sync"]},{cliName:"deploy-run",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,humanOnly:!0,groupPath:["deploy-run"]},{cliName:"deploy-sync",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["deploy-sync"]},{cliName:"setup",menuGroup:"setup",mcpTool:wp,mcpExposed:!0,mutating:!0,groupPath:["setup"]},{cliName:"doctor",menuGroup:"setup",mcpTool:td,mcpExposed:!0,mutating:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:Il,mcpExposed:!0,mutating:!1,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:$p,mcpExposed:!0,mutating:!1,groupPath:["version"]},{cliName:"change-stats",menuGroup:null,mcpTool:Ul,mcpExposed:!1,mutating:!1,groupPath:["change-stats"]},{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 Fp=e=>Ar.filter(t=>t.menuGroup===e),Lp=e=>Ar.some(t=>t.longRunning===!0&&t.groupPath.join(" ")===e);var oM=(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},Jk=e=>jp.flatMap(({key:t,label:r})=>Fp(t).flatMap(n=>{let o=oM(e,n.groupPath);return o?[{name:n.groupPath.join(" "),description:o.description(),group:r}]:[]}));import Bp from"node:process";var sM="MODULE_TYPELESS_PACKAGE_JSON",iM=(e,t)=>typeof e=="object"&&e!==null?e.code:t,Kk=!1,Up=()=>{if(Kk)return;Kk=!0;let e=Bp.emitWarning.bind(Bp);Bp.emitWarning=((t,...r)=>{iM(r[0],r[1])!==sM&&e(t,...r)})};import{Command as vF,InvalidArgumentError as zb,Option as qb}from"commander";import{resolve as wF}from"node:path";import Be from"node:process";import{cd as kF}from"zx";import Hk from"node:process";import{$ as aM}from"zx";var Wp=async()=>{let e=await Y(),t=await Promise.all([{label:"project (committed)",path:e.main},{label:"user global",path:e.userGlobal},{label:"user project",path:e.userProject}].map(async i=>({...i,exists:await se(i.path)}))),r=t.at(-1)?.exists===!0,n=await Xo(e.userProject,r),o=r?Zo(n):"";d.info(`Project name: ${e.projectName}
444
453
  `),d.info(`Config merge chain (later overrides earlier):
445
- `);for(let i of t){let a=i.exists?" [\u2713]":" [ ]",c=i.path===e.userProject&&o!==""?` ${o}`:"";d.info(`${a} ${i.label.padEnd(22)} ${w(i.path)}${c}`)}let s={projectName:e.projectName,layers:t.map(i=>({label:i.label,path:i.path,exists:i.exists})),hasOverrides:n.hasOverrides,overrideKeys:n.overrideKeys};return{content:[{type:"text",text:JSON.stringify(s,null,2)}],structuredContent:s}},Mp=async()=>{let e=await ee(),t=Vk.env.EDITOR||Vk.env.VISUAL||"vi",r=await wn(e);r.createdConfig&&d.info(kn(r)),d.info(`Opening ${w(e.userProject)} in ${t} (per-machine override \u2014 every key except "mcp")`),await Z_({stdio:"inherit"})`${t} ${e.userProject}`,Lt();let n={path:e.userProject,editor:t};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}};var jp=async({key:e,global:t})=>{Ni(e,"config-unset");let r=t?"global":"project",{file:n,previous:o,changed:s}=await _i(r,e,a=>e in a?Object.fromEntries(Object.entries(a).filter(([c])=>c!==e)):null);d.info(s?`Removed ${e} from the ${Eo[r]} (${w(n)})`:`${e} is not set in the ${Eo[r]} (${w(n)}) \u2014 nothing to remove`);let i={key:e,removed:s,previous:o??null,scope:r,path:n};return{content:b(JSON.stringify(i,null,2)),structuredContent:i}};import Yk from"node:fs/promises";import Fs from"node:path";import pM from"node:process";import{pathToFileURL as mM}from"node:url";import{execFile as rM,spawn as nM}from"node:child_process";import ir from"node:fs/promises";import oM from"node:os";import sr from"node:path";import Jk from"node:process";import{promisify as sM}from"node:util";import Gk from"node:fs/promises";import Q_ from"node:path";import{pathToFileURL as eM}from"node:url";var tM=".infra-kit-import-from-app.mjs",Fp=async(e,t)=>{let r=Q_.join(e,tM);await Gk.writeFile(r,`export const resolveHere = (specifier) => import.meta.resolve(specifier)
446
- `);try{let{resolveHere:n}=await import(eM(r).href);return await import(n(t))}finally{await Gk.rm(r,{force:!0})}};var iM=sM(rM),Kk="3.39.0",aM=10*1024*1024,cM=960,lM=60,Lp=(e,t=500)=>e.length>t?`${e.slice(0,t)}\u2026`:e,uM=e=>{try{let{FunctionError:t}=JSON.parse(e);return t===void 0?void 0:`FunctionError=${t}`}catch{return`unparseable invoke metadata: ${Lp(e)}`}},Wn=class extends Error{constructor(t){super(t),this.name="DeploySkipped"}},dM=(e,t,r)=>new Promise((n,o)=>{let s=nM(e,t,{cwd:r.cwd,env:r.env,stdio:"inherit"});s.on("error",o),s.on("exit",(i,a)=>{i===0?n():o(new Error(`${e} exited with ${a??i}`))})}),rc={run:dM,capture:async(e,t,r)=>{let{stdout:n}=await iM(e,t,{...r,maxBuffer:aM});return n},sleep:e=>new Promise(t=>{setTimeout(t,e)}),random:Math.random,log:e=>{Jk.stdout.write(`${e}
447
- `)}},tc=e=>({AWS_RETRY_MODE:"adaptive",AWS_MAX_ATTEMPTS:"10",...e,AWS_PAGER:""}),Hk=async e=>{let t=JSON.parse(await ir.readFile(sr.join(e,"package.json"),"utf-8")),r=t.devDependencies?.turbo??t.dependencies?.turbo,n=r?.replace(/^[\^~=v]+/,"");if(n===void 0||!/^\d+\.\d+\.\d+/.test(n))throw new Error(`the root package.json must pin turbo to an exact version (found ${r??"none"})`);return n},Up=async e=>{let t=await ir.readdir(e,{withFileTypes:!0});await Promise.all(t.filter(r=>r.isDirectory()).map(r=>{let n=sr.join(e,r.name);return r.name==="node_modules"?ir.rm(n,{recursive:!0,force:!0}):Up(n)}))},Bp=async(e,t,r)=>{let n=r.appPath??t;if(n===void 0)throw new Error("pass app and appPath, or put the deploy script in the app it deploys");if(r.app!==void 0)return{app:r.app,appPath:n};try{let o=JSON.parse(await ir.readFile(sr.join(e,n,"package.json"),"utf-8"));if(o.name)return{app:o.name,appPath:n}}catch{}throw new Error(`${n} has no package.json name to deploy; pass app explicitly`)},Wp=({root:e,service:t,project:r,scriptDir:n,env:o=Jk.env,deps:s=rc})=>{let i=async(v,R,T,E={})=>{s.log(`COMMAND: ${[R,...T].join(" ")}`);try{await s.run(R,T,{cwd:E.cwd??e,env:E.env??o})}catch(B){throw new Error(`${v} failed: ${B.message}`)}},a=async(v,R,T={})=>{let{attempts:E=8,initialDelaySeconds:B=3,maxDelaySeconds:Z=60}=T,we=async re=>{try{return await R()}catch(bt){if(re>=E)throw new Error(`${v} failed after ${E} attempts: ${bt.message}`);let Vs=Math.min(Z,B*2**(re-1)),Gs=Math.round((Vs/2+s.random()*Vs/2)*10)/10;return s.log(`Attempt ${re}/${E} failed. Retrying in ${Gs}s...`),await s.sleep(Gs*1e3),we(re+1)}};return we(1)},c=async(v,R,T=o)=>{s.log(`COMMAND: aws ${R.join(" ")}`),await a(v,()=>s.run("aws",R,{cwd:e,env:tc(T)}))},l=async(v,R={})=>{await i(`aws ${v.slice(0,2).join(" ")}`,"aws",v,{cwd:R.cwd,env:tc(R.env??o)})},u=async v=>{let R=await Promise.all(v.map(async T=>{try{let E=await s.capture("aws",["ssm","get-parameter","--name",T,"--query","Parameter.Value","--output","text"],{cwd:e,env:tc(o)});return[T,E.trim()]}catch(E){throw new Error(`SSM parameter ${T}: ${E instanceof Error?E.message:String(E)}`)}}));return Object.fromEntries(R)},p=async v=>{let R=[`turbo@${await Hk(e)}`,...v?[`serverless@${Kk}`]:[]];await i("Install tools","pnpm",["add","-g",...R])},m=async(v,R)=>{let T=sr.join(e,"out"),E={...o,...R.buildEnv},B=R.buildTask??E.TURBO_BUILD_TASK??"build";return await ir.rm(T,{recursive:!0,force:!0}),await i(`Prune to ${v}`,"turbo",["prune",v],{env:E}),await i("Install dependencies","pnpm",["install"],{cwd:T,env:E}),await i(`Build ${v}`,"pnpm",["exec","turbo",B,`--filter=${v}`,"--env-mode=loose"],{cwd:T,env:E}),R.installProd&&(s.log("COMMAND: remove every node_modules under ./out"),await Up(T),await i("Install production dependencies","pnpm",["install","--frozen-lockfile","--node-linker=hoisted","--prod"],{cwd:T,env:E}),await i("Show node_modules size","du",["-sm","./node_modules/"],{cwd:T})),T},f=(v,R,T)=>({stage:v,outDir:R,appDir:T,importFromApp:E=>Fp(T,E)}),h=async(v,R,T)=>{if(R!==void 0){s.log(`Running ${v} hooks...`);try{await R(T)}catch(E){throw new Error(`${v} hooks failed: ${E.message}`)}s.log(`${v} hooks completed successfully`)}},S=async v=>{let{app:R,appPath:T}=await Bp(e,n,v);await p(!0);let E={...o,...v.buildEnv},B=await m(R,{installProd:!0,buildTask:v.buildTask,buildEnv:v.buildEnv}),Z=f(v.stage,B,sr.join(B,T));await h("Pre-deployment",v.preDeploy,Z),await i("Deploy with Serverless","serverless",["deploy","--stage",v.stage,"--force"],{cwd:Z.appDir,env:E}),v.restApiId===void 0?s.log(`Skipping API Gateway deployment for ${R}: no restApiId.`):await c("Create API Gateway deployment",["apigateway","create-deployment","--rest-api-id",v.restApiId,"--stage-name","api"],E),await h("Post-deployment",v.postDeploy,Z)},k=async v=>{let{app:R,appPath:T}=await Bp(e,n,v);await p(!1);let E={...o,...v.buildEnv},B=await m(R,{installProd:!1,buildTask:v.buildTask,buildEnv:v.buildEnv}),Z=f(v.stage,B,sr.join(B,T)),we=`s3://${v.bucket}${v.destPath??""}`,re=v.sourcePath??"./dist";await i("Sync to S3","aws",["s3","sync",re,we,...v.syncFlags??[],"--only-show-errors"],{cwd:Z.appDir,env:tc(E)}),await c("Invalidate CloudFront",["cloudfront","create-invalidation","--distribution-id",v.cloudfrontId,"--paths",v.invalidationPath??"/*"],E),await h("Post-deployment",v.postDeploy,Z)},A=async(v,R,T)=>{let E=await ir.mkdtemp(sr.join(oM.tmpdir(),"infra-kit-lambda-")),B=sr.join(E,"response.json"),Z=["lambda","invoke","--function-name",v.functionName,...T===void 0?[]:["--region",T],"--cli-binary-format","raw-in-base64-out","--payload",v.payload??R,"--cli-read-timeout",String(cM),"--cli-connect-timeout",String(lM),B],we=Date.now();s.log(`COMMAND: aws ${Z.join(" ")}`);try{let re=await s.capture("aws",Z,{cwd:e,env:{...o,AWS_PAGER:""}}).then(uM,Rc=>`aws CLI failed: ${Lp(Rc instanceof Error?Rc.message:String(Rc))}`),bt=await ir.readFile(B,"utf-8").catch(()=>""),Vs=((Date.now()-we)/1e3).toFixed(1),Gs=re!==void 0&&bt?`; response: ${Lp(bt)}`:"";return{outcome:`${v.functionName} (${Vs}s)`,failure:re===void 0?void 0:re+Gs}}finally{await ir.rm(E,{recursive:!0,force:!0})}};return{root:e,service:t,project:r,ssm:u,aws:l,run:(v,R,T={})=>s.run(v,R,{cwd:T.cwd??e,env:T.env??o}),capture:(v,R,T={})=>s.capture(v,R,{cwd:T.cwd??e,env:T.env??o}),retry:a,skip:v=>{throw new Wn(v)},pruneAndBuild:m,deployBackendApi:S,deployFrontendUi:k,invokeLambdas:async v=>{let{region:R,payload:T="{}",blocking:E=[],steps:B=[]}=v;for(let Z of E){let{outcome:we,failure:re}=await A(Z,T,R);if(re!==void 0)throw new Error(`Lambda ${we} failed: ${re}`);s.log(`Lambda ${we} OK`)}for(let Z of B){let we=await Promise.all(Z.map(re=>A(re,T,R).catch(bt=>({outcome:re.functionName,failure:String(bt)}))));for(let{outcome:re,failure:bt}of we)s.log(bt===void 0?`Lambda ${re} OK`:`Warning: Lambda ${re} failed, continuing: ${bt}`)}},importFromApp:Fp}};var qk=e=>({content:b(JSON.stringify(e,null,2)),structuredContent:e}),fM=async(e,t)=>{let r=Fs.join(e,"devops","scripts",`deploy-${t}.sh`);try{await Yk.access(r)}catch{throw new g(void 0,{operation:`deploy ${t}`,remediation:`set services['${t}'].deploy in infra-kit.deploy.ts, e.g. 'apps/<app>/deploy.ts'`,stderrExcerpt:`${t} has no deploy in infra-kit.deploy.ts and no devops/scripts/deploy-${t}.sh`})}return r},gM=e=>`::add-mask::${e.replaceAll("%","%25").replaceAll("\r","%0D").replaceAll(`
448
- `,"%0A")}`,hM=(e,t)=>{let r=(e??"").split(`
449
- `).filter(n=>n.trim()!=="").map(n=>{let o=n.indexOf("="),s=n.slice(0,Math.max(o,0));if(!/^[A-Z_][A-Z0-9_]*$/.test(s))throw new g(void 0,{operation:"deploy-run",remediation:"write each extra-env line as KEY=VALUE with an upper-case KEY",stderrExcerpt:"an extra-env line is not KEY=VALUE"});return[s,n.slice(o+1)]});for(let[,n]of r)n!==""&&t(gM(n));return Object.fromEntries(r)},yM=async e=>{try{await Yk.access(e)}catch{throw new g(void 0,{operation:`run ${Fs.basename(e)}`,remediation:"create it, or fix the deploy path in infra-kit.deploy.ts",stderrExcerpt:`${e} does not exist`})}let t=await import(mM(e).href);if(typeof t.default!="function")throw new g(void 0,{operation:`run ${Fs.basename(e)}`,remediation:"export the deploy as `export default (async (toolkit) => { \u2026 }) satisfies DeployScript`",stderrExcerpt:"the script has no default-exported function"});return t.default},Vp=async e=>{let{service:t,env:r=pM.env}=e;if(!/^[a-z0-9-]+$/.test(t))throw new g(void 0,{operation:"deploy-run",remediation:"pass the service as infra-kit.deploy.ts names it, e.g. client-be",stderrExcerpt:`invalid service name '${t}'`});if(he()&&r.INFRA_KIT_DEPLOY_VIA!==Rs)throw new O({status:"refused",agentMode:j.source},2,{operation:`deploy ${t}`,remediation:"ask a human to run `infra-kit deploy-run` from their own shell, or deploy through `infra-kit release deploy-selected` (CI) or `infra-kit local deploy-selected`, which check the environment first",stderrExcerpt:"deploy-run deploys with whatever AWS credentials are loaded: refused in agent mode"});let n=e.cwd??await $(),o=e.deps??rc,{INFRA_KIT_EXTRA_ENV:s,...i}=r,a={...i,...hM(s,o.log)},c=await vt(n),l=c?.services[t]?.deploy;if(l===void 0)await o.run("sh",[await fM(n,t)],{cwd:n,env:a});else{let u=await yM(Fs.join(n,l)),p=Wp({root:n,service:t,project:c?.project,scriptDir:Fs.dirname(l),env:a,deps:o});try{await u(p)}catch(m){if(!(m instanceof Wn))throw m;return d.info(`\u23ED\uFE0F ${t} skipped: ${m.message}`),qk({status:"skipped",service:t,reason:m.message})}}return d.info(`\u2705 ${t} deployed`),qk({status:"deployed",service:t})};import{DEPLOY_CONFIG_FILE as Ls}from"@slip-stream-kit/config/internal";import oc from"node:fs/promises";import sc from"node:path";var Gp=async e=>{try{return await oc.readFile(e,"utf-8")}catch{return}},nc=e=>({content:b(JSON.stringify(e,null,2)),structuredContent:e}),vM={created:"missing",updated:"differs",unchanged:"matches",removed:"no longer generated"},zk=async(e,t)=>(await Promise.all(t.map(async n=>{let o=sc.join(e,n);return(await Gp(o))?.startsWith(Fn)?[{path:n,absolute:o}]:[]}))).flat(),wM=async(e,t)=>t.replaceV1!==!0?[]:(await zk(e,vd)).map(r=>({...r,status:"removed"})),kM=async(e,t)=>{let n=(await Promise.all(Object.entries(t.services).map(async([o,s])=>s.deploy===void 0?[]:await Gp(sc.join(e,s.deploy))===void 0?[`${o}: ${s.deploy}`]:[]))).flat();if(n.length>0)throw new Error(`Deploy scripts named in ${Ls} do not exist: ${n.join(", ")}`)},bM=async(e,t)=>{if(t.replaceV1===!0)return;let r=await zk(e,wd);if(r.length===0)return;let n=r.map(o=>o.path).join(", ");throw new Error(`${n} ${r.length===1?"was":"were"} generated under replaceV1, which ${Ls} no longer sets. Restore the hand-written v1 workflows from git history (or set replaceV1 again) before syncing.`)},Jp=async(e={})=>{let t=e.cwd??await $(),r=await vt(t);if(r===void 0)return(e.check?d.info.bind(d):d.error.bind(d))(`No ${Ls} at ${t}, nothing to generate.`),nc({status:"missing-config",ok:!!e.check,files:[]});await bM(t,r),await kM(t,r);let n=await Promise.all(Ed(r).map(async a=>{let c=sc.join(t,a.path),l=await Gp(c),u="unchanged";return l===void 0?u="created":l!==a.content&&(u="updated"),{...a,absolute:c,status:u}})),o=await wM(t,r),s=[...n.filter(a=>a.status!=="unchanged"),...o],i=[...n,...o].map(({path:a,status:c})=>({path:a,status:c}));if(s.length===0)return d.info(`\u2705 Deploy workflows match ${Ls}.`),nc({status:"unchanged",ok:!0,files:i});if(e.check){d.error(`\u274C Deploy workflows differ from ${Ls}; run \`infra-kit deploy-sync\` and commit:`);for(let a of s)d.error(` ${a.path} (${vM[a.status]})`);return nc({status:"drift",ok:!1,files:i})}for(let a of s){if(a.status==="removed"){await oc.rm(a.absolute),d.info(`\u{1F5D1}\uFE0F Removed ${a.path}`);continue}await oc.mkdir(sc.dirname(a.absolute),{recursive:!0}),await oc.writeFile(a.absolute,a.content),d.info(`\u270F\uFE0F ${a.status==="created"?"Created":"Updated"} ${a.path}`)}return nc({status:"written",ok:!0,files:i})};var Xk="https://dashboard.doppler.com/workplace/projects",RM=(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}"): ${Xk}/${e}`],Kp=async({env:e})=>{let r=!!(await Qe())?.envs[e];await If(e);let n=await dr(),o=await Ut();r?d.info(`Removed the "${e}" service token from ${w(o)}.`):d.info(`No "${e}" service token was stored in ${w(o)} \u2014 nothing to remove.`);for(let i of RM(n,e))d.warn(i);let s={env:e,removed:r,storePath:o,revokeUrl:`${Xk}/${n}`};return{content:b(JSON.stringify(s,null,2)),structuredContent:s}};import SM from"@inquirer/confirm";import EM from"@inquirer/input";import PM from"@inquirer/password";import xM from"@inquirer/select";import TM from"node:fs/promises";import kt from"node:process";import{$ as ic}from"zx";var CM=async({stdin:e,fromEnv:t})=>{if(e)return{token:await Zk(),source:"stdin"};if(t){let n=kt.env[t];if(!n)throw new Error(`${t} is not set (or is empty) \u2014 nothing to store.`);return{token:n,source:"env"}}if(!kt.stdin.isTTY){let n=await Zk();if(n)return{token:n,source:"stdin"};if(!X())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 y.setInteractive(),{token:(await _(n=>PM({message:"Paste the Doppler service token (input is hidden)",mask:!0},n),{output:kt.stderr,whenHeadless:{refuse:"stdin"}})).trim(),source:"prompt"}},Zk=async()=>{let e=[];kt.stdin.setEncoding("utf8");for await(let t of kt.stdin)e.push(t);return e.join("").trim()},Hp="DOPPLER_CONFIG",$M=3e4,AM=async(e,t,r)=>{let n=ic.quiet;ic.quiet=!0;let o;try{o=(await ic({env:so(e)})`doppler secrets download --no-file --format json --project ${t} --config ${r}`.timeout($M)).stdout}catch(s){throw OM(s,r)}finally{ic.quiet=n}return Wc(o)},OM=(e,t)=>{let r=rf(e)??(e instanceof Error?e.message:String(e));if(_f(r)!=="auth")return e instanceof Error?e:new Error(String(e));let n=Mf(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(`
450
- `))},DM=e=>[`Could not verify this token's scope: the Doppler payload for "${e}" carries no ${Hp}.`,"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(`
451
- `),eb=async(e,t,r,n)=>{let o=await AM(e,t,r);Uc(o,r);let s=o.some(([i])=>i===Hp);if(!s&&!n)throw new Error(DM(r));return s},Qk="\0new-env",IM=async()=>{if(X()||!kt.stdin.isTTY)throw new O({status:"argument_required",argument:"env",agentMode:j.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([Yf(),Qe()]),r=Math.max(0,...e.map(({env:s})=>s.length));y.setInteractive();let n=await _(s=>xM({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:Qk}]},s),{output:kt.stderr,whenHeadless:"refuse"});return n!==Qk?n:(await _(s=>EM({message:"Doppler config name",validate:i=>/^\S+$/.test(i.trim())||"Enter a config name without spaces"},s),{output:kt.stderr,whenHeadless:"refuse"})).trim()},NM=async(e,t,r)=>_(n=>SM({message:`Replace the "${e}" token ${$e(t)} with ${$e(r)}?`,default:!0},n),{output:kt.stderr,whenHeadless:"refuse"}),_M=(e,t,r,n)=>{switch(t){case"stored":return`Stored the "${e}" service token (${$e(r)})`;case"replaced":return`Replaced the "${e}" service token ${$e(n??"")} \u2192 ${$e(r)}`;case"unchanged":return`The "${e}" service token is already ${$e(r)} \u2014 nothing to write`;case"kept":return`Kept the existing "${e}" service token ${$e(n??"")} \u2014 nothing was written`;default:return We(t)}},qp=async({env:e,stdin:t,fromEnv:r,force:n})=>{let o=await dr(),s=e??await IM(),{token:i,source:a}=await CM({stdin:t,fromEnv:r});if(!i)throw new Error("No token provided \u2014 nothing was written.");let c=await eb(i,o,s,n),l=(await Qe())?.envs[s],u;l===i?u="unchanged":l!==void 0&&a==="prompt"&&!await NM(s,l,i)?u="kept":(await Ic({[s]:i}),u=l===void 0?"stored":"replaced");let p=await Ut();d.info(`${_M(s,u,i,l)} in ${w(p)} (mode 0600).`),c||d.warn(`Scope was NOT verified (no ${Hp} in the payload) \u2014 accepted because --force was given.`);let m={env:s,status:u,source:a,redactedToken:$e(i),previousRedactedToken:l===void 0?null:$e(l),storePath:p,scopeVerified:c};return y.print(),{content:b(JSON.stringify(m,null,2)),structuredContent:m}},MM=e=>/^(["']).*\1$/.test(e)?e.slice(1,-1):e,tb=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?MM(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},jM=e=>(e instanceof Error?e.message:String(e)).split(`
452
- `)[0]??"",FM=(e,t)=>e===void 0?"stored":e===t?"unchanged":"replaced",LM=async(e,t,r,n)=>{let o=$e(e.token);try{let s=await eb(e.token,t,e.env,n);return{env:e.env,status:FM(r,e.token),redactedToken:o,scopeVerified:s}}catch(s){return{env:e.env,status:"failed",redactedToken:o,scopeVerified:!1,error:jM(s)}}},Yp=async({fromFile:e,force:t})=>{let r=await dr(),n=tb(await TM.readFile(e,"utf8")),o=await Qe(),s=await Promise.all(n.map(p=>LM(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 Ic(i);let a=await Ut(),c=Math.max(...s.map(({env:p})=>p.length));d.info(`Token import from ${w(e)} \u2192 ${w(a)}:`);for(let p of s){let m=p.error?` ${p.error}`:"";d.info(` ${p.env.padEnd(c)} ${p.status.padEnd(9)} ${p.redactedToken}${m}`)}d.warn(`${w(e)} still holds live tokens in plain text \u2014 delete it.`);let l=s.filter(p=>p.status==="failed").length;l>0&&(kt.exitCode=1);let u={storePath:a,rows:s,failedCount:l};return{content:b(JSON.stringify(u,null,2)),structuredContent:u}};var zp=async(e,t,r=!0)=>{let{from:n,version:o,env:s,services:i,skipTerraform:a,yes:c,dryRun:l,printEnv:u}=e,p=await Dd(n);if(r&&y.addOption("--from",p),Od(p,{"--version":o,"--skip-terraform":a,"--dry-run":l,"--print-env":u}),p==="local")throw new g(void 0,{operation:"deploy --from local",remediation:"use --from ci to dispatch the release workflow",stderrExcerpt:"local deploys are disabled for now \u2014 deploys run in CI only"});return t==="all"?$a({version:o,env:s,skipTerraform:a,confirmedCommand:c}):Aa({version:o,env:s,services:i,skipTerraform:a,confirmedCommand:c})},Xp=async e=>zp(e,"all"),Zp=async e=>zp(e,"selected"),ac=async(e,t)=>{let r=`release deploy-${t} --from local`;return d.warn(`\`local deploy-${t}\` is deprecated and will be removed \u2014 use \`${r}\` instead.`),zp({...e,from:"local"},t,!1)};import{VENDOR_CONFIG_FILE as nb}from"@slip-stream-kit/config/internal";import Qp from"node:fs/promises";import Vn from"node:path";import rb from"node:process";import{pathToFileURL as BM}from"node:url";var ob="~/projects",em=async(e={})=>{if(e.init){await WM(e.cwd);return}await UM()},UM=async()=>{let e=Pn(),t=await oe(e);if(d.info(`Factory config: ${w(e)} ${t?"[\u2713]":"[ ]"}`),!t){d.info("\nNot found \u2014 run `infra-kit vendor config --init` to scaffold it."),rb.exitCode=1;return}let{workspaceDir:r,source:n,targets:o}=await ta(),s=xn(r),i=await oe(s),a=Vn.join(s,n),c=await oe(a);d.info(`workspaceDir: ${r} (resolved: ${s}) ${i?"[\u2713 exists]":"[ ] not found"}`),d.info(`Source: ${c?"[\u2713]":"[ ]"} ${n} ${w(a)}${c?"":" (not found \u2014 clone it)"}`),d.info("Targets:");let l=i&&c;for(let u of o){let p=Vn.join(s,u),m=await oe(p);m||(l=!1);let f=m?"[\u2713]":"[ ]",h=m?"":" (not found \u2014 clone or remove)";d.info(` ${f} ${u} ${w(p)}${h}`)}l||(rb.exitCode=1)},WM=async e=>{let t=Pn();if(await oe(t)){d.info(`Factory config already exists at ${w(t)} \u2014 leaving it untouched.`);return}let r=e??await $(),n=await VM(r);await Qp.mkdir(Vn.dirname(t),{recursive:!0}),await Qp.writeFile(t,GM(Vn.basename(r),n),"utf-8"),d.info(`\u2713 Created ${w(t)}`),n.length>0&&d.info(` Seeded ${n.length} target(s) from the source ${nb}.`),d.info(` Edit \`workspaceDir\` (placeholder: ${ob}) to point at where your repos live.`),d.info(` \`source\` is seeded with ${Vn.basename(r)} (this repo); change it if the source is another repo.`),n.length===0&&d.info(" Add at least one repo name to `targets` before running vendor sync/manifest/diff.")},VM=async e=>{try{let t=Vn.join(e,nb),r=await Qp.stat(t),s=(await import(`${BM(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[]},GM=(e,t)=>`${JSON.stringify({workspaceDir:ob,source:e,targets:t},null,2)}
453
- `;import{existsSync as Zj}from"node:fs";import Qj from"node:fs/promises";import Db from"node:path";import Ib from"node:process";import{z as eF}from"zod";import{chmodSync as ZM,copyFileSync as QM,lstatSync as ej,mkdirSync as fb,readdirSync as tj,readlinkSync as rj,rmSync as nj,rmdirSync as gb,symlinkSync as oj,unlinkSync as sj,writeFileSync as ij}from"node:fs";import Pe from"node:path";import{lstatSync as JM,readlinkSync as sb}from"node:fs";import KM from"node:path";var HM=new Set(["ENOENT","ENOTDIR"]),cc=e=>{let t;try{t=JM(e)}catch(r){if(HM.has(r.code??""))return null;throw r}return t.isSymbolicLink()?{kind:"link",text:sb(e)}:t.isFile()?{kind:"file",executable:(t.mode&64)!==0,sha:_r(e)}:{kind:"other"}},ib=(e,t)=>{let r=KM.join(e,t.path),n=t.mode==="120000"?{kind:"link",text:sb(r)}:{kind:"file",executable:t.mode==="100755",sha:_r(r)};return{...t,fingerprint:n}},ab=(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 qM}from"zx";var z=async(e,t,r={})=>{let{input:n,allowFailure:o=!1}=r,s=await qM({cwd:e,quiet:!0,input:n,nothrow:o})`git ${t}`;return s.exitCode===0?s.stdout:""},lc=e=>e.slice(0,7),nt=e=>e.split("\0").filter(t=>t.length>0);import YM from"node:path";var tm=`${se}/`,ar=`${se}/README.md`,Bs=`${se}/${ze}`,lb=e=>e.startsWith(tm),cb=e=>{let t=YM.posix.normalize(e);return t.endsWith("/")?t.slice(0,-1):t},ub=e=>{let t=cb(e.path),r=e.target===void 0?t:cb(e.target);return{path:t,target:r,vendored:lb(r),module:e.module??null}},db=e=>e.copy.map(ub),Us=(e,t)=>t.length===0?!1:e.split("/").some(r=>t.includes(r)),Ws=(e,t)=>e.filter(r=>!Us(r.path,t)),uc=(e,t)=>e===t.path?t.target:`${t.target}${e.slice(t.path.length)}`,Gn=e=>[...new Set(e)].sort(),pb=e=>e.startsWith(tm)?e.slice(tm.length):null;var dc=e=>`# vendor/ \u2014 mirrored from ${e}
454
+ `);for(let i of t){let a=i.exists?" [\u2713]":" [ ]",c=i.path===e.userProject&&o!==""?` ${o}`:"";d.info(`${a} ${i.label.padEnd(22)} ${w(i.path)}${c}`)}let s={projectName:e.projectName,layers:t.map(i=>({label:i.label,path:i.path,exists:i.exists})),hasOverrides:n.hasOverrides,overrideKeys:n.overrideKeys};return{content:[{type:"text",text:JSON.stringify(s,null,2)}],structuredContent:s}},Gp=async()=>{let e=await Y(),t=Hk.env.EDITOR||Hk.env.VISUAL||"vi",r=await En(e);r.createdConfig&&d.info(Pn(r)),d.info(`Opening ${w(e.userProject)} in ${t} (per-machine override \u2014 every key except "mcp")`),await aM({stdio:"inherit"})`${t} ${e.userProject}`,Ut();let n={path:e.userProject,editor:t};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}};var Vp=async({key:e,global:t})=>{Fi(e,"config-unset");let r=t?"global":"project",{file:n,previous:o,changed:s}=await Li(r,e,a=>e in a?Object.fromEntries(Object.entries(a).filter(([c])=>c!==e)):null);d.info(s?`Removed ${e} from the ${Ao[r]} (${w(n)})`:`${e} is not set in the ${Ao[r]} (${w(n)}) \u2014 nothing to remove`);let i={key:e,removed:s,previous:o??null,scope:r,path:n};return{content:R(JSON.stringify(i,null,2)),structuredContent:i}};import Qk from"node:fs/promises";import Ws from"node:path";import bM from"node:process";import{pathToFileURL as RM}from"node:url";import{execFile as dM,spawn as pM}from"node:child_process";import cr from"node:fs/promises";import mM from"node:os";import ar from"node:path";import Yk from"node:process";import{promisify as fM}from"node:util";import qk from"node:fs/promises";import cM from"node:path";import{pathToFileURL as lM}from"node:url";var uM=".infra-kit-import-from-app.mjs",Jp=async(e,t)=>{let r=cM.join(e,uM);await qk.writeFile(r,`export const resolveHere = (specifier) => import.meta.resolve(specifier)
455
+ `);try{let{resolveHere:n}=await import(lM(r).href);return await import(n(t))}finally{await qk.rm(r,{force:!0})}};var gM=fM(dM),zk="3.39.0",hM=10*1024*1024,yM=960,vM=60,Kp=(e,t=500)=>e.length>t?`${e.slice(0,t)}\u2026`:e,wM=e=>{try{let{FunctionError:t}=JSON.parse(e);return t===void 0?void 0:`FunctionError=${t}`}catch{return`unparseable invoke metadata: ${Kp(e)}`}},qn=class extends Error{constructor(t){super(t),this.name="DeploySkipped"}},kM=(e,t,r)=>new Promise((n,o)=>{let s=pM(e,t,{cwd:r.cwd,env:r.env,stdio:"inherit"});s.on("error",o),s.on("exit",(i,a)=>{i===0?n():o(new Error(`${e} exited with ${a??i}`))})}),ic={run:kM,capture:async(e,t,r)=>{let{stdout:n}=await gM(e,t,{...r,maxBuffer:hM});return n},sleep:e=>new Promise(t=>{setTimeout(t,e)}),random:Math.random,log:e=>{Yk.stdout.write(`${e}
456
+ `)}},sc=e=>({AWS_RETRY_MODE:"adaptive",AWS_MAX_ATTEMPTS:"10",...e,AWS_PAGER:""}),Xk=async e=>{let t=JSON.parse(await cr.readFile(ar.join(e,"package.json"),"utf-8")),r=t.devDependencies?.turbo??t.dependencies?.turbo,n=r?.replace(/^[\^~=v]+/,"");if(n===void 0||!/^\d+\.\d+\.\d+/.test(n))throw new Error(`the root package.json must pin turbo to an exact version (found ${r??"none"})`);return n},qp=async e=>{let t=await cr.readdir(e,{withFileTypes:!0});await Promise.all(t.filter(r=>r.isDirectory()).map(r=>{let n=ar.join(e,r.name);return r.name==="node_modules"?cr.rm(n,{recursive:!0,force:!0}):qp(n)}))},Hp=async(e,t,r)=>{let n=r.appPath??t;if(n===void 0)throw new Error("pass app and appPath, or put the deploy script in the app it deploys");if(r.app!==void 0)return{app:r.app,appPath:n};try{let o=JSON.parse(await cr.readFile(ar.join(e,n,"package.json"),"utf-8"));if(o.name)return{app:o.name,appPath:n}}catch{}throw new Error(`${n} has no package.json name to deploy; pass app explicitly`)},Yp=({root:e,service:t,project:r,scriptDir:n,env:o=Yk.env,deps:s=ic})=>{let i=async(v,S,P,$={})=>{s.log(`COMMAND: ${[S,...P].join(" ")}`);try{await s.run(S,P,{cwd:$.cwd??e,env:$.env??o})}catch(O){throw new Error(`${v} failed: ${O.message}`)}},a=async(v,S,P={})=>{let{attempts:$=8,initialDelaySeconds:O=3,maxDelaySeconds:B=60}=P,be=async ne=>{try{return await S()}catch(St){if(ne>=$)throw new Error(`${v} failed after ${$} attempts: ${St.message}`);let Hs=Math.min(B,O*2**(ne-1)),qs=Math.round((Hs/2+s.random()*Hs/2)*10)/10;return s.log(`Attempt ${ne}/${$} failed. Retrying in ${qs}s...`),await s.sleep(qs*1e3),be(ne+1)}};return be(1)},c=async(v,S,P=o)=>{s.log(`COMMAND: aws ${S.join(" ")}`),await a(v,()=>s.run("aws",S,{cwd:e,env:sc(P)}))},l=async(v,S={})=>{await i(`aws ${v.slice(0,2).join(" ")}`,"aws",v,{cwd:S.cwd,env:sc(S.env??o)})},u=async v=>{let S=await Promise.all(v.map(async P=>{try{let $=await s.capture("aws",["ssm","get-parameter","--name",P,"--query","Parameter.Value","--output","text"],{cwd:e,env:sc(o)});return[P,$.trim()]}catch($){throw new Error(`SSM parameter ${P}: ${$ instanceof Error?$.message:String($)}`)}}));return Object.fromEntries(S)},p=async v=>{let S=[`turbo@${await Xk(e)}`,...v?[`serverless@${zk}`]:[]];await i("Install tools","pnpm",["add","-g",...S])},m=async(v,S)=>{let P=ar.join(e,"out"),$={...o,...S.buildEnv},O=S.buildTask??$.TURBO_BUILD_TASK??"build";return await cr.rm(P,{recursive:!0,force:!0}),await i(`Prune to ${v}`,"turbo",["prune",v],{env:$}),await i("Install dependencies","pnpm",["install"],{cwd:P,env:$}),await i(`Build ${v}`,"pnpm",["exec","turbo",O,`--filter=${v}`,"--env-mode=loose"],{cwd:P,env:$}),S.installProd&&(s.log("COMMAND: remove every node_modules under ./out"),await qp(P),await i("Install production dependencies","pnpm",["install","--frozen-lockfile","--node-linker=hoisted","--prod"],{cwd:P,env:$}),await i("Show node_modules size","du",["-sm","./node_modules/"],{cwd:P})),P},f=(v,S,P)=>({stage:v,outDir:S,appDir:P,importFromApp:$=>Jp(P,$)}),h=async(v,S,P)=>{if(S!==void 0){s.log(`Running ${v} hooks...`);try{await S(P)}catch($){throw new Error(`${v} hooks failed: ${$.message}`)}s.log(`${v} hooks completed successfully`)}},b=async v=>{let{app:S,appPath:P}=await Hp(e,n,v);await p(!0);let $={...o,...v.buildEnv},O=await m(S,{installProd:!0,buildTask:v.buildTask,buildEnv:v.buildEnv}),B=f(v.stage,O,ar.join(O,P));await h("Pre-deployment",v.preDeploy,B),await i("Deploy with Serverless","serverless",["deploy","--stage",v.stage,"--force"],{cwd:B.appDir,env:$}),v.restApiId===void 0?s.log(`Skipping API Gateway deployment for ${S}: no restApiId.`):await c("Create API Gateway deployment",["apigateway","create-deployment","--rest-api-id",v.restApiId,"--stage-name","api"],$),await h("Post-deployment",v.postDeploy,B)},T=async v=>{let{app:S,appPath:P}=await Hp(e,n,v);await p(!1);let $={...o,...v.buildEnv},O=await m(S,{installProd:!1,buildTask:v.buildTask,buildEnv:v.buildEnv}),B=f(v.stage,O,ar.join(O,P)),be=`s3://${v.bucket}${v.destPath??""}`,ne=v.sourcePath??"./dist";await i("Sync to S3","aws",["s3","sync",ne,be,...v.syncFlags??[],"--only-show-errors"],{cwd:B.appDir,env:sc($)}),await c("Invalidate CloudFront",["cloudfront","create-invalidation","--distribution-id",v.cloudfrontId,"--paths",v.invalidationPath??"/*"],$),await h("Post-deployment",v.postDeploy,B)},k=async(v,S,P)=>{let $=await cr.mkdtemp(ar.join(mM.tmpdir(),"infra-kit-lambda-")),O=ar.join($,"response.json"),B=["lambda","invoke","--function-name",v.functionName,...P===void 0?[]:["--region",P],"--cli-binary-format","raw-in-base64-out","--payload",v.payload??S,"--cli-read-timeout",String(yM),"--cli-connect-timeout",String(vM),O],be=Date.now();s.log(`COMMAND: aws ${B.join(" ")}`);try{let ne=await s.capture("aws",B,{cwd:e,env:{...o,AWS_PAGER:""}}).then(wM,xc=>`aws CLI failed: ${Kp(xc instanceof Error?xc.message:String(xc))}`),St=await cr.readFile(O,"utf-8").catch(()=>""),Hs=((Date.now()-be)/1e3).toFixed(1),qs=ne!==void 0&&St?`; response: ${Kp(St)}`:"";return{outcome:`${v.functionName} (${Hs}s)`,failure:ne===void 0?void 0:ne+qs}}finally{await cr.rm($,{recursive:!0,force:!0})}};return{root:e,service:t,project:r,ssm:u,aws:l,run:(v,S,P={})=>s.run(v,S,{cwd:P.cwd??e,env:P.env??o}),capture:(v,S,P={})=>s.capture(v,S,{cwd:P.cwd??e,env:P.env??o}),retry:a,skip:v=>{throw new qn(v)},pruneAndBuild:m,deployBackendApi:b,deployFrontendUi:T,invokeLambdas:async v=>{let{region:S,payload:P="{}",blocking:$=[],steps:O=[]}=v;for(let B of $){let{outcome:be,failure:ne}=await k(B,P,S);if(ne!==void 0)throw new Error(`Lambda ${be} failed: ${ne}`);s.log(`Lambda ${be} OK`)}for(let B of O){let be=await Promise.all(B.map(ne=>k(ne,P,S).catch(St=>({outcome:ne.functionName,failure:String(St)}))));for(let{outcome:ne,failure:St}of be)s.log(St===void 0?`Lambda ${ne} OK`:`Warning: Lambda ${ne} failed, continuing: ${St}`)}},importFromApp:Jp}};var Zk=e=>({content:R(JSON.stringify(e,null,2)),structuredContent:e}),SM=async(e,t)=>{let r=Ws.join(e,"devops","scripts",`deploy-${t}.sh`);try{await Qk.access(r)}catch{throw new g(void 0,{operation:`deploy ${t}`,remediation:`set services['${t}'].deploy in infra-kit.deploy.ts, e.g. 'apps/<app>/deploy.ts'`,stderrExcerpt:`${t} has no deploy in infra-kit.deploy.ts and no devops/scripts/deploy-${t}.sh`})}return r},EM=e=>`::add-mask::${e.replaceAll("%","%25").replaceAll("\r","%0D").replaceAll(`
457
+ `,"%0A")}`,PM=(e,t)=>{let r=(e??"").split(`
458
+ `).filter(n=>n.trim()!=="").map(n=>{let o=n.indexOf("="),s=n.slice(0,Math.max(o,0));if(!/^[A-Z_][A-Z0-9_]*$/.test(s))throw new g(void 0,{operation:"deploy-run",remediation:"write each extra-env line as KEY=VALUE with an upper-case KEY",stderrExcerpt:"an extra-env line is not KEY=VALUE"});return[s,n.slice(o+1)]});for(let[,n]of r)n!==""&&t(EM(n));return Object.fromEntries(r)},xM=async e=>{try{await Qk.access(e)}catch{throw new g(void 0,{operation:`run ${Ws.basename(e)}`,remediation:"create it, or fix the deploy path in infra-kit.deploy.ts",stderrExcerpt:`${e} does not exist`})}let t=await import(RM(e).href);if(typeof t.default!="function")throw new g(void 0,{operation:`run ${Ws.basename(e)}`,remediation:"export the deploy as `export default (async (toolkit) => { \u2026 }) satisfies DeployScript`",stderrExcerpt:"the script has no default-exported function"});return t.default},zp=async e=>{let{service:t,env:r=bM.env}=e;if(!/^[a-z0-9-]+$/.test(t))throw new g(void 0,{operation:"deploy-run",remediation:"pass the service as infra-kit.deploy.ts names it, e.g. client-be",stderrExcerpt:`invalid service name '${t}'`});if(ye()&&r.INFRA_KIT_DEPLOY_VIA!==Ts)throw new D({status:"refused",agentMode:F.source},2,{operation:`deploy ${t}`,remediation:"ask a human to run `infra-kit deploy-run` from their own shell, or deploy through `infra-kit release deploy-selected` (CI) or `infra-kit local deploy-selected`, which check the environment first",stderrExcerpt:"deploy-run deploys with whatever AWS credentials are loaded: refused in agent mode"});let n=e.cwd??await A(),o=e.deps??ic,{INFRA_KIT_EXTRA_ENV:s,...i}=r,a={...i,...PM(s,o.log)},c=await kt(n),l=c?.services[t]?.deploy;if(l===void 0)await o.run("sh",[await SM(n,t)],{cwd:n,env:a});else{let u=await xM(Ws.join(n,l)),p=Yp({root:n,service:t,project:c?.project,scriptDir:Ws.dirname(l),env:a,deps:o});try{await u(p)}catch(m){if(!(m instanceof qn))throw m;return d.info(`\u23ED\uFE0F ${t} skipped: ${m.message}`),Zk({status:"skipped",service:t,reason:m.message})}}return d.info(`\u2705 ${t} deployed`),Zk({status:"deployed",service:t})};import{DEPLOY_CONFIG_FILE as Gs}from"@slip-stream-kit/config/internal";import cc from"node:fs/promises";import lc from"node:path";var Xp=async e=>{try{return await cc.readFile(e,"utf-8")}catch{return}},ac=e=>({content:R(JSON.stringify(e,null,2)),structuredContent:e}),TM={created:"missing",updated:"differs",unchanged:"matches",removed:"no longer generated"},eb=async(e,t)=>(await Promise.all(t.map(async n=>{let o=lc.join(e,n);return(await Xp(o))?.startsWith(Gn)?[{path:n,absolute:o}]:[]}))).flat(),CM=async(e,t)=>t.replaceV1!==!0?[]:(await eb(e,Pd)).map(r=>({...r,status:"removed"})),$M=async(e,t)=>{let n=(await Promise.all(Object.entries(t.services).map(async([o,s])=>s.deploy===void 0?[]:await Xp(lc.join(e,s.deploy))===void 0?[`${o}: ${s.deploy}`]:[]))).flat();if(n.length>0)throw new Error(`Deploy scripts named in ${Gs} do not exist: ${n.join(", ")}`)},AM=async(e,t)=>{if(t.replaceV1===!0)return;let r=await eb(e,xd);if(r.length===0)return;let n=r.map(o=>o.path).join(", ");throw new Error(`${n} ${r.length===1?"was":"were"} generated under replaceV1, which ${Gs} no longer sets. Restore the hand-written v1 workflows from git history (or set replaceV1 again) before syncing.`)},Zp=async(e={})=>{let t=e.cwd??await A(),r=await kt(t);if(r===void 0)return(e.check?d.info.bind(d):d.error.bind(d))(`No ${Gs} at ${t}, nothing to generate.`),ac({status:"missing-config",ok:!!e.check,files:[]});await AM(t,r),await $M(t,r);let n=await Promise.all(Od(r).map(async a=>{let c=lc.join(t,a.path),l=await Xp(c),u="unchanged";return l===void 0?u="created":l!==a.content&&(u="updated"),{...a,absolute:c,status:u}})),o=await CM(t,r),s=[...n.filter(a=>a.status!=="unchanged"),...o],i=[...n,...o].map(({path:a,status:c})=>({path:a,status:c}));if(s.length===0)return d.info(`\u2705 Deploy workflows match ${Gs}.`),ac({status:"unchanged",ok:!0,files:i});if(e.check){d.error(`\u274C Deploy workflows differ from ${Gs}; run \`infra-kit deploy-sync\` and commit:`);for(let a of s)d.error(` ${a.path} (${TM[a.status]})`);return ac({status:"drift",ok:!1,files:i})}for(let a of s){if(a.status==="removed"){await cc.rm(a.absolute),d.info(`\u{1F5D1}\uFE0F Removed ${a.path}`);continue}await cc.mkdir(lc.dirname(a.absolute),{recursive:!0}),await cc.writeFile(a.absolute,a.content),d.info(`\u270F\uFE0F ${a.status==="created"?"Created":"Updated"} ${a.path}`)}return ac({status:"written",ok:!0,files:i})};var tb="https://dashboard.doppler.com/workplace/projects",OM=(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}"): ${tb}/${e}`],Qp=async({env:e})=>{let r=!!(await tt())?.envs[e];await Bf(e);let n=await mr(),o=await Gt();r?d.info(`Removed the "${e}" service token from ${w(o)}.`):d.info(`No "${e}" service token was stored in ${w(o)} \u2014 nothing to remove.`);for(let i of OM(n,e))d.warn(i);let s={env:e,removed:r,storePath:o,revokeUrl:`${tb}/${n}`};return{content:R(JSON.stringify(s,null,2)),structuredContent:s}};import DM from"@inquirer/confirm";import IM from"@inquirer/input";import NM from"@inquirer/password";import _M from"@inquirer/select";import MM from"node:fs/promises";import Rt from"node:process";import{$ as uc}from"zx";var jM=async({stdin:e,fromEnv:t})=>{if(e)return{token:await rb(),source:"stdin"};if(t){let n=Rt.env[t];if(!n)throw new Error(`${t} is not set (or is empty) \u2014 nothing to store.`);return{token:n,source:"env"}}if(!Rt.stdin.isTTY){let n=await rb();if(n)return{token:n,source:"stdin"};if(!Q())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 y.setInteractive(),{token:(await M(n=>NM({message:"Paste the Doppler service token (input is hidden)",mask:!0},n),{output:Rt.stderr,whenHeadless:{refuse:"stdin"}})).trim(),source:"prompt"}},rb=async()=>{let e=[];Rt.stdin.setEncoding("utf8");for await(let t of Rt.stdin)e.push(t);return e.join("").trim()},em="DOPPLER_CONFIG",FM=3e4,LM=async(e,t,r)=>{let n=uc.quiet;uc.quiet=!0;let o;try{o=(await uc({env:po(e)})`doppler secrets download --no-file --format json --project ${t} --config ${r}`.timeout(FM)).stdout}catch(s){throw BM(s,r)}finally{uc.quiet=n}return Kc(o)},BM=(e,t)=>{let r=uf(e)??(e instanceof Error?e.message:String(e));if(Wf(r)!=="auth")return e instanceof Error?e:new Error(String(e));let n=Gf(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(`
459
+ `))},UM=e=>[`Could not verify this token's scope: the Doppler payload for "${e}" carries no ${em}.`,"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(`
460
+ `),ob=async(e,t,r,n)=>{let o=await LM(e,t,r);Jc(o,r);let s=o.some(([i])=>i===em);if(!s&&!n)throw new Error(UM(r));return s},nb="\0new-env",WM=async()=>{if(Q()||!Rt.stdin.isTTY)throw new D({status:"argument_required",argument:"env",agentMode:F.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([rg(),tt()]),r=Math.max(0,...e.map(({env:s})=>s.length));y.setInteractive();let n=await M(s=>_M({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:nb}]},s),{output:Rt.stderr,whenHeadless:"refuse"});return n!==nb?n:(await M(s=>IM({message:"Doppler config name",validate:i=>/^\S+$/.test(i.trim())||"Enter a config name without spaces"},s),{output:Rt.stderr,whenHeadless:"refuse"})).trim()},GM=async(e,t,r)=>M(n=>DM({message:`Replace the "${e}" token ${Oe(t)} with ${Oe(r)}?`,default:!0},n),{output:Rt.stderr,whenHeadless:"refuse"}),VM=(e,t,r,n)=>{switch(t){case"stored":return`Stored the "${e}" service token (${Oe(r)})`;case"replaced":return`Replaced the "${e}" service token ${Oe(n??"")} \u2192 ${Oe(r)}`;case"unchanged":return`The "${e}" service token is already ${Oe(r)} \u2014 nothing to write`;case"kept":return`Kept the existing "${e}" service token ${Oe(n??"")} \u2014 nothing was written`;default:return Ve(t)}},tm=async({env:e,stdin:t,fromEnv:r,force:n})=>{let o=await mr(),s=e??await WM(),{token:i,source:a}=await jM({stdin:t,fromEnv:r});if(!i)throw new Error("No token provided \u2014 nothing was written.");let c=await ob(i,o,s,n),l=(await tt())?.envs[s],u;l===i?u="unchanged":l!==void 0&&a==="prompt"&&!await GM(s,l,i)?u="kept":(await jc({[s]:i}),u=l===void 0?"stored":"replaced");let p=await Gt();d.info(`${VM(s,u,i,l)} in ${w(p)} (mode 0600).`),c||d.warn(`Scope was NOT verified (no ${em} in the payload) \u2014 accepted because --force was given.`);let m={env:s,status:u,source:a,redactedToken:Oe(i),previousRedactedToken:l===void 0?null:Oe(l),storePath:p,scopeVerified:c};return y.print(),{content:R(JSON.stringify(m,null,2)),structuredContent:m}},JM=e=>/^(["']).*\1$/.test(e)?e.slice(1,-1):e,sb=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?JM(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},KM=e=>(e instanceof Error?e.message:String(e)).split(`
461
+ `)[0]??"",HM=(e,t)=>e===void 0?"stored":e===t?"unchanged":"replaced",qM=async(e,t,r,n)=>{let o=Oe(e.token);try{let s=await ob(e.token,t,e.env,n);return{env:e.env,status:HM(r,e.token),redactedToken:o,scopeVerified:s}}catch(s){return{env:e.env,status:"failed",redactedToken:o,scopeVerified:!1,error:KM(s)}}},rm=async({fromFile:e,force:t})=>{let r=await mr(),n=sb(await MM.readFile(e,"utf8")),o=await tt(),s=await Promise.all(n.map(p=>qM(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 jc(i);let a=await Gt(),c=Math.max(...s.map(({env:p})=>p.length));d.info(`Token import from ${w(e)} \u2192 ${w(a)}:`);for(let p of s){let m=p.error?` ${p.error}`:"";d.info(` ${p.env.padEnd(c)} ${p.status.padEnd(9)} ${p.redactedToken}${m}`)}d.warn(`${w(e)} still holds live tokens in plain text \u2014 delete it.`);let l=s.filter(p=>p.status==="failed").length;l>0&&(Rt.exitCode=1);let u={storePath:a,rows:s,failedCount:l};return{content:R(JSON.stringify(u,null,2)),structuredContent:u}};var nm=async(e,t,r=!0)=>{let{from:n,version:o,env:s,services:i,skipTerraform:a,yes:c,dryRun:l,printEnv:u}=e,p=await Ld(n);if(r&&y.addOption("--from",p),Fd(p,{"--version":o,"--skip-terraform":a,"--dry-run":l,"--print-env":u}),p==="local")throw new g(void 0,{operation:"deploy --from local",remediation:"use --from ci to dispatch the release workflow",stderrExcerpt:"local deploys are disabled for now \u2014 deploys run in CI only"});return t==="all"?Ia({version:o,env:s,skipTerraform:a,confirmedCommand:c}):Na({version:o,env:s,services:i,skipTerraform:a,confirmedCommand:c})},om=async e=>nm(e,"all"),sm=async e=>nm(e,"selected"),dc=async(e,t)=>{let r=`release deploy-${t} --from local`;return d.warn(`\`local deploy-${t}\` is deprecated and will be removed \u2014 use \`${r}\` instead.`),nm({...e,from:"local"},t,!1)};import{VENDOR_CONFIG_FILE as ab}from"@slip-stream-kit/config/internal";import im from"node:fs/promises";import Yn from"node:path";import ib from"node:process";import{pathToFileURL as YM}from"node:url";var cb="~/projects",am=async(e={})=>{if(e.init){await XM(e.cwd);return}await zM()},zM=async()=>{let e=An(),t=await se(e);if(d.info(`Factory config: ${w(e)} ${t?"[\u2713]":"[ ]"}`),!t){d.info("\nNot found \u2014 run `infra-kit vendor config --init` to scaffold it."),ib.exitCode=1;return}let{workspaceDir:r,source:n,targets:o}=await sa(),s=On(r),i=await se(s),a=Yn.join(s,n),c=await se(a);d.info(`workspaceDir: ${r} (resolved: ${s}) ${i?"[\u2713 exists]":"[ ] not found"}`),d.info(`Source: ${c?"[\u2713]":"[ ]"} ${n} ${w(a)}${c?"":" (not found \u2014 clone it)"}`),d.info("Targets:");let l=i&&c;for(let u of o){let p=Yn.join(s,u),m=await se(p);m||(l=!1);let f=m?"[\u2713]":"[ ]",h=m?"":" (not found \u2014 clone or remove)";d.info(` ${f} ${u} ${w(p)}${h}`)}l||(ib.exitCode=1)},XM=async e=>{let t=An();if(await se(t)){d.info(`Factory config already exists at ${w(t)} \u2014 leaving it untouched.`);return}let r=e??await A(),n=await ZM(r);await im.mkdir(Yn.dirname(t),{recursive:!0}),await im.writeFile(t,QM(Yn.basename(r),n),"utf-8"),d.info(`\u2713 Created ${w(t)}`),n.length>0&&d.info(` Seeded ${n.length} target(s) from the source ${ab}.`),d.info(` Edit \`workspaceDir\` (placeholder: ${cb}) to point at where your repos live.`),d.info(` \`source\` is seeded with ${Yn.basename(r)} (this repo); change it if the source is another repo.`),n.length===0&&d.info(" Add at least one repo name to `targets` before running vendor sync/manifest/diff.")},ZM=async e=>{try{let t=Yn.join(e,ab),r=await im.stat(t),s=(await import(`${YM(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[]},QM=(e,t)=>`${JSON.stringify({workspaceDir:cb,source:e,targets:t},null,2)}
462
+ `;import{existsSync as aF}from"node:fs";import cF from"node:fs/promises";import Mb from"node:path";import jb from"node:process";import{z as lF}from"zod";import{chmodSync as aj,copyFileSync as cj,lstatSync as lj,mkdirSync as vb,readdirSync as uj,readlinkSync as dj,rmSync as pj,rmdirSync as wb,symlinkSync as mj,unlinkSync as fj,writeFileSync as gj}from"node:fs";import Te from"node:path";import{lstatSync as ej,readlinkSync as lb}from"node:fs";import tj from"node:path";var rj=new Set(["ENOENT","ENOTDIR"]),pc=e=>{let t;try{t=ej(e)}catch(r){if(rj.has(r.code??""))return null;throw r}return t.isSymbolicLink()?{kind:"link",text:lb(e)}:t.isFile()?{kind:"file",executable:(t.mode&64)!==0,sha:Lr(e)}:{kind:"other"}},ub=(e,t)=>{let r=tj.join(e,t.path),n=t.mode==="120000"?{kind:"link",text:lb(r)}:{kind:"file",executable:t.mode==="100755",sha:Lr(r)};return{...t,fingerprint:n}},db=(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 nj}from"zx";var Z=async(e,t,r={})=>{let{input:n,allowFailure:o=!1}=r,s=await nj({cwd:e,quiet:!0,input:n,nothrow:o})`git ${t}`;return s.exitCode===0?s.stdout:""},mc=e=>e.slice(0,7),st=e=>e.split("\0").filter(t=>t.length>0);import oj from"node:path";var cm=`${ie}/`,lr=`${ie}/README.md`,Vs=`${ie}/${Ze}`,mb=e=>e.startsWith(cm),pb=e=>{let t=oj.posix.normalize(e);return t.endsWith("/")?t.slice(0,-1):t},fb=e=>{let t=pb(e.path),r=e.target===void 0?t:pb(e.target);return{path:t,target:r,vendored:mb(r),module:e.module??null}},gb=e=>e.copy.map(fb),Js=(e,t)=>t.length===0?!1:e.split("/").some(r=>t.includes(r)),Ks=(e,t)=>e.filter(r=>!Js(r.path,t)),fc=(e,t)=>e===t.path?t.target:`${t.target}${e.slice(t.path.length)}`,zn=e=>[...new Set(e)].sort(),hb=e=>e.startsWith(cm)?e.slice(cm.length):null;var gc=e=>`# vendor/ \u2014 mirrored from ${e}
454
463
 
455
464
  **DO NOT EDIT files in this folder here.**
456
465
 
@@ -461,19 +470,19 @@ fail \`ik vendor check\` in CI.
461
470
  To change a vendored package, edit it in \`${e}\` and re-run the sync there.
462
471
 
463
472
  See \`.sync-manifest.json\` for the source commit and per-file checksums.
464
- `;var zM=new Set(["100644","100755","120000"]),XM=(e,t)=>{let r=new Map;for(let n of nt(e)){let o=n.indexOf(" "),s=n.slice(0,n.indexOf(" ")),i=n.slice(o+1);o<0||!zM.has(s)||Us(i,t)||r.set(i,{path:i,mode:s})}return[...r.values()]},rm=async(e,t,r)=>{let n=await z(e,["--literal-pathspecs","ls-files","-z","-s","--",t]);return XM(n,r)},mb=async e=>nt(await z(e,["--literal-pathspecs","ls-files","-z","--",se]));var Jn=e=>["git","-C",e.root,"--literal-pathspecs","checkout","HEAD","--",...e.recoveryPaths],hb=e=>{let t=cc(e);t!==null&&(t.kind==="other"?gb(e):sj(e))},aj=(e,t,r)=>{let n=Pe.join(e,r.source),o=Pe.join(t,r.target);if(fb(Pe.dirname(o),{recursive:!0}),hb(o),r.mode==="120000"){oj(rj(n),o);return}QM(n,o),ZM(o,r.mode==="100755"?493:420)},cj=async(e,t)=>{let r=new Set;for(let n of nt(await z(e,["ls-files","-z"]))){if(t.has(n))continue;let o=Pe.posix.dirname(n);for(;o!==".";)r.add(o),o=Pe.posix.dirname(o)}return r},lj=async(e,t)=>{if(t.length===0)return;let r=await cj(e,new Set(t)),n=[...new Set(t.map(o=>Pe.dirname(Pe.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)&&!(!ej(s,{throwIfNoEntry:!1})?.isDirectory()||tj(s).length>0||r.has(Pe.relative(e,s).split(Pe.sep).join("/")));)gb(s),s=Pe.dirname(s)}},yb=(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,ar,...s].map(pb).filter(a=>a!==null&&!Va(a));return Gn(i)},vb=async(e,t,r,n)=>{let o=Pe.join(e,se);fb(o,{recursive:!0}),ij(Pe.join(e,ar),dc(t.name));let s=yb(r,await mb(e),n);yp(o,{source:t.name,commit:t.headSha},s)},nm=async({source:e,plan:t,onBeforeFirstWrite:r})=>{if(t.status!=="changed")return{touched:[],manifestWritten:!1};r?.(Jn(t));let n=Pe.resolve(t.root),o=t.entries.flatMap(a=>a.deletes);for(let a of o)hb(Pe.join(n,a));await lj(n,o);for(let a of t.entries)a.pruned&&a.deletes.length>0&&nj(Pe.join(n,a.target),{recursive:!0,force:!0});let s=t.entries.flatMap(a=>a.writes);for(let a of s)aj(e.root,n,a);let i=s.map(a=>a.target);return t.writeVendorMeta?(await vb(n,e,t.entries,o),{touched:Gn([...o,...i,ar,Bs]),manifestWritten:!0}):{touched:Gn([...o,...i]),manifestWritten:!1}},om=async(e,t)=>(await vb(e,t,[],[]),[ar,Bs]);var sm=(e,t)=>`[ROOT] vendor: sync from ${e}@${lc(t)}`,uj=e=>{let{stdout:t,stderr:r}=e;return[t,r].filter(o=>typeof o=="string"&&o.trim().length>0).join(`
465
- `).trim()||String(e)},im=async(e,t,r)=>{if(t.length===0)return{ok:!0};let n=t.join("\0"),o=["--pathspec-from-file=-","--pathspec-file-nul"];try{return await z(e,["--literal-pathspecs","add","-A",...o],{input:n}),await z(e,["--literal-pathspecs","commit","--only","-m",r,...o],{input:n}),{ok:!0}}catch(s){return{ok:!1,output:uj(s)}}};var wb=20,dj=20,cm=(e,t)=>e.length<=t?[...e]:[...e.slice(0,t),`\u2026and ${e.length-t} more`],am=(e,t,r)=>{let{entry:n}=e,o=new Set(t.tracked),s=[],i=[];for(let u of Ws(e.files,r)){let p=uc(u.path,n);if(s.push(p),ab(u.fingerprint,t.onDisk[p]??null))continue;let m=o.has(p)?"modified":"added";i.push({source:u.path,target:p,mode:u.mode,change:m})}let a=new Set(s),c=Ws(t.tracked.map(u=>({path:u})),r).map(u=>u.path).filter(u=>!a.has(u)),l=i.filter(u=>u.change==="added").length;return{...n,targetPaths:s,writes:i,deletes:c,counts:{added:l,modified:i.length-l,removed:c.length},pruned:!1}},jr=(e,t,r,n=[])=>({name:e.name,root:e.root,status:t,message:r,notes:n,warnings:[],entries:[],writeVendorMeta:!1,recoveryPaths:[]}),lm=(e,t)=>e.entries.filter((r,n)=>t[n]!=="release").map(r=>r.entry.target),pj=(e,t,r,n)=>{let o=["git","-C",t.root,"--literal-pathspecs","status","--",...lm(e,r)];return jr(t,"fail",`blocked: ${n.length} uncommitted path(s) under synced paths`,[...cm(n,wb),Ue(o)])},mj=(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=lc(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}`,...cm(e.lines,dj)],warnings:[]}},fj=e=>{let{added:t,modified:r,removed:n}=e.counts;return t+r+n===0?null:`${e.target}: ${t} added, ${r} modified, ${n} removed`},gj=e=>{let t=r=>e.reduce((n,o)=>n+o.counts[r],0);return`${t("added")} added, ${t("modified")} modified, ${t("removed")} removed`},hj=(e,t,r)=>{let n=e.flatMap(o=>[...o.writes.filter(i=>i.change==="modified").map(i=>i.target),...o.deletes]);return Gn([...n,...r?t.headVendorMeta:[]])},yj=e=>e.entries.filter(t=>t.scope==="release"&&t.tracked.length>0).map(t=>`${t.target}: not in vendorTarget.modules, left in place for this repo to own`),vj=(e,t)=>{let r=t.entries.map(f=>f.scope);if(t.dirty.length>0)return pj(e,t,r,t.dirty);if(t.pruneConflicts.length>0)return jr(t,"fail","blocked: a module this repo dropped is still a dependency",[...cm(t.pruneConflicts,wb)]);let n=e.entries.flatMap((f,h)=>{let S=t.entries[h]??{target:f.entry.target,scope:"sync",tracked:[],onDisk:{}};return S.scope==="release"?[]:S.scope==="sync"?[am(f,S,e.exclude)]:[{...am({...f,files:[]},S,e.exclude),pruned:!0}]}),o=n.some(f=>f.vendored),s=n.some(f=>f.writes.length+f.deletes.length>0),i=o&&(!t.readmeCurrent||!t.manifestPresent),a={...jr(t,"ok","up to date"),branch:t.branch,entries:n,writeVendorMeta:o};if(!s&&!i)return a;let c=mj(t.changelog,e.name),l=t.manifestSource!==null&&t.manifestSource!==e.name?[`vendor/ was last synced from ${t.manifestSource}, not ${e.name}: this sync replaces it`]:[],u=n.map(fj).filter(f=>f!==null),m=t.entries.some(f=>f.scope==="prune"&&f.tracked.length>0)?["vendored modules removed: run pnpm install to update the lockfile"]:[];return{...a,status:"changed",message:`${gj(n)} on ${t.branch}`,notes:[...u,...m,...yj(t),...i?["vendor/README.md and manifest rewritten"]:[],...c.notes],warnings:[...l,...c.warnings],recoveryPaths:hj(n,t,o)}},pc=(e,t)=>{switch(t.kind){case"missing":return jr(t,"skipped",`not checked out at ${t.root}`);case"source":return jr(t,"skipped","this is the source repo");case"not-git":return jr(t,"fail",`not a git repo: ${t.reason}`);case"bad-selection":return jr(t,"fail",`vendorTarget: ${t.reason}`);case"repo":return vj(e,t)}};import{existsSync as xj,readFileSync as Tj,realpathSync as mc}from"node:fs";import fc from"node:path";import{readFileSync as kb}from"node:fs";import Kn from"node:path";var wj=["dependencies","devDependencies","peerDependencies","optionalDependencies"],kj=e=>{let t=e.flatMap(({entry:r})=>r.module===null?[]:[r.module]);return[...new Set(t)].sort()},bb=(e,t)=>{if(t.kind==="invalid")return{reason:t.reason};let r=kj(e);if(t.kind==="modules"){let n=t.modules.filter(o=>!r.includes(o));if(n.length>0){let o=r.length>0?r.join(", "):"none";return{reason:`unknown module(s) ${n.join(", ")} in vendorTarget.modules; the source offers: ${o}`}}}return e.map(({entry:n})=>n.module===null||t.kind==="all"||t.modules.includes(n.module)?"sync":n.vendored?"prune":"release")},Rb=e=>{try{return JSON.parse(kb(e,"utf8"))}catch{return null}},bj=(e,t)=>t.files.flatMap(r=>{let n=Kn.posix.relative(t.entry.path,r.path);if(Kn.posix.basename(n)!=="package.json"||n.split("/").length>2)return[];let o=Rb(Kn.join(e,r.path))?.name;return typeof o=="string"?[o]:[]}),Rj=e=>wj.flatMap(t=>{let r=e[t];return r!==null&&typeof r=="object"?Object.keys(r):[]}),Sb=(e,t)=>{let r=e.indexOf(t);for(;r>=0;){if(!/[\w-]/.test(e[r+t.length]??""))return!0;r=e.indexOf(t,r+1)}return!1},Sj=["*.sh","*.yml","*.yaml"],Ej=(e,t,r)=>{let n=Rj(t).includes(r)?[`${e} depends on ${r}`]:[],o=t.scripts!==null&&typeof t.scripts=="object"?t.scripts:{};for(let[s,i]of Object.entries(o))typeof i=="string"&&Sb(i,r)&&n.push(`${e} script "${s}" runs ${r}`);return n},Pj=async(e,t,r)=>{let n=["grep","-z","-l","-F","-e",t,"--",...Sj];return nt(await z(e,n,{allowFailure:!0})).filter(s=>r(s)&&Sb(kb(Kn.join(e,s),"utf8"),t)).map(s=>`${s} uses ${t}`)},Eb=async(e,t,r)=>{let n=new Map;for(let{facts:c}of r)for(let l of bj(e,c))n.set(l,c.entry.module??"");if(n.size===0)return[];let o=r.map(({target:c})=>`${c}/`),s=c=>!o.some(l=>c.startsWith(l)),i=nt(await z(t,["ls-files","-z","--","*package.json"])).filter(c=>Kn.posix.basename(c)==="package.json"&&s(c)),a=[];for(let[c,l]of n){let u=i.flatMap(p=>{let m=Rb(Kn.join(t,p));return m===null?[]:Ej(p,m,c)});u.push(...await Pj(t,c,s));for(let p of u)a.push(`${p}: add "${l}" to vendorTarget.modules or stop using it`)}return a.sort()};var um=async(e,t)=>{let r=t.exclude??[],n=(await z(e,["rev-parse","HEAD"])).trim(),o=await Ae(e),s=await Promise.all(db(t).map(async i=>{let a=await rm(e,i.path,r);return{entry:i,files:a.map(c=>ib(e,c))}}));return{root:e,selfRoots:[...new Set([mc(e),mc(o)])],name:fc.basename(o),headSha:n,entries:s,exclude:r}},gc=e=>{let t=nt(e)[Symbol.iterator](),r=[];for(let n of t)r.push(n.slice(3)),/^[RC]|^.[RC]/u.test(n)&&t.next();return r},Cj=async(e,t,r)=>{let n=lm(e,t);if(n.length===0)return[];let o=await z(r,["--literal-pathspecs","status","--porcelain","-z","--untracked-files=all","--",...n]);return gc(o).filter(s=>!Us(s,e.exclude))},$j=async(e,t,r)=>Promise.all(e.entries.map(async({entry:n,files:o},s)=>{let i=t[s],a=await rm(r,n.target,e.exclude),c={},l=i==="sync"?o:[];for(let u of Ws(l,e.exclude)){let p=uc(u.path,n);c[p]=cc(fc.join(r,p))}return{target:n.target,scope:i,tracked:a.map(u=>u.path),onDisk:c}})),Aj=async e=>{try{return nt(await z(e,["--literal-pathspecs","ls-tree","-z","--name-only","HEAD","--",ar,Bs]))}catch{return[]}},Oj=e=>{try{let{commit:t,source:r}=Ds(fc.join(e,se));return{commit:t,source:r}}catch{return null}},Dj=async(e,t,r)=>{if(r===null)return{kind:"unknown-sha"};if(await Ce(e.root,r)===null)return{kind:"unresolvable",sha:r};let n=e.entries.filter((i,a)=>t[a]==="sync").map(({entry:i})=>i.path);if(n.length===0)return{kind:"log",sha:r,lines:[]};let s=(await z(e.root,["--literal-pathspecs","log","--oneline",`${r}..HEAD`,"--",...n])).split(`
466
- `).filter(i=>i.length>0);return{kind:"log",sha:r,lines:s}},Ij=(e,t)=>{try{return Tj(fc.join(e,ar),"utf8")===dc(t)}catch{return!1}},Nj=async e=>{try{return{toplevel:(await z(e,["rev-parse","--show-toplevel"])).trim()}}catch(t){return{reason:String(t.stderr??t).trim().split(`
467
- `)[0]??"git rev-parse failed"}}},_j=async e=>{try{return(await z(e,["rev-parse","--abbrev-ref","HEAD"])).trim()}catch{return"HEAD"}},hc=async(e,t)=>{if(!xj(t.root))return{...t,kind:"missing"};let r=mc(t.root);if(e.selfRoots.includes(r))return{...t,kind:"source"};let n=await Nj(t.root);if("reason"in n)return{...t,kind:"not-git",reason:n.reason};if(mc(n.toplevel)!==r)return{...t,kind:"not-git",reason:`it sits inside the repo at ${n.toplevel}`};let o=bb(e.entries,t.selection??{kind:"all"});if("reason"in o)return{...t,kind:"bad-selection",reason:o.reason};let s=Oj(t.root),i=s?.commit??null,[a,c,l,u,p]=await Promise.all([_j(t.root),Cj(e,o,t.root),$j(e,o,t.root),Aj(t.root),Dj(e,o,i)]),m=l.flatMap((f,h)=>f.scope==="prune"&&f.tracked.length>0?[{facts:e.entries[h],target:f.target}]:[]);return{...t,kind:"repo",branch:a,dirty:c,entries:l,headVendorMeta:u,readmeCurrent:Ij(t.root,e.name),manifestPresent:s!==null,manifestSource:s?.source??null,changelog:p,pruneConflicts:await Eb(e.root,t.root,m)}};var Mj=20,jj=(e,t)=>!t.commit||e.status!=="changed"||e.branch===void 0?e.notes:[...e.notes,`--commit lands on ${e.branch}`],Fj=(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:",Ue(Jn(r))]};let o=e.applied?`wrote ${r.message}`:r.message;return{name:n,status:r.status,message:o,notes:t.mode==="applied"?r.notes:jj(r,t)}},Lj=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(`
468
- `).slice(0,Mj)},Bj=(e,t)=>{let r=e.plan.warnings.map(n=>({name:"changelog",status:"warn",message:n}));return{label:e.plan.name,rows:[Fj(e,t),...r,...e.commit?[Lj(e.commit)]:[]]}},Uj={preview:"infra-kit vendor sync (preview)",check:"infra-kit vendor sync --check",applied:"infra-kit vendor sync"},dm=(e,t,r)=>{let n=r.mode==="preview"?["re-run with --yes from a real terminal to apply"]:[];return{title:Uj[r.mode],sections:[{label:"source",rows:[...e]},...t.map(o=>Bj(o,r))],hints:n}},Pb=e=>e.sections.some(t=>t.rows.some(r=>r.status==="fail")),xb=(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 Wj=20,pm=async(e,t)=>(await z(e,t,{allowFailure:!0})).trim(),Vj=async e=>gc(await z(e,["status","--porcelain","-z","--untracked-files=normal"])),Gj=async e=>(await pm(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"]},Jj=async e=>{let[t,r]=await Promise.all([pm(e,["symbolic-ref","--quiet","--short","refs/remotes/origin/HEAD"]),pm(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}`}},Tb=async e=>{let t=await Vj(e);if(t.length>0){let n=t.slice(0,Wj),o=t.length>n.length?`, and ${t.length-n.length} more`:"";throw new O({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([Gj(e),Jj(e)]);return[{name:"working tree",status:"ok",message:"clean"},...r.filter(n=>n!==null)]};import Yj from"node:path";import{readFileSync as Kj}from"node:fs";import Hj from"node:path";import{z as qj}from"zod";var Cb=e=>{let t;try{t=Kj(Hj.join(e,"infra-kit.json"),"utf8")}catch{return{kind:"all"}}let r;try{r=JSON.parse(t)?.vendorTarget}catch(o){return{kind:"invalid",reason:`infra-kit.json is not valid JSON: ${o.message}`}}if(r===void 0)return{kind:"all"};let n=kf.safeParse(r);return n.success?{kind:"modules",modules:n.data.modules}:{kind:"invalid",reason:qj.prettifyError(n.error)}};var $b=(e,t)=>{let r=t.filter(s=>!e.targets.includes(s));if(r.length>0)throw new O({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=xn(e.workspaceDir);return(t.length>0?e.targets.filter(s=>t.includes(s)):e.targets).map(s=>{let i=Yj.join(n,s);return{name:s,root:i,selection:Cb(i)}})},zj="rewrite vendor/README.md and vendor/.sync-manifest.json from the tracked vendor/ files",Xj=async(e,t)=>{let r=await hc(e,t),n=pc(e,r);return r.kind!=="repo"||n.status==="fail"?n:{...n,status:"changed",message:`${zj} on ${r.branch}`,notes:[],warnings:[],branch:r.branch,entries:[],writeVendorMeta:!0,recoveryPaths:r.headVendorMeta}},Ab=async(e,t,r)=>Promise.all(t.map(async n=>r?Xj(e,n):pc(e,await hc(e,n))));var Nb="sync vendored files",tF=e=>{let t=Db.join(xn(e.workspaceDir),e.source);if(Zj(t))return t;throw new O({status:"refused",reason:"source-missing",source:t},1,{operation:Nb,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'})},mm=(e,t)=>new O({status:"refused",reason:"not-a-vendor-source"},1,{operation:Nb,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`}),rF=async e=>{let t=Db.join(e,"infra-kit.json"),r;try{r=JSON.parse(await Qj.readFile(t,"utf8"))}catch(s){throw mm(t,`is unreadable: ${s instanceof Error?s.message:String(s)}`)}let n=r?.vendorSource;if(n==null)throw mm(t,"has no vendorSource block");let o=wf.safeParse(n);if(!o.success)throw mm(t,`has an invalid vendorSource: ${eF.prettifyError(o.error)}`);return o.data},Ob=(e,t)=>{Ib.stderr.write(`${e.name}: if this run dies, restore the tracked paths with:
469
- ${Ue(t)}
470
- `)},nF=async(e,t,r)=>r?(Ob(t,Jn(t)),om(t.root,e)):(await nm({source:e,plan:t,onBeforeFirstWrite:o=>{Ob(t,o)}})).touched,oF=async(e,t,r)=>{if(t.status!=="changed")return{plan:t,applied:!1};let n;try{n=await nF(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 im(t.root,n,sm(e.name,e.headSha));return{plan:t,applied:!0,commit:o}},sF=async(e,t,r)=>{let n=[];for(let o of t)n.push(await oF(e,o,r));return n},_b=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})),fm=({mode:e,report:t,outcomes:r,source:n,print:o})=>{o&&pt(t);let s=r.map(a=>a.plan);return{structuredContent:{mode:e,source:{root:n.root,name:n.name,headSha:n.headSha},targets:_b(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:Pb(t),report:t.sections}}},iF=async e=>{let t=await ta(),r=tF(t),n=await Tb(r),o=await rF(r),s=$b(t,e.targets??[]),i=await um(r,o),a=await Ab(i,s,!!e.manifestOnly);return{source:i,sourceRows:n,plans:a}},gm=async(e={})=>{let{source:t,sourceRows:r,plans:n}=await iF(e),o=n.map(m=>({plan:m,applied:!1})),s={commit:e.commit,manifestOnly:e.manifestOnly},i=e.check?"check":"preview",a=dm(r,o,{...s,mode:i}),c=!n.some(m=>m.status==="changed");if(e.check||c)return fm({mode:i,report:a,outcomes:o,source:t,print:!0});let l=!e.confirmedCommand&&!X();if(l&&!Ib.stdin.isTTY)return pt(a),fm({mode:"preview",report:a,outcomes:o,source:t,print:!1});l&&pt({...a,hints:[]}),await J(e.confirmedCommand,`Sync vendored files from ${t.name} into these targets?`,{plan:_b(n),throwOnDecline:!0});let u=await sF(t,n,e),p=dm(r,u,{...s,mode:"applied"});if(l){let m=u.filter(f=>f.applied).map(f=>f.plan.name);pt(xb(a,p,m))}return fm({mode:"applied",report:p,outcomes:u,source:t,print:!l})};var yc=(e,t=!0)=>({line:e,reproducible:t});import vc from"node:fs";import aF from"node:os";import cF from"node:path";import Lb from"node:process";var wc="INFRA_KIT_SESSION_REPORT",hm=null,Mb=!1,jb=[],Bb=(e=Lb.env)=>{Mb||(hm=e[wc]??null,Mb=!0,delete e[wc])};var Ub=(e,t)=>{if(!hm)return;let r=e.summary??(jb.length>0?[...jb]:void 0),n={...e,...r?{summary:r}:{}},o=t?.write??((s,i)=>{vc.writeFileSync(s,i)});try{o(hm,JSON.stringify(n))}catch{}},Fb=0,Wb=e=>{let t=e?.tmpdir?.()??aF.tmpdir(),r=e?.pid??Lb.pid;return Fb+=1,cF.join(t,`infra-kit-session-${r}-${Fb}.json`)},Vb=(e,t)=>{if(!(t?.exists??(i=>vc.existsSync(i)))(e))return null;let n=t?.read??(i=>vc.readFileSync(i,"utf-8")),o=t?.unlink??(i=>vc.unlinkSync(i)),s;try{s=n(e)}catch{return null}finally{try{o(e)}catch{}}try{return JSON.parse(s)}catch{return null}};var ym=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");for(let r of e.commands)ym(r)};var vm=e=>{e.options.some(r=>r.long==="--debug")||e.option("--debug","Raise the log level to debug (logs stay on stderr)");for(let r of e.commands)vm(r)};var pF=(e,t)=>[...t,e],mF=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 jh(()=>ka({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}));D(r),r.structuredContent.failedMerges>0&&(Fe.exitCode=1)}),Jb=e=>(Fe.stdout.write(`${e.structuredContent.filePath}
471
- `),D(e)),fF=e=>e.description("List all release branches").action(async()=>{D(await Oa())}),gF=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".',pF,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let n=t.release.map(Wu),o=n.length>0?n:void 0;D(await Na({releases:o,confirmedCommand:t.yes}))}),hF=e=>{if(e==="")return e;try{return Er(e)}catch(t){throw t instanceof In?new Kb(t.message):t}},yF=e=>{let t=Number(e);if(!Number.isInteger(t)||t<=0)throw new Kb("Expected a positive whole number of days.");return t},vF=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)',hF).option("-y, --yes","Skip confirmation prompt").action(async t=>{D(await _a({version:t.version,description:t.description,releaseDate:t.releaseDate,confirmedCommand:t.yes}))}),Hb=e=>e.option("-f, --from <where>",`Where the deploy runs: ${tr.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"),wF=e=>Hb(e).description("Deploy every service to any environment, in CI or from this machine").action(async t=>{D(await Xp({from:t.from,version:t.version,env:t.env,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),kF=e=>Hb(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=>{D(await Zp({from:t.from,version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),bF=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=>{D(await Ra({version:t.version,confirmedCommand:t.yes}))}),RF=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=>{D(await Fa({version:t.version,moveIssuesTo:t.moveIssuesTo,skipJira:t.skipJira,confirmedCommand:t.yes}))}),SF=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{D(await ec({confirmedCommand:t.yes}))}),EF=e=>e.description("Add git worktrees for release branches or feature branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-f, --feature <names>","Feature worktrees by comma, each on a feature/<name> branch, e.g. checkout-v2").option("-b, --base <branch>","Base for new feature branches: dev (default; the default branch without one), main, or a release, e.g. 1.4.0").option("-g, --github-desktop","Open created worktrees in GitHub Desktop").option("--no-github-desktop","Skip GitHub Desktop prompt").option("--orca","Open created worktrees in Orca (pane layout from worktrees.orca.layout)").option("--no-orca","Skip the Orca prompt").action(async t=>{D(await za({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature,base:t.base,githubDesktop:t.githubDesktop,orca:t.orca}))}),PF=e=>e.description("List all git worktrees with detailed information").action(async()=>{D(await Xa())}),xF=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=>{D(await Qa({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature,self:t.self}))}),TF=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=>{D(await em({init:t.init}))}),CF=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await Ha();D(t),t.structuredContent.ok||(Fe.exitCode=1)}),$F=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 gm({targets:t,confirmedCommand:r.yes,check:r.check,commit:r.commit,manifestOnly:r.manifestOnly})}catch(a){if(!Et(a))throw a;d.info("Operation cancelled.");return}D(n);let{failed:o,changed:s,mode:i}=n.structuredContent;(o||i==="check"&&s)&&(Fe.exitCode=1)}),AF=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{D(await _p())}),OF=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{D(await Mp())}),DF=new Set(["version"]),kc=e=>{let t=[];for(let r=e;r&&r.parent;r=r.parent)t.unshift(r.name());return t.join(" ")},wm=()=>{let e=new lF().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");mF(t.command("merge-dev")),fF(t.command("list")),gF(t.command("create")),vF(t.command("edit")),wF(t.command("deploy-all")),kF(t.command("deploy-selected")),bF(t.command("deliver")),RF(t.command("remove"));let r=e.command("worktrees").description("Git worktree management commands");EF(r.command("add")),PF(r.command("list")),xF(r.command("remove")),SF(r.command("sync"));let n=e.command("config").description("Manage infra-kit configuration files");AF(n.command("path")),OF(n.command("edit")),e.command("config-get").description("Print the fully merged infra-kit config (project + user-global + per-project override layers)").argument("[key]","Print only this top-level key (e.g. worktrees)").action(async a=>{D(await Mi({key:a}))}),e.command("config-set").description("Set a top-level key in this project\u2019s per-machine config override (validated before it is kept)").argument("<key>","Top-level config key (e.g. protectedEnvs, worktrees)").argument("<value>",`JSON value, or a bare string (e.g. cli-only, '{"openInOrca":true}')`).option("--global","Write ~/.infra-kit/infra-kit.json (every project on this machine) instead").action(async(a,c,l)=>{D(await Ll({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)=>{D(await jp({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=>{D(await ac({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=>{D(await ac({env:a.env,services:a.service,yes:a.yes,dryRun:a.dryRun,printEnv:a.printEnv},"selected"))}),e.command("audit").description("Audit against infra-kit.config.ts rules (--all for every package, --root for the monorepo root)").option("-a, --all","Audit every non-vendor workspace package").option("-r, --root","Audit the monorepo root (turbo pipeline + root commands)").option("--fix","Write the infra-kit guidance block into CLAUDE.md for the audited scope before checking (CLI-only)").option("--design","With --fix: scaffold DESIGN.md for frontend/mobile packages that lack one").action(async a=>{if(a.design&&!a.fix){d.error("--design requires --fix (it scaffolds DESIGN.md; there is nothing to scaffold without a fix run)"),Fe.exitCode=1;return}let c=await $i({all:a.all,root:a.root,fix:a.fix,design:a.design});D(c);let{allPassed:l,fixed:u}=c.structuredContent,p=(u??[]).some(m=>m.action==="failed");(!l||p)&&(Fe.exitCode=1)}),e.command("deploy-run").description("Deploy a service: its deploy.ts from infra-kit.deploy.ts, else its devops/scripts .sh (what the CI deploy job runs)").argument("<service>","The service as infra-kit.deploy.ts names it, e.g. client-be").action(async a=>{D(await Vp({service:a}))}),e.command("deploy-sync").description("Generate the deploy-all / deploy-selected workflows from infra-kit.deploy.ts").option("--check","Compare only; exit 1 when the committed workflows differ from the manifest").action(async a=>{let c=await Jp({check:a.check});D(c),c.structuredContent.ok||(Fe.exitCode=1)});let i=e.command("vendor").description("Mirror and verify the vendored starter files");CF(i.command("check")),TF(i.command("config")),$F(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 da({fix:!!a.fix});lr.enabled||Yl(c.structuredContent.checks,{ascii:!!a.ascii}),c.structuredContent.checks.some(u=>u.name==="plugin installed"&&u.status==="fail")&&(Fe.exitCode=1),D(c)}),e.command("dev").description("Run local dev servers for an app (or every app); api + ui").argument("[app]","An app \u2014 its api/ui plus the backends its routes can run locally (omit to run every app)").option("-w, --watch","Rebuild and restart on file save (the default)").option("--no-watch","Build once and never restart on save").option("--app <names>","Further narrow to these app folder names (comma-separated)").option("--target <keys>","Run exactly these <app>/api|<app>/ui packages (comma-separated); part-level, unlike --app").option("--orca","Run each app in its own Orca pane (one tab, N panes; falls back to single terminal when Orca is not running)").option("--self","Run only the app of the current directory (infer from cwd; use inside apps/<app>/\u2026)").option("-V, --verbose","Print full boot narration (default: quiet; full detail always in the session log)").option("--routes","Print each app\u2019s registered METHOD /path routes at startup (default: off)").option("--reuse","For test runners: start nothing when this worktree already serves one of these apps, exit on a boot failure").option("--no-ui-health","Do not probe the frontends\u2019 liveness (vite\u2019s HMR ping); their rows carry no health dot (also: INFRA_KIT_NO_UI_HEALTH=1)").action(async(a,c)=>{let{runDevServerCli:l}=await import("./dev-server.js"),u=!!(Fe.stdout.isTTY&&Fe.stdin.isTTY);await l({...c,appName:a},u,lr.enabled)}),e.command("dev-status").description("Show what `infra-kit dev` currently has running (reads dev-context fragments; starts nothing)").action(async()=>{D(await ji())}),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)=>{D(await ga({app:c.app,dryRun:c.dryRun,yes:c.yes,cloud:c.cloud,playwrightArgs:a}))}),e.command("setup").description("Set this machine up: shell integration, agent files, the Claude Code skills plugin, then the external tools").option("--tools <ids...>","Limit to these tools (brew, git, aws, gh, doppler, portless)").option("--update [ids...]","Update what is already installed; never install a missing tool").option("--skip-tools","Do the local setup only, then REPORT what each tool needs \u2014 installs nothing").option("--ascii","Render the report with ASCII markers instead of unicode glyphs (row messages are unchanged)").addOption(new Gb("--unattended","Background run: no tool installs, no writes to git-tracked files").hideHelp()).addOption(new Gb("--auto","Unattended setup for the machine and every infra-kit project, once per version").hideHelp()).action(async a=>{if(a.auto){D(await sp());return}D(await Wa({tools:a.tools,update:a.update,skipTools:a.skipTools,ascii:!!a.ascii,unattended:a.unattended}))}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{D(await qa())}),e.command("change-stats").description("Change-failure baseline for this git repo: agent vs human commits, revert and 72h follow-up-fix rates").option("--since <days>",`Window in days, ending now (default ${So})`,yF).action(async a=>{D(await Ii({since:a.since}))}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{D(await va())}),e.command("env-list").description("List available Doppler configs for the detected project, and whether a service token resolves for each").action(async()=>{D(await Xf())}),e.command("env-load").description("Load Doppler env vars for a config. Source the returned file path to apply.").option("-c, --config <config>","Environment config name to load (e.g. dev, arthur). Omitted: the picker opens on defaultEnv; headless runs load it").action(async a=>{Jb(await Bc({config:a.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{Jb(await ya())}),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.");D(await Yp({fromFile:c.fromFile,force:c.force}));return}D(await qp({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=>{D(await wa({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=>{D(await Kp({env:a}))});for(let a of e.commands)tf(a);return ym(e),vm(e),e.hook("preAction",async(a,c)=>{let{C:l}=e.opts();l!==void 0&&dF(uF(Fe.cwd(),l)),y.start(kc(c)),lr.enabled=!!c.optsWithGlobals().json,lr.enabled&&(d.level="warn"),j.source=ti({env:Fe.env,stdinIsTTY:Fe.stdin.isTTY===!0,flag:!!c.optsWithGlobals().agent}),DF.has(kc(c))||await Ru()}),e.hook("postAction",(a,c)=>{let l=kc(c);if(Dp(l))return;let p=y.snapshot()?.formattedOptions??"",m=p?` ${p}`:"",f=`infra-kit ${l}${m}`;Ub({equivalent:yc(f,!0)})}),e};import IF from"node:process";var NF={exit:IF.exit,emit:D,logger:d},qb=(e,t=NF)=>Oe(e)?(t.logger.info("Operation cancelled."),t.exit(0)):e instanceof O?(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 km=(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 _F from"node:fs";import bm from"node:path";import Hn from"node:process";var Xb=new Set([...vf,Yn,"XDG_CACHE_HOME","CLAUDE_PROJECT_DIR","CLAUDE_PLUGIN_ROOT"]),Zb=null,bc=new Set,Rm=null,Yb=!1;var zb=e=>{try{return _F.statSync(e)}catch{return null}},MF=()=>{if(Yb)return null;try{return Br()}catch{return Yb=!0,d.debug(`session-env: ${Yn} unset \u2014 no overlay`),null}},jF=e=>{let t=bm.join(e,Fr),r=bm.join(e,Js),n=zb(t),o=zb(r);return n&&!(o&&o.mtimeMs>n.mtimeMs)?Dm(bm.join(e,Ks),Hn.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"}},FF=e=>e.kind==="load"?{kind:"load",vars:Am(e.file),signature:e.signature}:e.kind==="clear"?{kind:"clear",unset:Om(e.file),signature:e.signature}:e;var LF=()=>{let e=MF();if(e===null)return{kind:"no-session"};let t=jF(e);return t.signature===Rm?null:FF(t)},BF=()=>{for(let e of bc){let t=Zb[e];t===void 0?delete Hn.env[e]:Hn.env[e]=t}bc.clear()},UF=(e,t,r)=>{if(Xb.has(t)){e.skipped.push(t);return}Hn.env[t]=r,bc.add(t),e.set.push(t)},WF=(e,t)=>{if(Xb.has(t)){e.skipped.push(t);return}delete Hn.env[t],bc.add(t),e.unset.push(t)},VF=e=>{let t={set:[],unset:[],skipped:[]};if(e.kind==="load")for(let[r,n]of Object.entries(e.vars))UF(t,r,n);if(e.kind==="clear")for(let r of e.unset)WF(t,r);return t},GF=e=>e.kind==="load"?`load, ${Object.keys(e.vars).length} vars`:e.kind,Sm=(e=LF())=>{if(Zb??={...Hn.env},e===null||e.kind==="no-session"||e.signature===Rm)return{set:[],unset:[],changed:!1};BF();let{set:t,unset:r,skipped:n}=VF(e);return Rm=e.signature,n.length>0&&d.warn(`session-env: skipped protected names [${n.join(", ")}]`),d.debug(`session-env applied: set [${t.join(", ")}] unset [${r.join(", ")}] (${GF(e)})`),{set:t,unset:r,changed:!0}};import{chalkStderr as dL}from"chalk";import{spawn as pL}from"node:child_process";import Le from"node:process";import{Chalk as JF}from"chalk";var qn=new JF({level:1}),ot={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."},KF={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"}},Qb={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},eR={unicode:"\u2500",ascii:"-"},HF=3,Em=e=>e,qF={ok:e=>qn.green(e),findings:e=>qn.yellow(e),failed:e=>qn.red(e),cancelled:e=>qn.gray(e)},xm=e=>e?{dim:t=>qn.dim(t),bold:t=>qn.bold(t)}:{dim:Em,bold:Em},YF=(e,t)=>e?qF[t]:Em,Pm=e=>[...e].length,zF=(e,t)=>{if(t==null)return e;let r=Math.max(0,t-1);return Pm(e)<=r?e:[...e].slice(0,r).join("")},tR=e=>{let t=xm(e.color===!0).dim,r=KF[e.canSuspend?"suspend":"plain"],n=e.ascii===!0?r.ascii:r.unicode;return t(zF(n,e.width))},rR=(e,t={})=>{let r=xm(t.color===!0);return`${r.dim(ot.reproPrefix.trim())} ${r.bold(e)}`},XF=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,ZF=(e,t)=>e==="findings"?t!=null?`${t} ${ot.findingsSuffix}`:ot.findingsPlain:{ok:ot.ok,failed:ot.failed,cancelled:ot.cancelled}[e],QF=(e,t,r,n)=>{if(t==null)return"";let o=t-2-e;return o<HF?"":` ${n(r.repeat(o))}`},nR=e=>{let t=e.color===!0,r=xm(t),n=YF(t,e.outcome),o=e.ascii===!0,s=e.equivalent.reproducible?ot.reproPrefix:ot.nonReproPrefix,i=o?Qb[e.outcome].ascii:Qb[e.outcome].unicode,a=ZF(e.outcome,e.findingsCount),c=[XF(e.durationMs)],l=e.summary?.[0]?.split(`
472
- `)[0];l!=null&&l.length>0&&c.push(l);let u=`${i} ${a}`,p=`${ot.sep}${c.join(ot.sep)}`,m=Pm(u)+Pm(p),f=QF(m,e.width,o?eR.ascii:eR.unicode,r.dim),h=[`${n(u)}${r.dim(p)}${f}`];return e.showEquivalent!==!1&&h.unshift(`${r.dim(s.trim())} ${r.bold(e.equivalent.line)}`),e.envNotice===!0&&h.push(r.dim(ot.envNotice)),h.join(`
473
- `)};var eL=new Set([130,143]),oR=(e,t,r,n=!1)=>r?t!=null||e===0?"ok":"findings":n&&e!=null&&eL.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import tL from"node:process";var rL={3:"quit",4:"quit",26:"suspend",27:"quit"},nL=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":rL[t]??"continue"},oL=150,sL="\r\x1B[2K",iL=`\r
474
- `,sR=(e,t)=>{iR(e),e.stdin.on("data",t),e.listener=t},iR=e=>{e.listener!==null&&(e.stdin.off("data",e.listener),e.listener=null)},aR=(e,t)=>{Cf(),e.stdin.setRawMode(!0),e.stdin.isPaused()&&e.stdin.resume(),sR(e,t)},cR=e=>{e.hintOnScreen&&(e.hintOnScreen=!1,e.deps.write(sL)),iR(e),e.stdin.isTTY===!0&&e.stdin.isRaw===!0&&e.stdin.setRawMode(!1),$f()},aL=e=>{e.settled||(e.settled=!0,cR(e))},lR=(e,t)=>{let r=tR({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},cL=async e=>{await new Promise(t=>{setTimeout(t,e)})},lL=(e,t,r)=>{cR(e),t(),aR(e,r),lR(e,iL)},uL=async e=>new Promise(t=>{let r=n=>{let o=nL(n),s=e.deps.suspend;if(o==="quit"){t("quit");return}if(o==="suspend"&&s!==void 0){lL(e,s,r);return}t("palette")};sR(e,r),lR(e,"")}),uR=async(e,t)=>{if(e.quitRequested())return"quit";let r=t.stdin??tL.stdin;if(r.isTTY!==!0)return"palette";let n={deps:t,stdin:r,listener:null,hintOnScreen:!1,settled:!1};try{return aR(n,()=>{}),e.armed(),await cL(t.drainMs??oL),await uL(n)}finally{aL(n)}};import dR from"node:process";var cr={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},pR=(e,t)=>{let r=t?.write??(s=>{dR.stderr.write(s)}),n=t?.stdin??dR.stdin,o=[cr.saveCursor,cr.scrollRegion,cr.restoreCursor,cr.column,cr.sgr,cr.cursor,cr.wrap];e.entersAltScreen===!0&&o.push(cr.primaryBuffer),r(o.join("")),n.isTTY===!0&&n.isRaw===!0&&n.setRawMode?.(!1)};var mR=e=>`infra-kit ${e.groupPath.join(" ")}`,mL=()=>{fL();let e=Le.stderr.columns;return e!=null&&e>0?e:void 0},fL=()=>{let e=Le.stderr;typeof e._refreshSize=="function"&&e._refreshSize()},gL=e=>new Promise(t=>{e.on("exit",(r,n)=>{t({code:r,signal:n})}),e.on("error",()=>{t({code:1,signal:null})})}),hL=async(e,t,r)=>{let n=Wb(),o={...t.env,[wc]:n,INFRA_KIT_NO_AUTO_UPDATE:"1"},s=t.now(),i={code:1,signal:null};r();try{let p=t.spawn(Le.execPath,[t.cliPath,...e.groupPath],{stdio:"inherit",env:o});i=await gL(p)}catch{i={code:1,signal:null}}finally{t.resetTerminal({entersAltScreen:e.entersAltScreen})}let a=Vb(n),c=oR(i.code,i.signal,a!=null,e.longRunning),l=mR(e),u=a?.equivalent??yc(l,!0);return nR({equivalent:u,outcome:c,durationMs:t.now()-s,summary:a?.summary,envNotice:e.sessionEnvNotice,ascii:t.ascii,color:t.color,width:t.columns(),showEquivalent:!(u.reproducible&&u.line===l)})},yL=1e3,vL=(e,t)=>e!=null&&t-e<=yL,Tm=e=>{e.resetTerminal(),e.exit(0)},wL=(e,t)=>{let r=null,n=!1,o=()=>{let c=e();if(c==="child"){r=t.now();return}c!=="pause"&&Tm(t)},s=()=>{let c=e();if(c==="palette"){Tm(t);return}if(!vL(r,t.now())){if(c==="pause"){Tm(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}},fR=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),kL=Le.platform==="win32"?void 0:()=>{Af()},bL=(e,t)=>r=>uR(r,{write:e,columns:t.columns,ascii:t.ascii,color:t.color,suspend:kL}),gR=async(e,t)=>{let r={spawn:t.spawn??pL,now:t.now??(()=>Date.now()),env:t.env??Le.env,cliPath:t.cliPath,ascii:t.ascii??!(Le.stdout.isTTY&&Le.env.TERM!=="dumb"),color:t.color??dL.level>0,columns:t.columns??mL,resetTerminal:t.resetTerminal??(u=>{pR(u)})},n=t.write??(u=>Le.stderr.write(u)),o="palette",s=t.signals??{register:(u,p)=>{Le.on(u,p)},unregister:(u,p)=>{Le.off(u,p)},exit:u=>{Le.exit(u)},raise:u=>{Le.kill(Le.pid,u)},now:()=>Date.now(),resetTerminal:()=>{o==="pause"&&n("\r\x1B[2K"),r.resetTerminal({entersAltScreen:!1})}},i={dispose:()=>{},childStarted:()=>{},quitRequested:()=>!1},a=t.installSignals===!1?i:wL(()=>o,s),c={armed:()=>{o="pause"},quitRequested:()=>a.quitRequested()},l=t.afterRun??bL(n,r);try{for(;;){if(a.quitRequested())return;o="palette";let u=await t.renderPalette(e);if(u==null)return;let p=t.resolveCommand(u);if(!p)continue;let m=rR(mR(p),{color:r.color});n(`
473
+ `;var sj=new Set(["100644","100755","120000"]),ij=(e,t)=>{let r=new Map;for(let n of st(e)){let o=n.indexOf(" "),s=n.slice(0,n.indexOf(" ")),i=n.slice(o+1);o<0||!sj.has(s)||Js(i,t)||r.set(i,{path:i,mode:s})}return[...r.values()]},lm=async(e,t,r)=>{let n=await Z(e,["--literal-pathspecs","ls-files","-z","-s","--",t]);return ij(n,r)},yb=async e=>st(await Z(e,["--literal-pathspecs","ls-files","-z","--",ie]));var Xn=e=>["git","-C",e.root,"--literal-pathspecs","checkout","HEAD","--",...e.recoveryPaths],kb=e=>{let t=pc(e);t!==null&&(t.kind==="other"?wb(e):fj(e))},hj=(e,t,r)=>{let n=Te.join(e,r.source),o=Te.join(t,r.target);if(vb(Te.dirname(o),{recursive:!0}),kb(o),r.mode==="120000"){mj(dj(n),o);return}cj(n,o),aj(o,r.mode==="100755"?493:420)},yj=async(e,t)=>{let r=new Set;for(let n of st(await Z(e,["ls-files","-z"]))){if(t.has(n))continue;let o=Te.posix.dirname(n);for(;o!==".";)r.add(o),o=Te.posix.dirname(o)}return r},vj=async(e,t)=>{if(t.length===0)return;let r=await yj(e,new Set(t)),n=[...new Set(t.map(o=>Te.dirname(Te.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)&&!(!lj(s,{throwIfNoEntry:!1})?.isDirectory()||uj(s).length>0||r.has(Te.relative(e,s).split(Te.sep).join("/")));)wb(s),s=Te.dirname(s)}},bb=(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,lr,...s].map(hb).filter(a=>a!==null&&!Ha(a));return zn(i)},Rb=async(e,t,r,n)=>{let o=Te.join(e,ie);vb(o,{recursive:!0}),gj(Te.join(e,lr),gc(t.name));let s=bb(r,await yb(e),n);Ep(o,{source:t.name,commit:t.headSha},s)},um=async({source:e,plan:t,onBeforeFirstWrite:r})=>{if(t.status!=="changed")return{touched:[],manifestWritten:!1};r?.(Xn(t));let n=Te.resolve(t.root),o=t.entries.flatMap(a=>a.deletes);for(let a of o)kb(Te.join(n,a));await vj(n,o);for(let a of t.entries)a.pruned&&a.deletes.length>0&&pj(Te.join(n,a.target),{recursive:!0,force:!0});let s=t.entries.flatMap(a=>a.writes);for(let a of s)hj(e.root,n,a);let i=s.map(a=>a.target);return t.writeVendorMeta?(await Rb(n,e,t.entries,o),{touched:zn([...o,...i,lr,Vs]),manifestWritten:!0}):{touched:zn([...o,...i]),manifestWritten:!1}},dm=async(e,t)=>(await Rb(e,t,[],[]),[lr,Vs]);var pm=(e,t)=>`[ROOT] vendor: sync from ${e}@${mc(t)}`,wj=e=>{let{stdout:t,stderr:r}=e;return[t,r].filter(o=>typeof o=="string"&&o.trim().length>0).join(`
474
+ `).trim()||String(e)},mm=async(e,t,r)=>{if(t.length===0)return{ok:!0};let n=t.join("\0"),o=["--pathspec-from-file=-","--pathspec-file-nul"];try{return await Z(e,["--literal-pathspecs","add","-A",...o],{input:n}),await Z(e,["--literal-pathspecs","commit","--only","-m",r,...o],{input:n}),{ok:!0}}catch(s){return{ok:!1,output:wj(s)}}};var Sb=20,kj=20,gm=(e,t)=>e.length<=t?[...e]:[...e.slice(0,t),`\u2026and ${e.length-t} more`],fm=(e,t,r)=>{let{entry:n}=e,o=new Set(t.tracked),s=[],i=[];for(let u of Ks(e.files,r)){let p=fc(u.path,n);if(s.push(p),db(u.fingerprint,t.onDisk[p]??null))continue;let m=o.has(p)?"modified":"added";i.push({source:u.path,target:p,mode:u.mode,change:m})}let a=new Set(s),c=Ks(t.tracked.map(u=>({path:u})),r).map(u=>u.path).filter(u=>!a.has(u)),l=i.filter(u=>u.change==="added").length;return{...n,targetPaths:s,writes:i,deletes:c,counts:{added:l,modified:i.length-l,removed:c.length},pruned:!1}},Ur=(e,t,r,n=[])=>({name:e.name,root:e.root,status:t,message:r,notes:n,warnings:[],entries:[],writeVendorMeta:!1,recoveryPaths:[]}),hm=(e,t)=>e.entries.filter((r,n)=>t[n]!=="release").map(r=>r.entry.target),bj=(e,t,r,n)=>{let o=["git","-C",t.root,"--literal-pathspecs","status","--",...hm(e,r)];return Ur(t,"fail",`blocked: ${n.length} uncommitted path(s) under synced paths`,[...gm(n,Sb),Ge(o)])},Rj=(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=mc(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}`,...gm(e.lines,kj)],warnings:[]}},Sj=e=>{let{added:t,modified:r,removed:n}=e.counts;return t+r+n===0?null:`${e.target}: ${t} added, ${r} modified, ${n} removed`},Ej=e=>{let t=r=>e.reduce((n,o)=>n+o.counts[r],0);return`${t("added")} added, ${t("modified")} modified, ${t("removed")} removed`},Pj=(e,t,r)=>{let n=e.flatMap(o=>[...o.writes.filter(i=>i.change==="modified").map(i=>i.target),...o.deletes]);return zn([...n,...r?t.headVendorMeta:[]])},xj=e=>e.entries.filter(t=>t.scope==="release"&&t.tracked.length>0).map(t=>`${t.target}: not in vendorTarget.modules, left in place for this repo to own`),Tj=(e,t)=>{let r=t.entries.map(f=>f.scope);if(t.dirty.length>0)return bj(e,t,r,t.dirty);if(t.pruneConflicts.length>0)return Ur(t,"fail","blocked: a module this repo dropped is still a dependency",[...gm(t.pruneConflicts,Sb)]);let n=e.entries.flatMap((f,h)=>{let b=t.entries[h]??{target:f.entry.target,scope:"sync",tracked:[],onDisk:{}};return b.scope==="release"?[]:b.scope==="sync"?[fm(f,b,e.exclude)]:[{...fm({...f,files:[]},b,e.exclude),pruned:!0}]}),o=n.some(f=>f.vendored),s=n.some(f=>f.writes.length+f.deletes.length>0),i=o&&(!t.readmeCurrent||!t.manifestPresent),a={...Ur(t,"ok","up to date"),branch:t.branch,entries:n,writeVendorMeta:o};if(!s&&!i)return a;let c=Rj(t.changelog,e.name),l=t.manifestSource!==null&&t.manifestSource!==e.name?[`vendor/ was last synced from ${t.manifestSource}, not ${e.name}: this sync replaces it`]:[],u=n.map(Sj).filter(f=>f!==null),m=t.entries.some(f=>f.scope==="prune"&&f.tracked.length>0)?["vendored modules removed: run pnpm install to update the lockfile"]:[];return{...a,status:"changed",message:`${Ej(n)} on ${t.branch}`,notes:[...u,...m,...xj(t),...i?["vendor/README.md and manifest rewritten"]:[],...c.notes],warnings:[...l,...c.warnings],recoveryPaths:Pj(n,t,o)}},hc=(e,t)=>{switch(t.kind){case"missing":return Ur(t,"skipped",`not checked out at ${t.root}`);case"source":return Ur(t,"skipped","this is the source repo");case"not-git":return Ur(t,"fail",`not a git repo: ${t.reason}`);case"bad-selection":return Ur(t,"fail",`vendorTarget: ${t.reason}`);case"repo":return Tj(e,t)}};import{existsSync as _j,readFileSync as Mj,realpathSync as yc}from"node:fs";import vc from"node:path";import{readFileSync as Eb}from"node:fs";import Zn from"node:path";var Cj=["dependencies","devDependencies","peerDependencies","optionalDependencies"],$j=e=>{let t=e.flatMap(({entry:r})=>r.module===null?[]:[r.module]);return[...new Set(t)].sort()},Pb=(e,t)=>{if(t.kind==="invalid")return{reason:t.reason};let r=$j(e);if(t.kind==="modules"){let n=t.modules.filter(o=>!r.includes(o));if(n.length>0){let o=r.length>0?r.join(", "):"none";return{reason:`unknown module(s) ${n.join(", ")} in vendorTarget.modules; the source offers: ${o}`}}}return e.map(({entry:n})=>n.module===null||t.kind==="all"||t.modules.includes(n.module)?"sync":n.vendored?"prune":"release")},xb=e=>{try{return JSON.parse(Eb(e,"utf8"))}catch{return null}},Aj=(e,t)=>t.files.flatMap(r=>{let n=Zn.posix.relative(t.entry.path,r.path);if(Zn.posix.basename(n)!=="package.json"||n.split("/").length>2)return[];let o=xb(Zn.join(e,r.path))?.name;return typeof o=="string"?[o]:[]}),Oj=e=>Cj.flatMap(t=>{let r=e[t];return r!==null&&typeof r=="object"?Object.keys(r):[]}),Tb=(e,t)=>{let r=e.indexOf(t);for(;r>=0;){if(!/[\w-]/.test(e[r+t.length]??""))return!0;r=e.indexOf(t,r+1)}return!1},Dj=["*.sh","*.yml","*.yaml"],Ij=(e,t,r)=>{let n=Oj(t).includes(r)?[`${e} depends on ${r}`]:[],o=t.scripts!==null&&typeof t.scripts=="object"?t.scripts:{};for(let[s,i]of Object.entries(o))typeof i=="string"&&Tb(i,r)&&n.push(`${e} script "${s}" runs ${r}`);return n},Nj=async(e,t,r)=>{let n=["grep","-z","-l","-F","-e",t,"--",...Dj];return st(await Z(e,n,{allowFailure:!0})).filter(s=>r(s)&&Tb(Eb(Zn.join(e,s),"utf8"),t)).map(s=>`${s} uses ${t}`)},Cb=async(e,t,r)=>{let n=new Map;for(let{facts:c}of r)for(let l of Aj(e,c))n.set(l,c.entry.module??"");if(n.size===0)return[];let o=r.map(({target:c})=>`${c}/`),s=c=>!o.some(l=>c.startsWith(l)),i=st(await Z(t,["ls-files","-z","--","*package.json"])).filter(c=>Zn.posix.basename(c)==="package.json"&&s(c)),a=[];for(let[c,l]of n){let u=i.flatMap(p=>{let m=xb(Zn.join(t,p));return m===null?[]:Ij(p,m,c)});u.push(...await Nj(t,c,s));for(let p of u)a.push(`${p}: add "${l}" to vendorTarget.modules or stop using it`)}return a.sort()};var ym=async(e,t)=>{let r=t.exclude??[],n=(await Z(e,["rev-parse","HEAD"])).trim(),o=await De(e),s=await Promise.all(gb(t).map(async i=>{let a=await lm(e,i.path,r);return{entry:i,files:a.map(c=>ub(e,c))}}));return{root:e,selfRoots:[...new Set([yc(e),yc(o)])],name:vc.basename(o),headSha:n,entries:s,exclude:r}},wc=e=>{let t=st(e)[Symbol.iterator](),r=[];for(let n of t)r.push(n.slice(3)),/^[RC]|^.[RC]/u.test(n)&&t.next();return r},jj=async(e,t,r)=>{let n=hm(e,t);if(n.length===0)return[];let o=await Z(r,["--literal-pathspecs","status","--porcelain","-z","--untracked-files=all","--",...n]);return wc(o).filter(s=>!Js(s,e.exclude))},Fj=async(e,t,r)=>Promise.all(e.entries.map(async({entry:n,files:o},s)=>{let i=t[s],a=await lm(r,n.target,e.exclude),c={},l=i==="sync"?o:[];for(let u of Ks(l,e.exclude)){let p=fc(u.path,n);c[p]=pc(vc.join(r,p))}return{target:n.target,scope:i,tracked:a.map(u=>u.path),onDisk:c}})),Lj=async e=>{try{return st(await Z(e,["--literal-pathspecs","ls-tree","-z","--name-only","HEAD","--",lr,Vs]))}catch{return[]}},Bj=e=>{try{let{commit:t,source:r}=js(vc.join(e,ie));return{commit:t,source:r}}catch{return null}},Uj=async(e,t,r)=>{if(r===null)return{kind:"unknown-sha"};if(await Ae(e.root,r)===null)return{kind:"unresolvable",sha:r};let n=e.entries.filter((i,a)=>t[a]==="sync").map(({entry:i})=>i.path);if(n.length===0)return{kind:"log",sha:r,lines:[]};let s=(await Z(e.root,["--literal-pathspecs","log","--oneline",`${r}..HEAD`,"--",...n])).split(`
475
+ `).filter(i=>i.length>0);return{kind:"log",sha:r,lines:s}},Wj=(e,t)=>{try{return Mj(vc.join(e,lr),"utf8")===gc(t)}catch{return!1}},Gj=async e=>{try{return{toplevel:(await Z(e,["rev-parse","--show-toplevel"])).trim()}}catch(t){return{reason:String(t.stderr??t).trim().split(`
476
+ `)[0]??"git rev-parse failed"}}},Vj=async e=>{try{return(await Z(e,["rev-parse","--abbrev-ref","HEAD"])).trim()}catch{return"HEAD"}},kc=async(e,t)=>{if(!_j(t.root))return{...t,kind:"missing"};let r=yc(t.root);if(e.selfRoots.includes(r))return{...t,kind:"source"};let n=await Gj(t.root);if("reason"in n)return{...t,kind:"not-git",reason:n.reason};if(yc(n.toplevel)!==r)return{...t,kind:"not-git",reason:`it sits inside the repo at ${n.toplevel}`};let o=Pb(e.entries,t.selection??{kind:"all"});if("reason"in o)return{...t,kind:"bad-selection",reason:o.reason};let s=Bj(t.root),i=s?.commit??null,[a,c,l,u,p]=await Promise.all([Vj(t.root),jj(e,o,t.root),Fj(e,o,t.root),Lj(t.root),Uj(e,o,i)]),m=l.flatMap((f,h)=>f.scope==="prune"&&f.tracked.length>0?[{facts:e.entries[h],target:f.target}]:[]);return{...t,kind:"repo",branch:a,dirty:c,entries:l,headVendorMeta:u,readmeCurrent:Wj(t.root,e.name),manifestPresent:s!==null,manifestSource:s?.source??null,changelog:p,pruneConflicts:await Cb(e.root,t.root,m)}};var Jj=20,Kj=(e,t)=>!t.commit||e.status!=="changed"||e.branch===void 0?e.notes:[...e.notes,`--commit lands on ${e.branch}`],Hj=(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:",Ge(Xn(r))]};let o=e.applied?`wrote ${r.message}`:r.message;return{name:n,status:r.status,message:o,notes:t.mode==="applied"?r.notes:Kj(r,t)}},qj=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(`
477
+ `).slice(0,Jj)},Yj=(e,t)=>{let r=e.plan.warnings.map(n=>({name:"changelog",status:"warn",message:n}));return{label:e.plan.name,rows:[Hj(e,t),...r,...e.commit?[qj(e.commit)]:[]]}},zj={preview:"infra-kit vendor sync (preview)",check:"infra-kit vendor sync --check",applied:"infra-kit vendor sync"},vm=(e,t,r)=>{let n=r.mode==="preview"?["re-run with --yes from a real terminal to apply"]:[];return{title:zj[r.mode],sections:[{label:"source",rows:[...e]},...t.map(o=>Yj(o,r))],hints:n}},$b=e=>e.sections.some(t=>t.rows.some(r=>r.status==="fail")),Ab=(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 Xj=20,wm=async(e,t)=>(await Z(e,t,{allowFailure:!0})).trim(),Zj=async e=>wc(await Z(e,["status","--porcelain","-z","--untracked-files=normal"])),Qj=async e=>(await wm(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"]},eF=async e=>{let[t,r]=await Promise.all([wm(e,["symbolic-ref","--quiet","--short","refs/remotes/origin/HEAD"]),wm(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}`}},Ob=async e=>{let t=await Zj(e);if(t.length>0){let n=t.slice(0,Xj),o=t.length>n.length?`, and ${t.length-n.length} more`:"";throw new D({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([Qj(e),eF(e)]);return[{name:"working tree",status:"ok",message:"clean"},...r.filter(n=>n!==null)]};import oF from"node:path";import{readFileSync as tF}from"node:fs";import rF from"node:path";import{z as nF}from"zod";var Db=e=>{let t;try{t=tF(rF.join(e,"infra-kit.json"),"utf8")}catch{return{kind:"all"}}let r;try{r=JSON.parse(t)?.vendorTarget}catch(o){return{kind:"invalid",reason:`infra-kit.json is not valid JSON: ${o.message}`}}if(r===void 0)return{kind:"all"};let n=Tf.safeParse(r);return n.success?{kind:"modules",modules:n.data.modules}:{kind:"invalid",reason:nF.prettifyError(n.error)}};var Ib=(e,t)=>{let r=t.filter(s=>!e.targets.includes(s));if(r.length>0)throw new D({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=>{let i=oF.join(n,s);return{name:s,root:i,selection:Db(i)}})},sF="rewrite vendor/README.md and vendor/.sync-manifest.json from the tracked vendor/ files",iF=async(e,t)=>{let r=await kc(e,t),n=hc(e,r);return r.kind!=="repo"||n.status==="fail"?n:{...n,status:"changed",message:`${sF} on ${r.branch}`,notes:[],warnings:[],branch:r.branch,entries:[],writeVendorMeta:!0,recoveryPaths:r.headVendorMeta}},Nb=async(e,t,r)=>Promise.all(t.map(async n=>r?iF(e,n):hc(e,await kc(e,n))));var Fb="sync vendored files",uF=e=>{let t=Mb.join(On(e.workspaceDir),e.source);if(aF(t))return t;throw new D({status:"refused",reason:"source-missing",source:t},1,{operation:Fb,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'})},km=(e,t)=>new D({status:"refused",reason:"not-a-vendor-source"},1,{operation:Fb,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`}),dF=async e=>{let t=Mb.join(e,"infra-kit.json"),r;try{r=JSON.parse(await cF.readFile(t,"utf8"))}catch(s){throw km(t,`is unreadable: ${s instanceof Error?s.message:String(s)}`)}let n=r?.vendorSource;if(n==null)throw km(t,"has no vendorSource block");let o=xf.safeParse(n);if(!o.success)throw km(t,`has an invalid vendorSource: ${lF.prettifyError(o.error)}`);return o.data},_b=(e,t)=>{jb.stderr.write(`${e.name}: if this run dies, restore the tracked paths with:
478
+ ${Ge(t)}
479
+ `)},pF=async(e,t,r)=>r?(_b(t,Xn(t)),dm(t.root,e)):(await um({source:e,plan:t,onBeforeFirstWrite:o=>{_b(t,o)}})).touched,mF=async(e,t,r)=>{if(t.status!=="changed")return{plan:t,applied:!1};let n;try{n=await pF(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 mm(t.root,n,pm(e.name,e.headSha));return{plan:t,applied:!0,commit:o}},fF=async(e,t,r)=>{let n=[];for(let o of t)n.push(await mF(e,o,r));return n},Lb=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})),bm=({mode:e,report:t,outcomes:r,source:n,print:o})=>{o&&ft(t);let s=r.map(a=>a.plan);return{structuredContent:{mode:e,source:{root:n.root,name:n.name,headSha:n.headSha},targets:Lb(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:$b(t),report:t.sections}}},gF=async e=>{let t=await sa(),r=uF(t),n=await Ob(r),o=await dF(r),s=Ib(t,e.targets??[]),i=await ym(r,o),a=await Nb(i,s,!!e.manifestOnly);return{source:i,sourceRows:n,plans:a}},Rm=async(e={})=>{let{source:t,sourceRows:r,plans:n}=await gF(e),o=n.map(m=>({plan:m,applied:!1})),s={commit:e.commit,manifestOnly:e.manifestOnly},i=e.check?"check":"preview",a=vm(r,o,{...s,mode:i}),c=!n.some(m=>m.status==="changed");if(e.check||c)return bm({mode:i,report:a,outcomes:o,source:t,print:!0});let l=!e.confirmedCommand&&!Q();if(l&&!jb.stdin.isTTY)return ft(a),bm({mode:"preview",report:a,outcomes:o,source:t,print:!1});l&&ft({...a,hints:[]}),await H(e.confirmedCommand,`Sync vendored files from ${t.name} into these targets?`,{plan:Lb(n),throwOnDecline:!0});let u=await fF(t,n,e),p=vm(r,u,{...s,mode:"applied"});if(l){let m=u.filter(f=>f.applied).map(f=>f.plan.name);ft(Ab(a,p,m))}return bm({mode:"applied",report:p,outcomes:u,source:t,print:!l})};var bc=(e,t=!0)=>({line:e,reproducible:t});import Rc from"node:fs";import hF from"node:os";import yF from"node:path";import Gb from"node:process";var Sc="INFRA_KIT_SESSION_REPORT",Sm=null,Bb=!1,Ub=[],Vb=(e=Gb.env)=>{Bb||(Sm=e[Sc]??null,Bb=!0,delete e[Sc])};var Jb=(e,t)=>{if(!Sm)return;let r=e.summary??(Ub.length>0?[...Ub]:void 0),n={...e,...r?{summary:r}:{}},o=t?.write??((s,i)=>{Rc.writeFileSync(s,i)});try{o(Sm,JSON.stringify(n))}catch{}},Wb=0,Kb=e=>{let t=e?.tmpdir?.()??hF.tmpdir(),r=e?.pid??Gb.pid;return Wb+=1,yF.join(t,`infra-kit-session-${r}-${Wb}.json`)},Hb=(e,t)=>{if(!(t?.exists??(i=>Rc.existsSync(i)))(e))return null;let n=t?.read??(i=>Rc.readFileSync(i,"utf-8")),o=t?.unlink??(i=>Rc.unlinkSync(i)),s;try{s=n(e)}catch{return null}finally{try{o(e)}catch{}}try{return JSON.parse(s)}catch{return null}};var Em=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");for(let r of e.commands)Em(r)};var Pm=e=>{e.options.some(r=>r.long==="--debug")||e.option("--debug","Raise the log level to debug (logs stay on stderr)");for(let r of e.commands)Pm(r)};var bF=(e,t)=>[...t,e],RF=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 Wh(()=>Ea({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}));I(r),r.structuredContent.failedMerges>0&&(Be.exitCode=1)}),Yb=e=>(Be.stdout.write(`${e.structuredContent.filePath}
480
+ `),I(e)),SF=e=>e.description("List all release branches").action(async()=>{I(await _a())}),EF=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".',bF,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let n=t.release.map(Yu),o=n.length>0?n:void 0;I(await Fa({releases:o,confirmedCommand:t.yes}))}),PF=e=>{if(e==="")return e;try{return Cr(e)}catch(t){throw t instanceof Fn?new zb(t.message):t}},xF=e=>{let t=Number(e);if(!Number.isInteger(t)||t<=0)throw new zb("Expected a positive whole number of days.");return t},TF=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)',PF).option("-y, --yes","Skip confirmation prompt").action(async t=>{I(await La({version:t.version,description:t.description,releaseDate:t.releaseDate,confirmedCommand:t.yes}))}),Xb=e=>e.option("-f, --from <where>",`Where the deploy runs: ${nr.join(" | ")} (required)`).option("-v, --version <version>",'With --from ci: version (e.g. 1.2.5) or release name to deploy; "dev" ("main" with gitFlow main) deploys from that 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"),CF=e=>Xb(e).description("Deploy every service to any environment, in CI or from this machine").action(async t=>{I(await om({from:t.from,version:t.version,env:t.env,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),$F=e=>Xb(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=>{I(await sm({from:t.from,version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),AF=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=>{I(await xa({version:t.version,confirmedCommand:t.yes}))}),OF=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=>{I(await Wa({version:t.version,moveIssuesTo:t.moveIssuesTo,skipJira:t.skipJira,confirmedCommand:t.yes}))}),DF=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{I(await oc({confirmedCommand:t.yes}))}),IF=e=>e.description("Add git worktrees for release branches or feature branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-f, --feature <names>","Feature worktrees by comma, each on a feature/<name> branch, e.g. checkout-v2").option("-b, --base <branch>","Base for new feature branches: dev (default; the default branch without one), main, or a release, e.g. 1.4.0").option("-g, --github-desktop","Open created worktrees in GitHub Desktop").option("--no-github-desktop","Skip GitHub Desktop prompt").option("--orca","Open created worktrees in Orca (pane layout from worktrees.orca.layout)").option("--no-orca","Skip the Orca prompt").action(async t=>{I(await ec({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature,base:t.base,githubDesktop:t.githubDesktop,orca:t.orca}))}),NF=e=>e.description("List all git worktrees with detailed information").action(async()=>{I(await tc())}),_F=e=>e.description("Remove git worktrees for release or feature branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release and feature worktrees").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-f, --feature <names>","Feature worktrees by comma, e.g. checkout-v2").option("--self","Remove the worktree this runs in, closing its Orca tabs (handed off to Orca)").action(async t=>{I(await nc({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature,self:t.self}))}),MF=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=>{I(await am({init:t.init}))}),jF=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await Xa();I(t),t.structuredContent.ok||(Be.exitCode=1)}),FF=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 Rm({targets:t,confirmedCommand:r.yes,check:r.check,commit:r.commit,manifestOnly:r.manifestOnly})}catch(a){if(!xt(a))throw a;d.info("Operation cancelled.");return}I(n);let{failed:o,changed:s,mode:i}=n.structuredContent;(o||i==="check"&&s)&&(Be.exitCode=1)}),LF=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{I(await Wp())}),BF=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{I(await Gp())}),UF=new Set(["version"]),Ec=e=>{let t=[];for(let r=e;r&&r.parent;r=r.parent)t.unshift(r.name());return t.join(" ")},xm=()=>{let e=new vF().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");RF(t.command("merge-dev")),SF(t.command("list")),EF(t.command("create")),TF(t.command("edit")),CF(t.command("deploy-all")),$F(t.command("deploy-selected")),AF(t.command("deliver")),OF(t.command("remove"));let r=e.command("worktrees").description("Git worktree management commands");IF(r.command("add")),NF(r.command("list")),_F(r.command("remove")),DF(r.command("sync"));let n=e.command("config").description("Manage infra-kit configuration files");LF(n.command("path")),BF(n.command("edit")),e.command("config-get").description("Print the fully merged infra-kit config (project + user-global + per-project override layers)").argument("[key]","Print only this top-level key (e.g. worktrees)").action(async a=>{I(await Bi({key:a}))}),e.command("config-set").description("Set a top-level key in this project\u2019s per-machine config override (validated before it is kept)").argument("<key>","Top-level config key (e.g. protectedEnvs, worktrees)").argument("<value>",`JSON value, or a bare string (e.g. cli-only, '{"openInOrca":true}')`).option("--global","Write ~/.infra-kit/infra-kit.json (every project on this machine) instead").action(async(a,c,l)=>{I(await Gl({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)=>{I(await Vp({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=>{I(await dc({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=>{I(await dc({env:a.env,services:a.service,yes:a.yes,dryRun:a.dryRun,printEnv:a.printEnv},"selected"))}),e.command("audit").description("Audit against infra-kit.config.ts rules (--all for every package, --root for the monorepo root)").option("-a, --all","Audit every non-vendor workspace package").option("-r, --root","Audit the monorepo root (turbo pipeline + root commands)").option("--fix","Write the infra-kit guidance block into CLAUDE.md for the audited scope before checking (CLI-only)").option("--design","With --fix: scaffold DESIGN.md for frontend/mobile packages that lack one").action(async a=>{if(a.design&&!a.fix){d.error("--design requires --fix (it scaffolds DESIGN.md; there is nothing to scaffold without a fix run)"),Be.exitCode=1;return}let c=await Ii({all:a.all,root:a.root,fix:a.fix,design:a.design});I(c);let{allPassed:l,fixed:u}=c.structuredContent,p=(u??[]).some(m=>m.action==="failed");(!l||p)&&(Be.exitCode=1)}),e.command("deploy-run").description("Deploy a service: its deploy.ts from infra-kit.deploy.ts, else its devops/scripts .sh (what the CI deploy job runs)").argument("<service>","The service as infra-kit.deploy.ts names it, e.g. client-be").action(async a=>{I(await zp({service:a}))}),e.command("deploy-sync").description("Generate the deploy-all / deploy-selected workflows from infra-kit.deploy.ts").option("--check","Compare only; exit 1 when the committed workflows differ from the manifest").action(async a=>{let c=await Zp({check:a.check});I(c),c.structuredContent.ok||(Be.exitCode=1)});let i=e.command("vendor").description("Mirror and verify the vendored starter files");jF(i.command("check")),MF(i.command("config")),FF(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 ga({fix:!!a.fix});dr.enabled||Ql(c.structuredContent.checks,{ascii:!!a.ascii}),c.structuredContent.checks.some(u=>u.name==="plugin installed"&&u.status==="fail")&&(Be.exitCode=1),I(c)}),e.command("dev").description("Run local dev servers for an app (or every app); api + ui").argument("[app]","An app \u2014 its api/ui plus the backends its routes can run locally (omit to run every app)").option("-w, --watch","Rebuild and restart on file save (the default)").option("--no-watch","Build once and never restart on save").option("--app <names>","Further narrow to these app folder names (comma-separated)").option("--target <keys>","Run exactly these <app>/api|<app>/ui packages (comma-separated); part-level, unlike --app").option("--orca","Run each app in its own Orca pane (one tab, N panes; falls back to single terminal when Orca is not running)").option("--self","Run only the app of the current directory (infer from cwd; use inside apps/<app>/\u2026)").option("-V, --verbose","Print full boot narration (default: quiet; full detail always in the session log)").option("--routes","Print each app\u2019s registered METHOD /path routes at startup (default: off)").option("--reuse","For test runners: start nothing when this worktree already serves one of these apps, exit on a boot failure").option("--no-ui-health","Do not probe the frontends\u2019 liveness (vite\u2019s HMR ping); their rows carry no health dot (also: INFRA_KIT_NO_UI_HEALTH=1)").action(async(a,c)=>{let{runDevServerCli:l}=await import("./dev-server.js"),u=!!(Be.stdout.isTTY&&Be.stdin.isTTY);await l({...c,appName:a},u,dr.enabled)}),e.command("dev-status").description("Show what `infra-kit dev` currently has running (reads dev-context fragments; starts nothing)").action(async()=>{I(await Ui())}),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)=>{I(await wa({app:c.app,dryRun:c.dryRun,yes:c.yes,cloud:c.cloud,playwrightArgs:a}))}),e.command("setup").description("Set this machine up: shell integration, agent files, the Claude Code skills plugin, then the external tools").option("--tools <ids...>","Limit to these tools (brew, git, aws, gh, doppler, portless)").option("--update [ids...]","Update what is already installed; never install a missing tool").option("--skip-tools","Do the local setup only, then REPORT what each tool needs \u2014 installs nothing").option("--ascii","Render the report with ASCII markers instead of unicode glyphs (row messages are unchanged)").addOption(new qb("--unattended","Background run: no tool installs, no writes to git-tracked files").hideHelp()).addOption(new qb("--auto","Unattended setup for the machine and every infra-kit project, once per version").hideHelp()).action(async a=>{if(a.auto){I(await pp());return}I(await Ka({tools:a.tools,update:a.update,skipTools:a.skipTools,ascii:!!a.ascii,unattended:a.unattended}))}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{I(await Za())}),e.command("change-stats").description("Change-failure baseline for this git repo: agent vs human commits, revert and 72h follow-up-fix rates").option("--since <days>",`Window in days, ending now (default ${$o})`,xF).action(async a=>{I(await ji({since:a.since}))}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{I(await Ra())}),e.command("env-list").description("List available Doppler configs for the detected project, and whether a service token resolves for each").action(async()=>{I(await og())}),e.command("env-load").description("Load Doppler env vars for a config. Source the returned file path to apply.").option("-c, --config <config>","Environment config name to load (e.g. dev, arthur). Omitted: the picker opens on defaultEnv; headless runs load it").action(async a=>{Yb(await Vc({config:a.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{Yb(await ba())}),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.");I(await rm({fromFile:c.fromFile,force:c.force}));return}I(await tm({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=>{I(await Sa({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=>{I(await Qp({env:a}))});for(let a of e.commands)lf(a);return Em(e),Pm(e),e.hook("preAction",async(a,c)=>{let{C:l}=e.opts();l!==void 0&&kF(wF(Be.cwd(),l)),y.start(Ec(c)),dr.enabled=!!c.optsWithGlobals().json,dr.enabled&&(d.level="warn"),F.source=si({env:Be.env,stdinIsTTY:Be.stdin.isTTY===!0,flag:!!c.optsWithGlobals().agent}),UF.has(Ec(c))||await $u()}),e.hook("postAction",(a,c)=>{let l=Ec(c);if(Lp(l))return;let p=y.snapshot()?.formattedOptions??"",m=p?` ${p}`:"",f=`infra-kit ${l}${m}`;Jb({equivalent:bc(f,!0)})}),e};import WF from"node:process";var GF={exit:WF.exit,emit:I,logger:d},Zb=(e,t=GF)=>Ie(e)?(t.logger.info("Operation cancelled."),t.exit(0)):e instanceof D?(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 Tm=(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 VF from"node:fs";import Cm from"node:path";import Qn from"node:process";var tR=new Set([...Pf,to,"XDG_CACHE_HOME","CLAUDE_PROJECT_DIR","CLAUDE_PLUGIN_ROOT"]),rR=null,Pc=new Set,$m=null,Qb=!1;var eR=e=>{try{return VF.statSync(e)}catch{return null}},JF=()=>{if(Qb)return null;try{return Vr()}catch{return Qb=!0,d.debug(`session-env: ${to} unset \u2014 no overlay`),null}},KF=e=>{let t=Cm.join(e,Wr),r=Cm.join(e,Ys),n=eR(t),o=eR(r);return n&&!(o&&o.mtimeMs>n.mtimeMs)?Lm(Cm.join(e,zs),Qn.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"}},HF=e=>e.kind==="load"?{kind:"load",vars:jm(e.file),signature:e.signature}:e.kind==="clear"?{kind:"clear",unset:Fm(e.file),signature:e.signature}:e;var qF=()=>{let e=JF();if(e===null)return{kind:"no-session"};let t=KF(e);return t.signature===$m?null:HF(t)},YF=()=>{for(let e of Pc){let t=rR[e];t===void 0?delete Qn.env[e]:Qn.env[e]=t}Pc.clear()},zF=(e,t,r)=>{if(tR.has(t)){e.skipped.push(t);return}Qn.env[t]=r,Pc.add(t),e.set.push(t)},XF=(e,t)=>{if(tR.has(t)){e.skipped.push(t);return}delete Qn.env[t],Pc.add(t),e.unset.push(t)},ZF=e=>{let t={set:[],unset:[],skipped:[]};if(e.kind==="load")for(let[r,n]of Object.entries(e.vars))zF(t,r,n);if(e.kind==="clear")for(let r of e.unset)XF(t,r);return t},QF=e=>e.kind==="load"?`load, ${Object.keys(e.vars).length} vars`:e.kind,Am=(e=qF())=>{if(rR??={...Qn.env},e===null||e.kind==="no-session"||e.signature===$m)return{set:[],unset:[],changed:!1};YF();let{set:t,unset:r,skipped:n}=ZF(e);return $m=e.signature,n.length>0&&d.warn(`session-env: skipped protected names [${n.join(", ")}]`),d.debug(`session-env applied: set [${t.join(", ")}] unset [${r.join(", ")}] (${QF(e)})`),{set:t,unset:r,changed:!0}};import{chalkStderr as kL}from"chalk";import{spawn as bL}from"node:child_process";import Ue from"node:process";import{Chalk as eL}from"chalk";var eo=new eL({level:1}),it={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."},tL={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"}},nR={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},oR={unicode:"\u2500",ascii:"-"},rL=3,Om=e=>e,nL={ok:e=>eo.green(e),findings:e=>eo.yellow(e),failed:e=>eo.red(e),cancelled:e=>eo.gray(e)},Im=e=>e?{dim:t=>eo.dim(t),bold:t=>eo.bold(t)}:{dim:Om,bold:Om},oL=(e,t)=>e?nL[t]:Om,Dm=e=>[...e].length,sL=(e,t)=>{if(t==null)return e;let r=Math.max(0,t-1);return Dm(e)<=r?e:[...e].slice(0,r).join("")},sR=e=>{let t=Im(e.color===!0).dim,r=tL[e.canSuspend?"suspend":"plain"],n=e.ascii===!0?r.ascii:r.unicode;return t(sL(n,e.width))},iR=(e,t={})=>{let r=Im(t.color===!0);return`${r.dim(it.reproPrefix.trim())} ${r.bold(e)}`},iL=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,aL=(e,t)=>e==="findings"?t!=null?`${t} ${it.findingsSuffix}`:it.findingsPlain:{ok:it.ok,failed:it.failed,cancelled:it.cancelled}[e],cL=(e,t,r,n)=>{if(t==null)return"";let o=t-2-e;return o<rL?"":` ${n(r.repeat(o))}`},aR=e=>{let t=e.color===!0,r=Im(t),n=oL(t,e.outcome),o=e.ascii===!0,s=e.equivalent.reproducible?it.reproPrefix:it.nonReproPrefix,i=o?nR[e.outcome].ascii:nR[e.outcome].unicode,a=aL(e.outcome,e.findingsCount),c=[iL(e.durationMs)],l=e.summary?.[0]?.split(`
481
+ `)[0];l!=null&&l.length>0&&c.push(l);let u=`${i} ${a}`,p=`${it.sep}${c.join(it.sep)}`,m=Dm(u)+Dm(p),f=cL(m,e.width,o?oR.ascii:oR.unicode,r.dim),h=[`${n(u)}${r.dim(p)}${f}`];return e.showEquivalent!==!1&&h.unshift(`${r.dim(s.trim())} ${r.bold(e.equivalent.line)}`),e.envNotice===!0&&h.push(r.dim(it.envNotice)),h.join(`
482
+ `)};var lL=new Set([130,143]),cR=(e,t,r,n=!1)=>r?t!=null||e===0?"ok":"findings":n&&e!=null&&lL.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import uL from"node:process";var dL={3:"quit",4:"quit",26:"suspend",27:"quit"},pL=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":dL[t]??"continue"},mL=150,fL="\r\x1B[2K",gL=`\r
483
+ `,lR=(e,t)=>{uR(e),e.stdin.on("data",t),e.listener=t},uR=e=>{e.listener!==null&&(e.stdin.off("data",e.listener),e.listener=null)},dR=(e,t)=>{_f(),e.stdin.setRawMode(!0),e.stdin.isPaused()&&e.stdin.resume(),lR(e,t)},pR=e=>{e.hintOnScreen&&(e.hintOnScreen=!1,e.deps.write(fL)),uR(e),e.stdin.isTTY===!0&&e.stdin.isRaw===!0&&e.stdin.setRawMode(!1),Mf()},hL=e=>{e.settled||(e.settled=!0,pR(e))},mR=(e,t)=>{let r=sR({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},yL=async e=>{await new Promise(t=>{setTimeout(t,e)})},vL=(e,t,r)=>{pR(e),t(),dR(e,r),mR(e,gL)},wL=async e=>new Promise(t=>{let r=n=>{let o=pL(n),s=e.deps.suspend;if(o==="quit"){t("quit");return}if(o==="suspend"&&s!==void 0){vL(e,s,r);return}t("palette")};lR(e,r),mR(e,"")}),fR=async(e,t)=>{if(e.quitRequested())return"quit";let r=t.stdin??uL.stdin;if(r.isTTY!==!0)return"palette";let n={deps:t,stdin:r,listener:null,hintOnScreen:!1,settled:!1};try{return dR(n,()=>{}),e.armed(),await yL(t.drainMs??mL),await wL(n)}finally{hL(n)}};import gR from"node:process";var ur={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},hR=(e,t)=>{let r=t?.write??(s=>{gR.stderr.write(s)}),n=t?.stdin??gR.stdin,o=[ur.saveCursor,ur.scrollRegion,ur.restoreCursor,ur.column,ur.sgr,ur.cursor,ur.wrap];e.entersAltScreen===!0&&o.push(ur.primaryBuffer),r(o.join("")),n.isTTY===!0&&n.isRaw===!0&&n.setRawMode?.(!1)};var yR=e=>`infra-kit ${e.groupPath.join(" ")}`,RL=()=>{SL();let e=Ue.stderr.columns;return e!=null&&e>0?e:void 0},SL=()=>{let e=Ue.stderr;typeof e._refreshSize=="function"&&e._refreshSize()},EL=e=>new Promise(t=>{e.on("exit",(r,n)=>{t({code:r,signal:n})}),e.on("error",()=>{t({code:1,signal:null})})}),PL=async(e,t,r)=>{let n=Kb(),o={...t.env,[Sc]:n,INFRA_KIT_NO_AUTO_UPDATE:"1"},s=t.now(),i={code:1,signal:null};r();try{let p=t.spawn(Ue.execPath,[t.cliPath,...e.groupPath],{stdio:"inherit",env:o});i=await EL(p)}catch{i={code:1,signal:null}}finally{t.resetTerminal({entersAltScreen:e.entersAltScreen})}let a=Hb(n),c=cR(i.code,i.signal,a!=null,e.longRunning),l=yR(e),u=a?.equivalent??bc(l,!0);return aR({equivalent:u,outcome:c,durationMs:t.now()-s,summary:a?.summary,envNotice:e.sessionEnvNotice,ascii:t.ascii,color:t.color,width:t.columns(),showEquivalent:!(u.reproducible&&u.line===l)})},xL=1e3,TL=(e,t)=>e!=null&&t-e<=xL,Nm=e=>{e.resetTerminal(),e.exit(0)},CL=(e,t)=>{let r=null,n=!1,o=()=>{let c=e();if(c==="child"){r=t.now();return}c!=="pause"&&Nm(t)},s=()=>{let c=e();if(c==="palette"){Nm(t);return}if(!TL(r,t.now())){if(c==="pause"){Nm(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}},vR=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),$L=Ue.platform==="win32"?void 0:()=>{jf()},AL=(e,t)=>r=>fR(r,{write:e,columns:t.columns,ascii:t.ascii,color:t.color,suspend:$L}),wR=async(e,t)=>{let r={spawn:t.spawn??bL,now:t.now??(()=>Date.now()),env:t.env??Ue.env,cliPath:t.cliPath,ascii:t.ascii??!(Ue.stdout.isTTY&&Ue.env.TERM!=="dumb"),color:t.color??kL.level>0,columns:t.columns??RL,resetTerminal:t.resetTerminal??(u=>{hR(u)})},n=t.write??(u=>Ue.stderr.write(u)),o="palette",s=t.signals??{register:(u,p)=>{Ue.on(u,p)},unregister:(u,p)=>{Ue.off(u,p)},exit:u=>{Ue.exit(u)},raise:u=>{Ue.kill(Ue.pid,u)},now:()=>Date.now(),resetTerminal:()=>{o==="pause"&&n("\r\x1B[2K"),r.resetTerminal({entersAltScreen:!1})}},i={dispose:()=>{},childStarted:()=>{},quitRequested:()=>!1},a=t.installSignals===!1?i:CL(()=>o,s),c={armed:()=>{o="pause"},quitRequested:()=>a.quitRequested()},l=t.afterRun??AL(n,r);try{for(;;){if(a.quitRequested())return;o="palette";let u=await t.renderPalette(e);if(u==null)return;let p=t.resolveCommand(u);if(!p)continue;let m=iR(yR(p),{color:r.color});n(`
475
484
  ${m}
476
- `),a.childStarted();let f=await hL(p,r,()=>{o="child"});if(n(`
485
+ `),a.childStarted();let f=await PL(p,r,()=>{o="child"});if(n(`
477
486
  ${f}
478
- `),await l(c)==="quit")return}}finally{a.dispose()}};Np();Bb();var wR=wm(),yR=async(e=Be.argv)=>{Sm(),xf(e);try{await wR.parseAsync(e)}catch(t){qb(t)}},xL=()=>{try{if(Be.env.INFRA_KIT_NO_LOCATION_WARN||Be.argv.includes("--json"))return;Mm({selfRealPath:EL(vR(import.meta.url)),cwd:Be.cwd(),env:Be.env,realpath:xe,home:PL(),exists:SL})&&d.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};xL();ef((e,t)=>{d.debug(e,t)});Eu(L.version);var kR=()=>Uk(wR.commands),TL=async()=>{let e=kR(),t=null;try{if(Be.stdout.isTTY&&Be.stdin.isTTY){let{runCommandPalette:r}=await import("./boot-ST2534PA.js");t=await r(e)}else{let r=km(e.map(o=>[o.name,o.description])),n=e.flatMap((o,s)=>[...e[s-1]?.group===o.group?[]:[new hR(" "),new hR(`\u2014 ${o.group} \u2014`)],{name:r[s]??o.name,value:o.name}]);t=await _(o=>RL({message:"Select a command to run",choices:n},o),{output:Be.stderr})}}catch(r){if(!Oe(r))throw r}return t},CL=async()=>{let{runCommandPalette:e}=await import("./boot-ST2534PA.js"),t=vR(import.meta.url),r=new Map(xr.map(n=>[n.groupPath.join(" "),n]));await gR(kR(),{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(Be.argv.length<=2){let e={stdoutIsTTY:!!Be.stdout.isTTY,stdinIsTTY:!!Be.stdin.isTTY,stderrIsTTY:!!Be.stderr.isTTY};if(fR(Be.env,e))await CL();else{let t=await TL();t&&await yR(["node","infra-kit",...t.split(" ")])}}else await yR();
487
+ `),await l(c)==="quit")return}}finally{a.dispose()}};Up();Vb();var SR=xm(),bR=async(e=We.argv)=>{Am(),If(e);try{await SR.parseAsync(e)}catch(t){Zb(t)}},_L=()=>{try{if(We.env.INFRA_KIT_NO_LOCATION_WARN||We.argv.includes("--json"))return;Gm({selfRealPath:IL(RR(import.meta.url)),cwd:We.cwd(),env:We.env,realpath:Ce,home:NL(),exists:DL})&&d.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};_L();cf((e,t)=>{d.debug(e,t)});Ou(U.version);var ER=()=>Jk(SR.commands),ML=async()=>{let e=ER(),t=null;try{if(We.stdout.isTTY&&We.stdin.isTTY){let{runCommandPalette:r}=await import("./boot-ST2534PA.js");t=await r(e)}else{let r=Tm(e.map(o=>[o.name,o.description])),n=e.flatMap((o,s)=>[...e[s-1]?.group===o.group?[]:[new kR(" "),new kR(`\u2014 ${o.group} \u2014`)],{name:r[s]??o.name,value:o.name}]);t=await M(o=>OL({message:"Select a command to run",choices:n},o),{output:We.stderr})}}catch(r){if(!Ie(r))throw r}return t},jL=async()=>{let{runCommandPalette:e}=await import("./boot-ST2534PA.js"),t=RR(import.meta.url),r=new Map(Ar.map(n=>[n.groupPath.join(" "),n]));await wR(ER(),{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(We.argv.length<=2){let e={stdoutIsTTY:!!We.stdout.isTTY,stdinIsTTY:!!We.stdin.isTTY,stderrIsTTY:!!We.stderr.isTTY};if(vR(We.env,e))await jL();else{let t=await ML();t&&await bR(["node","infra-kit",...t.split(" ")])}}else await bR();
479
488
  //# sourceMappingURL=cli.js.map