infra-kit 0.35.0 → 0.37.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 Sf,e as Vr,f as Of,g as Lt,h as oi,i as Df,j as If,k as Nf,l as _f,m as Mf,n as jf,o as Ff,p as Lf,s as Ic,t as Wf,u as Ae}from"./chunk-5SGMD57Z.js";import{a as Am,b as Be,c as Om,d as vc,e as Dm,f as Im,g as Nm,h as _m,i as Yn,j as Mm,k as jm,l as Fm,m as Lm,n as Bm,o as zn,p as Um,q as Wm,r as Vm,s as Gm,t as wc,u as Hs,v as Nt,w as Jm,x as qs,y as Km}from"./chunk-PP44RGIU.js";import{a as le,b as Y,c as jt,d as Qn,e as Ec,f as ei,g as ti,h as Pc,i as eo,j as ar,k as xc,l as ri,m as yf,n as kt,o as to,p as Cc,q as $c,r as Ac,s as xf,u as Oc}from"./chunk-QS7RKE5P.js";import{b as qn,c as Js,d as yc,e as Pm,f as Ks,g as xm,i as Tm,k as Cm,m as Ee,o as $m}from"./chunk-REDCBY4O.js";import{a as Rf}from"./chunk-V2ZLQPLI.js";import{B as no,D as _c,H as Mc,I as jc,a as b,b as C,c as Tf,d as Cf,e as cr,f as $f,g as lr,h as Af,i as Dc,j as Bf,k as ro,l as Bt,m as Gr,n as st,o as si,p as Ut,q as Uf,r as ii,s as Vf,t as Gf,u as it,y as Nc}from"./chunk-YVIJUGOB.js";import{a as y,b as bt,c as vf,d as wf,e as _,f as ni,g as G,i as Ft,j as Ze,k as Ef,l as Tc,m as Pf}from"./chunk-BYCCXWPB.js";import{$ as _t,A as Qm,B as ef,C as tf,D as Xs,E as Zs,F as xe,G as Xn,H as Wr,I as Qs,J as rf,K as nf,L as of,M as bc,N as Rc,O as sf,P as d,Q as Ue,R as ne,S as w,T as Xe,U as af,V as cf,W as lf,X as O,Y as df,Z as pf,_ as mf,a as ir,aa as ff,b as D,ba as Sc,c as Hm,ca as gf,d as j,da as hf,e as ge,ea as ee,f as Z,fa as H,g as Ys,ga as Zn,h as qm,ha as Mt,i as g,j as Ym,k as zs,l as Q,m as ve,n as Pe,o as zm,p as kc,q as ce,r as re,s as Br,t as Xm,u as ot,v as we,w as A,x as $e,y as Ur,z as Zm}from"./chunk-GDOQUC23.js";import{a as uf}from"./chunk-MFAFQVTW.js";import{a as L}from"./chunk-TFOXJRVH.js";import{a as Mr,b as Ls,c as Bs,d as Hn,e as km,f as jr,g as Us,h as Ws,i as bm,j as Vs,k as Gs,l as Rm,m as Sm,n as wt,o as Fr,p as It,q as fe,r as Em,s as Lr}from"./chunk-GCOYOWGH.js";import{a as kf,b as bf}from"./chunk-QWVLAZ6N.js";import QF,{Separator as eR}from"@inquirer/select";import{existsSync as eL,realpathSync as tL}from"node:fs";import{homedir as rL}from"node:os";import Le from"node:process";import{fileURLToPath as rR}from"node:url";import Jg from"node:process";import{z as Ie}from"zod";import Zf from"node:fs";import Kr from"node:path";import{packageConfigSchema as Hf}from"@slip-stream-kit/config/internal";import qf from"node:fs/promises";import ai from"node:path";import{pathToFileURL as dR}from"node:url";import{z as Yf}from"zod";import Jf from"node:path";var oo=["frontend","backend","lib","e2e","mobile"],sR={ui:"frontend",api:"backend",tests:"e2e"},iR="mobile-app",aR=[{type:"e2e",packages:["@playwright/test"]},{type:"mobile",packages:["@capacitor/core","@capacitor/cli"]},{type:"backend",packages:["serverless"]}],cR=(e,t)=>{let r=Jf.relative(t,e).split(Jf.sep).filter(s=>s!==""&&s!=="."),[n,,o]=r;if(r.length===3&&n==="apps"&&o!==void 0){let s=sR[o];if(s)return s}return r.at(-1)===iR?"mobile":null},lR=e=>{let t=new Set([...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{}),...Object.keys(e.peerDependencies??{})]);for(let n of aR)if(n.packages.some(o=>t.has(o)))return n.type;return t.has("vite")&&t.has("react")&&!!e.scripts?.dev?"frontend":null},so=({packageDir:e,repoRoot:t,pkgJson:r,declaredType:n})=>n??cR(e,t)??lR(r)??"lib";var at={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},Kf=2e3,Fc={"e2e-test":"pnpm exec playwright test","e2e-test-ui":"pnpm exec playwright test --ui","e2e-test-ui-demo":`E2E_SLOW_MO=\${E2E_SLOW_MO:-${Kf}} 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"},ur={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"]},io=(e,t=at)=>({requiredScripts:e.requiredScripts??[...t.requiredScripts],requiredFiles:e.requiredFiles??[...t.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...t.turboTasks]});import uR from"node:fs/promises";var Oe=async e=>{try{return await uR.access(e),!0}catch{return!1}};var ue="infra-kit.config.ts",dr=async e=>{try{let t=await qf.readFile(ai.join(e,"package.json"),"utf-8");return JSON.parse(t)}catch{return{}}},Lc=async e=>{let t=await qf.stat(e),o=(await import(`${dR(e).href}?mtime=${Number(t.mtimeMs)}`)).default;if(o===void 0)throw new Error(`${ue} at ${e} has no default export`);return typeof o=="function"?await o():o},Rt=async e=>{let t=ai.join(e,ue);if(await Oe(t))try{let n=(await Lc(t))?.type;return oo.find(o=>o===n)}catch{return}},zf=e=>e,ao=async(e,t=at)=>{let r=ai.join(e,ue);if(!await Oe(r))throw new Error(`${ue} not found at ${r}`);let n=await Lc(r),o=Hf.safeParse(n);if(!o.success)throw new Error(`Invalid ${ue} at ${r}: ${Yf.prettifyError(o.error)}`);return io(zf(o.data),t)},ct=async e=>{let t=ai.join(e,ue);if(!await Oe(t))return;let r=Hf.safeParse(await Lc(t));if(!r.success)throw new Error(`Invalid ${ue} at ${t}: ${Yf.prettifyError(r.error)}`);return zf(r.data)};import Xf from"node:fs/promises";import ci from"node:path";import pR from"yaml";var mR="pnpm-workspace.yaml",fR=async e=>(await Xf.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(r=>r.isDirectory()).map(r=>ci.join(e,r.name)),gR=async(e,t)=>{let r=[];for(let n of e){if(t==="*"){r.push(...await fR(n));continue}let o=ci.join(n,t);await Oe(o)&&r.push(o)}return r},hR=async(e,t)=>{let r=[e];for(let n of t.split("/"))r=await gR(r,n);return r},ke=async e=>{let t=await Xf.readFile(ci.join(e,mR),"utf-8"),n=((pR.parse(t)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),o=new Set;for(let s of n){let i=await hR(e,s);for(let a of i)await Oe(ci.join(a,"package.json"))&&o.add(a)}return[...o].sort()};import co from"node:path";var lo=async e=>{let t=co.resolve(e);for(;t!==co.dirname(t);){if(await Oe(co.join(t,"package.json")))return t;t=co.dirname(t)}if(await Oe(co.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 We=(e,t,r)=>{let n=e.indexOf(t),o=e.indexOf(r);return n!==-1&&o!==-1&&o>=n},Wt=(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}`:"")},pr=(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},li=(e,t,r)=>`${e}
2
+ import{c as xf,e as Gr,f as Nf,g as Ut,h as ci,i as _f,j as Mf,k as jf,l as Ff,m as Lf,n as Bf,o as Uf,p as Wf,s as Mc,t as Jf,u as Ae}from"./chunk-B6IURMIL.js";import{a as Im,b as Be,c as Nm,d as bc,e as _m,f as Mm,g as jm,h as Fm,i as zn,j as Lm,k as Bm,l as Um,m as Wm,n as Vm,o as Xn,p as Gm,q as Jm,r as Km,s as Hm,t as Rc,u as Xs,v as Mt,w as qm,x as Zs,y as Ym}from"./chunk-PP44RGIU.js";import{a as le,b as Y,c as Lt,d as eo,e as Tc,f as oi,g as si,h as Cc,i as to,j as lr,k as $c,l as ii,m as kf,n as Rt,o as ro,p as Oc,q as Dc,r as Ic,s as $f,u as Nc}from"./chunk-QS7RKE5P.js";import{b as Yn,c as Ys,d as kc,e as Cm,f as zs,g as $m,i as Am,k as Om,m as Pe,o as Dm}from"./chunk-REDCBY4O.js";import{a as Pf}from"./chunk-V2ZLQPLI.js";import{B as oo,D as Fc,H as Lc,I as Bc,a as b,b as C,c as Af,d as Of,e as ur,f as Df,g as dr,h as If,i as _c,j as Vf,k as no,l as Wt,m as Jr,n as st,o as li,p as Vt,q as Gf,r as ui,s as Kf,t as Hf,u as it,y as jc}from"./chunk-PQLGZPG5.js";import{a as h,b as St,c as bf,d as Rf,e as M,f as ai,g as J,i as Bt,j as Ze,k as Tf,l as Ac,m as Cf}from"./chunk-HSTMUEBW.js";import{$ as jt,A as rf,B as nf,C as of,D as ti,E as ri,F as Te,G as Zn,H as Vr,I as ni,J as sf,K as af,L as cf,M as Ec,N as Pc,O as lf,P as d,Q as Ue,R as ne,S as w,T as Xe,U as uf,V as df,W as pf,X as D,Y as ff,Z as gf,_ as hf,a as cr,aa as yf,b as I,ba as xc,c as zm,ca as vf,d as j,da as wf,e as he,ea as ee,f as Z,fa as K,g as Qs,ga as Qn,h as Xm,ha as Ft,i as g,j as Zm,k as ei,l as Q,m as we,n as xe,o as Qm,p as Sc,q as ce,r as re,s as Ur,t as ef,u as ot,v as ke,w as A,x as $e,y as Wr,z as tf}from"./chunk-JJOFP6OM.js";import{a as mf}from"./chunk-MFAFQVTW.js";import{a as L}from"./chunk-VJW64LZM.js";import{a as jr,b as Vs,c as Gs,d as qn,e as Sm,f as Fr,g as Js,h as Ks,i as Em,j as Hs,k as qs,l as Pm,m as xm,n as bt,o as Lr,p as _t,q as ge,r as Tm,s as Br}from"./chunk-GCOYOWGH.js";import{a as Sf,b as Ef}from"./chunk-QWVLAZ6N.js";import dL,{Separator as uR}from"@inquirer/select";import{existsSync as pL,realpathSync as mL}from"node:fs";import{homedir as fL}from"node:os";import Le from"node:process";import{fileURLToPath as pR}from"node:url";import qg from"node:process";import{z as Ie}from"zod";import tg from"node:fs";import Hr from"node:path";import{packageConfigSchema as zf}from"@slip-stream-kit/config/internal";import Xf from"node:fs/promises";import di from"node:path";import{pathToFileURL as bR}from"node:url";import{z as Zf}from"zod";import qf from"node:path";var so=["frontend","backend","lib","e2e","mobile"],gR={ui:"frontend",api:"backend",tests:"e2e"},hR="mobile-app",yR=[{type:"e2e",packages:["@playwright/test"]},{type:"mobile",packages:["@capacitor/core","@capacitor/cli"]},{type:"backend",packages:["serverless"]}],vR=(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=gR[o];if(s)return s}return r.at(-1)===hR?"mobile":null},wR=e=>{let t=new Set([...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{}),...Object.keys(e.peerDependencies??{})]);for(let n of yR)if(n.packages.some(o=>t.has(o)))return n.type;return t.has("vite")&&t.has("react")&&!!e.scripts?.dev?"frontend":null},io=({packageDir:e,repoRoot:t,pkgJson:r,declaredType:n})=>n??vR(e,t)??wR(r)??"lib";var at={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},Yf=2e3,Uc={"e2e-test":"pnpm exec playwright test","e2e-test-ui":"pnpm exec playwright test --ui","e2e-test-ui-demo":`E2E_SLOW_MO=\${E2E_SLOW_MO:-${Yf}} 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"},pr={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"]},ao=(e,t=at)=>({requiredScripts:e.requiredScripts??[...t.requiredScripts],requiredFiles:e.requiredFiles??[...t.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...t.turboTasks]});import kR from"node:fs/promises";var Oe=async e=>{try{return await kR.access(e),!0}catch{return!1}};var ue="infra-kit.config.ts",mr=async e=>{try{let t=await Xf.readFile(di.join(e,"package.json"),"utf-8");return JSON.parse(t)}catch{return{}}},Wc=async e=>{let t=await Xf.stat(e),o=(await import(`${bR(e).href}?mtime=${Number(t.mtimeMs)}`)).default;if(o===void 0)throw new Error(`${ue} at ${e} has no default export`);return typeof o=="function"?await o():o},Et=async e=>{let t=di.join(e,ue);if(await Oe(t))try{let n=(await Wc(t))?.type;return so.find(o=>o===n)}catch{return}},Qf=e=>e,co=async(e,t=at)=>{let r=di.join(e,ue);if(!await Oe(r))throw new Error(`${ue} not found at ${r}`);let n=await Wc(r),o=zf.safeParse(n);if(!o.success)throw new Error(`Invalid ${ue} at ${r}: ${Zf.prettifyError(o.error)}`);return ao(Qf(o.data),t)},ct=async e=>{let t=di.join(e,ue);if(!await Oe(t))return;let r=zf.safeParse(await Wc(t));if(!r.success)throw new Error(`Invalid ${ue} at ${t}: ${Zf.prettifyError(r.error)}`);return Qf(r.data)};import eg from"node:fs/promises";import pi from"node:path";import RR from"yaml";var SR="pnpm-workspace.yaml",ER=async e=>(await eg.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(r=>r.isDirectory()).map(r=>pi.join(e,r.name)),PR=async(e,t)=>{let r=[];for(let n of e){if(t==="*"){r.push(...await ER(n));continue}let o=pi.join(n,t);await Oe(o)&&r.push(o)}return r},xR=async(e,t)=>{let r=[e];for(let n of t.split("/"))r=await PR(r,n);return r},be=async e=>{let t=await eg.readFile(pi.join(e,SR),"utf-8"),n=((RR.parse(t)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),o=new Set;for(let s of n){let i=await xR(e,s);for(let a of i)await Oe(pi.join(a,"package.json"))&&o.add(a)}return[...o].sort()};import lo from"node:path";var uo=async e=>{let t=lo.resolve(e);for(;t!==lo.dirname(t);){if(await Oe(lo.join(t,"package.json")))return t;t=lo.dirname(t)}if(await Oe(lo.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 We=(e,t,r)=>{let n=e.indexOf(t),o=e.indexOf(r);return n!==-1&&o!==-1&&o>=n},Gt=(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}`:"")},fr=(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},mi=(e,t,r)=>`${e}
4
4
  ${t}
5
- ${r}`,Jr=({content:e,body:t,startMarker:r,endMarker:n,placement:o="replace-in-place"})=>{let s=li(r,t,n),i=We(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?Wt(e,r,n)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
5
+ ${r}`,Kr=({content:e,body:t,startMarker:r,endMarker:n,placement:o="replace-in-place"})=>{let s=mi(r,t,n),i=We(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?Gt(e,r,n)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
6
6
  ${s}
7
7
  `:`${s}
8
- `};var be="<!-- infra-kit:begin -->",De="<!-- infra-kit:end -->",mr="<!-- infra-kit:version ",Ve="<!-- infra-kit:package:begin -->",Qe="<!-- infra-kit:package:end -->",St="<!-- infra-kit:package:version ";var yR=e=>{let t=e.indexOf(Ve)+Ve.length;return e.slice(t,e.indexOf(Qe))},vR=e=>{let t=e.indexOf(St);if(t===-1)return null;let r=e.slice(t+St.length).match(/^\S+\s+([^\s>]+)/)?.[1];return oo.find(n=>n===r)??null},Et=e=>{if(e===null)return{state:"missing"};if(!We(e,Ve,Qe))return e.includes(Ve)||e.includes(Qe)?{state:"malformed"}:We(e,be,De)?{state:"foreign-block"}:{state:"no-block"};let t=yR(e);if(t.trim()==="")return{state:"malformed"};let r={state:"ok"},n=pr(t,St),o=vR(t);return n!==null&&(r.version=n),o!==null&&(r.type=o),r};import wR from"node:fs";var lt=e=>{try{return wR.readFileSync(e,"utf-8")}catch{return null}};var Qf="pnpm-workspace.yaml",kR="CLAUDE.md",Uc=e=>{let t=Kr.resolve(e);for(;t!==Kr.dirname(t);){if(Zf.existsSync(Kr.join(t,Qf)))return t;t=Kr.dirname(t)}return Zf.existsSync(Kr.join(t,Qf))?t:null},Bc=new Map,ui=()=>{Bc.clear()},bR=async e=>{let t;try{t=await ke(e)}catch{return{adopted:!1,workspaceRoot:e}}for(let r of t){let n=Kr.join(r,kR),o=lt(n);if(o!==null&&Et(o).state==="ok")return{adopted:!0,workspaceRoot:e,evidencePath:n}}return{adopted:!1,workspaceRoot:e}},Hr=async e=>{if(e===null)return{adopted:!1,workspaceRoot:null};let t=Bc.get(e);if(t)return t;let r=await bR(e);return Bc.set(e,r),r};import fr from"node:fs";import Vt from"node:path";var eg=`---
8
+ `};var Re="<!-- infra-kit:begin -->",De="<!-- infra-kit:end -->",gr="<!-- infra-kit:version ",Ve="<!-- infra-kit:package:begin -->",Qe="<!-- infra-kit:package:end -->",Pt="<!-- infra-kit:package:version ";var TR=e=>{let t=e.indexOf(Ve)+Ve.length;return e.slice(t,e.indexOf(Qe))},CR=e=>{let t=e.indexOf(Pt);if(t===-1)return null;let r=e.slice(t+Pt.length).match(/^\S+\s+([^\s>]+)/)?.[1];return so.find(n=>n===r)??null},xt=e=>{if(e===null)return{state:"missing"};if(!We(e,Ve,Qe))return e.includes(Ve)||e.includes(Qe)?{state:"malformed"}:We(e,Re,De)?{state:"foreign-block"}:{state:"no-block"};let t=TR(e);if(t.trim()==="")return{state:"malformed"};let r={state:"ok"},n=fr(t,Pt),o=CR(t);return n!==null&&(r.version=n),o!==null&&(r.type=o),r};import $R from"node:fs";var lt=e=>{try{return $R.readFileSync(e,"utf-8")}catch{return null}};var rg="pnpm-workspace.yaml",AR="CLAUDE.md",Gc=e=>{let t=Hr.resolve(e);for(;t!==Hr.dirname(t);){if(tg.existsSync(Hr.join(t,rg)))return t;t=Hr.dirname(t)}return tg.existsSync(Hr.join(t,rg))?t:null},Vc=new Map,fi=()=>{Vc.clear()},OR=async e=>{let t;try{t=await be(e)}catch{return{adopted:!1,workspaceRoot:e}}for(let r of t){let n=Hr.join(r,AR),o=lt(n);if(o!==null&&xt(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=Vc.get(e);if(t)return t;let r=await OR(e);return Vc.set(e,r),r};import hr from"node:fs";import Jt from"node:path";var ng=`---
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 tg=`# {{packageName}}
77
+ `;var og=`# {{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 rg="# {{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 ng="# {{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 og=`# {{packageName}}
98
+ `;var sg="# {{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 ig="# {{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 ag=`# {{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 sg=`# {{packageName}}
119
+ `;var cg=`# {{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 ig="# 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 qr={"root/body":ig.trimEnd(),"package/frontend":ng.trimEnd(),"package/backend":tg.trimEnd(),"package/lib":og.trimEnd(),"package/e2e":rg.trimEnd(),"package/mobile":sg.trimEnd(),"design/skeleton":eg.trimEnd()};var Wc=/\{\{(\w+)\}\}/g,$R=/^- \{\{(\w+)\}\}$/,AR=e=>new Set([...e.matchAll(Wc)].map(t=>t[1])),OR=(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(", ")}`)},DR=(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(", ")}`)},IR=(e,t)=>e.filter(r=>{let n=$R.exec(r);return n===null||t[n[1]]!==""}),NR=(e,t)=>{for(let r of e)for(let n of r.matchAll(Wc)){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})`)}},Yr=(e,t)=>{let r=AR(e);DR(r,t),OR(r,t);let n=IR(e.split(`
143
- `),t);return NR(n,t),n.join(`
144
- `).replace(Wc,(o,s)=>t[s])};var _R="name: TODO",Vc=e=>{let t=Yr(qr["design/skeleton"],{packageName:e}),r=`name: ${e}`;return`${t.replace(_R,()=>r)}
145
- `};var MR=(e,t)=>`${St}${e} ${t} -->`,jR="`README.md` \u2014 what this package is and how to run it.",Gc="docs/e2e-playwright.md",FR=`\`${Gc}\` at the repo root \u2014 env setup, run modes, \`E2E_SLOW_MO\`, traces after a failure.`,LR=["ts-check","eslint-check","test"],BR="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.",UR="Run `pnpm run build` before a dependent package can see a change.",ag=(e,t)=>e?.includes(t)??!0,WR=e=>{let t=LR.filter(r=>ag(e,r)).map(r=>`pnpm run ${r}`);return t.length===0?"":`\`${t.join(" && ")}\` \u2014 this package only.`},Jc=e=>{let{version:t,type:r,packageName:n,relDir:o,hasReadme:s,hasE2eDoc:i,scripts:a,hasPublicSurface:c=!0}=e,l=Yr(qr[`package/${r}`],{packageName:n,relDir:o,type:r,readmeBullet:s?jR:"",checksBullet:WR(a),...r==="e2e"?{e2eDocBullet:i?FR:""}:{},...r==="lib"?{surfaceBullet:c?BR:"",buildBullet:ag(a,"build")?UR:""}:{}});return[MR(t,r),"",l,""].join(`
146
- `)};var VR=e=>`${mr}${e} -->`,uo=e=>{let t=Yr(qr["root/body"],{});return[VR(e),"",t,""].join(`
147
- `)};import zr from"node:fs";import GR from"node:path";var di=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`)},po=(e,t)=>{let r=mo(e,t);return r!=="unchanged"&&(zr.mkdirSync(GR.dirname(e),{recursive:!0}),zr.writeFileSync(e,t,"utf-8")),r},mo=(e,t)=>{di(e);let r=zr.existsSync(e)?zr.readFileSync(e,"utf-8"):null;return r===t?"unchanged":r===null?"created":"updated"},Kc=(e,t,r)=>{let n=zr.readFileSync(e,"utf-8");if(!We(n,t,r))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},cg=(e,t,r)=>We(e,t,r)?{before:e.slice(0,e.indexOf(t)),after:e.slice(e.indexOf(r)+r.length)}:null,Hc=(e,t,r,n)=>{let o=cg(e,r,n),s=cg(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 mi="<!-- infra-kit:import:begin -->",fi="<!-- infra-kit:import:end -->",JR="AGENTS.md",lg="CLAUDE.md",KR="README.md",qc="DESIGN.md",HR=["frontend","mobile"],qR=e=>fr.existsSync(e)?fr.readFileSync(e,"utf-8"):null,Yc=(e,t)=>{try{return fr.readdirSync(e).includes(t)}catch{return!1}},pi=(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},ug=({filePath:e,body:t,startMarker:r,endMarker:n,prepare:o,dryRun:s})=>{let i=qR(e),a=i===null?"":o?.(i)??i,c=Jr({content:a,body:t,startMarker:r,endMarker:n,placement:"replace-in-place"});if(s)return mo(e,c);let l=po(e,c);return Kc(e,r,n),i!==null&&Hc(a,c,r,n),l},YR=(e,t)=>{if(!fr.existsSync(e))return"unchanged";di(e);let r=fr.readFileSync(e,"utf-8"),n=Wt(r,be,De);return n===null?"unchanged":n.trim()===""?(t||fr.rmSync(e),"removed"):t?mo(e,n):po(e,n)},zR=(e,t,r)=>ug({filePath:e,dryRun:r,body:uo(t),startMarker:be,endMarker:De,prepare:n=>Wt(n,mi,fi)??n}),fo=async(e,{version:t,dryRun:r=!1})=>{let n=Vt.join(e,lg),o=Vt.join(e,JR),s=[];try{s.push({path:n,action:zR(n,t,r)})}catch(i){s.push(pi(n,i))}try{s.push({path:o,action:YR(o,r)})}catch(i){s.push(pi(o,i))}return s},XR=(e,t,r,n)=>{if(!HR.includes(r)||Yc(e,qc))return null;let o=Vt.join(e,qc),s=Vc(t);try{return{path:o,action:n?mo(o,s):po(o,s),type:r}}catch(i){return pi(o,i,r)}},gi=async(e,{repoRoot:t,version:r,declaredType:n})=>{let o=await dr(e),s=o.name??Vt.basename(e),i=so({packageDir:e,repoRoot:t,pkgJson:o,declaredType:n});return{body:Jc({version:r,type:i,packageName:s,relDir:Vt.relative(t,e).split(Vt.sep).join("/"),hasReadme:Yc(e,KR),hasDesign:Yc(e,qc),hasE2eDoc:fr.existsSync(Vt.join(t,Gc)),scripts:Object.keys(o.scripts??{}),hasPublicSurface:o.exports!==void 0||o.bin!==void 0}),type:i,packageName:s}},go=async(e,{repoRoot:t,version:r,design:n,declaredType:o,dryRun:s=!1})=>{let i=Vt.join(e,lg),{body:a,type:c,packageName:l}=await gi(e,{repoRoot:t,version:r,declaredType:o}),u=[];try{u.push({path:i,action:ug({filePath:i,body:a,startMarker:Ve,endMarker:Qe,dryRun:s}),type:c})}catch(p){u.push(pi(i,p,c))}if(n){let p=XR(e,l,c,s);p&&u.push(p)}return u};import wS from"node:path";import dg from"node:path";var zc="agent-guidance",ho="CLAUDE.md",ZR="\u2014 run: infra-kit audit --fix",QR={missing:`${ho} missing`,"no-block":`${ho} has no infra-kit block (expected ${Ve} \u2026 ${Qe})`,malformed:`${ho} block is malformed (end marker precedes start, or body is empty)`,"foreign-block":`${ho} carries the ROOT infra-kit block (${be}); a package needs the package block`},eS=e=>e.adopted?` (workspace adopted: ${dg.relative(e.workspaceRoot,e.evidencePath)} carries a package block)`:"",Xc=(e,t)=>{let r=Et(lt(dg.join(e,ho)));if(r.state==="ok"){let s=r.version??"unknown",i=r.type??"unknown";return{name:zc,status:"pass",message:`present (block from infra-kit ${s}, type ${i})`}}let n=`${QR[r.state]} ${ZR}`,o=r.state==="missing"?`${n}${eS(t)}`:n;return t.adopted?{name:zc,status:"fail",message:o}:{name:zc,status:"pass",message:`not yet adopted \u2014 ${o}`}};import tS from"node:path";var Zc=async(e,t=at)=>{try{let r=await ao(e,t);return{check:{name:ue,status:"pass",message:"present and valid"},rules:r}}catch(r){return{check:{name:ue,status:"fail",message:r.message},rules:null}}},pg="infra-kit.json",rS=async e=>await Oe(tS.join(e,ue))?{name:ue,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,Qc=async(e,t=ur)=>{let r=await rS(e),n=r?[r]:[];try{let{audit:o={}}=await H();return{checks:[{name:pg,status:"pass",message:"present and valid"},...n],rules:io(o,t)}}catch(o){return{checks:[{name:pg,status:"fail",message:o.message},...n],rules:null}}};import hi from"node:fs/promises";import Xr from"node:path";import{$ as nS}from"zx";var yo="playwright.config.ts",oS=[{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')"}],mg=e=>Object.entries(Fc).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"}}),sS="infra-kit-e2e",fg=async(e,t={})=>{let r=Xr.join(e,yo),n=await hi.readFile(r,"utf-8").catch(()=>null);return n===null?[{name:`e2e-config:${yo}`,status:"fail",message:`missing ${yo}`}]:oS.map(o=>{let s=`e2e-config:${o.name}`;return t.staticServer&&o.name===sS?{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:`${yo} lacks the shared e2e convention \u2014 expected: ${o.expected}`}})},iS=/['"`](?:[^'"`\n]*\/)?\.auth['"/`]/u,aS=/\.[cm]?[jt]sx?$/u,el=async(e,t)=>(await hi.readdir(e,{recursive:t,withFileTypes:!0}).catch(()=>[])).filter(n=>n.isFile()&&aS.test(n.name)).map(n=>Xr.join(n.parentPath,n.name)),cS=async e=>{let t=await el(Xr.join(e,"src"),!0);for(let r of[Xr.join(e,yo),...t]){let n=await hi.readFile(r,"utf-8").catch(()=>"");if(iS.test(n))return!0}return!1},gg=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 nS({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}`}},tl="E2E__BASIC_AUTH_USERNAME",rl="E2E__BASIC_AUTH_PASSWORD",lS=/\bE2E_\w*BASIC_AUTH_\w+/gu,uS=/_(?:USER(?:NAME)?|PASS(?:WORD)?)$/u,dS=/\/\*[\s\S]*?\*\//gu,pS=/(^|[^:])\/\/[^\n]*/gu,mS=e=>/USER(?:NAME)?$/u.test(e)?tl:rl,fS=e=>e.replace(dS,"").replace(pS,"$1"),hg=async e=>{let t="e2e-env:basic-auth",r=[...await el(e,!1),...await el(Xr.join(e,"src"),!0)],n=[];for(let o of r){let s=await hi.readFile(o,"utf-8").catch(()=>""),i=new Set([...fS(s).matchAll(lS)].map(a=>a[0]).filter(a=>uS.test(a)&&a!==tl&&a!==rl));for(let a of i)n.push(`${a} \u2192 ${mS(a)} (${Xr.relative(e,o)})`)}return n.length===0?{name:t,status:"pass",message:`basic auth read only from ${tl} / ${rl}`}:{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("; ")}`}},nl=async(e,t,r={})=>[...mg(t),...await fg(e,r),await gg(e),await hg(e)];import gS from"node:fs/promises";import hS from"node:path";var ol=async(e,t)=>Promise.all(t.map(async r=>{let n=await gS.stat(hS.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 sl=(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 yS from"node:fs/promises";import vS from"node:path";var Zr="turbo.json",il=async(e,t)=>{if(t.length===0)return[];let r;try{let o=await yS.readFile(vS.join(e,Zr),"utf-8");r=JSON.parse(o)}catch(o){return[{name:Zr,status:"fail",message:`cannot read/parse ${Zr}: ${o.message}`}]}let n=r.tasks;return n===null||typeof n!="object"?[{name:Zr,status:"fail",message:`no "tasks" object defined in ${Zr}`}]: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 ${Zr}`}})};var kS=async(e,t)=>{let{check:r,rules:n}=await Zc(e,t);return{checks:[r],rules:n}},bS={adopted:!1,workspaceRoot:null},RS=async(e,t,r)=>so({packageDir:e,repoRoot:r??e,pkgJson:t,declaredType:await Rt(e)}),SS=async e=>(await ct(e).catch(()=>{}))?.e2e?.server==="static",al=async(e,t=at,r={})=>{let n=await dr(e),o=n.name??wS.basename(e),{checks:s,rules:i}=r.isRoot?await Qc(e,t):await kS(e,t);r.isRoot||s.push(Xc(e,r.adoption??bS)),i&&(s.push(...sl(n.scripts??{},i.requiredScripts)),s.push(...await ol(e,i.requiredFiles)),s.push(...await il(e,i.turboTasks))),!r.isRoot&&await RS(e,n,r.repoRoot)==="e2e"&&s.push(...await nl(e,n.scripts??{},{staticServer:await SS(e)}));let a=s.every(c=>c.status!=="fail");return{packageDir:e,packageName:o,checks:s,passed:a}};var cl=["plugin","marketplace","add",jt],ll=["plugin","install",Y,"--scope","project"],yg=(e,t)=>ar({projectPath:e,home:t}).kind==="installed",yi=e=>((e??"").split(`
148
- `).find(r=>r.trim().length>0)??"").trim(),ES=(e,t)=>{if(eo(t))return null;d.debug({msg:`Running: ${Qn} ${cl.join(" ")}`});let r=e({args:cl});return r.ok?null:{step:"marketplace",error:yi(r.output)}},PS=(e,t)=>{d.debug({msg:`Running: ${Qn} ${ti.join(" ")}`});let r=e({args:ti});if(!r.ok)return{status:"update-failed",error:yi(r.output)};d.debug({msg:`Running: ${Qn} ${ei.join(" ")}`});let n=e({args:ei,cwd:t});return n.ok?{status:"updated"}:{status:"update-failed",error:yi(n.output)}},ul=e=>{let{projectRoot:t,home:r}=e,n=e.run??Pc;if(!n({args:Ec}).ok)return{status:"claude-missing"};if(yg(t,r))return e.cliIsStale?.()===!0?{status:"skipped-cli-stale"}:PS(n,t);let o=ES(n,r);if(o!==null)return{status:"failed",...o};d.debug({msg:`Running: ${Qn} ${ll.join(" ")}`});let s=n({args:ll,cwd:t});return s.ok?yg(t,r)?{status:"installed"}:{status:"unverified"}:{status:"failed",step:"install",error:yi(s.output)}};import xS from"node:fs";import TS from"node:path";var Ge=".mcp.json",ut="mcpServers",CS="infra-kit",$S=["mcp"],AS="/infra-kit/dist/mcp.js",dl=" ",gr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),vg=e=>{if(!gr(e))return!1;let{command:t,args:r}=e;return Array.isArray(r)?t===CS&&r[0]===$S[0]?!0:r.some(n=>typeof n=="string"&&n.endsWith(AS)):!1},wg=e=>/\n([ \t]+)"/.exec(e)?.[1]??dl,pl=e=>{try{return{kind:"raw",raw:xS.readFileSync(e,"utf-8")}}catch(t){return t.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable",error:t}}},ml=e=>{try{return JSON.parse(e)}catch{return}},fl=e=>e instanceof Error?e.message:String(e),Qr=e=>{let t=pl(TS.join(e,Ge));if(t.kind==="absent")return{kind:"missing-file"};if(t.kind==="unreadable")return{kind:"unparseable"};let r=ml(t.raw);if(!gr(r)||!gr(r[ut]))return{kind:"unparseable"};let n=r[ut];if(le in n)return{kind:"stale"};let o=Object.keys(n).find(s=>vg(n[s]));return o===void 0?{kind:"absent"}:{kind:"wrong-key",key:o}};import vi from"node:fs";import OS from"node:path";var Pt=`claude plugin install ${Y} --scope project`,en=`claude plugin marketplace update ${le} && claude plugin update ${Y} --scope project`,gl=`claude plugin marketplace add ${jt}`,Rg=" ",Sg=()=>({source:{source:"github",repo:jt}}),DS=()=>({extraKnownMarketplaces:{[le]:Sg()},enabledPlugins:{[Y]:!0}}),Eg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),IS=e=>/\n([ \t]+)"/.exec(e)?.[1]??Rg,kg=(e,t,r,n)=>{let o=e[t];return o===void 0?(e[t]={[r]:n},`${t}.${r}`):!Eg(o)||r in o?null:(o[r]=n,`${t}.${r}`)},bg=e=>[kg(e,"extraKnownMarketplaces",le,Sg()),kg(e,"enabledPlugins",Y,!0)].filter(r=>r!==null),NS=e=>{try{return vi.readFileSync(e,"utf-8")}catch{return null}},_S=e=>(vi.mkdirSync(OS.dirname(e),{recursive:!0}),vi.writeFileSync(e,`${JSON.stringify(DS(),null,Rg)}
149
- `,"utf-8"),{status:"created",path:e,added:[`extraKnownMarketplaces.${le}`,`enabledPlugins.${Y}`]}),hl=(e,{write:t=!0}={})=>{let r=NS(e);if(r===null)return t?_S(e):{status:"withheld",path:e,added:bg({})};let n;try{n=JSON.parse(r)}catch{n=void 0}if(!Eg(n))return d.warn(`Could not parse ${e} \u2014 left it untouched. Add "${Y}" to enabledPlugins by hand, or fix the JSON and re-run: infra-kit setup --skip-tools`),{status:"unparseable",path:e,added:[]};let o=bg(n);if(o.length===0)return{status:"unchanged",path:e,added:[]};if(!t)return{status:"withheld",path:e,added:o};let s=IS(r),i=r.endsWith(`
141
+ `;var lg="# 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 Yr={"root/body":lg.trimEnd(),"package/frontend":ig.trimEnd(),"package/backend":og.trimEnd(),"package/lib":ag.trimEnd(),"package/e2e":sg.trimEnd(),"package/mobile":cg.trimEnd(),"design/skeleton":ng.trimEnd()};var Jc=/\{\{(\w+)\}\}/g,LR=/^- \{\{(\w+)\}\}$/,BR=e=>new Set([...e.matchAll(Jc)].map(t=>t[1])),UR=(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(", ")}`)},WR=(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(", ")}`)},VR=(e,t)=>e.filter(r=>{let n=LR.exec(r);return n===null||t[n[1]]!==""}),GR=(e,t)=>{for(let r of e)for(let n of r.matchAll(Jc)){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})`)}},zr=(e,t)=>{let r=BR(e);WR(r,t),UR(r,t);let n=VR(e.split(`
143
+ `),t);return GR(n,t),n.join(`
144
+ `).replace(Jc,(o,s)=>t[s])};var JR="name: TODO",Kc=e=>{let t=zr(Yr["design/skeleton"],{packageName:e}),r=`name: ${e}`;return`${t.replace(JR,()=>r)}
145
+ `};var KR=(e,t)=>`${Pt}${e} ${t} -->`,HR="`README.md` \u2014 what this package is and how to run it.",Hc="docs/e2e-playwright.md",qR=`\`${Hc}\` at the repo root \u2014 env setup, run modes, \`E2E_SLOW_MO\`, traces after a failure.`,YR=["ts-check","eslint-check","test"],zR="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.",XR="Run `pnpm run build` before a dependent package can see a change.",ug=(e,t)=>e?.includes(t)??!0,ZR=e=>{let t=YR.filter(r=>ug(e,r)).map(r=>`pnpm run ${r}`);return t.length===0?"":`\`${t.join(" && ")}\` \u2014 this package only.`},qc=e=>{let{version:t,type:r,packageName:n,relDir:o,hasReadme:s,hasE2eDoc:i,scripts:a,hasPublicSurface:c=!0}=e,l=zr(Yr[`package/${r}`],{packageName:n,relDir:o,type:r,readmeBullet:s?HR:"",checksBullet:ZR(a),...r==="e2e"?{e2eDocBullet:i?qR:""}:{},...r==="lib"?{surfaceBullet:c?zR:"",buildBullet:ug(a,"build")?XR:""}:{}});return[KR(t,r),"",l,""].join(`
146
+ `)};var QR=e=>`${gr}${e} -->`,po=e=>{let t=zr(Yr["root/body"],{});return[QR(e),"",t,""].join(`
147
+ `)};import Xr from"node:fs";import eS from"node:path";var gi=e=>{let t;try{t=Xr.lstatSync(e)}catch{return}if(t.isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},mo=(e,t)=>{let r=fo(e,t);return r!=="unchanged"&&(Xr.mkdirSync(eS.dirname(e),{recursive:!0}),Xr.writeFileSync(e,t,"utf-8")),r},fo=(e,t)=>{gi(e);let r=Xr.existsSync(e)?Xr.readFileSync(e,"utf-8"):null;return r===t?"unchanged":r===null?"created":"updated"},Yc=(e,t,r)=>{let n=Xr.readFileSync(e,"utf-8");if(!We(n,t,r))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},dg=(e,t,r)=>We(e,t,r)?{before:e.slice(0,e.indexOf(t)),after:e.slice(e.indexOf(r)+r.length)}:null,zc=(e,t,r,n)=>{let o=dg(e,r,n),s=dg(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 yi="<!-- infra-kit:import:begin -->",vi="<!-- infra-kit:import:end -->",tS="AGENTS.md",pg="CLAUDE.md",rS="README.md",Xc="DESIGN.md",nS=["frontend","mobile"],oS=e=>hr.existsSync(e)?hr.readFileSync(e,"utf-8"):null,Zc=(e,t)=>{try{return hr.readdirSync(e).includes(t)}catch{return!1}},hi=(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},mg=({filePath:e,body:t,startMarker:r,endMarker:n,prepare:o,dryRun:s})=>{let i=oS(e),a=i===null?"":o?.(i)??i,c=Kr({content:a,body:t,startMarker:r,endMarker:n,placement:"replace-in-place"});if(s)return fo(e,c);let l=mo(e,c);return Yc(e,r,n),i!==null&&zc(a,c,r,n),l},sS=(e,t)=>{if(!hr.existsSync(e))return"unchanged";gi(e);let r=hr.readFileSync(e,"utf-8"),n=Gt(r,Re,De);return n===null?"unchanged":n.trim()===""?(t||hr.rmSync(e),"removed"):t?fo(e,n):mo(e,n)},iS=(e,t,r)=>mg({filePath:e,dryRun:r,body:po(t),startMarker:Re,endMarker:De,prepare:n=>Gt(n,yi,vi)??n}),go=async(e,{version:t,dryRun:r=!1})=>{let n=Jt.join(e,pg),o=Jt.join(e,tS),s=[];try{s.push({path:n,action:iS(n,t,r)})}catch(i){s.push(hi(n,i))}try{s.push({path:o,action:sS(o,r)})}catch(i){s.push(hi(o,i))}return s},aS=(e,t,r,n)=>{if(!nS.includes(r)||Zc(e,Xc))return null;let o=Jt.join(e,Xc),s=Kc(t);try{return{path:o,action:n?fo(o,s):mo(o,s),type:r}}catch(i){return hi(o,i,r)}},wi=async(e,{repoRoot:t,version:r,declaredType:n})=>{let o=await mr(e),s=o.name??Jt.basename(e),i=io({packageDir:e,repoRoot:t,pkgJson:o,declaredType:n});return{body:qc({version:r,type:i,packageName:s,relDir:Jt.relative(t,e).split(Jt.sep).join("/"),hasReadme:Zc(e,rS),hasDesign:Zc(e,Xc),hasE2eDoc:hr.existsSync(Jt.join(t,Hc)),scripts:Object.keys(o.scripts??{}),hasPublicSurface:o.exports!==void 0||o.bin!==void 0}),type:i,packageName:s}},ho=async(e,{repoRoot:t,version:r,design:n,declaredType:o,dryRun:s=!1})=>{let i=Jt.join(e,pg),{body:a,type:c,packageName:l}=await wi(e,{repoRoot:t,version:r,declaredType:o}),u=[];try{u.push({path:i,action:mg({filePath:i,body:a,startMarker:Ve,endMarker:Qe,dryRun:s}),type:c})}catch(p){u.push(hi(i,p,c))}if(n){let p=aS(e,l,c,s);p&&u.push(p)}return u};import $S from"node:path";import fg from"node:path";var Qc="agent-guidance",yo="CLAUDE.md",cS="\u2014 run: infra-kit audit --fix",lS={missing:`${yo} missing`,"no-block":`${yo} has no infra-kit block (expected ${Ve} \u2026 ${Qe})`,malformed:`${yo} block is malformed (end marker precedes start, or body is empty)`,"foreign-block":`${yo} carries the ROOT infra-kit block (${Re}); a package needs the package block`},uS=e=>e.adopted?` (workspace adopted: ${fg.relative(e.workspaceRoot,e.evidencePath)} carries a package block)`:"",el=(e,t)=>{let r=xt(lt(fg.join(e,yo)));if(r.state==="ok"){let s=r.version??"unknown",i=r.type??"unknown";return{name:Qc,status:"pass",message:`present (block from infra-kit ${s}, type ${i})`}}let n=`${lS[r.state]} ${cS}`,o=r.state==="missing"?`${n}${uS(t)}`:n;return t.adopted?{name:Qc,status:"fail",message:o}:{name:Qc,status:"pass",message:`not yet adopted \u2014 ${o}`}};import dS from"node:path";var tl=async(e,t=at)=>{try{let r=await co(e,t);return{check:{name:ue,status:"pass",message:"present and valid"},rules:r}}catch(r){return{check:{name:ue,status:"fail",message:r.message},rules:null}}},gg="infra-kit.json",pS=async e=>await Oe(dS.join(e,ue))?{name:ue,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,rl=async(e,t=pr)=>{let r=await pS(e),n=r?[r]:[];try{let{audit:o={}}=await K();return{checks:[{name:gg,status:"pass",message:"present and valid"},...n],rules:ao(o,t)}}catch(o){return{checks:[{name:gg,status:"fail",message:o.message},...n],rules:null}}};import ki from"node:fs/promises";import Zr from"node:path";import{$ as mS}from"zx";var vo="playwright.config.ts",fS=[{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')"}],hg=e=>Object.entries(Uc).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"}}),gS="infra-kit-e2e",yg=async(e,t={})=>{let r=Zr.join(e,vo),n=await ki.readFile(r,"utf-8").catch(()=>null);return n===null?[{name:`e2e-config:${vo}`,status:"fail",message:`missing ${vo}`}]:fS.map(o=>{let s=`e2e-config:${o.name}`;return t.staticServer&&o.name===gS?{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:`${vo} lacks the shared e2e convention \u2014 expected: ${o.expected}`}})},hS=/['"`](?:[^'"`\n]*\/)?\.auth['"/`]/u,yS=/\.[cm]?[jt]sx?$/u,nl=async(e,t)=>(await ki.readdir(e,{recursive:t,withFileTypes:!0}).catch(()=>[])).filter(n=>n.isFile()&&yS.test(n.name)).map(n=>Zr.join(n.parentPath,n.name)),vS=async e=>{let t=await nl(Zr.join(e,"src"),!0);for(let r of[Zr.join(e,vo),...t]){let n=await ki.readFile(r,"utf-8").catch(()=>"");if(hS.test(n))return!0}return!1},vg=async e=>{let t="e2e-auth:gitignored";if(!await vS(e))return{name:t,status:"pass",message:"no saved auth state referenced"};let r=await mS({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}`}},ol="E2E__BASIC_AUTH_USERNAME",sl="E2E__BASIC_AUTH_PASSWORD",wS=/\bE2E_\w*BASIC_AUTH_\w+/gu,kS=/_(?:USER(?:NAME)?|PASS(?:WORD)?)$/u,bS=/\/\*[\s\S]*?\*\//gu,RS=/(^|[^:])\/\/[^\n]*/gu,SS=e=>/USER(?:NAME)?$/u.test(e)?ol:sl,ES=e=>e.replace(bS,"").replace(RS,"$1"),wg=async e=>{let t="e2e-env:basic-auth",r=[...await nl(e,!1),...await nl(Zr.join(e,"src"),!0)],n=[];for(let o of r){let s=await ki.readFile(o,"utf-8").catch(()=>""),i=new Set([...ES(s).matchAll(wS)].map(a=>a[0]).filter(a=>kS.test(a)&&a!==ol&&a!==sl));for(let a of i)n.push(`${a} \u2192 ${SS(a)} (${Zr.relative(e,o)})`)}return n.length===0?{name:t,status:"pass",message:`basic auth read only from ${ol} / ${sl}`}:{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("; ")}`}},il=async(e,t,r={})=>[...hg(t),...await yg(e,r),await vg(e),await wg(e)];import PS from"node:fs/promises";import xS from"node:path";var al=async(e,t)=>Promise.all(t.map(async r=>{let n=await PS.stat(xS.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 cl=(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 TS from"node:fs/promises";import CS from"node:path";var Qr="turbo.json",ll=async(e,t)=>{if(t.length===0)return[];let r;try{let o=await TS.readFile(CS.join(e,Qr),"utf-8");r=JSON.parse(o)}catch(o){return[{name:Qr,status:"fail",message:`cannot read/parse ${Qr}: ${o.message}`}]}let n=r.tasks;return n===null||typeof n!="object"?[{name:Qr,status:"fail",message:`no "tasks" object defined in ${Qr}`}]: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 ${Qr}`}})};var AS=async(e,t)=>{let{check:r,rules:n}=await tl(e,t);return{checks:[r],rules:n}},OS={adopted:!1,workspaceRoot:null},DS=async(e,t,r)=>io({packageDir:e,repoRoot:r??e,pkgJson:t,declaredType:await Et(e)}),IS=async e=>(await ct(e).catch(()=>{}))?.e2e?.server==="static",ul=async(e,t=at,r={})=>{let n=await mr(e),o=n.name??$S.basename(e),{checks:s,rules:i}=r.isRoot?await rl(e,t):await AS(e,t);r.isRoot||s.push(el(e,r.adoption??OS)),i&&(s.push(...cl(n.scripts??{},i.requiredScripts)),s.push(...await al(e,i.requiredFiles)),s.push(...await ll(e,i.turboTasks))),!r.isRoot&&await DS(e,n,r.repoRoot)==="e2e"&&s.push(...await il(e,n.scripts??{},{staticServer:await IS(e)}));let a=s.every(c=>c.status!=="fail");return{packageDir:e,packageName:o,checks:s,passed:a}};var dl=["plugin","marketplace","add",Lt],pl=["plugin","install",Y,"--scope","project"],kg=(e,t)=>lr({projectPath:e,home:t}).kind==="installed",bi=e=>((e??"").split(`
148
+ `).find(r=>r.trim().length>0)??"").trim(),NS=(e,t)=>{if(to(t))return null;d.debug({msg:`Running: ${eo} ${dl.join(" ")}`});let r=e({args:dl});return r.ok?null:{step:"marketplace",error:bi(r.output)}},_S=(e,t)=>{d.debug({msg:`Running: ${eo} ${si.join(" ")}`});let r=e({args:si});if(!r.ok)return{status:"update-failed",error:bi(r.output)};d.debug({msg:`Running: ${eo} ${oi.join(" ")}`});let n=e({args:oi,cwd:t});return n.ok?{status:"updated"}:{status:"update-failed",error:bi(n.output)}},ml=e=>{let{projectRoot:t,home:r}=e,n=e.run??Cc;if(!n({args:Tc}).ok)return{status:"claude-missing"};if(kg(t,r))return e.cliIsStale?.()===!0?{status:"skipped-cli-stale"}:_S(n,t);let o=NS(n,r);if(o!==null)return{status:"failed",...o};d.debug({msg:`Running: ${eo} ${pl.join(" ")}`});let s=n({args:pl,cwd:t});return s.ok?kg(t,r)?{status:"installed"}:{status:"unverified"}:{status:"failed",step:"install",error:bi(s.output)}};import MS from"node:fs";import jS from"node:path";var Ge=".mcp.json",ut="mcpServers",FS="infra-kit",LS=["mcp"],BS="/infra-kit/dist/mcp.js",fl=" ",yr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),bg=e=>{if(!yr(e))return!1;let{command:t,args:r}=e;return Array.isArray(r)?t===FS&&r[0]===LS[0]?!0:r.some(n=>typeof n=="string"&&n.endsWith(BS)):!1},Rg=e=>/\n([ \t]+)"/.exec(e)?.[1]??fl,gl=e=>{try{return{kind:"raw",raw:MS.readFileSync(e,"utf-8")}}catch(t){return t.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable",error:t}}},hl=e=>{try{return JSON.parse(e)}catch{return}},yl=e=>e instanceof Error?e.message:String(e),en=e=>{let t=gl(jS.join(e,Ge));if(t.kind==="absent")return{kind:"missing-file"};if(t.kind==="unreadable")return{kind:"unparseable"};let r=hl(t.raw);if(!yr(r)||!yr(r[ut]))return{kind:"unparseable"};let n=r[ut];if(le in n)return{kind:"stale"};let o=Object.keys(n).find(s=>bg(n[s]));return o===void 0?{kind:"absent"}:{kind:"wrong-key",key:o}};import Ri from"node:fs";import US from"node:path";var Tt=`claude plugin install ${Y} --scope project`,tn=`claude plugin marketplace update ${le} && claude plugin update ${Y} --scope project`,vl=`claude plugin marketplace add ${Lt}`,Pg=" ",xg=()=>({source:{source:"github",repo:Lt}}),WS=()=>({extraKnownMarketplaces:{[le]:xg()},enabledPlugins:{[Y]:!0}}),Tg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),VS=e=>/\n([ \t]+)"/.exec(e)?.[1]??Pg,Sg=(e,t,r,n)=>{let o=e[t];return o===void 0?(e[t]={[r]:n},`${t}.${r}`):!Tg(o)||r in o?null:(o[r]=n,`${t}.${r}`)},Eg=e=>[Sg(e,"extraKnownMarketplaces",le,xg()),Sg(e,"enabledPlugins",Y,!0)].filter(r=>r!==null),GS=e=>{try{return Ri.readFileSync(e,"utf-8")}catch{return null}},JS=e=>(Ri.mkdirSync(US.dirname(e),{recursive:!0}),Ri.writeFileSync(e,`${JSON.stringify(WS(),null,Pg)}
149
+ `,"utf-8"),{status:"created",path:e,added:[`extraKnownMarketplaces.${le}`,`enabledPlugins.${Y}`]}),wl=(e,{write:t=!0}={})=>{let r=GS(e);if(r===null)return t?JS(e):{status:"withheld",path:e,added:Eg({})};let n;try{n=JSON.parse(r)}catch{n=void 0}if(!Tg(n))return d.warn(`Could not parse ${e} \u2014 left it untouched. Add "${Y}" to enabledPlugins by hand, or fix the JSON and re-run: infra-kit setup --skip-tools`),{status:"unparseable",path:e,added:[]};let o=Eg(n);if(o.length===0)return{status:"unchanged",path:e,added:[]};if(!t)return{status:"withheld",path:e,added:o};let s=VS(r),i=r.endsWith(`
150
150
  `)?`
151
- `:"";return vi.writeFileSync(e,`${JSON.stringify(n,null,s)}${i}`,"utf-8"),{status:"added",path:e,added:o}};var MS="empty-rules",jS=["requiredScripts","requiredFiles"],Pg=(e,t,r)=>jS.filter(n=>e[n]?.length===0).map(n=>({name:MS,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`})),xg=async(e,t)=>{try{if(t){let{audit:r={}}=await H();return Pg(r,ur,'infra-kit.json "audit"')}return Pg(await ct(e)??{},at,"infra-kit.config.ts")}catch{return[]}};import BS from"node:path";import US from"node:process";import yl from"node:fs/promises";import Tg from"node:path";var FS="infra-kit.json",Cg=["requiredScripts","requiredFiles","turbo"],vo=(e,t)=>[{path:e,action:"failed",message:t}],LS=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),$g=async e=>{let t=Tg.join(e,ue),r=Tg.join(e,FS),n;try{n=await ct(e)}catch(c){return vo(t,c.message)}if(!n)return[];let o={...n},s=Object.keys(o).filter(c=>!Cg.includes(c));if(s.length>0)return vo(t,`declares ${s.join(", ")}, which mean nothing at the repo root \u2014 remove them, then re-run`);let i=Object.fromEntries(Cg.filter(c=>o[c]!==void 0).map(c=>[c,o[c]])),a=[];if(Object.keys(i).length>0)try{let c=await yl.stat(r),l=await yl.readFile(r,"utf8"),u=JSON.parse(l);if(!LS(u))return vo(r,"is not a JSON object");if("audit"in u)return vo(r,`already has an "audit" block \u2014 merge ${ue}'s rules into it by hand, then delete ${ue}`);await cf({path:r,raw:l,migrated:{...u,audit:i},expectedMtimeMs:c.mtimeMs}),a.push({path:r,action:"updated"})}catch(c){return vo(r,c.message)}try{await yl.rm(t),a.push({path:t,action:"removed"})}catch(c){a.push({path:t,action:"failed",message:c.message})}return a};var WS=["unchanged","created"],VS=["unchanged","created","updated","removed","failed"],Ag=async(e,t,r)=>{let n=await Rt(e);return go(e,{repoRoot:t,version:L.version,design:r,declaredType:n})},GS=async(e,t)=>{if(e.root)return[...await $g(t),...await fo(t,{version:L.version})];if(e.all){let n=[];for(let o of await ke(t))n.push(...await Ag(o,t,e.design));return n}let r=await lo(e.cwd??US.cwd());return Ag(r,t,e.design)},JS=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 ${VS.filter(n=>WS.includes(n)||(t.get(n)??0)>0).map(n=>`${t.get(n)??0} ${n}`).join(", ")} (infra-kit ${L.version})`},KS=(e,t)=>{for(let r of e){if(r.action==="unchanged")continue;let n=BS.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(JS(e))},HS=e=>{let t={path:e.path,action:e.action};return e.type&&(t.type=e.type),t},Og=async(e,t)=>{let r=await A();ui();let n=await Hr(t),o=await GS(e,r);KS(o,r),ui();let s=await Hr(t),i=!e.all&&!e.root;return{fixed:o.map(HS),adoptionFlipped:i&&!n.adopted&&s.adopted}};import wi from"node:fs/promises";import ki from"node:path";import qS from"yaml";var wo="dependency-drift",vl="@slip-stream-kit/",YS="infra-kit",zS=["dependencies","devDependencies","optionalDependencies"],Ng=e=>e.startsWith("workspace:")||e.startsWith("link:")||e.startsWith("file:"),kl=e=>e.startsWith("catalog:"),XS=(e,t,r)=>{if(!kl(e))return e;let n=e.slice(8);return n===""||n==="default"?t.default[r]:t.named[n]?.[r]},Dg=e=>{let t=e.slice(Math.max(e.search(/\d/),0)).match(/^(\d+)\.(\d+)\.\d/);return t?[Number(t[1]),Number(t[2])]:null},ZS=(e,t)=>{let r=Dg(e),n=Dg(t);return!r||!n?!1:r[0]<n[0]||r[0]===n[0]&&r[1]<n[1]},QS=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},wl=e=>e.map(t=>`${t.file} "${t.spec}"`).join(", "),eE=(e,t)=>[...QS(e)].flatMap(([r,n])=>{if(t.default[r]!==void 0){let o=n.filter(s=>!kl(s.spec));return o.length===0?[]:[{name:`${wo}:catalog`,status:"warn",message:`${r} has a catalog entry (${t.default[r]}) but ${wl(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:`${wo}:catalog`,status:"warn",message:`${r} is pinned at more than one range: ${wl(n)} \u2014 add one entry to the pnpm-workspace.yaml catalog, then run \`ik audit --fix --root\``}]}),tE=(e,t,r)=>{let n=new Map;for(let o of e){let s=XS(o.spec,t,o.name);s!==void 0&&ZS(s,r)&&n.set(`${o.name}@${s}`,o.name)}return[...n.keys()].map(o=>({name:`${wo}: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===YS);return t.length===0?[]:[{name:`${wo}:infra-kit-pin`,status:"warn",message:`${wl(t)} \u2014 the repo runs the global infra-kit CLI; a local dependency is a second copy that can skew from it`}]},nE=(e,t,r)=>{let n=e.filter(i=>!Ng(i.spec)),o=n.filter(i=>i.name.startsWith(vl)),s=[...eE(o,t),...tE(o,t,r),...rE(n)];return s.length>0?s:[{name:wo,status:"pass",message:`no ${vl}* or infra-kit dependency drift`}]},oE=async e=>{try{return JSON.parse(await wi.readFile(e,"utf-8"))}catch{return null}},sE=async e=>{try{let t=qS.parse(await wi.readFile(ki.join(e,"pnpm-workspace.yaml"),"utf-8"))??{};return{default:t.catalog??{},named:t.catalogs??{}}}catch{return{default:{},named:{}}}},iE=async e=>{let t=await ke(e).catch(()=>[]);return[e,...t].map(r=>ki.join(r,"package.json"))},Ig=async e=>{let t=[];for(let r of await iE(e)){let n=await oE(r);if(!n)continue;let o=ki.relative(e,r);for(let s of zS){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},aE=async(e,t,r)=>{let n=t.filter(s=>s.name.startsWith(vl)&&!Ng(s.spec)&&!kl(s.spec)&&r.default[s.name]!==void 0),o=[...new Set(n.map(s=>s.file))];for(let s of o){let i=ki.join(e,s),a=await wi.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 wi.writeFile(i,`${JSON.stringify(c,null,l)}
152
- `,"utf-8")}return o},_g=async(e,t,r=L.version)=>{let n=await sE(e),o=await Ig(e),s=t?await aE(e,o,n):[],i=s.length>0?await Ig(e):o;return{checks:nE(i,n,r),rewritten:s}};import jg from"node:path";var bi="agent-guidance:drift",cE={root:"ik audit --fix --root",all:"ik audit --fix --all",package:"ik audit --fix"},Mg=(e,t)=>e.split(`
151
+ `:"";return Ri.writeFileSync(e,`${JSON.stringify(n,null,s)}${i}`,"utf-8"),{status:"added",path:e,added:o}};var KS="empty-rules",HS=["requiredScripts","requiredFiles"],Cg=(e,t,r)=>HS.filter(n=>e[n]?.length===0).map(n=>({name:KS,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`})),$g=async(e,t)=>{try{if(t){let{audit:r={}}=await K();return Cg(r,pr,'infra-kit.json "audit"')}return Cg(await ct(e)??{},at,"infra-kit.config.ts")}catch{return[]}};import zS from"node:path";import XS from"node:process";import kl from"node:fs/promises";import Ag from"node:path";var qS="infra-kit.json",Og=["requiredScripts","requiredFiles","turbo"],wo=(e,t)=>[{path:e,action:"failed",message:t}],YS=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Dg=async e=>{let t=Ag.join(e,ue),r=Ag.join(e,qS),n;try{n=await ct(e)}catch(c){return wo(t,c.message)}if(!n)return[];let o={...n},s=Object.keys(o).filter(c=>!Og.includes(c));if(s.length>0)return wo(t,`declares ${s.join(", ")}, which mean nothing at the repo root \u2014 remove them, then re-run`);let i=Object.fromEntries(Og.filter(c=>o[c]!==void 0).map(c=>[c,o[c]])),a=[];if(Object.keys(i).length>0)try{let c=await kl.stat(r),l=await kl.readFile(r,"utf8"),u=JSON.parse(l);if(!YS(u))return wo(r,"is not a JSON object");if("audit"in u)return wo(r,`already has an "audit" block \u2014 merge ${ue}'s rules into it by hand, then delete ${ue}`);await df({path:r,raw:l,migrated:{...u,audit:i},expectedMtimeMs:c.mtimeMs}),a.push({path:r,action:"updated"})}catch(c){return wo(r,c.message)}try{await kl.rm(t),a.push({path:t,action:"removed"})}catch(c){a.push({path:t,action:"failed",message:c.message})}return a};var ZS=["unchanged","created"],QS=["unchanged","created","updated","removed","failed"],Ig=async(e,t,r)=>{let n=await Et(e);return ho(e,{repoRoot:t,version:L.version,design:r,declaredType:n})},eE=async(e,t)=>{if(e.root)return[...await Dg(t),...await go(t,{version:L.version})];if(e.all){let n=[];for(let o of await be(t))n.push(...await Ig(o,t,e.design));return n}let r=await uo(e.cwd??XS.cwd());return Ig(r,t,e.design)},tE=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 ${QS.filter(n=>ZS.includes(n)||(t.get(n)??0)>0).map(n=>`${t.get(n)??0} ${n}`).join(", ")} (infra-kit ${L.version})`},rE=(e,t)=>{for(let r of e){if(r.action==="unchanged")continue;let n=zS.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(tE(e))},nE=e=>{let t={path:e.path,action:e.action};return e.type&&(t.type=e.type),t},Ng=async(e,t)=>{let r=await A();fi();let n=await qr(t),o=await eE(e,r);rE(o,r),fi();let s=await qr(t),i=!e.all&&!e.root;return{fixed:o.map(nE),adoptionFlipped:i&&!n.adopted&&s.adopted}};import Si from"node:fs/promises";import Ei from"node:path";import oE from"yaml";var ko="dependency-drift",bl="@slip-stream-kit/",sE="infra-kit",iE=["dependencies","devDependencies","optionalDependencies"],jg=e=>e.startsWith("workspace:")||e.startsWith("link:")||e.startsWith("file:"),Sl=e=>e.startsWith("catalog:"),aE=(e,t,r)=>{if(!Sl(e))return e;let n=e.slice(8);return n===""||n==="default"?t.default[r]:t.named[n]?.[r]},_g=e=>{let t=e.slice(Math.max(e.search(/\d/),0)).match(/^(\d+)\.(\d+)\.\d/);return t?[Number(t[1]),Number(t[2])]:null},cE=(e,t)=>{let r=_g(e),n=_g(t);return!r||!n?!1:r[0]<n[0]||r[0]===n[0]&&r[1]<n[1]},lE=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},Rl=e=>e.map(t=>`${t.file} "${t.spec}"`).join(", "),uE=(e,t)=>[...lE(e)].flatMap(([r,n])=>{if(t.default[r]!==void 0){let o=n.filter(s=>!Sl(s.spec));return o.length===0?[]:[{name:`${ko}:catalog`,status:"warn",message:`${r} has a catalog entry (${t.default[r]}) but ${Rl(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:`${ko}:catalog`,status:"warn",message:`${r} is pinned at more than one range: ${Rl(n)} \u2014 add one entry to the pnpm-workspace.yaml catalog, then run \`ik audit --fix --root\``}]}),dE=(e,t,r)=>{let n=new Map;for(let o of e){let s=aE(o.spec,t,o.name);s!==void 0&&cE(s,r)&&n.set(`${o.name}@${s}`,o.name)}return[...n.keys()].map(o=>({name:`${ko}:lockstep`,status:"warn",message:`${o} is behind the infra-kit ${r} lockstep release \u2014 bump it to ^${r}`}))},pE=e=>{let t=e.filter(r=>r.name===sE);return t.length===0?[]:[{name:`${ko}:infra-kit-pin`,status:"warn",message:`${Rl(t)} \u2014 the repo runs the global infra-kit CLI; a local dependency is a second copy that can skew from it`}]},mE=(e,t,r)=>{let n=e.filter(i=>!jg(i.spec)),o=n.filter(i=>i.name.startsWith(bl)),s=[...uE(o,t),...dE(o,t,r),...pE(n)];return s.length>0?s:[{name:ko,status:"pass",message:`no ${bl}* or infra-kit dependency drift`}]},fE=async e=>{try{return JSON.parse(await Si.readFile(e,"utf-8"))}catch{return null}},gE=async e=>{try{let t=oE.parse(await Si.readFile(Ei.join(e,"pnpm-workspace.yaml"),"utf-8"))??{};return{default:t.catalog??{},named:t.catalogs??{}}}catch{return{default:{},named:{}}}},hE=async e=>{let t=await be(e).catch(()=>[]);return[e,...t].map(r=>Ei.join(r,"package.json"))},Mg=async e=>{let t=[];for(let r of await hE(e)){let n=await fE(r);if(!n)continue;let o=Ei.relative(e,r);for(let s of iE){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},yE=async(e,t,r)=>{let n=t.filter(s=>s.name.startsWith(bl)&&!jg(s.spec)&&!Sl(s.spec)&&r.default[s.name]!==void 0),o=[...new Set(n.map(s=>s.file))];for(let s of o){let i=Ei.join(e,s),a=await Si.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 Si.writeFile(i,`${JSON.stringify(c,null,l)}
152
+ `,"utf-8")}return o},Fg=async(e,t,r=L.version)=>{let n=await gE(e),o=await Mg(e),s=t?await yE(e,o,n):[],i=s.length>0?await Mg(e):o;return{checks:mE(i,n,r),rewritten:s}};import Bg from"node:path";var Pi="agent-guidance:drift",vE={root:"ik audit --fix --root",all:"ik audit --fix --all",package:"ik audit --fix"},Lg=(e,t)=>e.split(`
153
153
  `).filter(r=>!r.startsWith(t)).join(`
154
- `),Fg=({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=li(r,t,n);if(Mg(a,o)===Mg(c,o))return{name:bi,status:"pass",message:`matches infra-kit ${s}`};let l=pr(a,o),u=cE[i];return l!==null&&kt(l,s)?{name:bi,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&&kt(s,l)?{name:bi,status:"warn",message:`block from infra-kit ${l} differs from what infra-kit ${s} generates \u2014 run \`${u}\``}:{name:bi,status:"warn",message:`block differs from what infra-kit ${s} generates (edited inside the markers?) \u2014 run \`${u}\``}},Lg=(e,t=L.version)=>{let r=lt(jg.join(e,"CLAUDE.md"));return r===null||!We(r,be,De)?null:Fg({content:r,expectedBody:uo(t),startMarker:be,endMarker:De,versionPrefix:mr,current:t,scope:"root"})},Bg=async(e,t,r,n=L.version)=>{let o=lt(jg.join(e,"CLAUDE.md"));if(o===null||Et(o).state!=="ok")return null;let s;try{({body:s}=await gi(e,{repoRoot:t,version:n,declaredType:await Rt(e)}))}catch{return null}return Fg({content:o,expectedBody:s,startMarker:Ve,endMarker:Qe,versionPrefix:St,current:n,scope:r})};import Wg from"node:fs";import Vg from"node:path";var bl="ik-mcp",Ug=(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:bl,args:r}};var Ri="run `infra-kit setup` (or `infra-kit audit --root --fix`)",lE=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((r,n)=>r===t[n]),Rl=e=>gr(e)&&e.command===bl,uE=(e,t)=>({...e??{},type:t.type,command:t.command,args:t.args}),dE=(e,t,r)=>{let n=[],o={...e},s=!1;for(let[i,a]of Object.entries(t)){let c=Ug(i,a),l=e[i];if(l!==void 0&&!Rl(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 ${Ri}, or drop mcp.${i} from infra-kit.json`});continue}if(Rl(l)&&l.type===c.type&&lE(l.args,c.args)){n.push({name:i,status:"unchanged",message:""});continue}if(r){o[i]=uE(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: ${Ri}`:`"${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: ${Ri}`})}for(let[i,a]of Object.entries(e))Object.hasOwn(t,i)||!Rl(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}},pE=(e,t,r)=>{let n=r===null?dl:wg(r),o=r===null||r.endsWith(`
154
+ `),Ug=({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=mi(r,t,n);if(Lg(a,o)===Lg(c,o))return{name:Pi,status:"pass",message:`matches infra-kit ${s}`};let l=fr(a,o),u=vE[i];return l!==null&&Rt(l,s)?{name:Pi,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&&Rt(s,l)?{name:Pi,status:"warn",message:`block from infra-kit ${l} differs from what infra-kit ${s} generates \u2014 run \`${u}\``}:{name:Pi,status:"warn",message:`block differs from what infra-kit ${s} generates (edited inside the markers?) \u2014 run \`${u}\``}},Wg=(e,t=L.version)=>{let r=lt(Bg.join(e,"CLAUDE.md"));return r===null||!We(r,Re,De)?null:Ug({content:r,expectedBody:po(t),startMarker:Re,endMarker:De,versionPrefix:gr,current:t,scope:"root"})},Vg=async(e,t,r,n=L.version)=>{let o=lt(Bg.join(e,"CLAUDE.md"));if(o===null||xt(o).state!=="ok")return null;let s;try{({body:s}=await wi(e,{repoRoot:t,version:n,declaredType:await Et(e)}))}catch{return null}return Ug({content:o,expectedBody:s,startMarker:Ve,endMarker:Qe,versionPrefix:Pt,current:n,scope:r})};import Jg from"node:fs";import Kg from"node:path";var El="ik-mcp",Gg=(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:El,args:r}};var xi="run `infra-kit setup` (or `infra-kit audit --root --fix`)",wE=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((r,n)=>r===t[n]),Pl=e=>yr(e)&&e.command===El,kE=(e,t)=>({...e??{},type:t.type,command:t.command,args:t.args}),bE=(e,t,r)=>{let n=[],o={...e},s=!1;for(let[i,a]of Object.entries(t)){let c=Gg(i,a),l=e[i];if(l!==void 0&&!Pl(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 ${xi}, or drop mcp.${i} from infra-kit.json`});continue}if(Pl(l)&&l.type===c.type&&wE(l.args,c.args)){n.push({name:i,status:"unchanged",message:""});continue}if(r){o[i]=kE(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: ${xi}`:`"${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: ${xi}`})}for(let[i,a]of Object.entries(e))Object.hasOwn(t,i)||!Pl(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}},RE=(e,t,r)=>{let n=r===null?fl:Rg(r),o=r===null||r.endsWith(`
155
155
  `)?`
156
- `:"";try{return Wg.mkdirSync(Vg.dirname(e),{recursive:!0}),Wg.writeFileSync(e,`${JSON.stringify(t,null,n)}${o}`,"utf-8"),!0}catch(s){return d.warn(`Could not write ${e} (${fl(s)}) \u2014 the ik-mcp entries were not updated.`),!1}},ko=({projectRoot:e,proxies:t,write:r})=>{let n=Vg.join(e,Ge),o=pl(n);if(o.kind==="unreadable")return d.warn(`Could not read ${n} (${fl(o.error)}) \u2014 left it untouched.`),{status:"unreadable",path:n,entries:[],wrote:!1};let s=o.kind==="raw"?o.raw:null,i=s===null?{}:ml(s);if(!gr(i))return d.warn(`Could not parse ${n} \u2014 left it untouched. Fix the JSON, then ${Ri}.`),{status:"unparseable",path:n,entries:[],wrote:!1};let a=i[ut];if(a!==void 0&&!gr(a))return d.warn(`${n} has a "${ut}" that is not an object \u2014 left it untouched.`),{status:"unparseable",path:n,entries:[],wrote:!1};let c=dE(a??{},t,r);if(!c.changed)return{status:"ok",path:n,entries:c.entries,wrote:!1};let l=pE(n,{...i,[ut]:c.servers},s);return{status:l?"ok":"failed",path:n,entries:c.entries,wrote:l}};var Gg=async(e,t)=>{let r;try{r=(await H()).mcp}catch{return null}if(!r||Object.keys(r).length===0)return null;let n=ko({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 mE="workspace adopted \u2014 every other package now needs a CLAUDE.md: run infra-kit audit --fix --all",fE=async e=>e.root?[{dir:await A(),baseline:ur,isRoot:!0}]:e.all?(await ke(await A())).map(r=>({dir:r})):[{dir:await lo(e.cwd??Jg.cwd())}],gE=async e=>e.root||e.all?await A():e.cwd??Jg.cwd(),hE=async()=>{try{return await A()}catch{return}},yE=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}},vE=async(e,t)=>{let{fixed:r,adoptionFlipped:n}=await Og(e,t);return n&&d.info(mE),r},wE=e=>{if(Qr(e).kind!=="stale")return null;let t=`${Ge} still registers "${le}" \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 "${le}" 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}},kE=e=>e.root?"root":e.all?"all":"package",bE=async(e,t,r)=>{let n=await xg(e.dir,e.isRoot===!0);if(!e.isRoot){let a=await Bg(e.dir,r??e.dir,kE(t));return a?[a,...n]:n}let o=Lg(e.dir),{checks:s,rewritten:i}=await _g(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]},Si=async(e={})=>{let t=Uc(await gE(e)),r=e.fix?await vE(e,t):void 0,n=await fE(e),o=await Hr(t),s=await hE(),i=[];for(let u of n){let p=await al(u.dir,u.baseline,{adoption:o,isRoot:u.isRoot,repoRoot:s});p.checks.push(...await bE(u,e,s)),p.passed=p.checks.every(m=>m.status!=="fail"),i.push(p)}if(e.root){let u=await Gg(n[0].dir,e.fix===!0);u&&i.push(u);let p=wE(n[0].dir);p&&i.push(p)}let{allPassed:a,warnCount:c}=yE(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}},RE={all:Ie.boolean().optional().describe("Audit every non-vendor workspace package"),root:Ie.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},SE={allPassed:Ie.boolean().describe("Whether every audited package passed all checks (warnings do not fail it)"),warnCount:Ie.number().int().describe("How many checks reported a warning"),packages:Ie.array(Ie.object({name:Ie.string(),passed:Ie.boolean(),checks:Ie.array(Ie.object({name:Ie.string(),status:Ie.enum(["pass","warn","fail"]),message:Ie.string()}))})).describe("Per-package check results")},Sl=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:RE,outputSchema:SE,handler:e=>Si({all:e.all,root:e.root})});import{z as F}from"zod";import{$ as IE}from"zx";var El=1.959963984540054,EE=[/^co-authored-by:\s*claude\b/imu,/^claude-session:/imu],Pl=/\b(?:fix(?:es|ed)?|hotfix|bugfix|regression)\b/iu,xl=["pnpm-lock.yaml","package-lock.json","yarn.lock","bun.lockb","CHANGELOG.md"],PE=/This reverts commit ([0-9a-f]{7,40})/u,Hg=/^Revert "(.*)"(?: \(#\d+\))?$/u,qg="",Ei="",Yg=`--format=${qg}%H${Ei}%ct${Ei}%B${Ei}`,zg=e=>e.split(qg).filter(t=>t.trim()!=="").map(t=>{let[r="",n="0",o="",s=""]=t.split(Ei),i=o.trim();return{hash:r,committedAt:Number(n),subject:i.split(`
156
+ `:"";try{return Jg.mkdirSync(Kg.dirname(e),{recursive:!0}),Jg.writeFileSync(e,`${JSON.stringify(t,null,n)}${o}`,"utf-8"),!0}catch(s){return d.warn(`Could not write ${e} (${yl(s)}) \u2014 the ik-mcp entries were not updated.`),!1}},bo=({projectRoot:e,proxies:t,write:r})=>{let n=Kg.join(e,Ge),o=gl(n);if(o.kind==="unreadable")return d.warn(`Could not read ${n} (${yl(o.error)}) \u2014 left it untouched.`),{status:"unreadable",path:n,entries:[],wrote:!1};let s=o.kind==="raw"?o.raw:null,i=s===null?{}:hl(s);if(!yr(i))return d.warn(`Could not parse ${n} \u2014 left it untouched. Fix the JSON, then ${xi}.`),{status:"unparseable",path:n,entries:[],wrote:!1};let a=i[ut];if(a!==void 0&&!yr(a))return d.warn(`${n} has a "${ut}" that is not an object \u2014 left it untouched.`),{status:"unparseable",path:n,entries:[],wrote:!1};let c=bE(a??{},t,r);if(!c.changed)return{status:"ok",path:n,entries:c.entries,wrote:!1};let l=RE(n,{...i,[ut]:c.servers},s);return{status:l?"ok":"failed",path:n,entries:c.entries,wrote:l}};var Hg=async(e,t)=>{let r;try{r=(await K()).mcp}catch{return null}if(!r||Object.keys(r).length===0)return null;let n=bo({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 SE="workspace adopted \u2014 every other package now needs a CLAUDE.md: run infra-kit audit --fix --all",EE=async e=>e.root?[{dir:await A(),baseline:pr,isRoot:!0}]:e.all?(await be(await A())).map(r=>({dir:r})):[{dir:await uo(e.cwd??qg.cwd())}],PE=async e=>e.root||e.all?await A():e.cwd??qg.cwd(),xE=async()=>{try{return await A()}catch{return}},TE=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}},CE=async(e,t)=>{let{fixed:r,adoptionFlipped:n}=await Ng(e,t);return n&&d.info(SE),r},$E=e=>{if(en(e).kind!=="stale")return null;let t=`${Ge} still registers "${le}" \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 "${le}" 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}},AE=e=>e.root?"root":e.all?"all":"package",OE=async(e,t,r)=>{let n=await $g(e.dir,e.isRoot===!0);if(!e.isRoot){let a=await Vg(e.dir,r??e.dir,AE(t));return a?[a,...n]:n}let o=Wg(e.dir),{checks:s,rewritten:i}=await Fg(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]},Ti=async(e={})=>{let t=Gc(await PE(e)),r=e.fix?await CE(e,t):void 0,n=await EE(e),o=await qr(t),s=await xE(),i=[];for(let u of n){let p=await ul(u.dir,u.baseline,{adoption:o,isRoot:u.isRoot,repoRoot:s});p.checks.push(...await OE(u,e,s)),p.passed=p.checks.every(m=>m.status!=="fail"),i.push(p)}if(e.root){let u=await Hg(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}=TE(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}},DE={all:Ie.boolean().optional().describe("Audit every non-vendor workspace package"),root:Ie.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},IE={allPassed:Ie.boolean().describe("Whether every audited package passed all checks (warnings do not fail it)"),warnCount:Ie.number().int().describe("How many checks reported a warning"),packages:Ie.array(Ie.object({name:Ie.string(),passed:Ie.boolean(),checks:Ie.array(Ie.object({name:Ie.string(),status:Ie.enum(["pass","warn","fail"]),message:Ie.string()}))})).describe("Per-package check results")},xl=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:DE,outputSchema:IE,handler:e=>Ti({all:e.all,root:e.root})});import{z as F}from"zod";import{$ as VE}from"zx";var Tl=1.959963984540054,NE=[/^co-authored-by:\s*claude\b/imu,/^claude-session:/imu],Cl=/\b(?:fix(?:es|ed)?|hotfix|bugfix|regression)\b/iu,$l=["pnpm-lock.yaml","package-lock.json","yarn.lock","bun.lockb","CHANGELOG.md"],_E=/This reverts commit ([0-9a-f]{7,40})/u,zg=/^Revert "(.*)"(?: \(#\d+\))?$/u,Xg="",Ci="",Zg=`--format=${Xg}%H${Ci}%ct${Ci}%B${Ci}`,Qg=e=>e.split(Xg).filter(t=>t.trim()!=="").map(t=>{let[r="",n="0",o="",s=""]=t.split(Ci),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)}}),xE=e=>EE.some(t=>t.test(e.body))?"agent":"human",Tl=e=>Hg.test(e.subject),TE=e=>!Tl(e)&&Pl.test(e.subject),CE=(e,t)=>{if(t===0)return null;let r=e/t,n=El*El,o=1+n/t,s=(r+n/(2*t))/o,i=El*Math.sqrt(r*(1-r)/t+n/(4*t*t))/o;return{low:Math.max(0,s-i),high:Math.min(1,s+i)}},Pi=e=>Math.round(e*1e4)/1e4,Kg=(e,t)=>{let r=CE(e,t);return{hits:e,n:t,rate:t===0?null:Pi(e/t),ci95:r&&{low:Pi(r.low),high:Pi(r.high)}}},$E=e=>{let t=new Set;for(let[r,n]of e.entries()){if(!Tl(n))continue;let o=e.slice(0,r),s=PE.exec(n.body)?.[1],i=Hg.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},AE=(e,t)=>{let r=new Set(e.files.filter(n=>!xl.includes(n.split("/").at(-1)??n)));return t.files.some(n=>r.has(n))},OE=(e,t,r)=>r.slice(t+1).some(n=>n.committedAt-e.committedAt<=259200&&TE(n)&&AE(e,n)),Xg=(e,t)=>{let r=$E(e),n=o=>{let s=e.map((u,p)=>({commit:u,position:p})).filter(({commit:u})=>o(xE(u))),i=s.filter(({commit:u})=>!Tl(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})=>OE(u,p,e)).length;return{commits:s.length,reverts:s.length-i.length,changes:i.length,revertRate:Kg(c,i.length),followUpFixRate:Kg(l,a.length)}};return{agent:n(o=>o==="agent"),human:n(o=>o==="human"),total:n(()=>!0)}},Cl=(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:Pi(e.rate-t.rate),intervalsOverlap:e.ci95.low<=t.ci95.high&&t.ci95.low<=e.ci95.high}};var bo=90,NE=864e5,_E=async(e,t)=>{if(await xe(e,"HEAD")===null)return[];let r=`--since=${t}`,n=await IE({cwd:e,quiet:!0})`git log --no-merges --name-only ${r} ${Yg}`;return zg(n.stdout).toReversed().sort((o,s)=>o.committedAt-s.committedAt)},rh=async({cwd:e,sinceDays:t,nowMs:r})=>{let n=new Date(r-t*NE).toISOString(),o=await _E(e,n),s=Xg(o,Math.floor(r/1e3));return{repoRoot:e,sinceDays:t,from:n,until:new Date(r).toISOString(),classes:s,comparison:{minN:30,revertRate:Cl(s.agent.revertRate,s.human.revertRate),followUpFixRate:Cl(s.agent.followUpFixRate,s.human.followUpFixRate)},heuristics:{agentTrailers:["Co-Authored-By: Claude\u2026","Claude-Session:"],fixSubjectPattern:Pl.source,followUpWindowHours:72,followUpIgnoredFiles:xl,mergesExcluded:!0}}},xi=e=>`${(e*100).toFixed(1)}%`,Zg=e=>e.rate===null||!e.ci95?"n/a (n=0)":`${xi(e.rate)} (${e.hits}/${e.n}, 95% CI ${xi(e.ci95.low)}\u2013${xi(e.ci95.high)})`,$l=(e,t)=>[` ${e}: ${t.commits} commits (${t.reverts} reverts)`,` revert rate: ${Zg(t.revertRate)}`,` ${72}h follow-up-fix rate: ${Zg(t.followUpFixRate)}`].join(`
159
- `),Ti=async({since:e=bo})=>{let t=await rh({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($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 = ${xi(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}},Qg=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")}),Al=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:Qg.describe("Changes later reverted by an in-range commit"),followUpFixRate:Qg.describe("Changes at least 72h old followed within 72h by a fix-subject commit touching a shared file")}),eh=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")}),Ol=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 ${bo})`)},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:Al,human:Al,total:Al}),comparison:F.object({minN:F.number(),revertRate:eh,followUpFixRate:eh}),heuristics:F.object({agentTrailers:F.array(F.string()),fixSubjectPattern:F.string(),followUpWindowHours:F.number(),followUpIgnoredFiles:F.array(F.string()),mergesExcluded:F.boolean()})},handler:Ti});import{z as Gt}from"zod";import Dl from"node:fs/promises";import ME from"node:path";var tn=()=>Object.keys(mf.shape).filter(e=>e!=="$schema"&&e!=="configVersion"),jE=new Set(["protectedEnvs"]),Ro={project:"per-project override",global:"user-global override"},Ci=(e,t)=>{if(ge()&&jE.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(!tn().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: ${tn().join(", ")}.`)}},nh=e=>{try{return JSON.parse(e)}catch{return e}},FE=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),LE=async e=>{let t;try{t=await Dl.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(!FE(r))throw new Error(`${w(e)} is not a JSON object \u2014 fix it with \`infra-kit config edit\`.`);return{raw:t,data:r}},BE=async(e,t)=>{t===null?await Dl.rm(e,{force:!0}):It(e,t,420),Zn()},$i=async(e,t,r)=>{let n=await ee(),o=e==="global"?n.userGlobal:n.userProject,{raw:s,data:i}=await LE(o),a=i[t],c=r({...i});if(c===null)return{file:o,previous:a,changed:!1};await Dl.mkdir(ME.dirname(o),{recursive:!0}),It(o,`${JSON.stringify(c,null,2)}
161
- `,420),Zn();try{await H({autoMigrate:"off"})}catch(l){throw await BE(o,s),new Error(`${l.message}
162
- ${w(o)} was left unchanged.`)}return{file:o,previous:a,changed:!0}},Il=async({key:e,value:t,global:r})=>{Ci(e,"config-set");let n=r?"global":"project",o=nh(t),{file:s,previous:i}=await $i(n,e,c=>({...c,[e]:o}));d.info(`Set ${e} = ${JSON.stringify(o)} in the ${Ro[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 Ai=async({key:e}={})=>{let[t,r]=await Promise.all([H(),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(!tn().includes(e))throw new Error(`Unknown config key "${e}". Top-level keys: ${tn().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}},UE={config:Gt.record(Gt.string(),Gt.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:Gt.string().describe("Absolute path to the project-level infra-kit.json (the base layer / committed source of truth)."),key:Gt.string().optional().describe("The top-level key asked for, when one was."),value:Gt.unknown().optional().describe("The merged value of `key` (null when no layer sets it)."),projectName:Gt.string().describe("Repository name the config is keyed to (the main-repo basename; shared across all worktrees of the repo).")},Nl=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:Gt.string().optional().describe("Report only this top-level key as `value` (e.g. `ide`).")},outputSchema:UE,handler:e=>Ai(e)});import HE from"node:fs";import{z as de}from"zod";import Eo from"node:fs";import rn from"node:path";import WE from"node:process";var VE=rn.join(".infra-kit","dev-context"),GE=".infra-kit",oh=(e,t)=>{let r=rn.resolve(e);for(;;){let n=rn.join(r,t);if(Eo.existsSync(n))return n;let o=rn.dirname(r);if(o===r)return;r=o}},JE=e=>{let t=oh(e,VE);if(t)return t;let r=oh(e,GE);return r?rn.join(r,"dev-context"):void 0},_l=e=>typeof e=="number"&&Number.isFinite(e)?e:0,So=e=>typeof e=="string"?e:"",KE=(e,t,r)=>{let n=rn.join(e,t);try{let o=Eo.statSync(n),s=JSON.parse(Eo.readFileSync(n,"utf-8"));if(typeof s!="object"||s===null)return null;let i=s;return{app:t.replace(/\.json$/,""),package:So(i.package),port:_l(i.port),alias:So(i.alias),origin:So(i.origin),release:So(i.release),env:So(i.env),pid:_l(i.pid),writtenAt:_l(i.writtenAt),mtimeMs:Math.round(o.mtimeMs),ageMs:Math.max(0,Math.round(r-o.mtimeMs))}}catch{return null}},Po=(e=WE.cwd())=>{let t=Date.now(),r=JE(e);if(!r||!Eo.existsSync(r))return{session:"none",fragmentDir:r,readAt:t,apps:[]};let n;try{n=Eo.readdirSync(r).filter(s=>s.endsWith(".json"))}catch{return{session:"none",fragmentDir:r,readAt:t,apps:[]}}let o=n.map(s=>KE(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 Oi=async(e={})=>{let t=e.now??Date.now,r=e.isListening??Yn,n=Po(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&&(HE.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}},qE={active:de.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:de.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:de.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:de.array(de.object({app:de.string().describe("App folder name (the fragment filename without .json)."),package:de.string().describe("The app package name the vite helper reads to decide a local route."),port:de.number().describe("The actual bound port the dev server is listening on."),pid:de.number().describe("PID of the dev-server process that wrote the fragment (ownership / staleness metadata)."),alias:de.string().describe("Registered portless hostname for the app."),origin:de.string().describe("Authoritative local origin the vite helper proxies to for this app."),release:de.string().describe("Release slug the runner recorded for this worktree."),env:de.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:de.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:de.string().describe("ISO 8601 filesystem mtime of the fragment file \u2014 the AUTHORITATIVE freshness signal."),ageSeconds:de.number().describe("Seconds since the fragment was last written on disk. A large value with live:false means a stale/abandoned fragment."),live:de.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.")},Ml=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:qE,handler:()=>Oi()});import{spawnSync as av}from"node:child_process";import ie from"node:fs";import cv from"node:os";import ye from"node:path";import gt from"node:process";import{z as Re}from"zod";import{execFileSync as YE}from"node:child_process";var sh=(e,t)=>{let r=e.filter(n=>!n.live).map(n=>n.name);return t?{prunable:[],withheld:r}:{prunable:r,withheld:[]}},zE=[/\binfra-kit\s+dev\b/,/cli\.js\s+dev\b/,/dev-server\.(?:js|ts)\b/],XE=e=>zE.some(t=>t.test(e)),ZE="/bin/ps",QE=()=>YE(ZE,["-eo","command="],{encoding:"utf8",maxBuffer:8<<20}).split(`
163
- `),ih=(e=QE)=>{try{return e().some(XE)}catch{return!0}};import{Chalk as eP}from"chalk";import jl from"node:process";var Fl={unicode:{ok:"\u2713",changed:"+",skipped:"-",manual:">",warn:"!",fail:"\u2717",separator:"\xB7",rule:"\u2500"},ascii:{ok:"ok",changed:"++",skipped:"--",manual:">>",warn:"!?",fail:"!!",separator:"-",rule:"-"}},tP=new Set(["warn","fail"]),rP=24,nn=" ",ah=" ",nP=(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:[""]},ch=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},oP=e=>{let t=new eP({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)}},lh=(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),sP=(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=lh(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}},iP=(e,t,r,n)=>{let o=sP(ch(e.rows),e.rows.length,t,r),s=Math.max(1,n-nn.length-e.label.length-o.plainWidth);return`${nn}${t.header(e.label)}${" ".repeat(s)}${o.text}`},aP=(e,t,r,n,o)=>{let s=tP.has(e.status),i=n.ok.length,a=e.name.padEnd(t),c=r[e.status],l=s?c(a):a,u=ah.length+i+1+t+2,p=Math.max(rP,o-u),[m,...f]=nP(e.message,p),v=" ".repeat(u),E=h=>s?h:r.dim(h);return[`${ah}${c(n[e.status])} ${l} ${E(m??"")}`.trimEnd(),...f.map(h=>`${v}${E(h)}`),...(e.notes??[]).map(h=>`${v}${h}`.trimEnd())]},cP=(e,t,r,n,o)=>{let s=ch(t),i=n.rule.repeat(Math.max(12,Math.min(o-nn.length,56))),a=lh(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[`${nn}${r.dim(i)}`,`${nn}${c}${l.join("")}`]},Ll=(e,t={})=>{let r=t.width??80,n=oP(t.color??!1),o=t.unicode??!0?Fl.unicode:Fl.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,"",`${nn}${n.dim(e.emptyMessage??"Nothing ran.")}`];let c=Math.max(...i.map(u=>u.name.length)),l=s.flatMap(u=>[iP(u,n,o,r),...u.rows.flatMap(p=>aP(p,c,n,o,r)),""]);return[a,"",...l,...cP(e,i,n,o,r)]},lP=new Set(["","0","false","none"]),uP=["LC_ALL","LC_CTYPE","LANG"],dP=(e,t)=>e.NO_COLOR!==void 0&&e.NO_COLOR!==""?!1:e.FORCE_COLOR!==void 0?!lP.has(e.FORCE_COLOR.toLowerCase()):!!t.isTTY,pP=(e,t)=>{if(t)return!1;let r=uP.map(n=>e[n]).find(n=>n!==void 0&&n!=="");return r===void 0?!0:/UTF-?8/i.test(r)},Bl=(e={})=>{let t=e.env??jl.env,r=e.stream??jl.stderr;return{color:dP(t,r),unicode:pP(t,e.ascii??!1),width:r.columns??80}},dt=(e,t={})=>{(t.write??(n=>{jl.stderr.write(n)}))(`${Ll(e,Bl(t)).join(`
158
+ `).map(a=>a.trim()).filter(Boolean)}}),ME=e=>NE.some(t=>t.test(e.body))?"agent":"human",Al=e=>zg.test(e.subject),jE=e=>!Al(e)&&Cl.test(e.subject),FE=(e,t)=>{if(t===0)return null;let r=e/t,n=Tl*Tl,o=1+n/t,s=(r+n/(2*t))/o,i=Tl*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,Yg=(e,t)=>{let r=FE(e,t);return{hits:e,n:t,rate:t===0?null:$i(e/t),ci95:r&&{low:$i(r.low),high:$i(r.high)}}},LE=e=>{let t=new Set;for(let[r,n]of e.entries()){if(!Al(n))continue;let o=e.slice(0,r),s=_E.exec(n.body)?.[1],i=zg.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},BE=(e,t)=>{let r=new Set(e.files.filter(n=>!$l.includes(n.split("/").at(-1)??n)));return t.files.some(n=>r.has(n))},UE=(e,t,r)=>r.slice(t+1).some(n=>n.committedAt-e.committedAt<=259200&&jE(n)&&BE(e,n)),eh=(e,t)=>{let r=LE(e),n=o=>{let s=e.map((u,p)=>({commit:u,position:p})).filter(({commit:u})=>o(ME(u))),i=s.filter(({commit:u})=>!Al(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})=>UE(u,p,e)).length;return{commits:s.length,reverts:s.length-i.length,changes:i.length,revertRate:Yg(c,i.length),followUpFixRate:Yg(l,a.length)}};return{agent:n(o=>o==="agent"),human:n(o=>o==="human"),total:n(()=>!0)}},Ol=(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 Ro=90,GE=864e5,JE=async(e,t)=>{if(await Te(e,"HEAD")===null)return[];let r=`--since=${t}`,n=await VE({cwd:e,quiet:!0})`git log --no-merges --name-only ${r} ${Zg}`;return Qg(n.stdout).toReversed().sort((o,s)=>o.committedAt-s.committedAt)},sh=async({cwd:e,sinceDays:t,nowMs:r})=>{let n=new Date(r-t*GE).toISOString(),o=await JE(e,n),s=eh(o,Math.floor(r/1e3));return{repoRoot:e,sinceDays:t,from:n,until:new Date(r).toISOString(),classes:s,comparison:{minN:30,revertRate:Ol(s.agent.revertRate,s.human.revertRate),followUpFixRate:Ol(s.agent.followUpFixRate,s.human.followUpFixRate)},heuristics:{agentTrailers:["Co-Authored-By: Claude\u2026","Claude-Session:"],fixSubjectPattern:Cl.source,followUpWindowHours:72,followUpIgnoredFiles:$l,mergesExcluded:!0}}},Ai=e=>`${(e*100).toFixed(1)}%`,th=e=>e.rate===null||!e.ci95?"n/a (n=0)":`${Ai(e.rate)} (${e.hits}/${e.n}, 95% CI ${Ai(e.ci95.low)}\u2013${Ai(e.ci95.high)})`,Dl=(e,t)=>[` ${e}: ${t.commits} commits (${t.reverts} reverts)`,` revert rate: ${th(t.revertRate)}`,` ${72}h follow-up-fix rate: ${th(t.followUpFixRate)}`].join(`
159
+ `),Oi=async({since:e=Ro})=>{let t=await sh({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(Dl("agent",r.agent)),d.info(Dl("human",r.human)),d.info(Dl("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 = ${Ai(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}},rh=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")}),Il=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:rh.describe("Changes later reverted by an in-range commit"),followUpFixRate:rh.describe("Changes at least 72h old followed within 72h by a fix-subject commit touching a shared file")}),nh=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")}),Nl=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 ${Ro})`)},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:Il,human:Il,total:Il}),comparison:F.object({minN:F.number(),revertRate:nh,followUpFixRate:nh}),heuristics:F.object({agentTrailers:F.array(F.string()),fixSubjectPattern:F.string(),followUpWindowHours:F.number(),followUpIgnoredFiles:F.array(F.string()),mergesExcluded:F.boolean()})},handler:Oi});import{z as Kt}from"zod";import _l from"node:fs/promises";import KE from"node:path";var rn=()=>Object.keys(hf.shape).filter(e=>e!=="$schema"&&e!=="configVersion"),HE=new Set(["protectedEnvs"]),So={project:"per-project override",global:"user-global override"},Di=(e,t)=>{if(he()&&HE.has(e))throw new D({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(!rn().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: ${rn().join(", ")}.`)}},ih=e=>{try{return JSON.parse(e)}catch{return e}},qE=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),YE=async e=>{let t;try{t=await _l.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(!qE(r))throw new Error(`${w(e)} is not a JSON object \u2014 fix it with \`infra-kit config edit\`.`);return{raw:t,data:r}},zE=async(e,t)=>{t===null?await _l.rm(e,{force:!0}):_t(e,t,420),Qn()},Ii=async(e,t,r)=>{let n=await ee(),o=e==="global"?n.userGlobal:n.userProject,{raw:s,data:i}=await YE(o),a=i[t],c=r({...i});if(c===null)return{file:o,previous:a,changed:!1};await _l.mkdir(KE.dirname(o),{recursive:!0}),_t(o,`${JSON.stringify(c,null,2)}
161
+ `,420),Qn();try{await K({autoMigrate:"off"})}catch(l){throw await zE(o,s),new Error(`${l.message}
162
+ ${w(o)} was left unchanged.`)}return{file:o,previous:a,changed:!0}},Ml=async({key:e,value:t,global:r})=>{Di(e,"config-set");let n=r?"global":"project",o=ih(t),{file:s,previous:i}=await Ii(n,e,c=>({...c,[e]:o}));d.info(`Set ${e} = ${JSON.stringify(o)} in the ${So[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 Ni=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(!rn().includes(e))throw new Error(`Unknown config key "${e}". Top-level keys: ${rn().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}},XE={config:Kt.record(Kt.string(),Kt.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:Kt.string().describe("Absolute path to the project-level infra-kit.json (the base layer / committed source of truth)."),key:Kt.string().optional().describe("The top-level key asked for, when one was."),value:Kt.unknown().optional().describe("The merged value of `key` (null when no layer sets it)."),projectName:Kt.string().describe("Repository name the config is keyed to (the main-repo basename; shared across all worktrees of the repo).")},jl=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:Kt.string().optional().describe("Report only this top-level key as `value` (e.g. `ide`).")},outputSchema:XE,handler:e=>Ni(e)});import nP from"node:fs";import{z as de}from"zod";import Po from"node:fs";import nn from"node:path";import ZE from"node:process";var QE=nn.join(".infra-kit","dev-context"),eP=".infra-kit",ah=(e,t)=>{let r=nn.resolve(e);for(;;){let n=nn.join(r,t);if(Po.existsSync(n))return n;let o=nn.dirname(r);if(o===r)return;r=o}},tP=e=>{let t=ah(e,QE);if(t)return t;let r=ah(e,eP);return r?nn.join(r,"dev-context"):void 0},Fl=e=>typeof e=="number"&&Number.isFinite(e)?e:0,Eo=e=>typeof e=="string"?e:"",rP=(e,t,r)=>{let n=nn.join(e,t);try{let o=Po.statSync(n),s=JSON.parse(Po.readFileSync(n,"utf-8"));if(typeof s!="object"||s===null)return null;let i=s;return{app:t.replace(/\.json$/,""),package:Eo(i.package),port:Fl(i.port),alias:Eo(i.alias),origin:Eo(i.origin),release:Eo(i.release),env:Eo(i.env),pid:Fl(i.pid),writtenAt:Fl(i.writtenAt),mtimeMs:Math.round(o.mtimeMs),ageMs:Math.max(0,Math.round(r-o.mtimeMs))}}catch{return null}},xo=(e=ZE.cwd())=>{let t=Date.now(),r=tP(e);if(!r||!Po.existsSync(r))return{session:"none",fragmentDir:r,readAt:t,apps:[]};let n;try{n=Po.readdirSync(r).filter(s=>s.endsWith(".json"))}catch{return{session:"none",fragmentDir:r,readAt:t,apps:[]}}let o=n.map(s=>rP(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 _i=async(e={})=>{let t=e.now??Date.now,r=e.isListening??zn,n=xo(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&&(nP.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}},oP={active:de.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:de.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:de.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:de.array(de.object({app:de.string().describe("App folder name (the fragment filename without .json)."),package:de.string().describe("The app package name the vite helper reads to decide a local route."),port:de.number().describe("The actual bound port the dev server is listening on."),pid:de.number().describe("PID of the dev-server process that wrote the fragment (ownership / staleness metadata)."),alias:de.string().describe("Registered portless hostname for the app."),origin:de.string().describe("Authoritative local origin the vite helper proxies to for this app."),release:de.string().describe("Release slug the runner recorded for this worktree."),env:de.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:de.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:de.string().describe("ISO 8601 filesystem mtime of the fragment file \u2014 the AUTHORITATIVE freshness signal."),ageSeconds:de.number().describe("Seconds since the fragment was last written on disk. A large value with live:false means a stale/abandoned fragment."),live:de.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.")},Ll=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:oP,handler:()=>_i()});import{spawnSync as uv}from"node:child_process";import ie from"node:fs";import dv from"node:os";import ve from"node:path";import gt from"node:process";import{z as Se}from"zod";import{execFileSync as sP}from"node:child_process";var ch=(e,t)=>{let r=e.filter(n=>!n.live).map(n=>n.name);return t?{prunable:[],withheld:r}:{prunable:r,withheld:[]}},iP=[/\binfra-kit\s+dev\b/,/cli\.js\s+dev\b/,/dev-server\.(?:js|ts)\b/],aP=e=>iP.some(t=>t.test(e)),cP="/bin/ps",lP=()=>sP(cP,["-eo","command="],{encoding:"utf8",maxBuffer:8<<20}).split(`
163
+ `),lh=(e=lP)=>{try{return e().some(aP)}catch{return!0}};import{Chalk as uP}from"chalk";import Bl from"node:process";var Ul={unicode:{ok:"\u2713",changed:"+",skipped:"-",manual:">",warn:"!",fail:"\u2717",separator:"\xB7",rule:"\u2500"},ascii:{ok:"ok",changed:"++",skipped:"--",manual:">>",warn:"!?",fail:"!!",separator:"-",rule:"-"}},dP=new Set(["warn","fail"]),pP=24,on=" ",uh=" ",mP=(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:[""]},dh=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},fP=e=>{let t=new uP({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)}},ph=(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),gP=(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=ph(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}},hP=(e,t,r,n)=>{let o=gP(dh(e.rows),e.rows.length,t,r),s=Math.max(1,n-on.length-e.label.length-o.plainWidth);return`${on}${t.header(e.label)}${" ".repeat(s)}${o.text}`},yP=(e,t,r,n,o)=>{let s=dP.has(e.status),i=n.ok.length,a=e.name.padEnd(t),c=r[e.status],l=s?c(a):a,u=uh.length+i+1+t+2,p=Math.max(pP,o-u),[m,...f]=mP(e.message,p),y=" ".repeat(u),E=O=>s?O:r.dim(O);return[`${uh}${c(n[e.status])} ${l} ${E(m??"")}`.trimEnd(),...f.map(O=>`${y}${E(O)}`),...(e.notes??[]).map(O=>`${y}${O}`.trimEnd())]},vP=(e,t,r,n,o)=>{let s=dh(t),i=n.rule.repeat(Math.max(12,Math.min(o-on.length,56))),a=ph(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[`${on}${r.dim(i)}`,`${on}${c}${l.join("")}`]},Wl=(e,t={})=>{let r=t.width??80,n=fP(t.color??!1),o=t.unicode??!0?Ul.unicode:Ul.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,"",`${on}${n.dim(e.emptyMessage??"Nothing ran.")}`];let c=Math.max(...i.map(u=>u.name.length)),l=s.flatMap(u=>[hP(u,n,o,r),...u.rows.flatMap(p=>yP(p,c,n,o,r)),""]);return[a,"",...l,...vP(e,i,n,o,r)]},wP=new Set(["","0","false","none"]),kP=["LC_ALL","LC_CTYPE","LANG"],bP=(e,t)=>e.NO_COLOR!==void 0&&e.NO_COLOR!==""?!1:e.FORCE_COLOR!==void 0?!wP.has(e.FORCE_COLOR.toLowerCase()):!!t.isTTY,RP=(e,t)=>{if(t)return!1;let r=kP.map(n=>e[n]).find(n=>n!==void 0&&n!=="");return r===void 0?!0:/UTF-?8/i.test(r)},Vl=(e={})=>{let t=e.env??Bl.env,r=e.stream??Bl.stderr;return{color:bP(t,r),unicode:RP(t,e.ascii??!1),width:r.columns??80}},dt=(e,t={})=>{(t.write??(n=>{Bl.stderr.write(n)}))(`${Wl(e,Vl(t)).join(`
164
164
  `)}
165
- `)};var mP="Tools & CLIs",fP="Shell & integration",gP="Project config",hP="Doppler env tokens",yP="Dev proxy (portless)",vP="Claude Code plugin",wP=`portless serving TLS on :${_t}`,Ul=[[mP,["brew installed","git installed","gh installed","gh authenticated","doppler installed","aws installed","package manager installed","typescript-language-server installed","orca installed"]],[fP,["zshrc init block","zshenv session block","pnpm enableGlobalVirtualStore","CLAUDE.md block","Guidance version"]],[gP,["infra-kit config valid","user override path","legacy user-global config","merge-dev resolutions"]],[hP,["tokens.json present","env tokens configured","tokens.json perms"]],[yP,["portless installed","portless node","portless service target",wP,"portless CA chain valid","portless CA trusted","portless routes"]],[vP,["claude CLI","marketplace registered","plugin installed","plugin version","plugin MCP server","CLI version","background setup","claude in chrome","Agent mode","Agent allowlist"]]],uh="Other",kP=Ul.map(([e])=>e),bP=new Map(Ul.flatMap(([e,t])=>t.map(r=>[r,e]))),cV=Ul.flatMap(([,e])=>e),Wl=new Set(["portless routes","tokens.json perms"]),RP=e=>{let t=new Map;for(let n of e){let o=bP.get(n.name)??uh,s=t.get(o);s?s.push(n):t.set(o,[n])}return[...kP,uh].flatMap(n=>{let o=t.get(n);return o&&o.length>0?[{label:n,checks:o}]:[]})};var SP=e=>{switch(e){case"pass":return"ok";case"fail":return"fail";case"warn":return"warn";case"skip":return"skipped";default:return Ue(e)}},EP=e=>{let t=e.filter(r=>r.status==="fail"&&Wl.has(r.name)).length;return{title:"infra-kit doctor",emptyMessage:"No checks ran.",sections:RP(e).map(r=>({label:r.label,rows:r.checks.map(n=>({name:n.name,status:SP(n.status),message:n.message}))})),hints:t>0?[`${t} fixable \u2014 run \`infra-kit doctor --fix\``]:[]}};var Vl=(e,t={})=>{dt(EP(e),t)};var PP=e=>e.replace(/&apos;/g,"'").replace(/&quot;/g,'"').replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&amp;/g,"&"),xP=e=>[...e.matchAll(/<string>([\s\S]*?)<\/string>/g)].map(t=>PP(t[1])),TP=e=>{let t=e.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/);return t===null?null:xP(t[1])},CP=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},$P=e=>{let t=e.split(`
166
- `).find(r=>r.startsWith("ExecStart="));return t===void 0?null:CP(t.slice(10))},dh=(e,t)=>{try{return e==="darwin"?TP(t):e==="linux"?$P(t):null}catch{return null}};import{Buffer as Ah}from"node:buffer";import _e from"node:fs/promises";import et from"node:path";import Oh from"node:process";import{$ as Wi}from"zx";import AP from"node:process";var xo=class extends Error{name="PromptCancelledError";constructor(){super("Prompt cancelled")}};var ph=e=>{let t={operation:"interactive branch selection",remediation:"pass the branch selection explicitly (`--version`/`--versions`/`--all`) for non-interactive, --json, or --agent runs"};if(Z())throw new O({status:"argument_required",argument:e,agentMode:j.source},2,t);if(!AP.stdin.isTTY)throw new g(void 0,t)},Jt=async e=>{ph("version");let{runBranchPicker:t}=await import("./boot-ST2534PA.js"),r=await t(e);if(r===null)throw new xo;return r},Kt=async(e,t)=>{ph("versions");let{runBranchMultiPicker:r}=await import("./boot-ST2534PA.js"),n=await r(e,t);if(n===null)throw new xo;return n};import{$ as wh}from"zx";import{$ as wV}from"zx";import{$ as sn}from"zx";import{$ as mh}from"zx";var Gl=async e=>{let{operation:t}=e;try{await mh({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 mh({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"})}},DP=4,on=async e=>{let{operation:t}=e,r=await Zm();if(r.length===0)return;d.error(`working tree has uncommitted changes:
165
+ `)};var SP="Tools & CLIs",EP="Shell & integration",PP="Project config",xP="Doppler env tokens",TP="Dev proxy (portless)",CP="Claude Code plugin",$P=`portless serving TLS on :${jt}`,Gl=[[SP,["brew installed","git installed","gh installed","gh authenticated","doppler installed","aws installed","package manager installed","typescript-language-server installed","orca installed"]],[EP,["zshrc init block","zshenv session block","pnpm enableGlobalVirtualStore","CLAUDE.md block","Guidance version"]],[PP,["infra-kit config valid","user override path","legacy user-global config","merge-dev resolutions"]],[xP,["tokens.json present","env tokens configured","tokens.json perms"]],[TP,["portless installed","portless node","portless service target",$P,"portless CA chain valid","portless CA trusted","portless routes"]],[CP,["claude CLI","marketplace registered","plugin installed","plugin version","plugin MCP server","CLI version","background setup","claude in chrome","Agent mode","Agent allowlist"]]],mh="Other",AP=Gl.map(([e])=>e),OP=new Map(Gl.flatMap(([e,t])=>t.map(r=>[r,e]))),kV=Gl.flatMap(([,e])=>e),Jl=new Set(["portless routes","tokens.json perms"]),DP=e=>{let t=new Map;for(let n of e){let o=OP.get(n.name)??mh,s=t.get(o);s?s.push(n):t.set(o,[n])}return[...AP,mh].flatMap(n=>{let o=t.get(n);return o&&o.length>0?[{label:n,checks:o}]:[]})};var IP=e=>{switch(e){case"pass":return"ok";case"fail":return"fail";case"warn":return"warn";case"skip":return"skipped";default:return Ue(e)}},NP=e=>{let t=e.filter(r=>r.status==="fail"&&Jl.has(r.name)).length;return{title:"infra-kit doctor",emptyMessage:"No checks ran.",sections:DP(e).map(r=>({label:r.label,rows:r.checks.map(n=>({name:n.name,status:IP(n.status),message:n.message}))})),hints:t>0?[`${t} fixable \u2014 run \`infra-kit doctor --fix\``]:[]}};var Kl=(e,t={})=>{dt(NP(e),t)};var _P=e=>e.replace(/&apos;/g,"'").replace(/&quot;/g,'"').replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&amp;/g,"&"),MP=e=>[...e.matchAll(/<string>([\s\S]*?)<\/string>/g)].map(t=>_P(t[1])),jP=e=>{let t=e.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/);return t===null?null:MP(t[1])},FP=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},LP=e=>{let t=e.split(`
166
+ `).find(r=>r.startsWith("ExecStart="));return t===void 0?null:FP(t.slice(10))},fh=(e,t)=>{try{return e==="darwin"?jP(t):e==="linux"?LP(t):null}catch{return null}};import{Buffer as Ih}from"node:buffer";import _e from"node:fs/promises";import et from"node:path";import Nh from"node:process";import{$ as Ki}from"zx";import BP from"node:process";var To=class extends Error{name="PromptCancelledError";constructor(){super("Prompt cancelled")}};var gh=e=>{let t={operation:"interactive branch selection",remediation:"pass the branch selection explicitly (`--version`/`--versions`/`--all`) for non-interactive, --json, or --agent runs"};if(Z())throw new D({status:"argument_required",argument:e,agentMode:j.source},2,t);if(!BP.stdin.isTTY)throw new g(void 0,t)},Ht=async e=>{gh("version");let{runBranchPicker:t}=await import("./boot-ST2534PA.js"),r=await t(e);if(r===null)throw new To;return r},qt=async(e,t)=>{gh("versions");let{runBranchMultiPicker:r}=await import("./boot-ST2534PA.js"),n=await r(e,t);if(n===null)throw new To;return n};import{$ as Rh}from"zx";import{$ as OV}from"zx";import{$ as an}from"zx";import{$ as hh}from"zx";var Hl=async e=>{let{operation:t}=e;try{await hh({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 hh({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"})}},WP=4,sn=async e=>{let{operation:t}=e,r=await tf();if(r.length===0)return;d.error(`working tree has uncommitted changes:
167
167
  ${r.join(`
168
- `)}`);let n=r.slice(0,DP),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}`})},To=async e=>{let{operation:t,base:r}=e;if(await Ur()===r)return;let n=(await ot(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}`})},Ne=async e=>{let{operation:t}=e;if(await ef())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 on({operation:t})};var IP=e=>e.map(t=>({pr:t,id:Q(t.headRefName)})).filter(t=>t.id!==null).sort((t,r)=>Xm(t.id,r.id,{a:t.pr.createdAt,b:r.pr.createdAt})).map(t=>t.pr),Co=200,fh=(e,t)=>{e.length<Co||d.warn({source:t,limit:Co},`\u26A0\uFE0F ${t} returned ${Co} PRs \u2014 the page is full, so older release PRs may be missing`)},NP=async()=>{let[e,t]=await Promise.all([sn`gh pr list --limit ${Co} --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,sn`gh pr list --limit ${Co} --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName,createdAt`]),r=JSON.parse(e.stdout),n=JSON.parse(t.stdout);fh(r,"release PR discovery (base dev)"),fh(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)}))},$o="find open release PRs",gh=async()=>{try{let e=await NP();if(e.length===0)throw new g(void 0,{operation:$o,remediation:"open a release PR first, or check you are in the right repo"});return IP(e)}catch(e){throw e instanceof g?e:(d.debug({err:e},"Error fetching release PRs"),new g(e,{operation:"fetch release PRs"}))}},Di=async()=>(await gh()).map(t=>t.headRefName),_P=e=>{let t=Ao(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=Jl(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}},V=async()=>(await gh()).map(_P),Ii=async e=>{let{branch:t,body:r}=e;try{await sn({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}},MP=async(e,t)=>{let r=sn({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`)},Ni=async e=>{let{id:t,jiraVersionUrl:r,type:n,description:o,baseSha:s}=e,i=zm(t,n),a=pt(n),c=sn({quiet:!0}),l=Pe(t),u=Oo(r,o);try{await on({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 MP(l,a),m}}catch(p){throw d.error({error:p,branchName:l},`Error creating release branch ${l}`),p}finally{await sn({quiet:!0,nothrow:!0})`git switch ${a}`}};import{$ as Kl}from"zx";var an=async e=>{let t=await Kl`gh pr list --head ${e} --state all --json number,state,title,baseRefName,headRefName --limit 1`;return JSON.parse(t.stdout)[0]??null},Hl=async e=>{let t=await Kl`gh pr list --head ${e} --state open --limit 5 --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)},_i=async e=>{try{let t=await Kl`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 Io from"node:process";var jP="x-seraph-loginreason",FP="AUTHENTICATED_FAILED",LP=(e,t=160)=>{let r=e.split(`
169
- `,1)[0].trim();return r.length>t?`${r.slice(0,t)}\u2026`:r},yh=(e,t)=>t===FP||e===401?"auth":e===403?"forbidden":e===404?"not-found-or-forbidden":"other",hh=(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}`,cn=class extends Error{status;kind;body;context;constructor(t){let r=yh(t.status,t.seraphLoginReason),n=LP(t.body);super(n===""?`${t.context}: ${hh(r,t.status)}`:`${t.context}: ${hh(r,t.status)}. Jira said: ${n}`),this.name="JiraApiError",this.status=t.status,this.kind=r,this.body=t.body,this.context=t.context}},Do=e=>e instanceof cn,vh=e=>e.headers.get(jP);var ln=async(e,t)=>{if(e.ok)return;let r=await e.text(),n=new cn({status:e.status,seraphLoginReason:vh(e),body:r,context:t});throw d.debug({status:e.status,kind:n.kind,body:r},t),n},hr=(e,t)=>`${e.baseUrl}/projects/${t.projectId}/versions/${t.id}/tab/release-report-all-issues`,ql=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 ln(l,"Failed to create Jira version"),{success:!0,version:await l.json()}},un=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 ln(a,"Failed to get Jira project versions"),await a.json()},xt=async(e,t)=>(await un(t)).find(o=>o.name===e)||null,dn=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 ln(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}},Yl=async(e,t)=>{let{versionName:r}=e,n=await xt(r,t);if(!n)throw new Error(`Version "${r}" not found in Jira project`);return await dn({versionId:n.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},t)},pn=async()=>{let e=Io.env.JIRA_BASE_URL,t=Io.env.JIRA_TOKEN||Io.env.JIRA_API_TOKEN,r=Io.env.JIRA_PROJECT_ID,n=Io.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}},Tt=async()=>{try{return await pn()}catch(e){return d.warn({err:e},"Jira configuration not available, skipping Jira integration"),null}};var Mi=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 ln(a,"Failed to get Jira version issue counts");let c=await a.json();return{issuesFixedCount:c.issuesFixedCount,issuesAffectedCount:c.issuesAffectedCount}},zl=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 ln(c,"Failed to remove Jira version")};var kh="dev",bh={regular:"dev",hotfix:"main"},pt=e=>bh[e],Ao=e=>{let t=Object.entries(bh).find(([,r])=>r===e);return t?t[0]:null},Oo=(e,t)=>(t??"").trim()!==""?`${e}
168
+ `)}`);let n=r.slice(0,WP),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}`})},Co=async e=>{let{operation:t,base:r}=e;if(await Wr()===r)return;let n=(await ot(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}`})},Ne=async e=>{let{operation:t}=e;if(await nf())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 sn({operation:t})};var VP=e=>e.map(t=>({pr:t,id:Q(t.headRefName)})).filter(t=>t.id!==null).sort((t,r)=>ef(t.id,r.id,{a:t.pr.createdAt,b:r.pr.createdAt})).map(t=>t.pr),$o=200,yh=(e,t)=>{e.length<$o||d.warn({source:t,limit:$o},`\u26A0\uFE0F ${t} returned ${$o} PRs \u2014 the page is full, so older release PRs may be missing`)},GP=async()=>{let[e,t]=await Promise.all([an`gh pr list --limit ${$o} --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,an`gh pr list --limit ${$o} --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName,createdAt`]),r=JSON.parse(e.stdout),n=JSON.parse(t.stdout);yh(r,"release PR discovery (base dev)"),yh(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)}))},Ao="find open release PRs",vh=async()=>{try{let e=await GP();if(e.length===0)throw new g(void 0,{operation:Ao,remediation:"open a release PR first, or check you are in the right repo"});return VP(e)}catch(e){throw e instanceof g?e:(d.debug({err:e},"Error fetching release PRs"),new g(e,{operation:"fetch release PRs"}))}},Mi=async()=>(await vh()).map(t=>t.headRefName),JP=e=>{let t=Oo(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=ql(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 vh()).map(JP),ji=async e=>{let{branch:t,body:r}=e;try{await an({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}},KP=async(e,t)=>{let r=an({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`)},Fi=async e=>{let{id:t,jiraVersionUrl:r,type:n,description:o,baseSha:s}=e,i=Qm(t,n),a=pt(n),c=an({quiet:!0}),l=xe(t),u=Do(r,o);try{await sn({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 KP(l,a),m}}catch(p){throw d.error({error:p,branchName:l},`Error creating release branch ${l}`),p}finally{await an({quiet:!0,nothrow:!0})`git switch ${a}`}};import{$ as Yl}from"zx";var cn=async e=>{let t=await Yl`gh pr list --head ${e} --state all --json number,state,title,baseRefName,headRefName --limit 1`;return JSON.parse(t.stdout)[0]??null},zl=async e=>{let t=await Yl`gh pr list --head ${e} --state open --limit 5 --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)},Li=async e=>{try{let t=await Yl`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 No from"node:process";var HP="x-seraph-loginreason",qP="AUTHENTICATED_FAILED",YP=(e,t=160)=>{let r=e.split(`
169
+ `,1)[0].trim();return r.length>t?`${r.slice(0,t)}\u2026`:r},kh=(e,t)=>t===qP||e===401?"auth":e===403?"forbidden":e===404?"not-found-or-forbidden":"other",wh=(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}`,ln=class extends Error{status;kind;body;context;constructor(t){let r=kh(t.status,t.seraphLoginReason),n=YP(t.body);super(n===""?`${t.context}: ${wh(r,t.status)}`:`${t.context}: ${wh(r,t.status)}. Jira said: ${n}`),this.name="JiraApiError",this.status=t.status,this.kind=r,this.body=t.body,this.context=t.context}},Io=e=>e instanceof ln,bh=e=>e.headers.get(HP);var un=async(e,t)=>{if(e.ok)return;let r=await e.text(),n=new ln({status:e.status,seraphLoginReason:bh(e),body:r,context:t});throw d.debug({status:e.status,kind:n.kind,body:r},t),n},vr=(e,t)=>`${e.baseUrl}/projects/${t.projectId}/versions/${t.id}/tab/release-report-all-issues`,Xl=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 un(l,"Failed to create Jira version"),{success:!0,version:await l.json()}},dn=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 un(a,"Failed to get Jira project versions"),await a.json()},Ct=async(e,t)=>(await dn(t)).find(o=>o.name===e)||null,pn=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 un(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}},Zl=async(e,t)=>{let{versionName:r}=e,n=await Ct(r,t);if(!n)throw new Error(`Version "${r}" not found in Jira project`);return await pn({versionId:n.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},t)},mn=async()=>{let e=No.env.JIRA_BASE_URL,t=No.env.JIRA_TOKEN||No.env.JIRA_API_TOKEN,r=No.env.JIRA_PROJECT_ID,n=No.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}},$t=async()=>{try{return await mn()}catch(e){return d.warn({err:e},"Jira configuration not available, skipping Jira integration"),null}};var Bi=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 un(a,"Failed to get Jira version issue counts");let c=await a.json();return{issuesFixedCount:c.issuesFixedCount,issuesAffectedCount:c.issuesAffectedCount}},Ql=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 un(c,"Failed to remove Jira version")};var Sh="dev",Eh={regular:"dev",hotfix:"main"},pt=e=>Eh[e],Oo=e=>{let t=Object.entries(Eh).find(([,r])=>r===e);return t?t[0]:null},Do=(e,t)=>(t??"").trim()!==""?`${e}
171
171
 
172
172
  ${t}`:`${e}
173
- `,Xl=async(e="regular")=>{let t=pt(e),r=wh({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 wh({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()},BP=async e=>{let{versionName:t,jiraConfig:r,description:n,releaseDate:o}=e,s=await xt(t,r);if(!s)return(await ql({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 dn({versionId:s.id,...a},r);return{...s,...a,...a.releaseDate===void 0?{}:{releaseDate:c.version.releaseDate}}},Zl=async e=>{let{id:t,jiraConfig:r,description:n,releaseDate:o,type:s="regular",baseSha:i}=e,a=ce(t),c=await BP({versionName:a,jiraConfig:r,description:n,...o===void 0?{}:{releaseDate:o}}),l=hr(r,c),u=await Ni({id:t,jiraVersionUrl:l,type:s,description:n,baseSha:i});return{version:re(t),type:s,branchName:u.branchName,prUrl:u.prUrl,jiraVersionUrl:l,releaseDate:c.releaseDate||null}},ji=async()=>{let e=new Map,t=await Tt();if(!t)return e;try{let r=await un(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},pe=async()=>{let e=await ji();return new Map([...e].flatMap(([t,{description:r}])=>r?[[t,r]]:[]))},No=(e,t,r)=>{let n=r?" ".repeat(r-e.length+3):" ",o=`[${t}]`.padEnd(11);return`${e}${n}${o}`},Jl=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",Fi=e=>e.flatMap(t=>{let r=Q(t);return r?[{branch:t,id:r,label:re(r)}]:[]}),Ct=e=>{try{return Pe(ve(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)})}},_o=e=>{if(e===kh)return kh;let t=Q(e);return t?re(t):e},$t=e=>e.flatMap(t=>{let r=Q(t);return r?[re(r)]:[]}),UP=(e,t)=>t?t.get(e)||"regular":void 0,me=e=>{let{branches:t,descriptions:r,types:n}=e;return Fi(t).map(({branch:o,id:s,label:i})=>({value:o,label:i,description:r.get(ce(s)),type:UP(o,n)}))};import Rh from"node:fs/promises";import WP from"node:path";import{$ as Ql}from"zx";var W="pnpm-lock.yaml",VP=/^(?:<{7}|={7}|>{7})(?:\s|$)/m,Eh=async(e,t)=>{let r=WP.join(e,W),n=`${t}:${W}`;try{let o=await Ql({cwd:e,quiet:!0})`git show ${n}`;await Rh.writeFile(r,o.stdout)}catch(o){return{ok:!1,reason:`dev has no ${W} to start from: ${Sh(o)}`}}try{await Ql({cwd:e,quiet:!0})`pnpm install --lockfile-only --ignore-scripts --no-frozen-lockfile`}catch(o){return{ok:!1,reason:`pnpm could not merge ${W}: ${Sh(o)}`}}return VP.test(await Rh.readFile(r,"utf8"))?{ok:!1,reason:`${W} still carries conflict markers after pnpm ran`}:(await Ql({cwd:e,quiet:!0})`git add -- ${W}`,{ok:!0})},Sh=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim()};import{$ as yr}from"zx";var eu="Merge remote-tracking branch 'origin/dev' into ",GP=e=>{let{stderr:t,message:r}=e;return String(t?.trim()||r||e).trim()},JP=2048,KP=e=>{let{stderr:t,stdout:r,exitCode:n}=e;return[t,r].map(s=>(s??"").trim().slice(-JP)).filter(s=>s.length>0).join(`
174
- `)||`the verify command exited with code ${n??"unknown"} and printed nothing`},HP=async e=>{try{return(await yr({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[]}},qP=async(e,t)=>{let r=GP(t),n=await HP(e);return n.length>0?{status:"conflict",conflictPaths:n,reason:r}:await of(e)?{status:"hook-failed",reason:r}:{status:"error",reason:r}},Ph=async e=>{let{cwd:t,worktreePath:r,branches:n}=e,o=[],s=await xe(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 YP({cwd:t,worktreePath:r,branch:i,devSha:s});o.push({...c,durationMs:Date.now()-a})}return o},YP=async e=>{let{cwd:t,worktreePath:r,branch:n,devSha:o}=e,s=`origin/${n}`;if(!await xe(t,s))return{branch:n,status:"error",reason:`${s} does not exist on origin`};if(await Xn(t,"origin/dev",s))return{branch:n,status:"up-to-date"};try{await bc(r),await yr({cwd:r,quiet:!0})`git checkout --detach ${s}`;let i=`${eu}${n}`;await yr({cwd:r,quiet:!0})`git merge origin/dev --no-edit -m ${i}`;let a=(await yr({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 qP(r,i)}}finally{await Rc(r)}},xh=e=>e.flatMap(t=>t.mergeSha?[{branch:t.branch,sha:t.mergeSha}]:[]),Th="pnpm install --frozen-lockfile",Ch=async e=>{let{worktreePath:t,refs:r,command:n}=e,o=[],s=new Map;for(let i of r)try{await bc(t),await yr({cwd:t,quiet:!0})`git checkout --detach ${i.sha}`,await yr({cwd:t,quiet:!0})`sh -c ${n}`,o.push(i)}catch(a){s.set(i.branch,KP(a))}finally{await Rc(t)}return{kept:o,failed:s}},Mo=async(e,t,r="origin/dev")=>{await yr({cwd:e,quiet:!0})`git fetch origin --prune`;let n=[],o=[];for(let s of t)await Xn(e,r,`origin/${s.branch}`)?o.push(s.branch):n.push(s);return{kept:n,nowUpToDate:o}};import tu from"node:process";var Li=new Set,Bi=e=>(Li.add(e),()=>{Li.delete(e)}),zP=async()=>{for(let e of[...Li])try{await e()}catch(t){d.warn({error:t,msg:"cleanup failed during shutdown"})}Li.clear()},XP=["SIGINT","SIGTERM"],$h=async(e,t={})=>{let{register:r=(i,a)=>{tu.on(i,a)},unregister:n=(i,a)=>{tu.off(i,a)},exit:o=i=>{tu.exit(i)}}=t,s=new Map;for(let i of XP){let a=()=>{zP().then(()=>{o(Sf(i))})};s.set(i,a),r(i,a)}try{return await e()}finally{for(let[i,a]of s)n(i,a)}};var ZP="pnpm install --frozen-lockfile --ignore-scripts",ru="pnpm install --frozen-lockfile",Dh=64*1024,jh=4096,Fo=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim().slice(-jh)},B=async(e,t)=>(await Wi({cwd:e,quiet:!0})`git ${t}`).stdout,ou=e=>e.split(`
176
- `).map(t=>t.trim()).filter(t=>t.length>0),fn=e=>e.split("\0").filter(t=>t.length>0),vr=async(e,t)=>{try{return(await B(e,["rev-parse","-q","--verify",t])).trim()||null}catch{return null}},Fh=async e=>et.resolve(e,(await B(e,["rev-parse","--git-common-dir"])).trim()),su=e=>e.then(()=>!0,()=>!1),jo=()=>({results:[],atomicPush:{attempted:!1,aborted:!1},declined:!1}),iu=e=>e?.length===1&&e[0]===W,Lh=async e=>et.join(await Fh(e),"infra-kit","merge-dev-resolutions"),au=async(e,t)=>et.join(await Lh(e),`${rf(t)}.json`),Bh=async e=>{try{return JSON.parse(await _e.readFile(e,"utf8"))}catch{return null}},gn=async(e,t)=>{let r=await au(e,t.branch);await _e.mkdir(et.dirname(r),{recursive:!0}),await _e.writeFile(r,`${JSON.stringify(t,null,2)}
177
- `)},Uh=async e=>{let t=await Lh(e),r=await _e.readdir(t).catch(()=>[]);return(await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(o=>Bh(et.join(t,o))))).filter(o=>o!==null)},Wh=async e=>Promise.all((await Uh(e)).map(async t=>({branch:t.branch,worktreePath:t.worktreePath,createdAt:t.createdAt,worktreeExists:await su(_e.stat(t.worktreePath))}))),Ih=(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}),QP=e=>e.editablePaths??e.conflictPaths,ex=e=>et.posix.basename(e)==="package.json",cu=e=>e.conflictPaths.includes(W)||e.lockfileBlob!==void 0,Vh=async(e,t)=>{if(!t.editablePaths)return t.conflictPaths.includes(W);if(t.lockfileBothSides||t.lockfileBlob!==void 0)return!0;let r=fn(await B(e,["diff","--cached","--name-only","-z","--no-renames",t.autoMergeTree]));return[...await uu(e),...r].some(ex)},Gh=e=>e.editablePaths?"only the editable paths may change":"only the conflicted paths may change",lu=async(e,t,r)=>{await B(e,["worktree","remove","--force",r]).catch(()=>_e.rm(r,{recursive:!0,force:!0})),await _e.rm(await au(e,t),{force:!0}).catch(()=>{}),await B(e,["worktree","prune"]).catch(()=>{})},Jh=async e=>fn(await B(e,["diff","--name-only","-z","--diff-filter=U"])),Ui=async e=>fn(await B(e,["status","--porcelain","-z","--untracked-files=all","--ignored=matching"])).filter(r=>r.startsWith("!! ")).map(r=>r.slice(3)),tx=async(e,t)=>{let r=(await B(e,["config","--type=bool","--get","rerere.enabled"]).catch(()=>"")).trim(),n=await su(_e.stat(et.join(await Fh(e),"rr-cache")));if(r==="false"||r===""&&!n)return[];let o=new Set(ou(await B(e,["rerere","remaining"])));return t.filter(s=>!o.has(s))},Kh=e=>e.split("/").includes("node_modules"),Vi=async(e,t)=>{let r=new Set(QP(t));t.editablePaths&&await Vh(e,t)&&r.add(W);let n=new Set([...t.ignoredAtHandoff,...t.ignoredByVerify??[]]),o=fn(await B(e,["diff","--cached","--name-only","-z","--no-renames",t.autoMergeTree])),s=[...await uu(e),...o].filter(a=>!r.has(a)),i=(await Ui(e)).filter(a=>!n.has(a)&&!Kh(a));return[...new Set([...s,...i,...await rx(e)])].sort()},uu=async e=>{let t=fn(await B(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},rx=async e=>(await B(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)),nx=async(e,t)=>{let r=`:(exclude)${W}`;try{return await B(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()}},ox=async(e,t)=>{let r=[];for(let n of t)(await su(_e.lstat(et.join(e,n)))||(await B(e,["--literal-pathspecs","ls-files","--",n])).length>0)&&r.push(n);r.length>0&&await B(e,["--literal-pathspecs","add","-A","--",...r])},nu=async e=>(await B(e,["write-tree"])).trim(),Hh=async e=>(await B(e,["rev-list","--parents","-n","1","HEAD"])).trim().split(" ").slice(1),sx=e=>{let t=`${ru} && `;if(e!==ru)return e?.startsWith(t)?e.slice(t.length):e},ix=e=>e?`${ru} && ${e}`:ZP,ax=async(e,t)=>{try{return await Wi({cwd:e,quiet:!0})`sh -c ${t}`,{command:t,ok:!0}}catch(r){return{command:t,ok:!1,reason:Fo(r)}}},qh=async(e,t)=>{let r=(await B(e,["diff","--cached","--stat",t.autoMergeTree])).trim(),n=async l=>(await B(e,["diff","--cached","--stat",l,"--",W])).trim(),o=cu(t)?{vsDev:await n(t.devSha),vsBase:await n(t.baseSha)}:void 0,s=await B(e,["diff","--cached",t.autoMergeTree,"--",".",`:(exclude)${W}`]),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=Ah.byteLength(a)>Dh;return{diffStat:r,...o?{lockfileDiffStat:o}:{},resolutionDiff:c?Ah.from(a).subarray(0,Dh).toString():a,resolutionDiffTruncated:c}},Yh=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 Nh(t,a,o,"conflict"));for(let a of n)i.set(a,await Nh(t,a,o,"verify-failed",s));return i},cx=async(e,t,r)=>{let n=async(a,c)=>fn(await B(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!==W).sort(),lockfileBothSides:o.includes(W)&&s.includes(W)}},lx=async(e,t,r,n)=>{let o=await Jh(e);if(t==="verify-failed"){if(o.length>0)return{reason:"the merge now conflicts \u2014 re-run release merge-dev"};let i=await vr(e,"HEAD"),a=await vr(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 cx(e,r,n),autoMergeTree:await nu(e),rererePreResolved:[],lockfileOnly:!1}}if(o.length===0)return{reason:"the merge no longer conflicts \u2014 re-run release merge-dev"};let s=await vr(e,"AUTO_MERGE");return s?{conflictPaths:o,autoMergeTree:s,rererePreResolved:await tx(e,o),lockfileOnly:iu(o)}:{reason:`git-too-old: the scope check needs AUTO_MERGE, written by git \u2265 2.42 (found ${(await B(e,["--version"])).trim()})`}},ux={conflict:"needs-agent","verify-failed":"verify-failed"},Nh=async(e,t,r,n,o)=>{let s=await Bh(await au(e,t));if(s)return{resolution:Ih(s,"exists"),reason:`resolution-exists: ${s.worktreePath} \u2014 finish it with --continue or drop it with --abort`};let i=await xe(e,`origin/${t}`);if(!i)return{reason:`origin/${t} does not exist on origin`};let a=nf(e,t),c=()=>lu(e,t,a),l=Bi(c);try{await B(e,["worktree","prune"]),await _e.mkdir(et.dirname(a),{recursive:!0}),await B(e,["worktree","add","--detach",a,i]),await Wi({cwd:a,quiet:!0})`git merge --no-commit ${r} -m ${eu+t}`.catch(()=>{});let u=await lx(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 Ui(a),cliVersion:L.version,createdAt:new Date().toISOString()};return await gn(e,p),{resolution:Ih(p,p.lockfileOnly?"lockfile-only":ux[n])}}catch(u){return await c(),{reason:Fo(u)}}finally{l()}},zh=async e=>{let{cwd:t,versions:r,all:n}=e,o=await Uh(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=Pe(ve(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 Kt(me({branches:s,descriptions:new Map}),{required:!0});return o.filter(a=>i.includes(a.branch))},dx=async(e,t)=>{let r=await _e.realpath(t).catch(()=>null);if(!r)return!1;let n=await ot(e);for(let o of n)if(await _e.realpath(o.path).catch(()=>o.path)===r)return!0;return!1},mn=(e,t,r,n)=>({...e,blocked:{code:t,detail:r,...n&&n.length>0?{paths:n}:{}}}),Xh=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 dx(e,n))return mn(o,"parents-mismatch",`the resolution worktree ${n} is gone \u2014 run --abort, then start again`);let s=await vr(n,"HEAD"),i=await vr(n,"MERGE_HEAD"),a=r??sx(t.handOffVerify);return s===t.baseSha&&i===t.devSha?hx(e,t,o,a):px(t,o,s,i)},px=async(e,t,r,n)=>{let o=e.worktreePath;if(r!==null&&r===e.unapprovedCommit)return mn(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 Hh(o),i=n?null:await vr(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 mn(t,"parents-mismatch",`expected HEAD ${e.baseSha} merging ${e.devSha}, or an approved merge commit of the two; found ${l}`)}let c=await Vi(o,e);return c.length>0?mn(t,"out-of-scope-edit",Gh(e),c):{...t,committed:!0,mergeSha:r,treeSha:i,lockfileMerged:cu(e),...await qh(o,e)}},_h=async(e,t)=>{let r=ou(await B(e,["--literal-pathspecs","ls-files","-s","--",t])),[n,o,s]=r.length===1?(r[0]??"").split(/\s+/):[];return n&&s==="0"?o??null:null},mx=async(e,t)=>{let r=t.worktreePath,n=await _h(r,W),o=t.lockfileBlob,s=o===void 0&&t.editablePaths!==void 0&&n===await vr(r,`${t.autoMergeTree}:${W}`),i=await Eh(r,t.devSha);if(!i.ok)return{code:"verify-failed",detail:i.reason,paths:[W]};let a=await _h(r,W);if(a!==null&&a!==o&&(t.lockfileBlob=a,await gn(e,t)),n!==null&&n!==a&&!s)return n===o?{code:"tree-changed",detail:`rebuilding ${W} from dev resolved differently than the last preview (the registry moved) \u2014 preview again`,paths:[W]}:{code:"out-of-scope-edit",detail:`${W} was staged by something other than the CLI; it has been rebuilt from dev \u2014 preview again`,paths:[W]};let c=await Vi(r,t);return c.length>0?{code:"out-of-scope-edit",detail:"merging the lockfile changed other paths",paths:c}:null},fx=async(e,t)=>{let r=t.worktreePath,n=new Set(t.editablePaths),o=t.editablePaths?(await uu(r)).filter(c=>n.has(c)):t.conflictPaths;await ox(r,o.filter(c=>c!==W));let s=await Vi(r,t);if(s.length>0)return{code:"out-of-scope-edit",detail:Gh(t),paths:s};let i=(await Jh(r)).filter(c=>c!==W);if(i.length>0)return{code:"unmerged-paths",detail:"these paths are still unmerged",paths:i};let a;try{a=await nx(r,t.editablePaths?t.autoMergeTree:"HEAD")}catch(c){return{code:"markers-remaining",detail:`the marker check could not run: ${Fo(c)}`}}return a.length>0?{code:"markers-remaining",detail:"conflict markers are still staged",paths:a}:await Vh(r,t)?mx(e,t):null},gx=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 Ui(o)),i=await ax(o,n),a=(await Ui(o)).filter(c=>!s.has(c)&&!Kh(c)&&et.posix.basename(c)!==".gitignore");return t.ignoredByVerify=[...new Set([...t.ignoredByVerify??[],...a])],await gn(e,t),i},hx=async(e,t,r,n)=>{let o=t.worktreePath,s=await fx(e,t);if(s)return{...r,blocked:s};let i=cu(t),a=await nu(o),c=await gx(e,t,a,ix(n)),l={...r,treeSha:a,lockfileMerged:i,verify:c};if(!c.ok)return mn(l,"verify-failed",c.reason??"the verify command failed");let u=await Vi(o,t),p=ou(await B(o,["diff","--name-only"]));return u.length>0||p.length>0||await nu(o)!==a?mn(l,"verify-mutated-tree","the verify step changed the tree",[...new Set([...u,...p])]):(c.reused||(t.verified={treeSha:a,command:c.command},await gn(e,t)),{...l,...await qh(o,t)})},yx=12e4,vx=async(e,t=yx)=>{let r=Wi({cwd:e,quiet:!0,detached:!0,stdio:["ignore","pipe","pipe"],env:{...Oh.env,GIT_TERMINAL_PROMPT:"0"}})`git commit --no-edit --cleanup=strip`,n=!1,o=setTimeout(()=>{n=!0;let s=r.child?.pid;try{s&&Oh.kill(-s,"SIGKILL")}catch{}},t);try{return await r,{ok:!0}}catch(s){if(!n)return{ok:!1,reason:Fo(s)};let i=(await B(e,["rev-parse","--git-path","index.lock"])).trim();return await _e.rm(et.resolve(e,i),{force:!0}),{ok:!1,reason:`git commit timed out after ${t}ms`}}finally{clearTimeout(o)}},wx={"verify-failed":"verify-failed","tree-changed":"tree-changed"},kx=e=>{let t=e.blocked;return{branch:e.branch,status:wx[t.code]??"blocked",conflictPaths:e.conflictPaths,pushed:!1,reason:[`${t.code}: ${t.detail}`,...t.paths?[`(${t.paths.join(", ")})`]:[]].join(" "),blocked:t}},bx=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 vx(o);if(!i.ok)return s("hook-failed",i.reason);let a=(await B(o,["rev-parse","HEAD"])).trim(),c=(await B(o,["rev-parse","HEAD^{tree}"])).trim();if(c!==t.treeSha)return r.unapprovedCommit=a,await gn(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 Hh(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}},Rx=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 Mo(e,[{branch:t.branch,sha:r}],t.devSha)).nowUpToDate}catch(c){let l={code:"parents-mismatch",detail:`origin/${t.branch}: ${Fo(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 xe(e,`origin/${t.branch}`);if(s===t.baseSha)return"keep";let i=s!==null&&await Xn(e,s,t.baseSha),a={code:"parents-mismatch",detail:`origin/${t.branch} ${i?"was rewound":"moved"} to ${s??"nothing"} since the hand-off at ${t.baseSha}`};return n("blocked",`parents-mismatch: ${a.detail}`,a)},Sx=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}`)},Zh=async e=>{let{cwd:t,versions:r,all:n,verify:o,trees:s=new Map,confirmedCommand:i}=e,a=await zh({cwd:t,versions:r,all:n});if(a.length===0)return d.info("\u2139\uFE0F No merge-dev resolutions in progress"),jo();if(i)return Mh(t,a,o,s);let c=[];for(let m of a){let f=await Xh(t,m,o);!f.blocked&&!f.committed&&f.treeSha&&(m.previewedTree=f.treeSha,await gn(t,m)),c.push(f)}Sx(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 G(i,`Commit and push the resolved merges for: ${[...p.keys()].join(", ")}?`,{plan:l,throwOnDecline:!0,rerun:Ex(p)})}catch(m){if(!bt(m))throw m;return{...jo(),declined:!0}}return Mh(t,a,o,p)},Qh=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},Ex=e=>{let t=[],r=!1;for(let o of wf())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"]},Px=async(e,t,r,n)=>{let o=await Xh(e,t,r);if(o.blocked)return kx(o);let s=await bx(e,o,t,n);if(!("sha"in s))return s;let i=await Rx(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 Qs(e,r),o=[];for(let s of t){let i=n.pushed||await Wr(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]}}},Mh=async(e,t,r,n)=>{let o=[],s=[];for(let u of t){let p=await Px(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 lu(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}},ey=async e=>{let{cwd:t,versions:r,all:n,confirmedCommand:o}=e,s=await zh({cwd:t,versions:r,all:n});if(s.length===0)return d.info("\u2139\uFE0F No merge-dev resolutions in progress"),jo();let i={branches:s.map(a=>({branch:a.branch,worktreePath:a.worktreePath}))};try{await G(o,`Discard the resolution worktrees for: ${s.map(a=>a.branch).join(", ")}?`,{plan:i,throwOnDecline:!0})}catch(a){if(!bt(a))throw a;return{...jo(),declined:!0}}for(let a of s)await lu(t,a.branch,a.worktreePath),d.info(`\u{1F5D1}\uFE0F Discarded the resolution for ${a.branch}`);return{...jo(),results:s.map(a=>({branch:a.branch,status:"aborted",conflictPaths:a.conflictPaths,pushed:!1}))}};import Tx from"node:fs";import Cx from"node:os";import $x from"node:path";var Ax="infra-kit.json",Ox="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)",Dx="Skipped agent-instruction files \u2014 no infra-kit.json at the repo root (the plugin pointer, the plugin install and .mcp.json are unaffected)",Lo=async()=>{let e;try{e=await A()}catch{return null}let t=e.trim();return t===""||t===Cx.homedir()?null:t},ty=async()=>{let e=await Lo();return e===null&&d.info(Ox),e},Ix=async()=>{let e=await Lo();return e===null?null:Tx.existsSync($x.join(e,Ax))?e:(d.info(Dx),null)};var Nx=async e=>{try{return await ke(e)}catch(t){return d.debug({err:t,msg:"Skipped per-package agent guidance \u2014 no workspace packages could be discovered."}),[]}},ry=async({dryRun:e=!1}={})=>{let t=await Ix(),r=L.version;if(t===null)return{skipped:!0,root:null,version:r,written:[]};let n=[...await fo(t,{version:r,dryRun:e})];for(let o of await Nx(t)){let s=await Rt(o);n.push(...await go(o,{repoRoot:t,version:r,declaredType:s,dryRun:e}))}return{skipped:!1,root:t,version:r,written:n}};import he from"node:fs";import zi from"node:os";import se from"node:path";import bu from"node:process";import du from"node:fs";import ny from"node:os";import oy from"node:path";import _x from"node:process";import{z as Ji}from"zod";var sy=e=>{try{return du.readFileSync(e,"utf-8")}catch{return null}},hn="claude in chrome",Mx="com.anthropic.claude_code_browser_extension",Gi="run `/chrome` inside Claude Code to set up Claude in Chrome",jx={darwin:["Library","Application Support","Google","Chrome","NativeMessagingHosts"],linux:[".config","google-chrome","NativeMessagingHosts"]},Fx=e=>{try{return du.accessSync(e,du.constants.X_OK),!0}catch{return!1}},iy=e=>{try{return JSON.parse(e)}catch{return null}},Lx=/^exec\s+(?<target>\S+)\s+--chrome-native-host\b/m,Bo=(e={})=>{let t=e.platform??_x.platform,r=e.home??ny.homedir(),n=e.readText??sy,o=e.isExecutable??Fx,s=jx[t];if(s===void 0)return{name:hn,status:"skip",message:`no Chrome native host location known for ${t}`};let i=oy.join(r,...s,`${Mx}.json`),a=n(i);if(a===null)return{name:hn,status:"warn",message:`Chrome native host not registered \u2014 ${Gi}`};let c=Ji.object({path:Ji.string().min(1)}).safeParse(iy(a));if(!c.success)return{name:hn,status:"fail",message:`${w(i)} has no host path \u2014 ${Gi} again`};let l=c.data.path;if(!o(l))return{name:hn,status:"fail",message:`Chrome native host ${w(l)} is missing or not executable \u2014 ${Gi} again`};let u=Lx.exec(n(l)??"")?.groups?.target;return u!==void 0&&!o(u)?{name:hn,status:"fail",message:`Chrome native host runs ${w(u)}, which no longer exists \u2014 ${Gi} again`}:{name:hn,status:"pass",message:`Native host registered (${w(l)}); /infra-kit:doctor checks the live connection`}},pu=(e={})=>{let t=e.home??ny.homedir(),r=e.readText??sy,n=Ji.object({claudeInChromeDefaultEnabled:Ji.boolean().optional()}).safeParse(iy(r(oy.join(t,".claude.json"))??""));return n.success&&n.data.claudeInChromeDefaultEnabled===!0};import Hi from"node:fs/promises";import Bx from"node:path";import Ux from"node:process";var ay=` // // Editor tooling only \u2014 a JSON Schema URL for completion and validation. Ignored at runtime.
173
+ `,eu=async(e="regular")=>{let t=pt(e),r=Rh({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 Rh({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()},zP=async e=>{let{versionName:t,jiraConfig:r,description:n,releaseDate:o}=e,s=await Ct(t,r);if(!s)return(await Xl({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 pn({versionId:s.id,...a},r);return{...s,...a,...a.releaseDate===void 0?{}:{releaseDate:c.version.releaseDate}}},tu=async e=>{let{id:t,jiraConfig:r,description:n,releaseDate:o,type:s="regular",baseSha:i}=e,a=ce(t),c=await zP({versionName:a,jiraConfig:r,description:n,...o===void 0?{}:{releaseDate:o}}),l=vr(r,c),u=await Fi({id:t,jiraVersionUrl:l,type:s,description:n,baseSha:i});return{version:re(t),type:s,branchName:u.branchName,prUrl:u.prUrl,jiraVersionUrl:l,releaseDate:c.releaseDate||null}},Ui=async()=>{let e=new Map,t=await $t();if(!t)return e;try{let r=await dn(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},pe=async()=>{let e=await Ui();return new Map([...e].flatMap(([t,{description:r}])=>r?[[t,r]]:[]))},_o=(e,t,r)=>{let n=r?" ".repeat(r-e.length+3):" ",o=`[${t}]`.padEnd(11);return`${e}${n}${o}`},ql=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",Wi=e=>e.flatMap(t=>{let r=Q(t);return r?[{branch:t,id:r,label:re(r)}]:[]}),At=e=>{try{return xe(we(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)})}},Mo=e=>{if(e===Sh)return Sh;let t=Q(e);return t?re(t):e},Ot=e=>e.flatMap(t=>{let r=Q(t);return r?[re(r)]:[]}),XP=(e,t)=>t?t.get(e)||"regular":void 0,me=e=>{let{branches:t,descriptions:r,types:n}=e;return Wi(t).map(({branch:o,id:s,label:i})=>({value:o,label:i,description:r.get(ce(s)),type:XP(o,n)}))};import Ph from"node:fs/promises";import ZP from"node:path";import{$ as ru}from"zx";var V="pnpm-lock.yaml",QP=/^(?:<{7}|={7}|>{7})(?:\s|$)/m,Th=async(e,t)=>{let r=ZP.join(e,V),n=`${t}:${V}`;try{let o=await ru({cwd:e,quiet:!0})`git show ${n}`;await Ph.writeFile(r,o.stdout)}catch(o){return{ok:!1,reason:`dev has no ${V} to start from: ${xh(o)}`}}try{await ru({cwd:e,quiet:!0})`pnpm install --lockfile-only --ignore-scripts --no-frozen-lockfile`}catch(o){return{ok:!1,reason:`pnpm could not merge ${V}: ${xh(o)}`}}return QP.test(await Ph.readFile(r,"utf8"))?{ok:!1,reason:`${V} still carries conflict markers after pnpm ran`}:(await ru({cwd:e,quiet:!0})`git add -- ${V}`,{ok:!0})},xh=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim()};import{$ as wr}from"zx";var nu="Merge remote-tracking branch 'origin/dev' into ",ex=e=>{let{stderr:t,message:r}=e;return String(t?.trim()||r||e).trim()},tx=2048,rx=e=>{let{stderr:t,stdout:r,exitCode:n}=e;return[t,r].map(s=>(s??"").trim().slice(-tx)).filter(s=>s.length>0).join(`
174
+ `)||`the verify command exited with code ${n??"unknown"} and printed nothing`},nx=async e=>{try{return(await wr({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[]}},ox=async(e,t)=>{let r=ex(t),n=await nx(e);return n.length>0?{status:"conflict",conflictPaths:n,reason:r}:await cf(e)?{status:"hook-failed",reason:r}:{status:"error",reason:r}},Ch=async e=>{let{cwd:t,worktreePath:r,branches:n}=e,o=[],s=await Te(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 sx({cwd:t,worktreePath:r,branch:i,devSha:s});o.push({...c,durationMs:Date.now()-a})}return o},sx=async e=>{let{cwd:t,worktreePath:r,branch:n,devSha:o}=e,s=`origin/${n}`;if(!await Te(t,s))return{branch:n,status:"error",reason:`${s} does not exist on origin`};if(await Zn(t,"origin/dev",s))return{branch:n,status:"up-to-date"};try{await Ec(r),await wr({cwd:r,quiet:!0})`git checkout --detach ${s}`;let i=`${nu}${n}`;await wr({cwd:r,quiet:!0})`git merge origin/dev --no-edit -m ${i}`;let a=(await wr({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 ox(r,i)}}finally{await Pc(r)}},$h=e=>e.flatMap(t=>t.mergeSha?[{branch:t.branch,sha:t.mergeSha}]:[]),Ah="pnpm install --frozen-lockfile",Oh=async e=>{let{worktreePath:t,refs:r,command:n}=e,o=[],s=new Map;for(let i of r)try{await Ec(t),await wr({cwd:t,quiet:!0})`git checkout --detach ${i.sha}`,await wr({cwd:t,quiet:!0})`sh -c ${n}`,o.push(i)}catch(a){s.set(i.branch,rx(a))}finally{await Pc(t)}return{kept:o,failed:s}},jo=async(e,t,r="origin/dev")=>{await wr({cwd:e,quiet:!0})`git fetch origin --prune`;let n=[],o=[];for(let s of t)await Zn(e,r,`origin/${s.branch}`)?o.push(s.branch):n.push(s);return{kept:n,nowUpToDate:o}};import ou from"node:process";var Vi=new Set,Gi=e=>(Vi.add(e),()=>{Vi.delete(e)}),ix=async()=>{for(let e of[...Vi])try{await e()}catch(t){d.warn({error:t,msg:"cleanup failed during shutdown"})}Vi.clear()},ax=["SIGINT","SIGTERM"],Dh=async(e,t={})=>{let{register:r=(i,a)=>{ou.on(i,a)},unregister:n=(i,a)=>{ou.off(i,a)},exit:o=i=>{ou.exit(i)}}=t,s=new Map;for(let i of ax){let a=()=>{ix().then(()=>{o(xf(i))})};s.set(i,a),r(i,a)}try{return await e()}finally{for(let[i,a]of s)n(i,a)}};var cx="pnpm install --frozen-lockfile --ignore-scripts",su="pnpm install --frozen-lockfile",_h=64*1024,Bh=4096,Lo=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim().slice(-Bh)},B=async(e,t)=>(await Ki({cwd:e,quiet:!0})`git ${t}`).stdout,au=e=>e.split(`
176
+ `).map(t=>t.trim()).filter(t=>t.length>0),gn=e=>e.split("\0").filter(t=>t.length>0),kr=async(e,t)=>{try{return(await B(e,["rev-parse","-q","--verify",t])).trim()||null}catch{return null}},Uh=async e=>et.resolve(e,(await B(e,["rev-parse","--git-common-dir"])).trim()),cu=e=>e.then(()=>!0,()=>!1),Fo=()=>({results:[],atomicPush:{attempted:!1,aborted:!1},declined:!1}),lu=e=>e?.length===1&&e[0]===V,Wh=async e=>et.join(await Uh(e),"infra-kit","merge-dev-resolutions"),uu=async(e,t)=>et.join(await Wh(e),`${sf(t)}.json`),Vh=async e=>{try{return JSON.parse(await _e.readFile(e,"utf8"))}catch{return null}},hn=async(e,t)=>{let r=await uu(e,t.branch);await _e.mkdir(et.dirname(r),{recursive:!0}),await _e.writeFile(r,`${JSON.stringify(t,null,2)}
177
+ `)},Gh=async e=>{let t=await Wh(e),r=await _e.readdir(t).catch(()=>[]);return(await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(o=>Vh(et.join(t,o))))).filter(o=>o!==null)},Jh=async e=>Promise.all((await Gh(e)).map(async t=>({branch:t.branch,worktreePath:t.worktreePath,createdAt:t.createdAt,worktreeExists:await cu(_e.stat(t.worktreePath))}))),Mh=(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}),lx=e=>e.editablePaths??e.conflictPaths,ux=e=>et.posix.basename(e)==="package.json",du=e=>e.conflictPaths.includes(V)||e.lockfileBlob!==void 0,Kh=async(e,t)=>{if(!t.editablePaths)return t.conflictPaths.includes(V);if(t.lockfileBothSides||t.lockfileBlob!==void 0)return!0;let r=gn(await B(e,["diff","--cached","--name-only","-z","--no-renames",t.autoMergeTree]));return[...await mu(e),...r].some(ux)},Hh=e=>e.editablePaths?"only the editable paths may change":"only the conflicted paths may change",pu=async(e,t,r)=>{await B(e,["worktree","remove","--force",r]).catch(()=>_e.rm(r,{recursive:!0,force:!0})),await _e.rm(await uu(e,t),{force:!0}).catch(()=>{}),await B(e,["worktree","prune"]).catch(()=>{})},qh=async e=>gn(await B(e,["diff","--name-only","-z","--diff-filter=U"])),Ji=async e=>gn(await B(e,["status","--porcelain","-z","--untracked-files=all","--ignored=matching"])).filter(r=>r.startsWith("!! ")).map(r=>r.slice(3)),dx=async(e,t)=>{let r=(await B(e,["config","--type=bool","--get","rerere.enabled"]).catch(()=>"")).trim(),n=await cu(_e.stat(et.join(await Uh(e),"rr-cache")));if(r==="false"||r===""&&!n)return[];let o=new Set(au(await B(e,["rerere","remaining"])));return t.filter(s=>!o.has(s))},Yh=e=>e.split("/").includes("node_modules"),Hi=async(e,t)=>{let r=new Set(lx(t));t.editablePaths&&await Kh(e,t)&&r.add(V);let n=new Set([...t.ignoredAtHandoff,...t.ignoredByVerify??[]]),o=gn(await B(e,["diff","--cached","--name-only","-z","--no-renames",t.autoMergeTree])),s=[...await mu(e),...o].filter(a=>!r.has(a)),i=(await Ji(e)).filter(a=>!n.has(a)&&!Yh(a));return[...new Set([...s,...i,...await px(e)])].sort()},mu=async e=>{let t=gn(await B(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},px=async e=>(await B(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)),mx=async(e,t)=>{let r=`:(exclude)${V}`;try{return await B(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()}},fx=async(e,t)=>{let r=[];for(let n of t)(await cu(_e.lstat(et.join(e,n)))||(await B(e,["--literal-pathspecs","ls-files","--",n])).length>0)&&r.push(n);r.length>0&&await B(e,["--literal-pathspecs","add","-A","--",...r])},iu=async e=>(await B(e,["write-tree"])).trim(),zh=async e=>(await B(e,["rev-list","--parents","-n","1","HEAD"])).trim().split(" ").slice(1),gx=e=>{let t=`${su} && `;if(e!==su)return e?.startsWith(t)?e.slice(t.length):e},hx=e=>e?`${su} && ${e}`:cx,yx=async(e,t)=>{try{return await Ki({cwd:e,quiet:!0})`sh -c ${t}`,{command:t,ok:!0}}catch(r){return{command:t,ok:!1,reason:Lo(r)}}},Xh=async(e,t)=>{let r=(await B(e,["diff","--cached","--stat",t.autoMergeTree])).trim(),n=async l=>(await B(e,["diff","--cached","--stat",l,"--",V])).trim(),o=du(t)?{vsDev:await n(t.devSha),vsBase:await n(t.baseSha)}:void 0,s=await B(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=Ih.byteLength(a)>_h;return{diffStat:r,...o?{lockfileDiffStat:o}:{},resolutionDiff:c?Ih.from(a).subarray(0,_h).toString():a,resolutionDiffTruncated:c}},Zh=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 jh(t,a,o,"conflict"));for(let a of n)i.set(a,await jh(t,a,o,"verify-failed",s));return i},vx=async(e,t,r)=>{let n=async(a,c)=>gn(await B(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)}},wx=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 kr(e,"HEAD"),a=await kr(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 vx(e,r,n),autoMergeTree:await iu(e),rererePreResolved:[],lockfileOnly:!1}}if(o.length===0)return{reason:"the merge no longer conflicts \u2014 re-run release merge-dev"};let s=await kr(e,"AUTO_MERGE");return s?{conflictPaths:o,autoMergeTree:s,rererePreResolved:await dx(e,o),lockfileOnly:lu(o)}:{reason:`git-too-old: the scope check needs AUTO_MERGE, written by git \u2265 2.42 (found ${(await B(e,["--version"])).trim()})`}},kx={conflict:"needs-agent","verify-failed":"verify-failed"},jh=async(e,t,r,n,o)=>{let s=await Vh(await uu(e,t));if(s)return{resolution:Mh(s,"exists"),reason:`resolution-exists: ${s.worktreePath} \u2014 finish it with --continue or drop it with --abort`};let i=await Te(e,`origin/${t}`);if(!i)return{reason:`origin/${t} does not exist on origin`};let a=af(e,t),c=()=>pu(e,t,a),l=Gi(c);try{await B(e,["worktree","prune"]),await _e.mkdir(et.dirname(a),{recursive:!0}),await B(e,["worktree","add","--detach",a,i]),await Ki({cwd:a,quiet:!0})`git merge --no-commit ${r} -m ${nu+t}`.catch(()=>{});let u=await wx(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 Ji(a),cliVersion:L.version,createdAt:new Date().toISOString()};return await hn(e,p),{resolution:Mh(p,p.lockfileOnly?"lockfile-only":kx[n])}}catch(u){return await c(),{reason:Lo(u)}}finally{l()}},Qh=async e=>{let{cwd:t,versions:r,all:n}=e,o=await Gh(t),s=o.map(a=>a.branch);if(r!==void 0)return(Array.isArray(r)?r:r.split(",")).map(c=>c.trim()).filter(c=>c.length>0).map(c=>{let l=xe(we(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 qt(me({branches:s,descriptions:new Map}),{required:!0});return o.filter(a=>i.includes(a.branch))},bx=async(e,t)=>{let r=await _e.realpath(t).catch(()=>null);if(!r)return!1;let n=await ot(e);for(let o of n)if(await _e.realpath(o.path).catch(()=>o.path)===r)return!0;return!1},fn=(e,t,r,n)=>({...e,blocked:{code:t,detail:r,...n&&n.length>0?{paths:n}:{}}}),ey=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 bx(e,n))return fn(o,"parents-mismatch",`the resolution worktree ${n} is gone \u2014 run --abort, then start again`);let s=await kr(n,"HEAD"),i=await kr(n,"MERGE_HEAD"),a=r??gx(t.handOffVerify);return s===t.baseSha&&i===t.devSha?xx(e,t,o,a):Rx(t,o,s,i)},Rx=async(e,t,r,n)=>{let o=e.worktreePath;if(r!==null&&r===e.unapprovedCommit)return fn(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 zh(o),i=n?null:await kr(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 fn(t,"parents-mismatch",`expected HEAD ${e.baseSha} merging ${e.devSha}, or an approved merge commit of the two; found ${l}`)}let c=await Hi(o,e);return c.length>0?fn(t,"out-of-scope-edit",Hh(e),c):{...t,committed:!0,mergeSha:r,treeSha:i,lockfileMerged:du(e),...await Xh(o,e)}},Fh=async(e,t)=>{let r=au(await B(e,["--literal-pathspecs","ls-files","-s","--",t])),[n,o,s]=r.length===1?(r[0]??"").split(/\s+/):[];return n&&s==="0"?o??null:null},Sx=async(e,t)=>{let r=t.worktreePath,n=await Fh(r,V),o=t.lockfileBlob,s=o===void 0&&t.editablePaths!==void 0&&n===await kr(r,`${t.autoMergeTree}:${V}`),i=await Th(r,t.devSha);if(!i.ok)return{code:"verify-failed",detail:i.reason,paths:[V]};let a=await Fh(r,V);if(a!==null&&a!==o&&(t.lockfileBlob=a,await hn(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 Hi(r,t);return c.length>0?{code:"out-of-scope-edit",detail:"merging the lockfile changed other paths",paths:c}:null},Ex=async(e,t)=>{let r=t.worktreePath,n=new Set(t.editablePaths),o=t.editablePaths?(await mu(r)).filter(c=>n.has(c)):t.conflictPaths;await fx(r,o.filter(c=>c!==V));let s=await Hi(r,t);if(s.length>0)return{code:"out-of-scope-edit",detail:Hh(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 mx(r,t.editablePaths?t.autoMergeTree:"HEAD")}catch(c){return{code:"markers-remaining",detail:`the marker check could not run: ${Lo(c)}`}}return a.length>0?{code:"markers-remaining",detail:"conflict markers are still staged",paths:a}:await Kh(r,t)?Sx(e,t):null},Px=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 Ji(o)),i=await yx(o,n),a=(await Ji(o)).filter(c=>!s.has(c)&&!Yh(c)&&et.posix.basename(c)!==".gitignore");return t.ignoredByVerify=[...new Set([...t.ignoredByVerify??[],...a])],await hn(e,t),i},xx=async(e,t,r,n)=>{let o=t.worktreePath,s=await Ex(e,t);if(s)return{...r,blocked:s};let i=du(t),a=await iu(o),c=await Px(e,t,a,hx(n)),l={...r,treeSha:a,lockfileMerged:i,verify:c};if(!c.ok)return fn(l,"verify-failed",c.reason??"the verify command failed");let u=await Hi(o,t),p=au(await B(o,["diff","--name-only"]));return u.length>0||p.length>0||await iu(o)!==a?fn(l,"verify-mutated-tree","the verify step changed the tree",[...new Set([...u,...p])]):(c.reused||(t.verified={treeSha:a,command:c.command},await hn(e,t)),{...l,...await Xh(o,t)})},Tx=12e4,Cx=async(e,t=Tx)=>{let r=Ki({cwd:e,quiet:!0,detached:!0,stdio:["ignore","pipe","pipe"],env:{...Nh.env,GIT_TERMINAL_PROMPT:"0"}})`git commit --no-edit --cleanup=strip`,n=!1,o=setTimeout(()=>{n=!0;let s=r.child?.pid;try{s&&Nh.kill(-s,"SIGKILL")}catch{}},t);try{return await r,{ok:!0}}catch(s){if(!n)return{ok:!1,reason:Lo(s)};let i=(await B(e,["rev-parse","--git-path","index.lock"])).trim();return await _e.rm(et.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"},Ax=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}},Ox=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 Cx(o);if(!i.ok)return s("hook-failed",i.reason);let a=(await B(o,["rev-parse","HEAD"])).trim(),c=(await B(o,["rev-parse","HEAD^{tree}"])).trim();if(c!==t.treeSha)return r.unapprovedCommit=a,await hn(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 zh(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}},Dx=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 jo(e,[{branch:t.branch,sha:r}],t.devSha)).nowUpToDate}catch(c){let l={code:"parents-mismatch",detail:`origin/${t.branch}: ${Lo(c)}`};return n("blocked",`parents-mismatch: ${l.detail}`,l)}if(o.includes(t.branch))return n("up-to-date",`origin/${t.branch} already carries ${t.devSha}`);let s=await Te(e,`origin/${t.branch}`);if(s===t.baseSha)return"keep";let i=s!==null&&await Zn(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)},Ix=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}`)},ty=async e=>{let{cwd:t,versions:r,all:n,verify:o,trees:s=new Map,confirmedCommand:i}=e,a=await Qh({cwd:t,versions:r,all:n});if(a.length===0)return d.info("\u2139\uFE0F No merge-dev resolutions in progress"),Fo();if(i)return Lh(t,a,o,s);let c=[];for(let m of a){let f=await ey(t,m,o);!f.blocked&&!f.committed&&f.treeSha&&(m.previewedTree=f.treeSha,await hn(t,m)),c.push(f)}Ix(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: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:Nx(p)})}catch(m){if(!St(m))throw m;return{...Fo(),declined:!0}}return Lh(t,a,o,p)},ry=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},Nx=e=>{let t=[],r=!1;for(let o of Rf())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"]},_x=async(e,t,r,n)=>{let o=await ey(e,t,r);if(o.blocked)return Ax(o);let s=await Ox(e,o,t,n);if(!("sha"in s))return s;let i=await Dx(e,t,s.sha);return i==="keep"?s:i},Mx=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 ni(e,r),o=[];for(let s of t){let i=n.pushed||await Vr(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(-Bh)}})}return{results:o,atomicPush:{attempted:!0,aborted:!n.pushed,abortedBy:n.stderr?.split(`
183
+ `)[0]}}},Lh=async(e,t,r,n)=>{let o=[],s=[];for(let u of t){let p=await _x(e,u,r,n.get(u.branch));"sha"in p?s.push({record:u,sha:p.sha}):o.push(p)}let i=await Mx(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 pu(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}},ny=async e=>{let{cwd:t,versions:r,all:n,confirmedCommand:o}=e,s=await Qh({cwd:t,versions:r,all:n});if(s.length===0)return d.info("\u2139\uFE0F No merge-dev resolutions in progress"),Fo();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(!St(a))throw a;return{...Fo(),declined:!0}}for(let a of s)await pu(t,a.branch,a.worktreePath),d.info(`\u{1F5D1}\uFE0F Discarded the resolution for ${a.branch}`);return{...Fo(),results:s.map(a=>({branch:a.branch,status:"aborted",conflictPaths:a.conflictPaths,pushed:!1}))}};import jx from"node:fs";import Fx from"node:os";import Lx from"node:path";var Bx="infra-kit.json",Ux="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)",Wx="Skipped agent-instruction files \u2014 no infra-kit.json at the repo root (the plugin pointer, the plugin install and .mcp.json are unaffected)",Bo=async()=>{let e;try{e=await A()}catch{return null}let t=e.trim();return t===""||t===Fx.homedir()?null:t},oy=async()=>{let e=await Bo();return e===null&&d.info(Ux),e},Vx=async()=>{let e=await Bo();return e===null?null:jx.existsSync(Lx.join(e,Bx))?e:(d.info(Wx),null)};var Gx=async e=>{try{return await be(e)}catch(t){return d.debug({err:t,msg:"Skipped per-package agent guidance \u2014 no workspace packages could be discovered."}),[]}},sy=async({dryRun:e=!1}={})=>{let t=await Vx(),r=L.version;if(t===null)return{skipped:!0,root:null,version:r,written:[]};let n=[...await go(t,{version:r,dryRun:e})];for(let o of await Gx(t)){let s=await Et(o);n.push(...await ho(o,{repoRoot:t,version:r,declaredType:s,dryRun:e}))}return{skipped:!1,root:t,version:r,written:n}};import ye from"node:fs";import ea from"node:os";import se from"node:path";import Eu from"node:process";import fu from"node:fs";import iy from"node:os";import ay from"node:path";import Jx from"node:process";import{z as Yi}from"zod";var cy=e=>{try{return fu.readFileSync(e,"utf-8")}catch{return null}},yn="claude in chrome",Kx="com.anthropic.claude_code_browser_extension",qi="run `/chrome` inside Claude Code to set up Claude in Chrome",Hx={darwin:["Library","Application Support","Google","Chrome","NativeMessagingHosts"],linux:[".config","google-chrome","NativeMessagingHosts"]},qx=e=>{try{return fu.accessSync(e,fu.constants.X_OK),!0}catch{return!1}},ly=e=>{try{return JSON.parse(e)}catch{return null}},Yx=/^exec\s+(?<target>\S+)\s+--chrome-native-host\b/m,Uo=(e={})=>{let t=e.platform??Jx.platform,r=e.home??iy.homedir(),n=e.readText??cy,o=e.isExecutable??qx,s=Hx[t];if(s===void 0)return{name:yn,status:"skip",message:`no Chrome native host location known for ${t}`};let i=ay.join(r,...s,`${Kx}.json`),a=n(i);if(a===null)return{name:yn,status:"warn",message:`Chrome native host not registered \u2014 ${qi}`};let c=Yi.object({path:Yi.string().min(1)}).safeParse(ly(a));if(!c.success)return{name:yn,status:"fail",message:`${w(i)} has no host path \u2014 ${qi} again`};let l=c.data.path;if(!o(l))return{name:yn,status:"fail",message:`Chrome native host ${w(l)} is missing or not executable \u2014 ${qi} again`};let u=Yx.exec(n(l)??"")?.groups?.target;return u!==void 0&&!o(u)?{name:yn,status:"fail",message:`Chrome native host runs ${w(u)}, which no longer exists \u2014 ${qi} again`}:{name:yn,status:"pass",message:`Native host registered (${w(l)}); /infra-kit:doctor checks the live connection`}},gu=(e={})=>{let t=e.home??iy.homedir(),r=e.readText??cy,n=Yi.object({claudeInChromeDefaultEnabled:Yi.boolean().optional()}).safeParse(ly(r(ay.join(t,".claude.json"))??""));return n.success&&n.data.claudeInChromeDefaultEnabled===!0};import Xi from"node:fs/promises";import zx from"node:path";import Xx from"node:process";var uy=` // // 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
@@ -293,7 +293,7 @@ ${l}`:l}).join(""),c=Ah.byteLength(a)>Dh;return{diffStat:r,...o?{lockfileDiffSta
293
293
  // // also fixes its modes), or by hand: both are supported, which is why the store carries no
294
294
  // // repo-identity field and no mandatory version. Pasting a token into an
295
295
  // // 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.`,mu=()=>`// infra-kit user-global config \u2014 ~/.infra-kit/infra-kit.json
296
+ // // the token first, because a config file can be committed, backed up by your editor, or shared.`,hu=()=>`// infra-kit user-global config \u2014 ~/.infra-kit/infra-kit.json
297
297
  //
298
298
  // Merge chain (later layers override earlier ones at top-level keys):
299
299
  // 1. <repo>/infra-kit.json \u2014 committed project config (required)
@@ -315,9 +315,9 @@ ${l}`:l}).join(""),c=Ah.byteLength(a)>Dh;return{diffStat:r,...o?{lockfileDiffSta
315
315
  // the committed project infra-kit.json (layer 1) and is usually NOT set in this
316
316
  // user-global layer \u2014 it is shown here only to document the full, valid config shape.
317
317
  {
318
- ${ay}
318
+ ${uy}
319
319
  }
320
- `,fu=e=>`// infra-kit user override for ${e} \u2014 ~/.infra-kit/projects/${e}/infra-kit.json
320
+ `,yu=e=>`// infra-kit user override for ${e} \u2014 ~/.infra-kit/projects/${e}/infra-kit.json
321
321
  //
322
322
  // Layer 3 (highest precedence) of the config merge chain. Shallow-merged on top of
323
323
  // <repo>/infra-kit.json (layer 1) and ~/.infra-kit/infra-kit.json (layer 2) \u2014 a
@@ -333,9 +333,9 @@ ${ay}
333
333
  // the committed project infra-kit.json (layer 1) and is usually NOT set in this
334
334
  // override layer \u2014 it is shown here only to document the full, valid config shape.
335
335
  {
336
- ${ay}
336
+ ${uy}
337
337
  }
338
- `,gu=()=>`// infra-kit factory registry \u2014 ~/.infra-kit/vendor.json
338
+ `,vu=()=>`// infra-kit factory registry \u2014 ~/.infra-kit/vendor.json
339
339
  //
340
340
  // Machine-local registry the vendor commands (sync/manifest/diff) read to know
341
341
  // where your project repos live, which one is the source and which ones to stamp. This .example.jsonc is
@@ -347,109 +347,109 @@ ${ay}
347
347
  // "source": "starter-workspace", // string \u2014 the one repo \`vendor sync\` copies from (its infra-kit.json holds vendorSource)
348
348
  // "targets": ["my-repo-a", "my-repo-b"] // string[] (>=1) \u2014 repo dir names resolved under workspaceDir
349
349
  }
350
- `;var cy=!1,Wx=e=>e.replace(/\.json$/,".example.jsonc"),Vx=async e=>{try{return await Hi.readFile(e,"utf-8")}catch{return null}},yn=async e=>{let t=e.userProject,r=Wx(t);await Hi.mkdir(Bx.dirname(t),{recursive:!0});let n=!await ne(t);n&&await Hi.writeFile(t,`{}
351
- `,"utf-8");let o=fu(e.projectName),s=await Vx(r)!==o;return s&&await Hi.writeFile(r,o,"utf-8"),n&&Zn(),{configPath:t,examplePath:r,createdConfig:n,refreshedExample:s}},vn=e=>`Created ${w(e.configPath)} \u2014 see ${w(e.examplePath)} for the annotated reference.`,hu=async()=>{if(Ux.env.INFRA_KIT_NO_SEED||cy)return;cy=!0;let e;try{e=await ee()}catch{return}if(await ne(e.main))try{let t=await yn(e);t.createdConfig?d.info(vn(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 eT}from"node:child_process";import yy from"node:fs";import Rn from"node:process";import{fileURLToPath as vy}from"node:url";import qi from"node:fs";import wn from"node:path";var ly="auto-setup.json",Gx="auto-setup.log",Jx="auto-setup.lock",uy="auto-setup.notified",Kx=3,Hx=3600*1e3,qx=()=>wn.join(wt(),ly),kn=()=>wn.join(wt(),Gx),dy=()=>wn.join(wt(),Jx),Yx=()=>wn.join(wt(),uy),zx=new Set(["ok","attention","failed"]),Xx=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"&&zx.has(r)&&Array.isArray(n)&&n.every(o=>typeof o=="string")},Zx=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(Xx)},bn=(e=t=>qi.readFileSync(t,"utf8"))=>{try{let t=JSON.parse(e(qx()));return Zx(t)?t:null}catch{return null}},py=e=>{let t=wt();qi.mkdirSync(t,{recursive:!0}),It(wn.join(t,ly),JSON.stringify(e),384)},Qx=e=>e.finishedMs===null||e.runs.some(t=>t.status==="failed"),my=(e=t=>qi.readFileSync(t,"utf8"))=>{try{let t=Number(e(Yx()).trim());return Number.isFinite(t)?t:null}catch{return null}},fy=e=>{let t=wt();qi.mkdirSync(t,{recursive:!0}),It(wn.join(t,uy),String(e),384)},gy=(e,t,r)=>{if(e===null)return!0;let n=r-e.startedMs;return n>=0&&n<Hx?!1:e.version!==t?!0:Qx(e)&&e.attempts<Kx};var hy=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],yu=e=>{let{argv:t,env:r,isTty:n,selfRealPath:o,cwd:s,realpath:i}=e;return hy.some(c=>{let l=r[c];return l!=null&&l!==""})?"opt-out":t.includes("--json")?"json":n?Tm(o,s,i)?"local-install":null:"not-a-tty"};var tT=e=>{eT(Rn.execPath,[e,"--parent-pid",String(Rn.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},rT=()=>vy(new URL("./update-check.js",import.meta.url)),nT=()=>yy.realpathSync(vy(new URL("./cli.js",import.meta.url))),oT=/^[\w@./+ -]+$/,sT=e=>oT.test(e),iT=(e,t,r)=>{!e?.latestVersion||!e.updateCommand||kt(e.latestVersion,t)&&e.updateCommand.every(sT)&&r(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${Ks(e.updateCommand)}`)},aT=(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(kn())}, or run: infra-kit setup`),o(e.finishedMs)},vu=(e,t={})=>{try{let r=t.argv??Rn.argv,n=t.env??Rn.env,o=t.isTty??!!Rn.stdout.isTTY,s=t.cwd??Rn.cwd(),i=t.nowMs??Date.now(),a=t.selfRealPath??nT(),c=t.readCache??to,l=t.spawnChild??tT,u=t.fileExists??(v=>yy.existsSync(v)),p=t.notify??(v=>{d.info(v)});if(yu({argv:r,env:n,isTty:o,selfRealPath:a,cwd:s,realpath:Ee})!==null)return;let m=c();iT(m,e,p);try{aT((t.readAutoSetup??bn)(),e,(t.readNotified??my)(),p,t.writeNotified??fy)}catch{}if(!Cc(m,i))return;let f=t.childPath??rT();if(!u(f))return;l(f)}catch{}};import ft from"node:fs/promises";import mt from"node:path";import{pathToFileURL as uT}from"node:url";import dT from"yaml";import{z as Pn}from"zod";import cT from"node:fs/promises";import wu from"node:os";import ku from"node:path";import{z as lT}from"zod";import{z as Uo}from"zod";var wy="vendor.json",ky=Uo.object({workspaceDir:Uo.string().min(1),source:Uo.string().min(1),targets:Uo.array(Uo.string()).min(1)}).strict().refine(e=>!e.targets.includes(e.source),{message:'the source repo must not also be listed in "targets"',path:["targets"]});var Sn=()=>ku.join(wu.homedir(),km,wy),En=e=>{if(e==="~")return wu.homedir();if(e.startsWith("~/"))return ku.join(wu.homedir(),e.slice(2));if(ku.isAbsolute(e))return e;throw new Error(`workspaceDir must be absolute or ~-prefixed, got: ${e}`)},Yi=async()=>{let e=Sn(),t;try{t=await cT.readFile(e,"utf-8")}catch{throw new Error(`Factory config not found at ${e}. infra-kit needs a machine-local factory registry to know where your project repos live, which one is the source and which to stamp. Run \`infra-kit vendor config --init\` to scaffold it, or create it manually as JSON:
350
+ `;var dy=!1,Zx=e=>e.replace(/\.json$/,".example.jsonc"),Qx=async e=>{try{return await Xi.readFile(e,"utf-8")}catch{return null}},vn=async e=>{let t=e.userProject,r=Zx(t);await Xi.mkdir(zx.dirname(t),{recursive:!0});let n=!await ne(t);n&&await Xi.writeFile(t,`{}
351
+ `,"utf-8");let o=yu(e.projectName),s=await Qx(r)!==o;return s&&await Xi.writeFile(r,o,"utf-8"),n&&Qn(),{configPath:t,examplePath:r,createdConfig:n,refreshedExample:s}},wn=e=>`Created ${w(e.configPath)} \u2014 see ${w(e.examplePath)} for the annotated reference.`,wu=async()=>{if(Xx.env.INFRA_KIT_NO_SEED||dy)return;dy=!0;let e;try{e=await ee()}catch{return}if(await ne(e.main))try{let t=await vn(e);t.createdConfig?d.info(wn(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 uT}from"node:child_process";import ky from"node:fs";import Sn from"node:process";import{fileURLToPath as by}from"node:url";import Zi from"node:fs";import kn from"node:path";var py="auto-setup.json",eT="auto-setup.log",tT="auto-setup.lock",my="auto-setup.notified",rT=3,nT=3600*1e3,oT=()=>kn.join(bt(),py),bn=()=>kn.join(bt(),eT),fy=()=>kn.join(bt(),tT),sT=()=>kn.join(bt(),my),iT=new Set(["ok","attention","failed"]),aT=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"&&iT.has(r)&&Array.isArray(n)&&n.every(o=>typeof o=="string")},cT=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(aT)},Rn=(e=t=>Zi.readFileSync(t,"utf8"))=>{try{let t=JSON.parse(e(oT()));return cT(t)?t:null}catch{return null}},gy=e=>{let t=bt();Zi.mkdirSync(t,{recursive:!0}),_t(kn.join(t,py),JSON.stringify(e),384)},lT=e=>e.finishedMs===null||e.runs.some(t=>t.status==="failed"),hy=(e=t=>Zi.readFileSync(t,"utf8"))=>{try{let t=Number(e(sT()).trim());return Number.isFinite(t)?t:null}catch{return null}},yy=e=>{let t=bt();Zi.mkdirSync(t,{recursive:!0}),_t(kn.join(t,my),String(e),384)},vy=(e,t,r)=>{if(e===null)return!0;let n=r-e.startedMs;return n>=0&&n<nT?!1:e.version!==t?!0:lT(e)&&e.attempts<rT};var wy=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],ku=e=>{let{argv:t,env:r,isTty:n,selfRealPath:o,cwd:s,realpath:i}=e;return wy.some(c=>{let l=r[c];return l!=null&&l!==""})?"opt-out":t.includes("--json")?"json":n?Am(o,s,i)?"local-install":null:"not-a-tty"};var dT=e=>{uT(Sn.execPath,[e,"--parent-pid",String(Sn.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},pT=()=>by(new URL("./update-check.js",import.meta.url)),mT=()=>ky.realpathSync(by(new URL("./cli.js",import.meta.url))),fT=/^[\w@./+ -]+$/,gT=e=>fT.test(e),hT=(e,t,r)=>{!e?.latestVersion||!e.updateCommand||Rt(e.latestVersion,t)&&e.updateCommand.every(gT)&&r(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${zs(e.updateCommand)}`)},yT=(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(bn())}, or run: infra-kit setup`),o(e.finishedMs)},bu=(e,t={})=>{try{let r=t.argv??Sn.argv,n=t.env??Sn.env,o=t.isTty??!!Sn.stdout.isTTY,s=t.cwd??Sn.cwd(),i=t.nowMs??Date.now(),a=t.selfRealPath??mT(),c=t.readCache??ro,l=t.spawnChild??dT,u=t.fileExists??(y=>ky.existsSync(y)),p=t.notify??(y=>{d.info(y)});if(ku({argv:r,env:n,isTty:o,selfRealPath:a,cwd:s,realpath:Pe})!==null)return;let m=c();hT(m,e,p);try{yT((t.readAutoSetup??Rn)(),e,(t.readNotified??hy)(),p,t.writeNotified??yy)}catch{}if(!Oc(m,i))return;let f=t.childPath??pT();if(!u(f))return;l(f)}catch{}};import ft from"node:fs/promises";import mt from"node:path";import{pathToFileURL as kT}from"node:url";import bT from"yaml";import{z as xn}from"zod";import vT from"node:fs/promises";import Ru from"node:os";import Su from"node:path";import{z as wT}from"zod";import{z as Wo}from"zod";var Ry="vendor.json",Sy=Wo.object({workspaceDir:Wo.string().min(1),source:Wo.string().min(1),targets:Wo.array(Wo.string()).min(1)}).strict().refine(e=>!e.targets.includes(e.source),{message:'the source repo must not also be listed in "targets"',path:["targets"]});var En=()=>Su.join(Ru.homedir(),Sm,Ry),Pn=e=>{if(e==="~")return Ru.homedir();if(e.startsWith("~/"))return Su.join(Ru.homedir(),e.slice(2));if(Su.isAbsolute(e))return e;throw new Error(`workspaceDir must be absolute or ~-prefixed, got: ${e}`)},Qi=async()=>{let e=En(),t;try{t=await vT.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
352
 
353
353
  {
354
354
  "workspaceDir": "~/projects",
355
355
  "source": "my-starter",
356
356
  "targets": ["my-repo"]
357
357
  }
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=ky.safeParse(r);if(!n.success)throw new Error(`Invalid factory config at ${e}: ${lT.prettifyError(n.error)}`);return n.data};var by=e=>e.replace(/\.json$/,".yml"),Ry=async()=>{let e;try{e=await ee()}catch{return}let t={label:"infra-kit.json",yml:by(e.main),json:e.main,schema:ff},r=[...Xe.withheld?[]:[t],{label:"~/.infra-kit/infra-kit.json",yml:mt.join(mt.dirname(e.userGlobal),"config.yml"),json:e.userGlobal,schema:Sc},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:by(e.userProject),json:e.userProject,schema:Sc}],n=0;for(let o of r){let[s,i]=await Promise.all([ne(o.yml),ne(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 ft.readFile(o.yml,"utf-8"),c=dT.parse(a)??{},l=o.schema.safeParse(c);if(!l.success){d.info(`\u26A0 Skipped ${w(o.yml)} \u2014 invalid config: ${Pn.prettifyError(l.error)}`);continue}await ft.mkdir(mt.dirname(o.json),{recursive:!0}),await ft.writeFile(o.json,`${JSON.stringify(l.data,null,2)}
359
- `,"utf-8"),await ft.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&&Mt()},Sy=async()=>{let e;try{e=await ee()}catch{return}let t=mt.dirname(e.userGlobal),r=[{from:mt.join(t,"config.json"),to:e.userGlobal},{from:mt.join(t,"config.example.jsonc"),to:mt.join(t,"infra-kit.example.jsonc")}],n=0;for(let{from:o,to:s}of r){let[i,a]=await Promise.all([ne(o),ne(s)]);if(i){if(a){d.info(`\u26A0 Skipped ${w(o)} \u2014 ${w(s)} already exists (remove the stale file manually)`);continue}try{await ft.mkdir(mt.dirname(s),{recursive:!0}),await ft.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&&Mt()},pT=Pn.object({workspaceDir:Pn.string().min(1),targets:Pn.array(Pn.string()).min(1)}).strict(),Ey=async()=>{let e=Sn(),t=mt.dirname(e),r=mt.join(t,"vendor.config.ts"),[n,o]=await Promise.all([ne(r),ne(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 ft.stat(r),c=(await import(`${uT(r).href}?mtime=${Number(s.mtimeMs)}`)).default,l=typeof c=="function",u=l?await c():c,p=pT.safeParse(u);if(!p.success){d.info(`\u26A0 Skipped ${w(r)} \u2014 invalid factory config: ${Pn.prettifyError(p.error)}`);return}await ft.mkdir(t,{recursive:!0}),await ft.writeFile(e,`${JSON.stringify(p.data,null,2)}
360
- `,"utf-8"),await ft.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}`)}}},Py=async()=>{let e=await mT(),t=0;for(let r of e)if(await ne(r))try{let n=await lf(r);if(!n.changed)continue;d.info(`\u2713 Migrated ${w(r)} (removed ${n.notes.join(" and ")})`),t++}catch(n){let o=n instanceof af?"changed while migrating":n.message;d.info(`\u26A0 Skipped ${w(r)} \u2014 ${o}`)}t>0&&Mt()},mT=async()=>{try{let e=await ee();return Xe.withheld?[e.userGlobal,e.userProject]:[e.main,e.userGlobal,e.userProject]}catch{return[hf()]}};var wr="# -- infra-kit:begin --",Ht="# -- infra-kit:end --",fT=[["# region infra-kit","# endregion infra-kit"]],gT="# infra-kit shell functions",xn=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},Tn="Run `source ~/.zshrc` or open a new terminal to activate.",hT={step:"migrations",outcome:"unchanged",message:"Config migrations checked (legacy yml layers, user-global filename, ide structure, factory config, retired project cache)",level:"silent"},Je=async(e,t)=>{try{return await t()}catch(r){throw new xn(e,r)}},Ru=async e=>{let t=[],r=(...s)=>{for(let i of s)t.push(i),e?.(i)};await Je("zshrc",()=>{r(wT())}),await Je("zshenv",()=>{r(kT())}),await Je("migrations",async()=>{await RT(),bT(),r(hT)}),await Je("user-config",()=>{r(ET())});let n=await Je("guidance",async()=>{let{entries:s,root:i}=await CT();return r(...s),i}),o=await Je("plugin-pointer",async()=>ty());return r(...AT(o,n)),await Je("worktrees",async()=>{r(...await _T(o))}),await Je("plugin-pointer",async()=>{await jT(o,r)}),await Je("mcp-proxies",async()=>{r(...await LT(o))}),await Je("project-config",async()=>{r(...await PT(o))}),await Je("token-perms",async()=>{r(await vT())}),await Je("chrome",()=>{r(yT())}),r(...ST()),t},yT=()=>{let e=Bo();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"}},vT=async()=>{let e=await Ef();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 Ty=e=>{let t=se.dirname(e);return he.existsSync(se.join(e,".git"))?e:t===e?null:Ty(t)},Cy=(e,t,r,n)=>{if(!Xe.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=he.realpathSync(t)}catch{}return Ty(se.dirname(o))===null?null:Vo(e,zi.homedir(),o,["the infra-kit block updated"])},$y=e=>he.existsSync(e)?he.readFileSync(e,"utf-8"):null,wT=()=>{let e=se.join(zi.homedir(),".zshrc"),t=$y(e),r=t===null?"":UT(t),n=Jr({content:r,body:Dy(),startMarker:wr,endMarker:Ht,placement:"append-end"}),o=Cy("zshrc",e,t,n);return o!==null?o:(he.writeFileSync(e,n),{step:"zshrc",outcome:"written",message:`Added infra-kit shell functions to ${e}`,level:"info"})},kT=()=>{let e=se.join(zi.homedir(),".zshenv"),t=$y(e),r=Jr({content:t??"",body:Su(),startMarker:wr,endMarker:Ht}),n=Cy("zshenv",e,t,r);return n!==null?n:(he.writeFileSync(e,r),{step:"zshenv",outcome:"written",message:`Added infra-kit session-env block to ${e}`,level:"info"})},bT=()=>{he.rmSync(se.join(wt(),"projects"),{recursive:!0,force:!0})},RT=async()=>{await Ry(),await Sy(),await Py(),await Ey()},ST=()=>{let e=bu.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:Tn,level:"info"}),t},ET=()=>{let e=se.join(zi.homedir(),".infra-kit"),t=se.join(e,"infra-kit.json");return he.mkdirSync(e,{recursive:!0}),he.writeFileSync(se.join(e,"infra-kit.example.jsonc"),mu(),"utf-8"),he.writeFileSync(se.join(e,"vendor.example.jsonc"),gu(),"utf-8"),he.existsSync(t)?{step:"user-config",outcome:"unchanged",message:`User-global config already present at ${t} (refreshed reference examples)`,level:"info"}:(he.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"})},PT=async e=>{if(bu.env.INFRA_KIT_NO_SEED)return[Wo("skipped","INFRA_KIT_NO_SEED is set")];if(e===null)return[Wo("skipped","not inside a git repository")];try{let t=await ee();if(!he.existsSync(t.main))return[Wo("skipped",`no project config at ${t.main}`)];let r=await yn(t);return r.createdConfig?[{step:"project-config",outcome:"written",message:vn(r),level:"info"}]:[Wo("unchanged","the user-project config was already present")]}catch(t){return d.debug({err:t,msg:"Skipped seeding the user-project config (init)."}),[Wo("warned",t instanceof Error?t.message:String(t))]}},Wo=(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},TT=(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},CT=async()=>{let{skipped:e,root:t,version:r,written:n}=await ry({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:TT(r,n)}},Xi=e=>`cd ${Am(e)} && infra-kit setup --skip-tools`,Vo=(e,t,r,n)=>({step:e,outcome:"manual",message:`${r} needs ${n.join(", ")} \u2014 left for a human to commit; run: ${Xi(t)}`,level:"info"}),$T=(e,t)=>{let r=se.relative(e,t.path);return t.status==="withheld"?Vo("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"}},xy=(e,t)=>{let r=Ge;if(t.kind==="stale"||t.kind==="wrong-key"){let o=t.kind==="stale"?le: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 ${ut} from ${se.join(e,Ge)} \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 "${le}" key`:`no ${r}`})`,level:"info"}},AT=(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 ${Y} plugin for that project. If that is not the repo you meant to set up, revert that file and uninstall the plugin.`,level:"warn"}],OT=()=>[gl,Pt].map(e=>({step:"plugin-pointer",outcome:"manual",message:e,level:"info"})),DT=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:Ks(e.updateCommand),level:"info"}]:[r]},IT=(e,t)=>e.status==="skipped-cli-stale"?DT(t):e.status==="updated"?[{step:"plugin-pointer",outcome:"unchanged",message:`Claude Code plugin ${Y} 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: ${en}`,level:"warn"}]:e.status==="installed"?[{step:"plugin-pointer",outcome:"written",message:`installed Claude Code plugin ${Y} (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"},...OT()]:[{step:"plugin-pointer",outcome:"warned",message:`Could not install the Claude Code plugin \u2014 ${e.status==="unverified"?"the install reported success but Claude Code recorded no installation":`the ${e.step} step failed: ${e.error}`}. Run by hand: ${Pt}`,level:"warn"}],Ay={stale:!1},NT=async()=>{let e=to(),t=e===null?await Ac(bu.env):e.latestVersion;return t===null||!Oc(t,L.version)?Ay:{stale:!0,latestVersion:t,updateCommand:e?.updateCommand??xm(t)}},_T=async e=>{if(e===null)return[];let r=`${await $e(e)}${fe}`,n=Object.values(Lr).filter(o=>!he.existsSync(se.join(r,o)));for(let o of Object.values(Lr))he.mkdirSync(se.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"}]},MT=(e,t)=>t?[{step:"plugin-pointer",outcome:"skipped",message:`Claude Code plugin ${Y} is installed; the update worker keeps it current`,level:"debug"}]:[Vo("plugin-pointer",e,".claude/settings.json",[`the ${Y} plugin installed`])],jT=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($T(e,hl(se.join(e,".claude","settings.json"),{write:!Xe.withheld})));let r=ar({projectPath:e}).kind==="installed";if(Xe.withheld){t(...MT(e,r),xy(e,Qr(e)));return}let n=r?await NT():Ay;t(...IT(ul({projectRoot:e,cliIsStale:()=>n.stale}),n)),t(xy(e,Qr(e)))}catch(r){let n=r instanceof Error?r.message:String(r);t({step:"plugin-pointer",outcome:"warned",message:`Could not finish the Claude Code plugin step for ${e} (${n}). Run by hand: ${Pt}`,level:"warn"})}},Oy=(e,t)=>{let r=se.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},FT=(e,t)=>{let r=t.entries.filter(i=>i.status==="drifted"),n=t.entries.filter(i=>i.status!=="drifted"),o=Oy(e,{...t,entries:n});if(t.status!=="ok"||r.length===0)return o;let s=r.map(i=>`ik-mcp "${i.name}"`);return[...o,Vo("mcp-proxies",e,se.relative(e,t.path),s)]},LT=async e=>{if(e===null)return[];if(!he.existsSync(se.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 H()).mcp}catch(r){let n=r instanceof Error?r.message:String(r),o=n.split(`
362
- `)[0]??n;return Xe.withheld?[Vo("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?[]:Xe.withheld?FT(e,ko({projectRoot:e,proxies:t,write:!1})):Oy(e,ko({projectRoot:e,proxies:t,write:!0}))},BT=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"),UT=e=>{let t=Wt(e,wr,Ht);if(t!==null)return t;for(let[a,c]of fT){let l=Wt(e,a,c);if(l!==null)return l}let r=e.indexOf(gT);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&&BT(o[s]);)s++;let i=o.slice(s).join(`
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=Sy.safeParse(r);if(!n.success)throw new Error(`Invalid factory config at ${e}: ${wT.prettifyError(n.error)}`);return n.data};var Ey=e=>e.replace(/\.json$/,".yml"),Py=async()=>{let e;try{e=await ee()}catch{return}let t={label:"infra-kit.json",yml:Ey(e.main),json:e.main,schema:yf},r=[...Xe.withheld?[]:[t],{label:"~/.infra-kit/infra-kit.json",yml:mt.join(mt.dirname(e.userGlobal),"config.yml"),json:e.userGlobal,schema:xc},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:Ey(e.userProject),json:e.userProject,schema:xc}],n=0;for(let o of r){let[s,i]=await Promise.all([ne(o.yml),ne(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 ft.readFile(o.yml,"utf-8"),c=bT.parse(a)??{},l=o.schema.safeParse(c);if(!l.success){d.info(`\u26A0 Skipped ${w(o.yml)} \u2014 invalid config: ${xn.prettifyError(l.error)}`);continue}await ft.mkdir(mt.dirname(o.json),{recursive:!0}),await ft.writeFile(o.json,`${JSON.stringify(l.data,null,2)}
359
+ `,"utf-8"),await ft.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&&Ft()},xy=async()=>{let e;try{e=await ee()}catch{return}let t=mt.dirname(e.userGlobal),r=[{from:mt.join(t,"config.json"),to:e.userGlobal},{from:mt.join(t,"config.example.jsonc"),to:mt.join(t,"infra-kit.example.jsonc")}],n=0;for(let{from:o,to:s}of r){let[i,a]=await Promise.all([ne(o),ne(s)]);if(i){if(a){d.info(`\u26A0 Skipped ${w(o)} \u2014 ${w(s)} already exists (remove the stale file manually)`);continue}try{await ft.mkdir(mt.dirname(s),{recursive:!0}),await ft.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&&Ft()},RT=xn.object({workspaceDir:xn.string().min(1),targets:xn.array(xn.string()).min(1)}).strict(),Ty=async()=>{let e=En(),t=mt.dirname(e),r=mt.join(t,"vendor.config.ts"),[n,o]=await Promise.all([ne(r),ne(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 ft.stat(r),c=(await import(`${kT(r).href}?mtime=${Number(s.mtimeMs)}`)).default,l=typeof c=="function",u=l?await c():c,p=RT.safeParse(u);if(!p.success){d.info(`\u26A0 Skipped ${w(r)} \u2014 invalid factory config: ${xn.prettifyError(p.error)}`);return}await ft.mkdir(t,{recursive:!0}),await ft.writeFile(e,`${JSON.stringify(p.data,null,2)}
360
+ `,"utf-8"),await ft.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}`)}}},Cy=async()=>{let e=await ST(),t=0;for(let r of e)if(await ne(r))try{let n=await pf(r);if(!n.changed)continue;d.info(`\u2713 Migrated ${w(r)} (removed ${n.notes.join(" and ")})`),t++}catch(n){let o=n instanceof uf?"changed while migrating":n.message;d.info(`\u26A0 Skipped ${w(r)} \u2014 ${o}`)}t>0&&Ft()},ST=async()=>{try{let e=await ee();return Xe.withheld?[e.userGlobal,e.userProject]:[e.main,e.userGlobal,e.userProject]}catch{return[wf()]}};var br="# -- infra-kit:begin --",Yt="# -- infra-kit:end --",ET=[["# region infra-kit","# endregion infra-kit"]],PT="# infra-kit shell functions",Tn=class extends Error{constructor(r,n){super(n instanceof Error?n.message:String(n),{cause:n});this.step=r;this.reason=n;this.name="InitStepError"}step;reason},Cn="Run `source ~/.zshrc` or open a new terminal to activate.",xT={step:"migrations",outcome:"unchanged",message:"Config migrations checked (legacy yml layers, user-global filename, ide structure, factory config, retired project cache)",level:"silent"},Je=async(e,t)=>{try{return await t()}catch(r){throw new Tn(e,r)}},Pu=async e=>{let t=[],r=(...s)=>{for(let i of s)t.push(i),e?.(i)};await Je("zshrc",()=>{r($T())}),await Je("zshenv",()=>{r(AT())}),await Je("migrations",async()=>{await DT(),OT(),r(xT)}),await Je("user-config",()=>{r(NT())});let n=await Je("guidance",async()=>{let{entries:s,root:i}=await FT();return r(...s),i}),o=await Je("plugin-pointer",async()=>oy());return r(...BT(o,n)),await Je("worktrees",async()=>{r(...await JT(o))}),await Je("plugin-pointer",async()=>{await HT(o,r)}),await Je("mcp-proxies",async()=>{r(...await YT(o))}),await Je("project-config",async()=>{r(...await _T(o))}),await Je("token-perms",async()=>{r(await CT())}),await Je("chrome",()=>{r(TT())}),r(...IT()),t},TT=()=>{let e=Uo();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"}:gu()?{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"}},CT=async()=>{let e=await Tf();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 Ay=e=>{let t=se.dirname(e);return ye.existsSync(se.join(e,".git"))?e:t===e?null:Ay(t)},Oy=(e,t,r,n)=>{if(!Xe.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 Ay(se.dirname(o))===null?null:Go(e,ea.homedir(),o,["the infra-kit block updated"])},Dy=e=>ye.existsSync(e)?ye.readFileSync(e,"utf-8"):null,$T=()=>{let e=se.join(ea.homedir(),".zshrc"),t=Dy(e),r=t===null?"":XT(t),n=Kr({content:r,body:_y(),startMarker:br,endMarker:Yt,placement:"append-end"}),o=Oy("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"})},AT=()=>{let e=se.join(ea.homedir(),".zshenv"),t=Dy(e),r=Kr({content:t??"",body:xu(),startMarker:br,endMarker:Yt}),n=Oy("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"})},OT=()=>{ye.rmSync(se.join(bt(),"projects"),{recursive:!0,force:!0})},DT=async()=>{await Py(),await xy(),await Cy(),await Ty()},IT=()=>{let e=Eu.env.SHELL??"",t=[];return e.includes("zsh")||t.push({step:"shell",outcome:"warned",message:`Your login shell ($SHELL=${e||"unset"}) is not zsh. The infra-kit shell integration (env-load/env-clear) is zsh-only and won't activate in bash/fish.`,level:"warn"}),t.push({step:"shell",outcome:"unchanged",message:Cn,level:"info"}),t},NT=()=>{let e=se.join(ea.homedir(),".infra-kit"),t=se.join(e,"infra-kit.json");return ye.mkdirSync(e,{recursive:!0}),ye.writeFileSync(se.join(e,"infra-kit.example.jsonc"),hu(),"utf-8"),ye.writeFileSync(se.join(e,"vendor.example.jsonc"),vu(),"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"})},_T=async e=>{if(Eu.env.INFRA_KIT_NO_SEED)return[Vo("skipped","INFRA_KIT_NO_SEED is set")];if(e===null)return[Vo("skipped","not inside a git repository")];try{let t=await ee();if(!ye.existsSync(t.main))return[Vo("skipped",`no project config at ${t.main}`)];let r=await vn(t);return r.createdConfig?[{step:"project-config",outcome:"written",message:wn(r),level:"info"}]:[Vo("unchanged","the user-project config was already present")]}catch(t){return d.debug({err:t,msg:"Skipped seeding the user-project config (init)."}),[Vo("warned",t instanceof Error?t.message:String(t))]}},Vo=(e,t)=>({step:"project-config",outcome:e,message:`Skipped seeding the user-project config \u2014 ${t}`,level:"silent"}),MT=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},jT=(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"},...MT(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},FT=async()=>{let{skipped:e,root:t,version:r,written:n}=await sy({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:jT(r,n)}},ta=e=>`cd ${Im(e)} && infra-kit setup --skip-tools`,Go=(e,t,r,n)=>({step:e,outcome:"manual",message:`${r} needs ${n.join(", ")} \u2014 left for a human to commit; run: ${ta(t)}`,level:"info"}),LT=(e,t)=>{let r=se.relative(e,t.path);return t.status==="withheld"?Go("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"}},$y=(e,t)=>{let r=Ge;if(t.kind==="stale"||t.kind==="wrong-key"){let o=t.kind==="stale"?le: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 ${ut} from ${se.join(e,Ge)} \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 "${le}" key`:`no ${r}`})`,level:"info"}},BT=(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 ${Y} plugin for that project. If that is not the repo you meant to set up, revert that file and uninstall the plugin.`,level:"warn"}],UT=()=>[vl,Tt].map(e=>({step:"plugin-pointer",outcome:"manual",message:e,level:"info"})),WT=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]},VT=(e,t)=>e.status==="skipped-cli-stale"?WT(t):e.status==="updated"?[{step:"plugin-pointer",outcome:"unchanged",message:`Claude Code plugin ${Y} 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: ${tn}`,level:"warn"}]:e.status==="installed"?[{step:"plugin-pointer",outcome:"written",message:`installed Claude Code plugin ${Y} (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"},...UT()]:[{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: ${Tt}`,level:"warn"}],Iy={stale:!1},GT=async()=>{let e=ro(),t=e===null?await Ic(Eu.env):e.latestVersion;return t===null||!Nc(t,L.version)?Iy:{stale:!0,latestVersion:t,updateCommand:e?.updateCommand??$m(t)}},JT=async e=>{if(e===null)return[];let r=`${await $e(e)}${ge}`,n=Object.values(Br).filter(o=>!ye.existsSync(se.join(r,o)));for(let o of Object.values(Br))ye.mkdirSync(se.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"}]},KT=(e,t)=>t?[{step:"plugin-pointer",outcome:"skipped",message:`Claude Code plugin ${Y} is installed; the update worker keeps it current`,level:"debug"}]:[Go("plugin-pointer",e,".claude/settings.json",[`the ${Y} plugin installed`])],HT=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(LT(e,wl(se.join(e,".claude","settings.json"),{write:!Xe.withheld})));let r=lr({projectPath:e}).kind==="installed";if(Xe.withheld){t(...KT(e,r),$y(e,en(e)));return}let n=r?await GT():Iy;t(...VT(ml({projectRoot:e,cliIsStale:()=>n.stale}),n)),t($y(e,en(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: ${Tt}`,level:"warn"})}},Ny=(e,t)=>{let r=se.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},qT=(e,t)=>{let r=t.entries.filter(i=>i.status==="drifted"),n=t.entries.filter(i=>i.status!=="drifted"),o=Ny(e,{...t,entries:n});if(t.status!=="ok"||r.length===0)return o;let s=r.map(i=>`ik-mcp "${i.name}"`);return[...o,Go("mcp-proxies",e,se.relative(e,t.path),s)]},YT=async e=>{if(e===null)return[];if(!ye.existsSync(se.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 Xe.withheld?[Go("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?[]:Xe.withheld?qT(e,bo({projectRoot:e,proxies:t,write:!1})):Ny(e,bo({projectRoot:e,proxies:t,write:!0}))},zT=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"),XT=e=>{let t=Gt(e,br,Yt);if(t!==null)return t;for(let[a,c]of ET){let l=Gt(e,a,c);if(l!==null)return l}let r=e.indexOf(PT);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&&zT(o[s]);)s++;let i=o.slice(s).join(`
364
364
  `);return n+(i?`
365
- ${i}`:"")},Dy=()=>{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
- `)},Iy=()=>`${wr}
367
- ${Dy()}
368
- ${Ht}`,Su=()=>["# 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
- `),Eu=()=>`${wr}
370
- ${Su()}
371
- ${Ht}`;import WT from"node:fs/promises";var Go=async(e,t)=>{if(!t)return{hasOverrides:!1,overrideKeys:[],unreadable:!1};try{let r=await WT.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}}},Jo=e=>e.unreadable?"(unreadable \u2014 invalid JSON)":e.overrideKeys.length===0?"(empty \u2014 no overrides)":`(${e.overrideKeys.length} override(s): ${e.overrideKeys.join(", ")})`;import GT from"node:fs";import JT from"node:os";import Ny from"node:path";import KT from"node:process";import{$ as VT}from"zx";var Cn=()=>VT({quiet:!0});var HT=()=>[Ny.join(JT.homedir(),".local","bin"),"/opt/homebrew/bin","/usr/local/bin"],qT=async e=>{try{return(await Cn()`command -v ${e}`).stdout.trim()||null}catch{return null}},Ko=()=>({runCommand:async e=>{let t=await Cn()`${e}`;return{stdout:`${t.stdout}
372
- ${t.stderr}`}},resolveBinPath:async e=>{let t=await qT(e);return t!==null?t:HT().map(r=>Ny.join(r,e)).find(r=>GT.existsSync(r))??null},realpath:Ee,platform:KT.platform});var qt=(...e)=>({steps:e,needsSudo:!1,fetchesNetworkScript:!1}),$n=e=>/\d{1,10}\.\d{1,10}\.\d{1,10}/.exec(e)?.[0]??null,An=["darwin","linux"],ta=e=>t=>yc(t,e)?"homebrew":"unknown",ra=(e,t)=>r=>r===null?null:t(e(r),r),xu=e=>ra(ta(e.kegName),t=>t==="homebrew"?qt(["brew","upgrade",e.brewFormula]):null),_y=e=>Js(e,"Homebrew")||Js(e,"homebrew")?"homebrew":"unknown",YT={id:"brew",binName:"brew",probeArgv:["brew","--version"],versionFrom:$n,platforms:An,prerequisites:[],bootstrapInstall:{steps:[["/bin/bash","-c","$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"]],needsSudo:!0,fetchesNetworkScript:!0},identify:_y,updateFor:ra(_y,e=>e==="homebrew"?qt(["brew","update"]):null)},Pu={brewFormula:"awscli",brewInstallSpec:"awscli",kegName:"awscli"},Fy="https://awscli.amazonaws.com/v2/install.sh",Ly={steps:[["/bin/bash","-c",`curl -fsSL ${Fy} | bash`]],needsSudo:!1,fetchesNetworkScript:!0},zT="/usr/local/aws-cli",XT=e=>qn(zT,e,Ee)?{steps:[["sudo","/bin/bash","-c",`curl -fsSL ${Fy} | bash -s -- --system`]],needsSudo:!0,fetchesNetworkScript:!0}:Ly,My=e=>yc(e,Pu.kegName)?"homebrew":Js(e,"aws-cli")?"script":"unknown",ZT={id:"aws",binName:"aws",...Pu,probeArgv:["aws","--version"],versionFrom:$n,platforms:An,prerequisites:[],bootstrapInstall:Ly,identify:My,updateFor:ra(My,(e,t)=>e==="homebrew"?qt(["brew","upgrade",Pu.brewFormula]):e==="script"?XT(t):null)},Zi={brewFormula:"git",brewInstallSpec:"git",kegName:"git"},QT={id:"git",binName:"git",...Zi,probeArgv:["git","--version"],versionFrom:$n,platforms:An,prerequisites:["brew"],bootstrapInstall:qt(["brew","install",Zi.brewInstallSpec]),identify:ta(Zi.kegName),updateFor:xu(Zi)},Qi={brewFormula:"gh",brewInstallSpec:"gh",kegName:"gh"},eC={id:"gh",binName:"gh",...Qi,probeArgv:["gh","--version"],versionFrom:$n,platforms:An,prerequisites:["brew"],bootstrapInstall:qt(["brew","install",Qi.brewInstallSpec]),identify:ta(Qi.kegName),updateFor:xu(Qi)},ea={brewFormula:"doppler",brewInstallSpec:"dopplerhq/cli/doppler",kegName:"doppler"},tC={id:"doppler",binName:"doppler",...ea,probeArgv:["doppler","--version"],versionFrom:$n,platforms:An,prerequisites:["brew"],bootstrapInstall:qt(["brew","install","gnupg"],["brew","install",ea.brewInstallSpec]),identify:ta(ea.kegName),updateFor:xu(ea)},Ho="portless",jy=e=>Pm(e,Ho)===null?"unknown":"npm",rC={id:"portless",binName:Ho,npmPackage:Ho,probeArgv:["portless","--version"],versionFrom:$n,platforms:[...An,"win32"],prerequisites:[],bootstrapInstall:qt(["npm","install","-g",Ho]),identify:jy,updateFor:ra(jy,e=>e==="npm"?qt(["npm","install","-g",`${Ho}@latest`]):null)},Tu={brew:YT,git:QT,aws:ZT,gh:eC,doppler:tC,portless:rC},kr=Object.keys(Tu),Ke=e=>Tu[e],Cu=(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 Ke(o).prerequisites)n(i,[...s,o]);t.push(o)}};for(let o of e)n(o,[]);return t};var By=e=>({id:e,present:!1,onPath:!1,binRealPath:null,version:null,manager:"unknown"}),Uy=async(e,t)=>{try{return await e(t)}catch{return null}},nC=async(e,t)=>{try{let r=await e.resolveBinPath(t);return r==null?null:e.realpath(r)}catch{return null}},Wy=async(e,t)=>{if(!Cu(e,t.platform))return By(e.id);let r=await Uy(t.runCommand,e.probeArgv),n=await nC(t,e.binName);if(r==null&&n==null)return By(e.id);let o=r??(n==null?null:await Uy(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)}},qo=async(e,t)=>Promise.all(e.map(r=>Wy(Ke(r),t)));import{$ as lC}from"zx";import{z as Vy}from"zod";var Gy=/^\d{4}-\d{2}-\d{2}$/,Yo=e=>{if(!Gy.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},Jy=e=>`Release date "${e}" is not a calendar date in yyyy-mm-dd form.`,On=class extends Error{constructor(t){super(Jy(t)),this.name="InvalidReleaseDateError"}},br=e=>{let t=e.trim();if(!Yo(t))throw new On(t);return t},zo=e=>{let t=e.trim();return t===""||Yo(t)?!0:Jy(t)},Au=Vy.string().refine(Yo,{message:"Expected a calendar date in yyyy-mm-dd form."}),Ou=Vy.string().refine(e=>e===""||Yo(e),{message:'Expected a calendar date in yyyy-mm-dd form, or "" to clear.'});var Yt=e=>e.slice(1).split(".").map(Number),Dn=e=>[...e].sort((t,r)=>{let[n,o,s]=Yt(t),[i,a,c]=Yt(r);return n!==i?(n??0)-(i??0):o!==a?(o??0)-(a??0):(s??0)-(c??0)});var Hy="next",oC=/^v?(\d+)\.(\d+)\.(\d+)$/,sC=e=>e.replace(/^.*release\//,""),Du=e=>{let t=sC(e.trim()),r=oC.exec(t);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null},Ky=e=>`${e[0]}.${e[1]}.${e[2]}`,Iu=e=>{let t=[...e.remoteBranches??[],...e.jiraVersions??[]],r=[],n=new Set;for(let o of t){let s=Du(o);if(!s)continue;let i=Ky(s);n.has(i)||(n.add(i),r.push(s))}return Dn(r.map(o=>Ky(o))).map(o=>Yt(`v${o}`))},Rr=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},Nu=(e,t)=>{if(e.length===0)throw new Rr;let r=e[e.length-1];if(t==="hotfix"){let[s,i]=r,a=e.reduce((c,l)=>l[0]===s&&l[1]===i?Math.max(c,l[2]):c,0);return`${s}.${i}.${a+1}`}let[n,o]=r;return`${n}.${o+1}.0`},In=(e,t)=>{try{return Nu(e,t)}catch(r){if(r instanceof Rr)return null;throw r}},_u=e=>e.trim().toLowerCase()===Hy,oa=e=>_u(e)||Du(e)!==null?{version:e}:{name:e},iC=e=>e==="regular"||e==="hotfix",qy=e=>"name"in e,aC=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:br(n)}},Mu=e=>{let t=e.trim();if(t==="")throw new Error("Release spec is empty");let r=t.indexOf(":"),{token:n,releaseDate:o}=aC(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(!iC(u))throw new Error(`Invalid release type "${l}". Expected "regular" or "hotfix".`);s=u}return na({...oa(n),type:s},{description:i,releaseDate:o})},ju=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},na=(e,t)=>{let{description:r,releaseDate:n}=t;return{...e,...r!==void 0&&r!==""?{description:r}:{},...n===void 0?{}:{releaseDate:n}}},cC=e=>{let t=e.name.trim();return zs(t),na({id:{kind:"name",name:t,raw:t},type:e.type},e)},Fu=(e,t)=>{let r=[...t];return e.map(n=>{if(qy(n))return cC(n);let o=n.version.trim();if(o==="")throw new Error("Release entry has an empty version");if(_u(o)){let a=Nu(r,n.type);return r.push(Yt(`v${a}`)),na({id:ve(a),type:n.type},n)}let s=Du(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),na({id:ve(i),type:n.type},n)})},Lu=e=>e.some(t=>!qy(t)&&_u(t.version));var uC=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),dC=async()=>{let e=await lC({quiet:!0})`git ls-remote --heads origin 'release/v*'`;return uC(e.stdout)},pC=async()=>{let e=await Tt();return e?(await un(e)).map(r=>r.name):[]},Xo=async()=>{let[e,t]=await Promise.allSettled([dC(),pC()]);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"),Iu({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:t.status==="fulfilled"?t.value:[]})};import mC from"node:fs";import fC from"node:path";var Bu=[".claude/settings.json",".claude/settings.local.json"],gC=["infra-kit","ik","pnpm exec infra-kit","pnpm exec ik","pnpm infra-kit"],hC=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),yC=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},vC=(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(hC).join(".*")}$`,"s").test(t)||n===t||n.startsWith(`${t} `)},wC=e=>{let t=e.groupPath.join(" ");return t===e.cliName?[t]:[t,e.cliName]},kC=()=>Sr.filter(e=>e.mutating),bC=e=>{let t=yC(e);return t===null?[]:kC().filter(r=>gC.some(n=>wC(r).some(o=>vC(t,`${n} ${o}`)))).map(r=>r.groupPath.join(" "))},RC=(e,t)=>{let r;try{r=mC.readFileSync(fC.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}},Yy=e=>{let t={present:[],unreadable:[],hits:[]};for(let r of Bu){let n=RC(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=bC(o);s.length>0&&t.hits.push({file:r,pattern:o,commands:s})}}}return t};var SC=e=>e.every(t=>t.status!=="fail"),EC=["brew","git","gh","doppler","aws"],PC=async e=>{let t=await qo(EC,e);return new Map(t.map(r=>[r.id,{manager:r.manager,version:r.version,present:r.present,onPath:r.onPath}]))},At=async(e,t,r,n)=>{try{return await Cn()`${t}`,{name:e,status:"pass",message:r}}catch{return{name:e,status:"fail",message:n}}},xC=async()=>{let e="orca installed",t=await Lt();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)"}},lv=(e,t,r,n)=>{let o=ye.join(cv.homedir(),t),s="Run: infra-kit setup --skip-tools";if(!ie.existsSync(o))return{name:e,status:"fail",message:`~/${t} not found. ${s}`};let i=ie.readFileSync(o,"utf-8"),a=i.indexOf(wr),c=i.indexOf(Ht);return a===-1||c===-1||c<a?{name:e,status:"fail",message:`infra-kit ${r} block missing from ~/${t}. ${s}`}:i.slice(a,c+Ht.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`}},TC=()=>lv("zshrc init block",".zshrc","shell",Iy()),CC=()=>lv("zshenv session block",".zshenv","session-env",Eu()),$C=async()=>{let e="pnpm enableGlobalVirtualStore";try{let t=await A(),r=ye.join(t,"pnpm-workspace.yaml");if(!ie.existsSync(r))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${r}`};let n=ie.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}`}}},AC=async()=>{try{return Mt(),{config:await H(),error:null}}catch(e){return{config:null,error:e}}},OC=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)"}},DC=384,Uu=448,IC=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(", "),NC=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}}})),_C=async(e,t={})=>{let r="env tokens configured",n=t.readStore??Ze,o=t.resolveToken??Af;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 NC(await ii(),o);return{name:r,status:"pass",message:IC(s)}},MC=()=>gt.env[lr]||void 0,jC=async(e={})=>{let t="tokens.json present",r=e.readStore??Ze,n=e.storePath??Ft;if((e.readEnvToken??MC)())return{name:t,status:"skip",message:`${lr} 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 ${lr} instead.`}}return{name:t,status:"pass",message:`${s} holds ${a.length} token(s): ${a.join(", ")}`}},Zo=(e,t)=>{let r=t(e);return r===null?null:r.mode&511},FC=async(e,t={})=>{let r="tokens.json perms",n=t.storePath??Ft,o=t.statPath??LC,s=t.chmodPath??ie.chmodSync,i;try{i=await n()}catch{return{name:r,status:"skip",message:"the token store path could not be resolved"}}if(Zo(i,o)===null)return{name:r,status:"skip",message:`No store to protect at ${w(i)} (see tokens.json present)`};let a=ye.dirname(i),c=ye.dirname(a),l=ye.dirname(c),p=[{target:l,expected:Uu,actual:Zo(l,o)},{target:c,expected:Uu,actual:Zo(c,o)},{target:a,expected:Uu,actual:Zo(a,o)},{target:i,expected:DC,actual:Zo(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 ${zy(f.actual)}, expected ${zy(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}`}},zy=e=>`0${e.toString(8).padStart(3,"0")}`,LC=e=>{try{return ie.statSync(e)}catch{return null}},BC=async()=>{let e="user override path";try{let t=await ee(),r=ie.existsSync(t.userProject),n=await Go(t.userProject,r),o=r?Jo(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}}},UC=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=ye.join(ye.dirname(t.userGlobal),"config.json");return ie.existsSync(r)?ie.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"}},Xy=/^\d+\.\d+\.\d+$/,Zy=(e,t)=>e===t||!Xy.test(e)||!Xy.test(t)?!1:Dn([`v${e}`,`v${t}`])[0]===`v${e}`,WC=async e=>{let t;try{t=await ke(e)}catch{return[]}return t.flatMap(r=>{let n=Et(lt(ye.join(r,"CLAUDE.md")));return n.state==="ok"&&n.version!==void 0?[n.version]:[]})},Qy=e=>Dn(e.map(t=>`v${t}`)).map(t=>t.slice(1)),VC=async(e,t,r)=>{let n="Guidance version",o=pr(t,mr),s=await WC(e),a=(o===null?s:[o,...s]).filter(p=>kt(p,r));if(a.length>0){let p=Qy(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&&Zy(o,r),l=s.filter(p=>Zy(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 ${Qy(l)[0]}, current ${r}) \u2014 run: infra-kit audit --fix --all`]:[]];return{name:n,status:"warn",message:u.join("; ")}},GC=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(!ie.existsSync(t))return e;let r=ye.dirname(t),n=ye.join(r,"CLAUDE.md"),o=ie.existsSync(n)?ie.readFileSync(n,"utf-8"):"",s=We(o,be,De);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 VC(r,o,L.version)]},JC=async()=>{try{let e=(await ee()).main;return ie.existsSync(e)?ye.dirname(e):null}catch{return null}},KC=e=>{let t=yf();return t===null||!kt(t,e)?"":` \u2014 plugin ${t} is fetched but not applied. Run: ${en}`},HC=e=>{let t=e.kind==="installed"?ri(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 ${Y} version ${t}${KC(t)}`}},ev=3,tv=(e,t)=>Ee(e)===Ee(t),qC=e=>{if(e===void 0||e.gitRoot===null)return"";let t=w(e.gitRoot);if(e.projectDir!==null){if(tv(e.projectDir,e.gitRoot))return"";let r=qn(e.gitRoot,Ee(e.projectDir),Ee)?"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 tv(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}`},YC=(e,t)=>{let r="plugin installed",n=qC(t);if(e.kind==="installed"){let{scope:c,projectPath:l}=e.installation,u=l===null?"":`, ${w(l)}`;return{name:r,status:"pass",message:`Plugin ${Y} installed (${c??"unknown"} scope${u})${n}`}}if(e.kind==="absent")return{name:r,status:"fail",message:`Plugin ${Y} is not installed. Run: ${Pt}${n}`};let o=e.installations.map(c=>c.projectPath===null?"(unnamed project)":w(c.projectPath)),s=o.length-ev,i=s>0?` and ${s} more`:"",a=`${o.slice(0,ev).join(", ")}${i}`;return{name:r,status:"fail",message:`Plugin ${Y} is installed for ${a} only, not this project. Run: ${Pt}${n}`}},zC=()=>At("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 XC=(e,...t)=>{try{return JSON.parse(ie.readFileSync(ye.join(e,...t),"utf-8"))}catch{return null}},ZC=e=>{if(e.kind!=="installed")return{kind:"not-installed"};let t=ri(e.installation),{installPath:r}=e.installation;if(r===null)return{kind:"skills-only",version:t};let n=XC(r,Ge),o=n!==null&&typeof n=="object"?n[ut]:void 0;return o==null||typeof o!="object"?{kind:"skills-only",version:t}:{kind:"stale-server",version:t,keys:Object.keys(o)}},rv=e=>`Plugin ${Y} ${e===null?"(version unreadable)":e}`,QC=e=>{let t="plugin MCP server";if(e.kind==="not-installed")return{name:t,status:"fail",message:`No infra-kit plugin installed for this project \u2014 no skills to drive the CLI. Run: ${Pt}`};if(e.kind==="stale-server"){let r=e.keys.length===0?"":` (under "${e.keys.join('", "')}")`;return{name:t,status:"pass",message:`${rv(e.version)} still carries an MCP server in its ${Ge}${r} \u2014 a copy from before the plugin went skills-only. Update it: infra-kit setup (or ${en}), then restart Claude Code`}}return{name:t,status:"pass",message:`${rv(e.version)} is skills-only \u2014 no ${Ge}, as shipped; the /infra-kit:* skills drive the infra-kit CLI`}},e$=(e,t)=>{let r=ar(e===null?{}:{projectPath:e}),n=eo();return[{name:"marketplace registered",status:n?"pass":"fail",message:n?`Marketplace ${le} is known to Claude Code`:`Marketplace ${le} is not registered. Run: claude plugin marketplace add ${jt}`},YC(r,t),HC(r),QC(ZC(r)),{name:"CLI version",status:"pass",message:`infra-kit CLI ${L.version}`}]},t$=(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(kn())}, or run: infra-kit setup`}},r$=({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(", ")},n$=e=>{let t="Agent mode",r=Ys(e),n=r$(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})`}},nv=4,o$=e=>{let t=e.slice(0,nv).join(", "),r=e.length-nv;return r>0?`${t} +${r} more`:t},s$=e=>{let t="Agent allowlist",{present:r,unreadable:n,hits:o}=Yy(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"} (${o$(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 ${Bu.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`}},i$=(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`},a$=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 Wh(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} (${i$(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`}},uv=e=>vc(["trust"],{bin:e}),c$=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),ov="ERR_TLS_CERT_ALTNAME_INVALID",dv=()=>`portless serving TLS on :${_t}`,l$=async(e,t,r)=>{let n=dv();return await e(_t,!0)?{name:n,status:"pass",message:`portless is serving HTTPS on :${_t}`}:{name:n,status:"fail",message:`No portless daemon is serving HTTPS on :${_t}. Install it once (needs root): \`${Nt(t,r)}\`.`}},u$=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(_t,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(ov)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${ov} 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=>c$.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 \`${uv(n)}\`, or reinstall: \`${Nt(n,o)}\`.`}:{name:s,status:"fail",message:`TLS handshake failed (${l.join(", ")})`}},d$=(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: \`${uv(r)}\` (no sudo needed).`}},p$=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 \`${vc(["alias","--remove","<name>"],{bin:r})}\`.`}},zt="portless service target",es=e=>({name:zt,status:"warn",message:e}),pv=e=>e==="darwin"?Im:e==="linux"?Nm:null,m$=e=>e==="darwin"?`sudo launchctl kickstart -k system/${Dm}`:`sudo systemctl restart ${_m}`,f$="/bin/ps",g$=e=>{try{let t=av(f$,["-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}},sv=e=>{try{return ie.readFileSync(e,"utf-8")}catch{return null}},h$=e=>{try{return ie.statSync(e).mtime}catch{return null}},y$=2e3,v$=e=>{try{let t=av(e,["-p","process.version"],{encoding:"utf-8",timeout:y$}),r=t.stdout?.trim()??"";return{version:r===""?null:r,status:t.status,signal:t.signal}}catch{return{version:null,status:null,signal:null}}},w$=(e,t)=>({platform:e.platform??gt.platform,readServiceFile:e.readServiceFile??sv,readFile:e.readFile??sv,exists:e.exists??ie.existsSync,realpath:e.realpath??Ee,mtime:e.mtime??h$,execPath:e.execPath??gt.execPath,home:e.home??cv.homedir(),cwd:e.cwd??gt.cwd(),repoRoot:e.repoRoot??Lo,stateDir:(e.stateDir??jm)(),processStartTime:e.processStartTime??g$,version:e.version??gt.version,arch:e.arch??gt.arch,nodeVersionOf:e.nodeVersionOf??v$,isGlobal:e.isGlobal??qs().node.isGlobal,nodeFs:e.nodeFs??ie,stableNode:null,stableNodeSidecar:null,bin:t}),ts="portless node",Er="~/.infra-kit/node",Qo=e=>({row:{name:ts,status:"fail",message:e},stableNode:null,sidecar:null}),iv=(e,t)=>{try{return e(t,{throwIfNoEntry:!1})}catch{return}},k$=e=>e.signal!==null?`killed by ${e.signal}`:e.status===null?"did not start":e.status!==0?`exit ${e.status}`:`printed ${e.version??"nothing"}`,b$=(e,t)=>e.status===0&&e.signal===null&&e.version===t.version,R$=e=>{let t=Wm(e.home),r=iv(e.nodeFs.lstatSync,t);if(r===void 0)return Qo(`${Er} is missing and could not be written \u2014 run \`infra-kit setup\` and see the debug log`);if(!r.isFile())return Qo(`${Er} is not a regular file; infra-kit will not replace it \u2014 move it away and run \`infra-kit setup\``);let n=Vm(e.home,e.nodeFs);if(n===null)return Qo(`${Er} has no readable node.source.json and it could not be rewritten \u2014 run \`infra-kit setup\``);let o=iv(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 Qo(`${Er} 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(!b$(c,e))return Qo(`${Er} does not run as Node ${e.version} (${k$(c)}). Re-run through the current Node: \`${Nt(e.bin,{...e,stableNode:null})}\`, then \`infra-kit setup\``)}return{row:{name:ts,status:"pass",message:`${Er} is Node ${n.version} (${n.arch}, ${n.method} of ${w(n.source)})`},stableNode:t,sidecar:n}},S$=e=>{if(pv(e.platform)===null)return{row:{name:ts,status:"skip",message:"no portless OS service on this platform"},stableNode:null,sidecar:null};let t=R$(e);return e.isGlobal()?t:{...t,row:{name:ts,status:"skip",message:`not a global install; the global infra-kit keeps ${Er} current`}}},mv=(e,t)=>{let r=w$(e,t),n=S$(r);return{seams:{...r,stableNode:n.stableNode,stableNodeSidecar:n.sidecar},node:n.row}},E$=(e,t)=>{let r=t.readFile(ye.join(e,"package.json"));try{let n=r===null?null:Re.object({version:Re.string()}).safeParse(JSON.parse(r));return n?.success===!0?n.data.version:"?"}catch{return"?"}},P$=e=>{let t=Number.parseInt(e.readFile(ye.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},T$=(e,t,r)=>{let n=P$(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(ye.join(e,"package.json")))?[`portless ${t}`]:[]];return i.length===0?null:i.join(" and ")},C$=async(e,t)=>{let r=t.realpath(t.cwd);return r===t.realpath(t.home)?!1:qn(await t.repoRoot()??r,e,t.realpath)},Pr=e=>({state:"drifted",row:e}),$$=async(e,t,r)=>{let n=Nt(r.bin,r);if(!r.exists(e))return Pr({name:zt,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=ye.join(wc(r.home),"dist","cli.js");if(t!==o)return Pr(es(`The service points at \`${t}\`, a version-specific location. Re-run once to switch it to the stable link: \`${n}\``));if(Hs(r.home,r.exists)===null)return Pr({name:zt,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(wc(r.home));if(await C$(s,r))return Pr({name:zt,status:"fail",message:`The service runs portless from a project checkout (${s}). Re-run \`service install\` from the global install: \`${n}\``});let i=A$(e,n,r);if(i!==null)return i;let a=E$(s,r),c=T$(s,a,r);return c!==null?{state:"converged",row:es(`The running daemon predates ${c} that \`dev\` will talk to. Restart it: \`${m$(r.platform)}\` (or reboot).`)}:{state:"converged",row:{name:zt,status:"pass",message:`service runs \`${e}\` (Node ${r.version}) + stable link \u2192 portless ${a}`}}},A$=(e,t,r)=>r.stableNode!==null?r.realpath(e)===r.realpath(r.stableNode)?null:Pr(es(`The service runs \`${e}\`, a path its package manager will remove. Re-run once to switch it to the stable node: \`${t}\``)):r.realpath(e)===r.realpath(r.execPath)?null:Pr(es(`The service runs \`${e}\`; infra-kit runs \`${r.execPath}\`. Works until the old Node is removed. Re-run when convenient: \`${t}\``)),fv=async e=>{let t=pv(e.platform);if(t===null)return{state:"absent",row:{name:zt,status:"skip",message:"no portless OS service file on this platform"}};let r=e.readServiceFile(t);if(r===null)return{state:"absent",row:{name:zt,status:"skip",message:`the OS service is not installed (no ${t})`}};let[n,o]=dh(e.platform,r)??[];return n===void 0||o===void 0?Pr(es(`could not parse ${t} \u2014 re-run \`${Nt(e.bin,e)}\` to rewrite it.`)):$$(n,o,e)},gv=async(e,t)=>{let{seams:r}=mv(e,t);return{state:(await fv(r)).state,stableNode:r.stableNode}},O$=()=>[ts,zt,dv(),"portless CA chain valid","portless CA trusted","portless routes"],D$=async(e={})=>{let t=e.resolveBin??Om,r=e.isProxyServing??Mm,n=e.handshake??Bm,o=e.caTrusted??Lm,s=e.routes??zn,i=e.isListening??Yn,a=(e.caPath??Fm)(),c=t();if(c===null)return[{name:"portless installed",status:"fail",message:"portless is not resolvable from node_modules \u2014 run `pnpm install`."},...O$().map(E=>({name:E,status:"skip",message:"portless not resolvable"}))];let l={name:"portless installed",status:"pass",message:"portless is resolvable from node_modules"},{seams:u,node:p}=mv(e,c),m=s(),f=await l$(r,c,u),v=f.status==="fail"?{name:"portless CA chain valid",status:"skip",message:"no daemon to handshake with"}:await u$(n,m,a,c,u);return[l,p,(await fv(u)).row,f,v,d$(o(),a,c),await p$(m,i,c)]},I$=async(e={})=>{let t="portless routes",r=e.routes??zn,n=e.isListening??Yn,o=e.devSessionRunning??ih,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}=sh(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??Um().removeAlias;for(let u of a)await l(u);return{name:t,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},sa=async(e={})=>{let t=await AC(),r=PC(e.probeDeps??Ko()),n=async(m,f)=>{let[v,E]=await Promise.all([f,r]),k=E.get(m);return k===void 0?v:{...v,detail:k}},o=await Promise.all([n("brew",At("brew installed",Ke("brew").probeArgv,"Homebrew is installed","Homebrew is not installed. Install from: https://brew.sh/")),n("git",At("git installed",Ke("git").probeArgv,"git is installed","git is not installed. Install with: brew install git")),n("gh",At("gh installed",Ke("gh").probeArgv,"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/")),At("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),n("doppler",At("doppler installed",Ke("doppler").probeArgv,"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli")),n("aws",At("aws installed",Ke("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")),At("package manager installed",["pnpm","--version"],"Installed: pnpm","pnpm is not installed. Install from: https://pnpm.io/installation"),At("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(TC()),Promise.resolve(CC()),$C(),Promise.resolve(OC(t)),jC(),_C(t),FC(e.fix??!1),BC(),UC()]),s=await D$(e.portlessDeps);if(e.fix){let m=await I$(),f=s.findIndex(v=>v.name===m.name);f>=0?s[f]=m:s.push(m)}let i=await JC(),a=await Lo(),c={projectDir:gt.env.CLAUDE_PROJECT_DIR||null,cwd:gt.cwd(),gitRoot:a},l=[await zC(),...e$(i,c),Bo(),n$({env:gt.env,stdinIsTTY:gt.stdin.isTTY===!0,flag:j.source==="flag"}),a===null?{name:"Agent allowlist",status:"skip",message:"no git root"}:s$(a)],u=[...o,await a$(a),...s,...await GC(),...l,t$(bn(),L.version)],p={checks:u.map(m=>({name:m.name,status:m.status,message:m.message,fixable:Wl.has(m.name),detail:m.detail})),allPassed:SC(u),cliVersion:L.version};return{content:b(JSON.stringify(p,null,2)),structuredContent:p}},Wu=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:Re.array(Re.object({name:Re.string().describe("Name of the check"),status:Re.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:Re.string().describe("Details about the check result"),fixable:Re.boolean().describe("Whether `infra-kit doctor --fix` repairs this row"),detail:Re.object({manager:Re.string().describe("Which package manager owns this install, read from its resolved path"),version:Re.string().nullable().describe("The version the tool reported, or null"),present:Re.boolean().describe("The tool is installed somewhere findable \u2014 on PATH or not"),onPath:Re.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:Re.boolean().describe("Whether no check failed (warnings and skips do not count)"),cliVersion:Re.string().describe("Version of the infra-kit CLI that produced this report")},handler:()=>sa()});import{E2E_MODE_ENV as iA}from"@slip-stream-kit/config/internal";import zu from"node:fs";import aA from"node:os";import ns from"node:path";import ca from"node:process";import{z as x}from"zod";var ht=(e,t,r)=>new O({status:"refused",reason:e,...t},2,r);import{describeProxyRoutes as N$,loadDev as _$,readAppAliasName as M$,readCloudOrigin as j$,readLocalContext as yv}from"@slip-stream-kit/config/internal";import hv from"node:fs";import xr from"node:path";import ia from"node:process";import{z as Vu}from"zod";var F$=async e=>{let t=xr.join(e,"apps"),r=hv.existsSync(t)?hv.readdirSync(t).toSorted():[],n=[];for(let o of r){let s=xr.join(t,o,"tests"),a=(await ct(s))?.e2e;a?.target!==void 0&&n.push({app:o,testsDir:s,e2e:{target:a.target}})}return n},L$=(e,t)=>{let[r,n]=xr.relative(e,t).split(xr.sep);return r==="apps"&&n?n:void 0},B$=(e,t,r,n)=>{let o=c=>e.find(l=>l.app===c),s=o(t)??(t===void 0?o(L$(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:Vu.toJSONSchema(Vu.object({app:Vu.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(", ")}`})},U$=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}})),W$=e=>Po(e).apps.find(t=>t.env!=="")?.env??null,Gu=async(e,t={})=>{let r=t.cwd??ia.cwd(),n=t.projectRoot??await A(),o=(t.env??ia.env)[jr]||null,s=t.healthProbe??Ic,i=B$(await F$(n),e,r,n),{target:a}=i.e2e,[c,l]=a.split("/"),u=xr.join(n,"apps",c,l),p=(await dr(u)).name,m=(await ct(u))?.deployedUrlEnv??null;if(!p)throw new g(void 0,{operation:`resolve e2e target ${a}`,remediation:`check \`e2e.target\` in ${xr.join(i.testsDir,"infra-kit.config.ts")}`,stderrExcerpt:`${u} has no package.json name`});let f=Wf(u),v=M$(p,u),E=`${v}.localhost`,k=`https://${E}`,h=0;if(l==="ui")h=(t.listRoutes??zn)().find(P=>P.name===E||P.name===v)?.port??0;else{let P=yv(u).info.get(p);h=P?.port??0,k=P?.origin??k}let R=h>0&&await s({tag:a,port:h,kind:l})==="ok",S=R?W$(u):null;return{app:i.app,testsDir:i.testsDir,target:a,kind:l,targetDir:u,packageName:p,deployedUrlEnv:m,release:f,env:o,servedEnv:S,localUrl:k,served:R}},vv=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}},Ju=async(e,t={})=>{let r=t.healthProbe??Ic,n=yv(e.targetDir),o=e.kind==="ui"?await _$(e.targetDir):void 0,s=o?.proxy?N$({proxy:o.proxy,localContext:n,env:e.env??void 0,cloud:j$(e.deployedUrlEnv??void 0,t.env??ia.env),getRelease:()=>e.release}):[],i=new Map([...n.info].map(([a,c])=>[a,c.port]));return{...vv(e),mode:"local",baseUrl:e.localUrl,routes:await U$(s,i,r)}},Ku=(e,t={})=>{let{env:r,deployedUrlEnv:n,target:o}=e;if(!n)throw ht("no_deployed_url_env",{target:o},{operation:`resolve the deployed app ${e.app}'s cloud e2e run targets`,remediation:`declare \`deployedUrlEnv: '<APP>_URL'\` in ${xr.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??ia.env)[n];if(!r||!s){let i=s?jr:n;throw ht("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 ${jr}, and ${i} is not set`})}return{...vv(e),mode:"cloud",baseUrl:s,routes:[]}};import V$ from"node:fs";import G$ from"node:path";import{stripVTControlCharacters as J$}from"node:util";import{z as I}from"zod";var wv=2e3,kv="--reporter=line,json",bv=e=>({PLAYWRIGHT_JSON_OUTPUT_FILE:e,PLAYWRIGHT_JSON_OUTPUT_NAME:e}),Rv=e=>e.some(t=>t==="--reporter"||t.startsWith("--reporter=")),Hu=I.object({message:I.string().optional()}),Sv=I.object({type:I.string()}),K$=I.object({status:I.string(),retry:I.number(),error:Hu.optional(),errors:I.array(Hu).optional(),annotations:I.array(Sv).optional(),attachments:I.array(I.object({name:I.string(),path:I.string().optional()})).optional()}),H$=I.object({projectName:I.string(),status:I.string(),expectedStatus:I.string().optional(),annotations:I.array(Sv).optional(),results:I.array(K$)}),q$=I.object({title:I.string(),file:I.string(),line:I.number().optional(),tests:I.array(H$)}),Ev=I.lazy(()=>I.object({title:I.string(),specs:I.array(q$).optional(),suites:I.array(Ev).optional()})),Y$=I.object({config:I.object({rootDir:I.string().optional()}).optional(),suites:I.array(Ev),errors:I.array(Hu).optional(),stats:I.object({expected:I.number(),unexpected:I.number(),flaky:I.number(),skipped:I.number()})}),Pv=e=>{let t=J$(e);return t.length>wv?`${t.slice(0,wv)}\u2026`:t},z$=e=>{let t=e.error?.message??e.errors?.[0]?.message;return t===void 0?null:Pv(t)},X$=e=>e.status==="unexpected"||e.status==="flaky",Z$=e=>{let t=new Map;for(let r of e)t.set(r.projectName,[...t.get(r.projectName)??[],r]);return t},Q$=e=>new Set([...e.annotations??[],...e.results.flatMap(t=>t.annotations??[])].map(t=>t.type)),eA=(e,t)=>{let r=e.filter(X$),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?z$(o):"Expected to fail, but passed.",tracePath:o?.attachments?.find(i=>i.name==="trace")?.path??null}},tA=e=>{let t=Y$.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=>[...Q$(k)])),v=m.some(k=>k.expectedStatus==="failed");if(!v&&!f.has("fixme")&&!f.has("skip"))return;let E=a.get(p)??{file:p,fail:0,fixme:0,skip:0};v&&(E.fail+=1),f.has("fixme")?E.fixme+=1:f.has("skip")&&(E.skip+=1),a.set(p,E)},u=(p,m)=>{for(let f of p.specs??[]){let v=r?.rootDir?G$.resolve(r.rootDir,f.file):f.file,E=[...m,f.title].join(" \u203A ");l(v,f.tests);for(let[k,h]of Z$(f.tests)){let R=eA(h,{title:E,file:v,line:f.line??null,project:k});R&&(R.runs>1&&R.failedRuns<R.runs&&(c+=1),i.push(R))}}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?[]:[Pv(p.message)])}},xv=e=>{try{return tA(JSON.parse(V$.readFileSync(e,"utf8")))}catch{return null}};import rs from"node:fs";import Cv from"node:path";import aa from"node:process";var rA=e=>Cv.join(e,"node_modules",".cache","infra-kit-e2e.lock"),nA=e=>{try{return aa.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Tv=e=>{try{return rs.writeFileSync(e,String(aa.pid),{flag:"wx"}),!0}catch(t){if(t.code==="EEXIST")return!1;throw t}},qu=e=>{try{let t=Number.parseInt(rs.readFileSync(e,"utf8"),10);return Number.isInteger(t)&&t>0?t:null}catch{return null}},$v=e=>{let t=rA(e);if(rs.mkdirSync(Cv.dirname(t),{recursive:!0}),!Tv(t)){let r=qu(t);if(r!==null&&r!==aa.pid&&nA(r))return{holder:r};if(rs.rmSync(t,{force:!0}),!Tv(t))return{holder:qu(t)??0}}return{release:()=>{qu(t)===aa.pid&&rs.rmSync(t,{force:!0})}}};import{spawn as oA}from"node:child_process";import sA from"node:os";import Yu from"node:process";var Av=(e,t,r)=>new Promise((n,o)=>{let s=oA(e,t,r),i=Yu.stdin.isTTY?["SIGTERM","SIGHUP"]:["SIGINT","SIGTERM","SIGHUP"],a=l=>{s.kill(l)},c=()=>{for(let l of i)Yu.off(l,a)};for(let l of i)Yu.on(l,a);s.once("error",l=>{c(),o(l)}),s.once("close",(l,u)=>{c(),n(l??(u?128+sA.constants.signals[u]:1))})});var cA=["playwright.config.ts","playwright.config.mts","playwright.config.js","playwright.config.mjs"],lA=e=>cA.some(t=>{try{return zu.readFileSync(ns.join(e,t),"utf8").includes("infraKitE2e")}catch{return!1}}),Xu=e=>`infra-kit dev ${e.target.split("/")[0]} --no-watch --reuse`,uA=(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
- `)},dA=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 ht("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(", ")}`})},pA=async(e,t)=>{if(e.env===null||!Bf(e.env))return;let r=await(t.protectedEnvAccess??st)();if(r.allowed)return;let n=`run ${e.app} e2e against "${e.env}"`;throw r.reason==="agent-blocked"?ht("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`}):ht("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`})},mA=e=>{if(!(e.servedEnv===null||e.servedEnv===e.env))throw ht("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"}"`})},fA=async(e,t)=>{if(e.served){mA(e);let p=await Ju(e,t);return dA(p),p}if(!lA(e.testsDir))throw ht("no_dev_server",{devCommand:Xu(e)},{operation:`run ${e.app} e2e locally`,remediation:`start it (\`${Xu(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:[]}},gA=(e,t,r)=>Av("pnpm",["exec","playwright","test",...t],{cwd:e.testsDir,env:{...ca.env,...r,[iA]:e.mode},stdio:["inherit",ir.enabled||Z()?2:"inherit","inherit"]}),hA=(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:ns.resolve(e.testsDir,s)}}let n=new Date().toISOString().replace(/[:.]/g,"-"),o=ns.join(e.testsDir,"test-results",`ik-e2e-${n}-${ca.pid}`);return{args:[...t,`--output=${o}`],outputDir:o}},yA=e=>{if(e.mode==="cloud")return()=>{};let t=$v(e.testsDir);if("holder"in t)throw ht("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},la=async(e,t={})=>{let r=await Gu(e.app,t),n=e.cloud?Ku(r,t):await fA(r,t);d.info(uA(n,r.served)),n.mode==="cloud"&&await pA(n,t);let o={...n,served:r.served,devCommand:n.mode==="local"&&!r.served?Xu(r):null,playwrightArgs:e.playwrightArgs??[]};if(e.dryRun)return Qu({...o,ran:!1,exitCode:null,...Zu});n.mode==="cloud"&&await G(e.yes,`Run ${n.app} e2e against ${n.baseUrl} ("${n.env}", shared)?`,{plan:o});let s=yA(n);try{return await vA(o,t.runPlaywright??gA)}finally{s()}},vA=async(e,t)=>{if(!Z()||Rv(e.playwrightArgs)){let i=await t(e,e.playwrightArgs,{});return i!==0&&(ca.exitCode=i),Qu({...e,ran:!0,exitCode:i,...Zu,report:Z()?"caller-reporter":"off"})}let{args:r,outputDir:n}=hA(e,e.playwrightArgs),o=zu.mkdtempSync(ns.join(aA.tmpdir(),"ik-e2e-report-")),s=ns.join(o,"report.json");try{let i=await t(e,[kv,...r],bv(s));i!==0&&(ca.exitCode=i);let a=xv(s);return Qu({...e,ran:!0,exitCode:i,...a?{report:"collected",...a}:{...Zu,report:"unavailable"},outputDir:n})}finally{zu.rmSync(o,{recursive:!0,force:!0})}},Zu={report:"off",outputDir:null,summary:null,failures:[],annotated:[],errors:[]},Qu=e=>({content:b(JSON.stringify(e,null,2)),structuredContent:e}),wA={app:x.string(),testsDir:x.string(),target:x.string().describe("The package under test, `<app>/ui` or `<app>/api`."),packageName:x.string(),mode:x.enum(["local","cloud"]).describe("local (default): this worktree\u2019s dev server. cloud (--cloud): the deployed app at env."),baseUrl:x.string().describe("The URL the run was pointed at: the local alias, or the deployed URL."),deployedUrlEnv:x.string().nullable().describe("The target\u2019s variable holding its deployed URL; a cloud run reads it. Null when it declares none."),release:x.string().describe("This worktree\u2019s release slug \u2014 the first label of every local alias."),env:x.string().nullable().describe("INFRA_KIT_ENV of this process; the env a cloud run targets."),servedEnv:x.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:x.string().describe("This worktree\u2019s address for the target, whether or not anything serves it."),served:x.boolean().describe("Whether this worktree\u2019s dev server already served the target when the run began."),devCommand:x.string().nullable().describe("Local runs with nothing served: the dev command the Playwright config starts, and stops after."),routes:x.array(x.object({path:x.string(),packageName:x.string(),source:x.enum(["local","cloud"]),target:x.string().nullable(),live:x.boolean().nullable()})).describe("Served local UI runs only: the dev proxy\u2019s route-by-route local/cloud split, local backends probed."),playwrightArgs:x.array(x.string()),ran:x.boolean().describe("False for --dry-run."),exitCode:x.number().nullable().describe("Playwright\u2019s exit code; null when it did not run."),report:x.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:x.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:x.object({expected:x.number(),unexpected:x.number(),flaky:x.number(),skipped:x.number(),repeatFlaky:x.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:x.array(x.object({title:x.string().describe("Describe path and test title, joined with \u203A."),file:x.string(),line:x.number().nullable(),project:x.string(),status:x.enum(["unexpected","flaky"]).describe("flaky: failed, then passed on a retry or in another --repeat-each repeat."),retry:x.number().describe("The retry index of the failed attempt reported here."),runs:x.number().describe("How many times the test ran in this project \u2014 its --repeat-each repeats."),failedRuns:x.number().describe("How many of those runs failed."),error:x.string().nullable().describe("The failure message, ANSI stripped, truncated to 2000 characters."),tracePath:x.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:x.array(x.object({file:x.string(),fail:x.number().describe("test.fail \u2014 green only while the bug it registers exists."),fixme:x.number().describe("test.fixme \u2014 skipped as unfinished."),skip:x.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:x.array(x.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.")},ed=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:x.string().optional().describe("App folder with an apps/<app>/tests e2e package; inferred from cwd when omitted."),dryRun:x.boolean().optional(),yes:x.boolean().optional(),cloud:x.boolean().optional().describe("Run against the deployed app at INFRA_KIT_ENV instead of this worktree."),playwrightArgs:x.array(x.string()).optional().describe("Passed to `playwright test` verbatim \u2014 a spec path, `--grep <title>`, `--project=chromium`.")},outputSchema:wA,handler:e=>la(e)});import ua from"node:fs";import td from"node:path";import{z as os}from"zod";var kA=e=>[...e.map(t=>`unset ${t}`),`unset ${jr}`,`unset ${Us}`,`unset ${Ws}`,`unset ${bm}`,`unset ${Vs}`],da=async()=>{let e=Fr(),t=td.join(e,Mr);if(!ua.existsSync(t))throw new Error("No loaded environment found. Run `env-load` first.");let r=Gs(t),n=kA(r),o=td.resolve(e,Ls);ua.mkdirSync(e,{recursive:!0,mode:448}),It(o,`${n.join(`
365
+ ${i}`:"")},_y=()=>{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
+ `)},My=()=>`${br}
367
+ ${_y()}
368
+ ${Yt}`,xu=()=>["# 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
+ `),Tu=()=>`${br}
370
+ ${xu()}
371
+ ${Yt}`;import ZT from"node:fs/promises";var Jo=async(e,t)=>{if(!t)return{hasOverrides:!1,overrideKeys:[],unreadable:!1};try{let r=await ZT.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}}},Ko=e=>e.unreadable?"(unreadable \u2014 invalid JSON)":e.overrideKeys.length===0?"(empty \u2014 no overrides)":`(${e.overrideKeys.length} override(s): ${e.overrideKeys.join(", ")})`;import eC from"node:fs";import tC from"node:os";import jy from"node:path";import rC from"node:process";import{$ as QT}from"zx";var $n=()=>QT({quiet:!0});var nC=()=>[jy.join(tC.homedir(),".local","bin"),"/opt/homebrew/bin","/usr/local/bin"],oC=async e=>{try{return(await $n()`command -v ${e}`).stdout.trim()||null}catch{return null}},Ho=()=>({runCommand:async e=>{let t=await $n()`${e}`;return{stdout:`${t.stdout}
372
+ ${t.stderr}`}},resolveBinPath:async e=>{let t=await oC(e);return t!==null?t:nC().map(r=>jy.join(r,e)).find(r=>eC.existsSync(r))??null},realpath:Pe,platform:rC.platform});var zt=(...e)=>({steps:e,needsSudo:!1,fetchesNetworkScript:!1}),An=e=>/\d{1,10}\.\d{1,10}\.\d{1,10}/.exec(e)?.[0]??null,On=["darwin","linux"],sa=e=>t=>kc(t,e)?"homebrew":"unknown",ia=(e,t)=>r=>r===null?null:t(e(r),r),$u=e=>ia(sa(e.kegName),t=>t==="homebrew"?zt(["brew","upgrade",e.brewFormula]):null),Fy=e=>Ys(e,"Homebrew")||Ys(e,"homebrew")?"homebrew":"unknown",sC={id:"brew",binName:"brew",probeArgv:["brew","--version"],versionFrom:An,platforms:On,prerequisites:[],bootstrapInstall:{steps:[["/bin/bash","-c","$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"]],needsSudo:!0,fetchesNetworkScript:!0},identify:Fy,updateFor:ia(Fy,e=>e==="homebrew"?zt(["brew","update"]):null)},Cu={brewFormula:"awscli",brewInstallSpec:"awscli",kegName:"awscli"},Uy="https://awscli.amazonaws.com/v2/install.sh",Wy={steps:[["/bin/bash","-c",`curl -fsSL ${Uy} | bash`]],needsSudo:!1,fetchesNetworkScript:!0},iC="/usr/local/aws-cli",aC=e=>Yn(iC,e,Pe)?{steps:[["sudo","/bin/bash","-c",`curl -fsSL ${Uy} | bash -s -- --system`]],needsSudo:!0,fetchesNetworkScript:!0}:Wy,Ly=e=>kc(e,Cu.kegName)?"homebrew":Ys(e,"aws-cli")?"script":"unknown",cC={id:"aws",binName:"aws",...Cu,probeArgv:["aws","--version"],versionFrom:An,platforms:On,prerequisites:[],bootstrapInstall:Wy,identify:Ly,updateFor:ia(Ly,(e,t)=>e==="homebrew"?zt(["brew","upgrade",Cu.brewFormula]):e==="script"?aC(t):null)},ra={brewFormula:"git",brewInstallSpec:"git",kegName:"git"},lC={id:"git",binName:"git",...ra,probeArgv:["git","--version"],versionFrom:An,platforms:On,prerequisites:["brew"],bootstrapInstall:zt(["brew","install",ra.brewInstallSpec]),identify:sa(ra.kegName),updateFor:$u(ra)},na={brewFormula:"gh",brewInstallSpec:"gh",kegName:"gh"},uC={id:"gh",binName:"gh",...na,probeArgv:["gh","--version"],versionFrom:An,platforms:On,prerequisites:["brew"],bootstrapInstall:zt(["brew","install",na.brewInstallSpec]),identify:sa(na.kegName),updateFor:$u(na)},oa={brewFormula:"doppler",brewInstallSpec:"dopplerhq/cli/doppler",kegName:"doppler"},dC={id:"doppler",binName:"doppler",...oa,probeArgv:["doppler","--version"],versionFrom:An,platforms:On,prerequisites:["brew"],bootstrapInstall:zt(["brew","install","gnupg"],["brew","install",oa.brewInstallSpec]),identify:sa(oa.kegName),updateFor:$u(oa)},qo="portless",By=e=>Cm(e,qo)===null?"unknown":"npm",pC={id:"portless",binName:qo,npmPackage:qo,probeArgv:["portless","--version"],versionFrom:An,platforms:[...On,"win32"],prerequisites:[],bootstrapInstall:zt(["npm","install","-g",qo]),identify:By,updateFor:ia(By,e=>e==="npm"?zt(["npm","install","-g",`${qo}@latest`]):null)},Au={brew:sC,git:lC,aws:cC,gh:uC,doppler:dC,portless:pC},Rr=Object.keys(Au),Ke=e=>Au[e],Ou=(e,t)=>e.platforms.includes(t),Du=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 Ke(o).prerequisites)n(i,[...s,o]);t.push(o)}};for(let o of e)n(o,[]);return t};var Vy=e=>({id:e,present:!1,onPath:!1,binRealPath:null,version:null,manager:"unknown"}),Gy=async(e,t)=>{try{return await e(t)}catch{return null}},mC=async(e,t)=>{try{let r=await e.resolveBinPath(t);return r==null?null:e.realpath(r)}catch{return null}},Jy=async(e,t)=>{if(!Ou(e,t.platform))return Vy(e.id);let r=await Gy(t.runCommand,e.probeArgv),n=await mC(t,e.binName);if(r==null&&n==null)return Vy(e.id);let o=r??(n==null?null:await Gy(t.runCommand,[n,...e.probeArgv.slice(1)]));return{id:e.id,present:!0,onPath:r!=null,binRealPath:n,version:o==null?null:e.versionFrom(o.stdout),manager:n==null?"unknown":e.identify(n)}},Yo=async(e,t)=>Promise.all(e.map(r=>Jy(Ke(r),t)));import{$ as wC}from"zx";import{z as Ky}from"zod";var Hy=/^\d{4}-\d{2}-\d{2}$/,zo=e=>{if(!Hy.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.`,Dn=class extends Error{constructor(t){super(qy(t)),this.name="InvalidReleaseDateError"}},Sr=e=>{let t=e.trim();if(!zo(t))throw new Dn(t);return t},Xo=e=>{let t=e.trim();return t===""||zo(t)?!0:qy(t)},Iu=Ky.string().refine(zo,{message:"Expected a calendar date in yyyy-mm-dd form."}),Nu=Ky.string().refine(e=>e===""||zo(e),{message:'Expected a calendar date in yyyy-mm-dd form, or "" to clear.'});var Xt=e=>e.slice(1).split(".").map(Number),In=e=>[...e].sort((t,r)=>{let[n,o,s]=Xt(t),[i,a,c]=Xt(r);return n!==i?(n??0)-(i??0):o!==a?(o??0)-(a??0):(s??0)-(c??0)});var zy="next",fC=/^v?(\d+)\.(\d+)\.(\d+)$/,gC=e=>e.replace(/^.*release\//,""),_u=e=>{let t=gC(e.trim()),r=fC.exec(t);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null},Yy=e=>`${e[0]}.${e[1]}.${e[2]}`,Mu=e=>{let t=[...e.remoteBranches??[],...e.jiraVersions??[]],r=[],n=new Set;for(let o of t){let s=_u(o);if(!s)continue;let i=Yy(s);n.has(i)||(n.add(i),r.push(s))}return In(r.map(o=>Yy(o))).map(o=>Xt(`v${o}`))},Er=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},ju=(e,t)=>{if(e.length===0)throw new Er;let r=e[e.length-1];if(t==="hotfix"){let[s,i]=r,a=e.reduce((c,l)=>l[0]===s&&l[1]===i?Math.max(c,l[2]):c,0);return`${s}.${i}.${a+1}`}let[n,o]=r;return`${n}.${o+1}.0`},Nn=(e,t)=>{try{return ju(e,t)}catch(r){if(r instanceof Er)return null;throw r}},Fu=e=>e.trim().toLowerCase()===zy,ca=e=>Fu(e)||_u(e)!==null?{version:e}:{name:e},hC=e=>e==="regular"||e==="hotfix",Xy=e=>"name"in e,yC=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:Sr(n)}},Lu=e=>{let t=e.trim();if(t==="")throw new Error("Release spec is empty");let r=t.indexOf(":"),{token:n,releaseDate:o}=yC(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(!hC(u))throw new Error(`Invalid release type "${l}". Expected "regular" or "hotfix".`);s=u}return aa({...ca(n),type:s},{description:i,releaseDate:o})},Bu=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},aa=(e,t)=>{let{description:r,releaseDate:n}=t;return{...e,...r!==void 0&&r!==""?{description:r}:{},...n===void 0?{}:{releaseDate:n}}},vC=e=>{let t=e.name.trim();return ei(t),aa({id:{kind:"name",name:t,raw:t},type:e.type},e)},Uu=(e,t)=>{let r=[...t];return e.map(n=>{if(Xy(n))return vC(n);let o=n.version.trim();if(o==="")throw new Error("Release entry has an empty version");if(Fu(o)){let a=ju(r,n.type);return r.push(Xt(`v${a}`)),aa({id:we(a),type:n.type},n)}let s=_u(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),aa({id:we(i),type:n.type},n)})},Wu=e=>e.some(t=>!Xy(t)&&Fu(t.version));var kC=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),bC=async()=>{let e=await wC({quiet:!0})`git ls-remote --heads origin 'release/v*'`;return kC(e.stdout)},RC=async()=>{let e=await $t();return e?(await dn(e)).map(r=>r.name):[]},Zo=async()=>{let[e,t]=await Promise.allSettled([bC(),RC()]);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"),Mu({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:t.status==="fulfilled"?t.value:[]})};import SC from"node:fs";import EC from"node:path";var Vu=[".claude/settings.json",".claude/settings.local.json"],PC=["infra-kit","ik","pnpm exec infra-kit","pnpm exec ik","pnpm infra-kit"],xC=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),TC=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},CC=(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(xC).join(".*")}$`,"s").test(t)||n===t||n.startsWith(`${t} `)},$C=e=>{let t=e.groupPath.join(" ");return t===e.cliName?[t]:[t,e.cliName]},AC=()=>Pr.filter(e=>e.mutating),OC=e=>{let t=TC(e);return t===null?[]:AC().filter(r=>PC.some(n=>$C(r).some(o=>CC(t,`${n} ${o}`)))).map(r=>r.groupPath.join(" "))},DC=(e,t)=>{let r;try{r=SC.readFileSync(EC.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}},Zy=e=>{let t={present:[],unreadable:[],hits:[]};for(let r of Vu){let n=DC(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=OC(o);s.length>0&&t.hits.push({file:r,pattern:o,commands:s})}}}return t};var IC=e=>e.every(t=>t.status!=="fail"),NC=["brew","git","gh","doppler","aws"],_C=async e=>{let t=await Yo(NC,e);return new Map(t.map(r=>[r.id,{manager:r.manager,version:r.version,present:r.present,onPath:r.onPath}]))},Dt=async(e,t,r,n)=>{try{return await $n()`${t}`,{name:e,status:"pass",message:r}}catch{return{name:e,status:"fail",message:n}}},MC=async()=>{let e="orca installed",t=await Ut();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)"}},pv=(e,t,r,n)=>{let o=ve.join(dv.homedir(),t),s="Run: infra-kit setup --skip-tools";if(!ie.existsSync(o))return{name:e,status:"fail",message:`~/${t} not found. ${s}`};let i=ie.readFileSync(o,"utf-8"),a=i.indexOf(br),c=i.indexOf(Yt);return a===-1||c===-1||c<a?{name:e,status:"fail",message:`infra-kit ${r} block missing from ~/${t}. ${s}`}:i.slice(a,c+Yt.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`}},jC=()=>pv("zshrc init block",".zshrc","shell",My()),FC=()=>pv("zshenv session block",".zshenv","session-env",Tu()),LC=async()=>{let e="pnpm enableGlobalVirtualStore";try{let t=await A(),r=ve.join(t,"pnpm-workspace.yaml");if(!ie.existsSync(r))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${r}`};let n=ie.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}`}}},BC=async()=>{try{return Ft(),{config:await K(),error:null}}catch(e){return{config:null,error:e}}},UC=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)"}},WC=384,Gu=448,VC=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(", "),GC=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}}})),JC=async(e,t={})=>{let r="env tokens configured",n=t.readStore??Ze,o=t.resolveToken??If;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 GC(await ui(),o);return{name:r,status:"pass",message:VC(s)}},KC=()=>gt.env[dr]||void 0,HC=async(e={})=>{let t="tokens.json present",r=e.readStore??Ze,n=e.storePath??Bt;if((e.readEnvToken??KC)())return{name:t,status:"skip",message:`${dr} 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 ${dr} instead.`}}return{name:t,status:"pass",message:`${s} holds ${a.length} token(s): ${a.join(", ")}`}},Qo=(e,t)=>{let r=t(e);return r===null?null:r.mode&511},qC=async(e,t={})=>{let r="tokens.json perms",n=t.storePath??Bt,o=t.statPath??YC,s=t.chmodPath??ie.chmodSync,i;try{i=await n()}catch{return{name:r,status:"skip",message:"the token store path could not be resolved"}}if(Qo(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:Gu,actual:Qo(l,o)},{target:c,expected:Gu,actual:Qo(c,o)},{target:a,expected:Gu,actual:Qo(a,o)},{target:i,expected:WC,actual:Qo(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 ${Qy(f.actual)}, expected ${Qy(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}`}},Qy=e=>`0${e.toString(8).padStart(3,"0")}`,YC=e=>{try{return ie.statSync(e)}catch{return null}},zC=async()=>{let e="user override path";try{let t=await ee(),r=ie.existsSync(t.userProject),n=await Jo(t.userProject,r),o=r?Ko(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}}},XC=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 ie.existsSync(r)?ie.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"}},ev=/^\d+\.\d+\.\d+$/,tv=(e,t)=>e===t||!ev.test(e)||!ev.test(t)?!1:In([`v${e}`,`v${t}`])[0]===`v${e}`,ZC=async e=>{let t;try{t=await be(e)}catch{return[]}return t.flatMap(r=>{let n=xt(lt(ve.join(r,"CLAUDE.md")));return n.state==="ok"&&n.version!==void 0?[n.version]:[]})},rv=e=>In(e.map(t=>`v${t}`)).map(t=>t.slice(1)),QC=async(e,t,r)=>{let n="Guidance version",o=fr(t,gr),s=await ZC(e),a=(o===null?s:[o,...s]).filter(p=>Rt(p,r));if(a.length>0){let p=rv(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&&tv(o,r),l=s.filter(p=>tv(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 ${rv(l)[0]}, current ${r}) \u2014 run: infra-kit audit --fix --all`]:[]];return{name:n,status:"warn",message:u.join("; ")}},e$=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(!ie.existsSync(t))return e;let r=ve.dirname(t),n=ve.join(r,"CLAUDE.md"),o=ie.existsSync(n)?ie.readFileSync(n,"utf-8"):"",s=We(o,Re,De);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 QC(r,o,L.version)]},t$=async()=>{try{let e=(await ee()).main;return ie.existsSync(e)?ve.dirname(e):null}catch{return null}},r$=e=>{let t=kf();return t===null||!Rt(t,e)?"":` \u2014 plugin ${t} is fetched but not applied. Run: ${tn}`},n$=e=>{let t=e.kind==="installed"?ii(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 ${Y} version ${t}${r$(t)}`}},nv=3,ov=(e,t)=>Pe(e)===Pe(t),o$=e=>{if(e===void 0||e.gitRoot===null)return"";let t=w(e.gitRoot);if(e.projectDir!==null){if(ov(e.projectDir,e.gitRoot))return"";let r=Yn(e.gitRoot,Pe(e.projectDir),Pe)?"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 ov(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}`},s$=(e,t)=>{let r="plugin installed",n=o$(t);if(e.kind==="installed"){let{scope:c,projectPath:l}=e.installation,u=l===null?"":`, ${w(l)}`;return{name:r,status:"pass",message:`Plugin ${Y} installed (${c??"unknown"} scope${u})${n}`}}if(e.kind==="absent")return{name:r,status:"fail",message:`Plugin ${Y} is not installed. Run: ${Tt}${n}`};let o=e.installations.map(c=>c.projectPath===null?"(unnamed project)":w(c.projectPath)),s=o.length-nv,i=s>0?` and ${s} more`:"",a=`${o.slice(0,nv).join(", ")}${i}`;return{name:r,status:"fail",message:`Plugin ${Y} is installed for ${a} only, not this project. Run: ${Tt}${n}`}},i$=()=>Dt("claude CLI",["claude","--version"],"Installed: claude","claude CLI not found on PATH \u2014 `infra-kit setup` cannot install the plugin; install Claude Code first");var a$=(e,...t)=>{try{return JSON.parse(ie.readFileSync(ve.join(e,...t),"utf-8"))}catch{return null}},c$=e=>{if(e.kind!=="installed")return{kind:"not-installed"};let t=ii(e.installation),{installPath:r}=e.installation;if(r===null)return{kind:"skills-only",version:t};let n=a$(r,Ge),o=n!==null&&typeof n=="object"?n[ut]:void 0;return o==null||typeof o!="object"?{kind:"skills-only",version:t}:{kind:"stale-server",version:t,keys:Object.keys(o)}},sv=e=>`Plugin ${Y} ${e===null?"(version unreadable)":e}`,l$=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: ${Tt}`};if(e.kind==="stale-server"){let r=e.keys.length===0?"":` (under "${e.keys.join('", "')}")`;return{name:t,status:"pass",message:`${sv(e.version)} still carries an MCP server in its ${Ge}${r} \u2014 a copy from before the plugin went skills-only. Update it: infra-kit setup (or ${tn}), then restart Claude Code`}}return{name:t,status:"pass",message:`${sv(e.version)} is skills-only \u2014 no ${Ge}, as shipped; the /infra-kit:* skills drive the infra-kit CLI`}},u$=(e,t)=>{let r=lr(e===null?{}:{projectPath:e}),n=to();return[{name:"marketplace registered",status:n?"pass":"fail",message:n?`Marketplace ${le} is known to Claude Code`:`Marketplace ${le} is not registered. Run: claude plugin marketplace add ${Lt}`},s$(r,t),n$(r),l$(c$(r)),{name:"CLI version",status:"pass",message:`infra-kit CLI ${L.version}`}]},d$=(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(bn())}, or run: infra-kit setup`}},p$=({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(", ")},m$=e=>{let t="Agent mode",r=Qs(e),n=p$(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})`}},iv=4,f$=e=>{let t=e.slice(0,iv).join(", "),r=e.length-iv;return r>0?`${t} +${r} more`:t},g$=e=>{let t="Agent allowlist",{present:r,unreadable:n,hits:o}=Zy(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"} (${f$(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 ${Vu.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`}},h$=(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`},y$=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 Jh(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} (${h$(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`}},mv=e=>bc(["trust"],{bin:e}),v$=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),av="ERR_TLS_CERT_ALTNAME_INVALID",fv=()=>`portless serving TLS on :${jt}`,w$=async(e,t,r)=>{let n=fv();return await e(jt,!0)?{name:n,status:"pass",message:`portless is serving HTTPS on :${jt}`}:{name:n,status:"fail",message:`No portless daemon is serving HTTPS on :${jt}. Install it once (needs root): \`${Mt(t,r)}\`.`}},k$=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(jt,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(av)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${av} 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=>v$.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 \`${mv(n)}\`, or reinstall: \`${Mt(n,o)}\`.`}:{name:s,status:"fail",message:`TLS handshake failed (${l.join(", ")})`}},b$=(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: \`${mv(r)}\` (no sudo needed).`}},R$=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 \`${bc(["alias","--remove","<name>"],{bin:r})}\`.`}},Zt="portless service target",ts=e=>({name:Zt,status:"warn",message:e}),gv=e=>e==="darwin"?Mm:e==="linux"?jm:null,S$=e=>e==="darwin"?`sudo launchctl kickstart -k system/${_m}`:`sudo systemctl restart ${Fm}`,E$="/bin/ps",P$=e=>{try{let t=uv(E$,["-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}},cv=e=>{try{return ie.readFileSync(e,"utf-8")}catch{return null}},x$=e=>{try{return ie.statSync(e).mtime}catch{return null}},T$=2e3,C$=e=>{try{let t=uv(e,["-p","process.version"],{encoding:"utf-8",timeout:T$}),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??gt.platform,readServiceFile:e.readServiceFile??cv,readFile:e.readFile??cv,exists:e.exists??ie.existsSync,realpath:e.realpath??Pe,mtime:e.mtime??x$,execPath:e.execPath??gt.execPath,home:e.home??dv.homedir(),cwd:e.cwd??gt.cwd(),repoRoot:e.repoRoot??Bo,stateDir:(e.stateDir??Bm)(),processStartTime:e.processStartTime??P$,version:e.version??gt.version,arch:e.arch??gt.arch,nodeVersionOf:e.nodeVersionOf??C$,isGlobal:e.isGlobal??Zs().node.isGlobal,nodeFs:e.nodeFs??ie,stableNode:null,stableNodeSidecar:null,bin:t}),rs="portless node",xr="~/.infra-kit/node",es=e=>({row:{name:rs,status:"fail",message:e},stableNode:null,sidecar:null}),lv=(e,t)=>{try{return e(t,{throwIfNoEntry:!1})}catch{return}},A$=e=>e.signal!==null?`killed by ${e.signal}`:e.status===null?"did not start":e.status!==0?`exit ${e.status}`:`printed ${e.version??"nothing"}`,O$=(e,t)=>e.status===0&&e.signal===null&&e.version===t.version,D$=e=>{let t=Jm(e.home),r=lv(e.nodeFs.lstatSync,t);if(r===void 0)return es(`${xr} is missing and could not be written \u2014 run \`infra-kit setup\` and see the debug log`);if(!r.isFile())return es(`${xr} is not a regular file; infra-kit will not replace it \u2014 move it away and run \`infra-kit setup\``);let n=Km(e.home,e.nodeFs);if(n===null)return es(`${xr} has no readable node.source.json and it could not be rewritten \u2014 run \`infra-kit setup\``);let o=lv(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 es(`${xr} 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(!O$(c,e))return es(`${xr} does not run as Node ${e.version} (${A$(c)}). Re-run through the current Node: \`${Mt(e.bin,{...e,stableNode:null})}\`, then \`infra-kit setup\``)}return{row:{name:rs,status:"pass",message:`${xr} is Node ${n.version} (${n.arch}, ${n.method} of ${w(n.source)})`},stableNode:t,sidecar:n}},I$=e=>{if(gv(e.platform)===null)return{row:{name:rs,status:"skip",message:"no portless OS service on this platform"},stableNode:null,sidecar:null};let t=D$(e);return e.isGlobal()?t:{...t,row:{name:rs,status:"skip",message:`not a global install; the global infra-kit keeps ${xr} current`}}},hv=(e,t)=>{let r=$$(e,t),n=I$(r);return{seams:{...r,stableNode:n.stableNode,stableNodeSidecar:n.sidecar},node:n.row}},N$=(e,t)=>{let r=t.readFile(ve.join(e,"package.json"));try{let n=r===null?null:Se.object({version:Se.string()}).safeParse(JSON.parse(r));return n?.success===!0?n.data.version:"?"}catch{return"?"}},_$=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)},M$=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?null:t},j$=(e,t,r)=>{let n=_$(r),o=a=>n!==null&&a!==null&&n.getTime()<a.getTime(),s=r.stableNodeSidecar,i=[...s!==null&&o(M$(s.versionChangedAt))?[`Node ${s.version}`]:[],...o(r.mtime(ve.join(e,"package.json")))?[`portless ${t}`]:[]];return i.length===0?null:i.join(" and ")},F$=async(e,t)=>{let r=t.realpath(t.cwd);return r===t.realpath(t.home)?!1:Yn(await t.repoRoot()??r,e,t.realpath)},Tr=e=>({state:"drifted",row:e}),L$=async(e,t,r)=>{let n=Mt(r.bin,r);if(!r.exists(e))return Tr({name:Zt,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(Rc(r.home),"dist","cli.js");if(t!==o)return Tr(ts(`The service points at \`${t}\`, a version-specific location. Re-run once to switch it to the stable link: \`${n}\``));if(Xs(r.home,r.exists)===null)return Tr({name:Zt,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(Rc(r.home));if(await F$(s,r))return Tr({name:Zt,status:"fail",message:`The service runs portless from a project checkout (${s}). Re-run \`service install\` from the global install: \`${n}\``});let i=B$(e,n,r);if(i!==null)return i;let a=N$(s,r),c=j$(s,a,r);return c!==null?{state:"converged",row:ts(`The running daemon predates ${c} that \`dev\` will talk to. Restart it: \`${S$(r.platform)}\` (or reboot).`)}:{state:"converged",row:{name:Zt,status:"pass",message:`service runs \`${e}\` (Node ${r.version}) + stable link \u2192 portless ${a}`}}},B$=(e,t,r)=>r.stableNode!==null?r.realpath(e)===r.realpath(r.stableNode)?null:Tr(ts(`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:Tr(ts(`The service runs \`${e}\`; infra-kit runs \`${r.execPath}\`. Works until the old Node is removed. Re-run when convenient: \`${t}\``)),yv=async e=>{let t=gv(e.platform);if(t===null)return{state:"absent",row:{name:Zt,status:"skip",message:"no portless OS service file on this platform"}};let r=e.readServiceFile(t);if(r===null)return{state:"absent",row:{name:Zt,status:"skip",message:`the OS service is not installed (no ${t})`}};let[n,o]=fh(e.platform,r)??[];return n===void 0||o===void 0?Tr(ts(`could not parse ${t} \u2014 re-run \`${Mt(e.bin,e)}\` to rewrite it.`)):L$(n,o,e)},vv=async(e,t)=>{let{seams:r}=hv(e,t);return{state:(await yv(r)).state,stableNode:r.stableNode}},U$=()=>[rs,Zt,fv(),"portless CA chain valid","portless CA trusted","portless routes"],W$=async(e={})=>{let t=e.resolveBin??Nm,r=e.isProxyServing??Lm,n=e.handshake??Vm,o=e.caTrusted??Wm,s=e.routes??Xn,i=e.isListening??zn,a=(e.caPath??Um)(),c=t();if(c===null)return[{name:"portless installed",status:"fail",message:"portless is not resolvable from node_modules \u2014 run `pnpm install`."},...U$().map(E=>({name:E,status:"skip",message:"portless not resolvable"}))];let l={name:"portless installed",status:"pass",message:"portless is resolvable from node_modules"},{seams:u,node:p}=hv(e,c),m=s(),f=await w$(r,c,u),y=f.status==="fail"?{name:"portless CA chain valid",status:"skip",message:"no daemon to handshake with"}:await k$(n,m,a,c,u);return[l,p,(await yv(u)).row,f,y,b$(o(),a,c),await R$(m,i,c)]},V$=async(e={})=>{let t="portless routes",r=e.routes??Xn,n=e.isListening??zn,o=e.devSessionRunning??lh,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}=ch(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??Gm().removeAlias;for(let u of a)await l(u);return{name:t,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},la=async(e={})=>{let t=await BC(),r=_C(e.probeDeps??Ho()),n=async(m,f)=>{let[y,E]=await Promise.all([f,r]),k=E.get(m);return k===void 0?y:{...y,detail:k}},o=await Promise.all([n("brew",Dt("brew installed",Ke("brew").probeArgv,"Homebrew is installed","Homebrew is not installed. Install from: https://brew.sh/")),n("git",Dt("git installed",Ke("git").probeArgv,"git is installed","git is not installed. Install with: brew install git")),n("gh",Dt("gh installed",Ke("gh").probeArgv,"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/")),Dt("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),n("doppler",Dt("doppler installed",Ke("doppler").probeArgv,"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli")),n("aws",Dt("aws installed",Ke("aws").probeArgv,"AWS CLI is installed","AWS CLI is not installed. Install from: https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html")),Dt("package manager installed",["pnpm","--version"],"Installed: pnpm","pnpm is not installed. Install from: https://pnpm.io/installation"),Dt("typescript-language-server installed",["typescript-language-server","--version"],"typescript-language-server is installed","typescript-language-server is not installed. Install from: https://github.com/typescript-language-server/typescript-language-server#installing"),MC(),Promise.resolve(jC()),Promise.resolve(FC()),LC(),Promise.resolve(UC(t)),HC(),JC(t),qC(e.fix??!1),zC(),XC()]),s=await W$(e.portlessDeps);if(e.fix){let m=await V$(),f=s.findIndex(y=>y.name===m.name);f>=0?s[f]=m:s.push(m)}let i=await t$(),a=await Bo(),c={projectDir:gt.env.CLAUDE_PROJECT_DIR||null,cwd:gt.cwd(),gitRoot:a},l=[await i$(),...u$(i,c),Uo(),m$({env:gt.env,stdinIsTTY:gt.stdin.isTTY===!0,flag:j.source==="flag"}),a===null?{name:"Agent allowlist",status:"skip",message:"no git root"}:g$(a)],u=[...o,await y$(a),...s,...await e$(),...l,d$(Rn(),L.version)],p={checks:u.map(m=>({name:m.name,status:m.status,message:m.message,fixable:Jl.has(m.name),detail:m.detail})),allPassed:IC(u),cliVersion:L.version};return{content:b(JSON.stringify(p,null,2)),structuredContent:p}},Ju=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:Se.array(Se.object({name:Se.string().describe("Name of the check"),status:Se.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:Se.string().describe("Details about the check result"),fixable:Se.boolean().describe("Whether `infra-kit doctor --fix` repairs this row"),detail:Se.object({manager:Se.string().describe("Which package manager owns this install, read from its resolved path"),version:Se.string().nullable().describe("The version the tool reported, or null"),present:Se.boolean().describe("The tool is installed somewhere findable \u2014 on PATH or not"),onPath:Se.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:Se.boolean().describe("Whether no check failed (warnings and skips do not count)"),cliVersion:Se.string().describe("Version of the infra-kit CLI that produced this report")},handler:()=>la()});import{E2E_MODE_ENV as hA}from"@slip-stream-kit/config/internal";import Qu from"node:fs";import yA from"node:os";import os from"node:path";import pa from"node:process";import{z as P}from"zod";var ht=(e,t,r)=>new D({status:"refused",reason:e,...t},2,r);import{describeProxyRoutes as G$,loadDev as J$,readAppAliasName as K$,readCloudOrigin as H$,readLocalContext as kv}from"@slip-stream-kit/config/internal";import wv from"node:fs";import Cr from"node:path";import ua from"node:process";import{z as Ku}from"zod";var q$=async e=>{let t=Cr.join(e,"apps"),r=wv.existsSync(t)?wv.readdirSync(t).toSorted():[],n=[];for(let o of r){let s=Cr.join(t,o,"tests"),a=(await ct(s))?.e2e;a?.target!==void 0&&n.push({app:o,testsDir:s,e2e:{target:a.target}})}return n},Y$=(e,t)=>{let[r,n]=Cr.relative(e,t).split(Cr.sep);return r==="apps"&&n?n:void 0},z$=(e,t,r,n)=>{let o=c=>e.find(l=>l.app===c),s=o(t)??(t===void 0?o(Y$(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:Ku.toJSONSchema(Ku.object({app:Ku.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(", ")}`})},X$=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}})),Z$=e=>xo(e).apps.find(t=>t.env!=="")?.env??null,Hu=async(e,t={})=>{let r=t.cwd??ua.cwd(),n=t.projectRoot??await A(),o=(t.env??ua.env)[Fr]||null,s=t.healthProbe??Mc,i=z$(await q$(n),e,r,n),{target:a}=i.e2e,[c,l]=a.split("/"),u=Cr.join(n,"apps",c,l),p=(await mr(u)).name,m=(await ct(u))?.deployedUrlEnv??null;if(!p)throw new g(void 0,{operation:`resolve e2e target ${a}`,remediation:`check \`e2e.target\` in ${Cr.join(i.testsDir,"infra-kit.config.ts")}`,stderrExcerpt:`${u} has no package.json name`});let f=Jf(u),y=K$(p,u),E=`${y}.localhost`,k=`https://${E}`,O=0;if(l==="ui")O=(t.listRoutes??Xn)().find(R=>R.name===E||R.name===y)?.port??0;else{let R=kv(u).info.get(p);O=R?.port??0,k=R?.origin??k}let v=O>0&&await s({tag:a,port:O,kind:l})==="ok",S=v?Z$(u):null;return{app:i.app,testsDir:i.testsDir,target:a,kind:l,targetDir:u,packageName:p,deployedUrlEnv:m,release:f,env:o,servedEnv:S,localUrl:k,served:v}},bv=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}},qu=async(e,t={})=>{let r=t.healthProbe??Mc,n=kv(e.targetDir),o=e.kind==="ui"?await J$(e.targetDir):void 0,s=o?.proxy?G$({proxy:o.proxy,localContext:n,env:e.env??void 0,cloud:H$(e.deployedUrlEnv??void 0,t.env??ua.env),getRelease:()=>e.release}):[],i=new Map([...n.info].map(([a,c])=>[a,c.port]));return{...bv(e),mode:"local",baseUrl:e.localUrl,routes:await X$(s,i,r)}},Yu=(e,t={})=>{let{env:r,deployedUrlEnv:n,target:o}=e;if(!n)throw ht("no_deployed_url_env",{target:o},{operation:`resolve the deployed app ${e.app}'s cloud e2e run targets`,remediation:`declare \`deployedUrlEnv: '<APP>_URL'\` in ${Cr.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??ua.env)[n];if(!r||!s){let i=s?Fr:n;throw ht("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 ${Fr}, and ${i} is not set`})}return{...bv(e),mode:"cloud",baseUrl:s,routes:[]}};import Q$ from"node:fs";import eA from"node:path";import{stripVTControlCharacters as tA}from"node:util";import{z as N}from"zod";var Rv=2e3,Sv="--reporter=line,json",Ev=e=>({PLAYWRIGHT_JSON_OUTPUT_FILE:e,PLAYWRIGHT_JSON_OUTPUT_NAME:e}),Pv=e=>e.some(t=>t==="--reporter"||t.startsWith("--reporter=")),zu=N.object({message:N.string().optional()}),xv=N.object({type:N.string()}),rA=N.object({status:N.string(),retry:N.number(),error:zu.optional(),errors:N.array(zu).optional(),annotations:N.array(xv).optional(),attachments:N.array(N.object({name:N.string(),path:N.string().optional()})).optional()}),nA=N.object({projectName:N.string(),status:N.string(),expectedStatus:N.string().optional(),annotations:N.array(xv).optional(),results:N.array(rA)}),oA=N.object({title:N.string(),file:N.string(),line:N.number().optional(),tests:N.array(nA)}),Tv=N.lazy(()=>N.object({title:N.string(),specs:N.array(oA).optional(),suites:N.array(Tv).optional()})),sA=N.object({config:N.object({rootDir:N.string().optional()}).optional(),suites:N.array(Tv),errors:N.array(zu).optional(),stats:N.object({expected:N.number(),unexpected:N.number(),flaky:N.number(),skipped:N.number()})}),Cv=e=>{let t=tA(e);return t.length>Rv?`${t.slice(0,Rv)}\u2026`:t},iA=e=>{let t=e.error?.message??e.errors?.[0]?.message;return t===void 0?null:Cv(t)},aA=e=>e.status==="unexpected"||e.status==="flaky",cA=e=>{let t=new Map;for(let r of e)t.set(r.projectName,[...t.get(r.projectName)??[],r]);return t},lA=e=>new Set([...e.annotations??[],...e.results.flatMap(t=>t.annotations??[])].map(t=>t.type)),uA=(e,t)=>{let r=e.filter(aA),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?iA(o):"Expected to fail, but passed.",tracePath:o?.attachments?.find(i=>i.name==="trace")?.path??null}},dA=e=>{let t=sA.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=>[...lA(k)])),y=m.some(k=>k.expectedStatus==="failed");if(!y&&!f.has("fixme")&&!f.has("skip"))return;let E=a.get(p)??{file:p,fail:0,fixme:0,skip:0};y&&(E.fail+=1),f.has("fixme")?E.fixme+=1:f.has("skip")&&(E.skip+=1),a.set(p,E)},u=(p,m)=>{for(let f of p.specs??[]){let y=r?.rootDir?eA.resolve(r.rootDir,f.file):f.file,E=[...m,f.title].join(" \u203A ");l(y,f.tests);for(let[k,O]of cA(f.tests)){let v=uA(O,{title:E,file:y,line:f.line??null,project:k});v&&(v.runs>1&&v.failedRuns<v.runs&&(c+=1),i.push(v))}}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?[]:[Cv(p.message)])}},$v=e=>{try{return dA(JSON.parse(Q$.readFileSync(e,"utf8")))}catch{return null}};import ns from"node:fs";import Ov from"node:path";import da from"node:process";var pA=e=>Ov.join(e,"node_modules",".cache","infra-kit-e2e.lock"),mA=e=>{try{return da.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Av=e=>{try{return ns.writeFileSync(e,String(da.pid),{flag:"wx"}),!0}catch(t){if(t.code==="EEXIST")return!1;throw t}},Xu=e=>{try{let t=Number.parseInt(ns.readFileSync(e,"utf8"),10);return Number.isInteger(t)&&t>0?t:null}catch{return null}},Dv=e=>{let t=pA(e);if(ns.mkdirSync(Ov.dirname(t),{recursive:!0}),!Av(t)){let r=Xu(t);if(r!==null&&r!==da.pid&&mA(r))return{holder:r};if(ns.rmSync(t,{force:!0}),!Av(t))return{holder:Xu(t)??0}}return{release:()=>{Xu(t)===da.pid&&ns.rmSync(t,{force:!0})}}};import{spawn as fA}from"node:child_process";import gA from"node:os";import Zu from"node:process";var Iv=(e,t,r)=>new Promise((n,o)=>{let s=fA(e,t,r),i=Zu.stdin.isTTY?["SIGTERM","SIGHUP"]:["SIGINT","SIGTERM","SIGHUP"],a=l=>{s.kill(l)},c=()=>{for(let l of i)Zu.off(l,a)};for(let l of i)Zu.on(l,a);s.once("error",l=>{c(),o(l)}),s.once("close",(l,u)=>{c(),n(l??(u?128+gA.constants.signals[u]:1))})});var vA=["playwright.config.ts","playwright.config.mts","playwright.config.js","playwright.config.mjs"],wA=e=>vA.some(t=>{try{return Qu.readFileSync(os.join(e,t),"utf8").includes("infraKitE2e")}catch{return!1}}),ed=e=>`infra-kit dev ${e.target.split("/")[0]} --no-watch --reuse`,kA=(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
+ `)},bA=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 ht("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(", ")}`})},RA=async(e,t)=>{if(e.env===null||!Vf(e.env))return;let r=await(t.protectedEnvAccess??st)();if(r.allowed)return;let n=`run ${e.app} e2e against "${e.env}"`;throw r.reason==="agent-blocked"?ht("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`}):ht("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`})},SA=e=>{if(!(e.servedEnv===null||e.servedEnv===e.env))throw ht("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"}"`})},EA=async(e,t)=>{if(e.served){SA(e);let p=await qu(e,t);return bA(p),p}if(!wA(e.testsDir))throw ht("no_dev_server",{devCommand:ed(e)},{operation:`run ${e.app} e2e locally`,remediation:`start it (\`${ed(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:[]}},PA=(e,t,r)=>Iv("pnpm",["exec","playwright","test",...t],{cwd:e.testsDir,env:{...pa.env,...r,[hA]:e.mode},stdio:["inherit",cr.enabled||Z()?2:"inherit","inherit"]}),xA=(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:os.resolve(e.testsDir,s)}}let n=new Date().toISOString().replace(/[:.]/g,"-"),o=os.join(e.testsDir,"test-results",`ik-e2e-${n}-${pa.pid}`);return{args:[...t,`--output=${o}`],outputDir:o}},TA=e=>{if(e.mode==="cloud")return()=>{};let t=Dv(e.testsDir);if("holder"in t)throw ht("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},ma=async(e,t={})=>{let r=await Hu(e.app,t),n=e.cloud?Yu(r,t):await EA(r,t);d.info(kA(n,r.served)),n.mode==="cloud"&&await RA(n,t);let o={...n,served:r.served,devCommand:n.mode==="local"&&!r.served?ed(r):null,playwrightArgs:e.playwrightArgs??[]};if(e.dryRun)return rd({...o,ran:!1,exitCode:null,...td});n.mode==="cloud"&&await J(e.yes,`Run ${n.app} e2e against ${n.baseUrl} ("${n.env}", shared)?`,{plan:o});let s=TA(n);try{return await CA(o,t.runPlaywright??PA)}finally{s()}},CA=async(e,t)=>{if(!Z()||Pv(e.playwrightArgs)){let i=await t(e,e.playwrightArgs,{});return i!==0&&(pa.exitCode=i),rd({...e,ran:!0,exitCode:i,...td,report:Z()?"caller-reporter":"off"})}let{args:r,outputDir:n}=xA(e,e.playwrightArgs),o=Qu.mkdtempSync(os.join(yA.tmpdir(),"ik-e2e-report-")),s=os.join(o,"report.json");try{let i=await t(e,[Sv,...r],Ev(s));i!==0&&(pa.exitCode=i);let a=$v(s);return rd({...e,ran:!0,exitCode:i,...a?{report:"collected",...a}:{...td,report:"unavailable"},outputDir:n})}finally{Qu.rmSync(o,{recursive:!0,force:!0})}},td={report:"off",outputDir:null,summary:null,failures:[],annotated:[],errors:[]},rd=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.")},nd=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=>ma(e)});import fa from"node:fs";import od from"node:path";import{z as ss}from"zod";var AA=e=>[...e.map(t=>`unset ${t}`),`unset ${Fr}`,`unset ${Js}`,`unset ${Ks}`,`unset ${Em}`,`unset ${Hs}`],ga=async()=>{let e=Lr(),t=od.join(e,jr);if(!fa.existsSync(t))throw new Error("No loaded environment found. Run `env-load` first.");let r=qs(t),n=AA(r),o=od.resolve(e,Vs);fa.mkdirSync(e,{recursive:!0,mode:448}),_t(o,`${n.join(`
375
375
  `)}
376
- `,384),ua.rmSync(t,{force:!0}),ua.rmSync(td.join(e,Bs),{force:!0});let s={filePath:o,variableCount:r.length,unsetStatements:n};return{content:b(JSON.stringify(s,null,2)),structuredContent:s}},rd=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:os.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{filePath:os.string().describe("Path to the file that must be sourced to apply"),variableCount:os.number().describe("Number of variables cleared"),unsetStatements:os.array(os.string()).describe("Unset statements generated")},handler:()=>da()});import bA from"node:path";import ss from"node:process";import{z as Nn}from"zod";var pa=async()=>{d.info("Environment session status:");let e=Fr(),t=ss.env[Hn],r=bA.join(e,Mr),n=0,o=0,s=ss.env[Us]??null,i=ss.env[Ws]??null,a=ss.env[Vs]??null;if(s){let l=Gs(r);l.length>0&&(o=l.length,n=l.filter(p=>p in ss.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})
376
+ `,384),fa.rmSync(t,{force:!0}),fa.rmSync(od.join(e,Gs),{force:!0});let s={filePath:o,variableCount:r.length,unsetStatements:n};return{content:b(JSON.stringify(s,null,2)),structuredContent:s}},sd=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:ss.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{filePath:ss.string().describe("Path to the file that must be sourced to apply"),variableCount:ss.number().describe("Number of variables cleared"),unsetStatements:ss.array(ss.string()).describe("Unset statements generated")},handler:()=>ga()});import OA from"node:path";import is from"node:process";import{z as _n}from"zod";var ha=async()=>{d.info("Environment session status:");let e=Lr(),t=is.env[qn],r=OA.join(e,jr),n=0,o=0,s=is.env[Js]??null,i=is.env[Ks]??null,a=is.env[Hs]??null;if(s){let l=qs(r);l.length>0&&(o=l.length,n=l.filter(p=>p in is.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
377
  `),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}},nd=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:Nn.string().describe("Current terminal session ID"),sessionLoadedCount:Nn.number().describe("Number of cached vars active in the current session"),sessionTotalCount:Nn.number().describe("Total number of cached var names"),sessionConfig:Nn.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:Nn.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:Nn.string().nullable().describe("ISO 8601 timestamp of when the env was loaded")},handler:pa});import RA from"node:process";import{z as Xt}from"zod";var Ov="****",Te=e=>typeof e!="string"||e.length<8?Ov:`${Ov}${e.slice(-4)}`;var Dv=(e,t,r)=>e.map(n=>{let o=r||t[n];return o?{env:n,source:r?`env:${lr}`:"store",redactedToken:Te(o),present:!0}:{env:n,source:"-",redactedToken:"-",present:!1}}),SA=["ENV","SOURCE","TOKEN","PRESENT"],Iv=(e,t)=>{let r=[...SA,...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())},ma=async({check:e}={})=>{let t=await ii(),r=await Ze(),n=RA.env[lr],o=Dv(t,r?.envs??{},n);if(e){let a=await cr();for(let c of o){if(!c.present)continue;let l=n||r.envs[c.env],u=await $f({childEnv:no(l),project:a,config:c.env});c.status=u.outcome}}for(let a of Iv(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}},od=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:Xt.boolean().optional().describe("Probe Doppler for each token\u2019s validity and scope (one cheap call per environment).")},outputSchema:{tokens:Xt.array(Xt.object({env:Xt.string().describe("Environment / Doppler config name"),source:Xt.string().describe('"store", "env:INFRA_KIT_ENV_TOKEN", or "-" when absent'),redactedToken:Xt.string().describe("Redacted token \u2014 last 4 chars at most, never the raw value"),present:Xt.boolean().describe("Whether a token is configured for this environment"),status:Xt.string().optional().describe("Only with check=true: valid | revoked | mis-scoped | unreachable")})).describe("One row per declared environment")},handler:ma});import{z as T}from"zod";import{$ as EA}from"zx";var PA=(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,TA=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(", ")},id=e=>({content:b(JSON.stringify(e,null,2)),structuredContent:e}),sd=new Set(["up-to-date","fast-forward","merged"]),CA=(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=Pe(ve(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))},$A={"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"},_v=e=>{let t=$A[e.status];if(e.status==="conflict"){let r=e.conflictPaths?.length??0;return`${t}: ${r} file(s)`}return e.reason?`${t}: ${e.reason}`:t},AA=(e,t)=>{d.info(`
380
- \u{1F4CB} Merge plan:`);for(let r of e)d.info(` ${r.branch} \u2014 ${_v(r)}`);for(let r of t)d.info(` ${r.branch} \u2014 skipped: ${r.reason}`)},OA=(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`},DA=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?[[ce(a),_v(i)]]:[]}));return Kt(me({branches:r,descriptions:s}),{required:!0})},IA=async e=>{let{cwd:t,worktreePath:r,entries:n,selected:o,verify:s}=e,i=n.filter(v=>o.includes(v.branch)),a=v=>{for(let E of v)d.info(`\u2139\uFE0F ${E} was merged by someone else while we planned \u2014 dropping it from the push`)},c=await Mo(t,xh(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 v=await Ch({worktreePath:r,refs:l,command:s});u=v.failed;for(let[k,h]of v.failed)d.info(`\u2717 ${k} failed verification \u2014 not pushing it. ${h.split(`
382
- `)[0]??""}`);let E=await Mo(t,v.kept);a(E.nowUpToDate),l=E.kept}if(l.length===0)return{pushed:!1,pushAborted:!1,verifyFailed:u};d.info(`
383
- \u2B06\uFE0F Pushing atomically: ${l.map(v=>v.branch).join(", ")}`);let p=await Qs(t,l);if(p.pushed)return{pushed:!0,pushAborted:!1,verifyFailed:u};let f=(await Promise.all(l.map(async v=>({branch:v.branch,landed:await Wr(t,v.branch)===v.sha})))).filter(v=>v.landed);return f.length>0&&d.warn(`\u26A0\uFE0F The push reported failure, but origin already carries ${f.map(v=>v.branch).join(", ")} \u2014 re-run to reconcile.`),{pushed:!1,pushAborted:!0,verifyFailed:u,abortedBy:p.stderr?.split(`
384
- `)[0],observedLanded:f.map(v=>v.branch)}},NA=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"})},Nv=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=>!sd.has(i.status));return id({successfulMerges:o.length-s.length,failedMerges:s.length,failedBranches:s.map(i=>i.branch),totalBranches:t.length,dryRun:!1,atomicPush:r,results:t,skipped:[]})},_A=async e=>{let{all:t,versions:r,verify:n,confirmedCommand:o}=e,s=await $e();if(e.abort)return Nv(await ey({cwd:s,versions:r,all:t,confirmedCommand:o}));let i=typeof n=="string"&&n.length>0?n:void 0;return Nv(await Zh({cwd:s,versions:r,all:t,verify:i,trees:Qh(e.tree),confirmedCommand:o}))},fa=async e=>{let{all:t,versions:r,dryRun:n=!1,verify:o,keepConflicts:s=!1,confirmedCommand:i}=e;NA(e);let a=o===!0?Th:o||void 0;if(await Gl({operation:"merge dev into release branches"}),e.continue||e.abort)return _A(e);let c=[],l=[];for(let $ of await V()){let J=xA($);J?l.push({branch:$.branch,reason:J}):c.push($.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 (${TA(l)})`),y.print(),id(PA(n,l));let u=await $e();try{await EA({cwd:u,quiet:!0})`git fetch origin --prune`}catch($){throw new g($,{operation:"fetch origin before planning the merges",remediation:"check network access and that `origin` is reachable"})}let p=r===void 0?c:CA(r,c,l),m=await sf({cwd:u},async $=>{let J=Bi($.remove);try{return await MA({cwd:u,worktree:$,toPlan:p,candidates:c,skipped:l,all:t,versions:r,dryRun:n,verify:a,keepConflicts:s,confirmedCommand:i})}finally{J()}}),{entries:f,selected:v,pushed:E,pushAborted:k,abortedBy:h,declined:R,verifyFailed:S,handOffs:P}=m,M=await ot(u).catch(()=>[]);return BA({entries:f,selected:v,pushed:E,pushAborted:k,abortedBy:h,declined:R,verifyFailed:S,handOffs:P,dryRun:n,worktrees:M,skipped:l})},MA=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 xe(t,"origin/dev"):null,f=await Ph({cwd:t,worktreePath:r.path,branches:n}),v={entries:f,pushed:!1,pushAborted:!1,declined:!1};if(AA(f,s),c)return{...v,selected:n};let E=await DA({entries:f,toPlan:n,all:i,explicit:a!==void 0});E.length===o.length?y.addOption("--all",!0):y.addOption("--versions",E);let k=f.filter($=>E.includes($.branch)&&$.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 G(p,`Are you sure you want to merge dev into these branches: ${E.join(", ")}?`,{throwOnDecline:!0,plan:jA(f,E,s)})}catch($){if(!bt($))throw $;return{...v,selected:E,declined:!0}}p||y.addOption("--yes",!0);let h=await IA({cwd:t,worktreePath:r.path,entries:f,selected:E,verify:l}),R=$=>f.filter(J=>E.includes(J.branch)&&$(J)).map(J=>J.branch),S=R($=>$.status==="conflict"),P=R($=>$.status==="merged"&&(h.verifyFailed?.has($.branch)??!1)),M=u&&m&&S.length+P.length>0?await Yh({cwd:t,conflicted:S,verifyFailed:P,devSha:m,verify:l}):void 0;return{entries:f,selected:E,declined:!1,...h,handOffs:M}},jA=(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:iu(n.conflictPaths)}:{},...n.reason?{reason:n.reason}:{}})),skipped:r}),FA=(e,t)=>e.resolution?`# ${e.branch} \u2014 ${e.status}, left to resolve in ${e.resolution.worktreePath} (then --continue)
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}},id=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:_n.string().describe("Current terminal session ID"),sessionLoadedCount:_n.number().describe("Number of cached vars active in the current session"),sessionTotalCount:_n.number().describe("Total number of cached var names"),sessionConfig:_n.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:_n.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:_n.string().nullable().describe("ISO 8601 timestamp of when the env was loaded")},handler:ha});import DA from"node:process";import{z as Qt}from"zod";var Nv="****",Ce=e=>typeof e!="string"||e.length<8?Nv:`${Nv}${e.slice(-4)}`;var _v=(e,t,r)=>e.map(n=>{let o=r||t[n];return o?{env:n,source:r?`env:${dr}`:"store",redactedToken:Ce(o),present:!0}:{env:n,source:"-",redactedToken:"-",present:!1}}),IA=["ENV","SOURCE","TOKEN","PRESENT"],Mv=(e,t)=>{let r=[...IA,...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())},ya=async({check:e}={})=>{let t=await ui(),r=await Ze(),n=DA.env[dr],o=_v(t,r?.envs??{},n);if(e){let a=await ur();for(let c of o){if(!c.present)continue;let l=n||r.envs[c.env],u=await Df({childEnv:oo(l),project:a,config:c.env});c.status=u.outcome}}for(let a of Mv(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}},ad=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:Qt.boolean().optional().describe("Probe Doppler for each token\u2019s validity and scope (one cheap call per environment).")},outputSchema:{tokens:Qt.array(Qt.object({env:Qt.string().describe("Environment / Doppler config name"),source:Qt.string().describe('"store", "env:INFRA_KIT_ENV_TOKEN", or "-" when absent'),redactedToken:Qt.string().describe("Redacted token \u2014 last 4 chars at most, never the raw value"),present:Qt.boolean().describe("Whether a token is configured for this environment"),status:Qt.string().optional().describe("Only with check=true: valid | revoked | mis-scoped | unreachable")})).describe("One row per declared environment")},handler:ya});import{z as x}from"zod";import{$ as NA}from"zx";var _A=(e,t)=>({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0,dryRun:e,atomicPush:{attempted:!1,aborted:!1},results:[],skipped:t}),MA=e=>e.dualBase?"open PRs to both dev and main":e.titleMismatch?"title/base mismatch":e.type==="hotfix"?"hotfix (targets main)":null,jA=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(", ")},ld=e=>({content:b(JSON.stringify(e,null,2)),structuredContent:e}),cd=new Set(["up-to-date","fast-forward","merged"]),FA=(e,t,r)=>{let n=(Array.isArray(e)?e:e.split(",")).map(a=>a.trim()).filter(a=>a.length>0),o=new Set(t),s=new Map(r.map(a=>[a.branch,a.reason])),i=new Set;for(let a of n){let c;try{c=xe(we(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))},LA={"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"},Fv=e=>{let t=LA[e.status];if(e.status==="conflict"){let r=e.conflictPaths?.length??0;return`${t}: ${r} file(s)`}return e.reason?`${t}: ${e.reason}`:t},BA=(e,t)=>{d.info(`
380
+ \u{1F4CB} Merge plan:`);for(let r of e)d.info(` ${r.branch} \u2014 ${Fv(r)}`);for(let r of t)d.info(` ${r.branch} \u2014 skipped: ${r.reason}`)},UA=(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`},WA=async e=>{let{entries:t,toPlan:r,all:n,explicit:o}=e;if(o||n)return r;h.setInteractive();let s=new Map(t.flatMap(i=>{let a=Q(i.branch);return a?[[ce(a),Fv(i)]]:[]}));return qt(me({branches:r,descriptions:s}),{required:!0})},VA=async e=>{let{cwd:t,worktreePath:r,entries:n,selected:o,verify:s}=e,i=n.filter(y=>o.includes(y.branch)),a=y=>{for(let E of y)d.info(`\u2139\uFE0F ${E} was merged by someone else while we planned \u2014 dropping it from the push`)},c=await jo(t,$h(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 y=await Oh({worktreePath:r,refs:l,command:s});u=y.failed;for(let[k,O]of y.failed)d.info(`\u2717 ${k} failed verification \u2014 not pushing it. ${O.split(`
382
+ `)[0]??""}`);let E=await jo(t,y.kept);a(E.nowUpToDate),l=E.kept}if(l.length===0)return{pushed:!1,pushAborted:!1,verifyFailed:u};d.info(`
383
+ \u2B06\uFE0F Pushing atomically: ${l.map(y=>y.branch).join(", ")}`);let p=await ni(t,l);if(p.pushed)return{pushed:!0,pushAborted:!1,verifyFailed:u};let f=(await Promise.all(l.map(async y=>({branch:y.branch,landed:await Vr(t,y.branch)===y.sha})))).filter(y=>y.landed);return f.length>0&&d.warn(`\u26A0\uFE0F The push reported failure, but origin already carries ${f.map(y=>y.branch).join(", ")} \u2014 re-run to reconcile.`),{pushed:!1,pushAborted:!0,verifyFailed:u,abortedBy:p.stderr?.split(`
384
+ `)[0],observedLanded:f.map(y=>y.branch)}},GA=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"})},jv=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=>!cd.has(i.status));return ld({successfulMerges:o.length-s.length,failedMerges:s.length,failedBranches:s.map(i=>i.branch),totalBranches:t.length,dryRun:!1,atomicPush:r,results:t,skipped:[]})},JA=async e=>{let{all:t,versions:r,verify:n,confirmedCommand:o}=e,s=await $e();if(e.abort)return jv(await ny({cwd:s,versions:r,all:t,confirmedCommand:o}));let i=typeof n=="string"&&n.length>0?n:void 0;return jv(await ty({cwd:s,versions:r,all:t,verify:i,trees:ry(e.tree),confirmedCommand:o}))},va=async e=>{let{all:t,versions:r,dryRun:n=!1,verify:o,keepConflicts:s=!1,confirmedCommand:i}=e;GA(e);let a=o===!0?Ah:o||void 0;if(await Hl({operation:"merge dev into release branches"}),e.continue||e.abort)return JA(e);let c=[],l=[];for(let T of await G()){let W=MA(T);W?l.push({branch:T.branch,reason:W}):c.push(T.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 (${jA(l)})`),h.print(),ld(_A(n,l));let u=await $e();try{await NA({cwd:u,quiet:!0})`git fetch origin --prune`}catch(T){throw new g(T,{operation:"fetch origin before planning the merges",remediation:"check network access and that `origin` is reachable"})}let p=r===void 0?c:FA(r,c,l),m=await lf({cwd:u},async T=>{let W=Gi(T.remove);try{return await KA({cwd:u,worktree:T,toPlan:p,candidates:c,skipped:l,all:t,versions:r,dryRun:n,verify:a,keepConflicts:s,confirmedCommand:i})}finally{W()}}),{entries:f,selected:y,pushed:E,pushAborted:k,abortedBy:O,declined:v,verifyFailed:S,handOffs:R}=m,$=await ot(u).catch(()=>[]);return zA({entries:f,selected:y,pushed:E,pushAborted:k,abortedBy:O,declined:v,verifyFailed:S,handOffs:R,dryRun:n,worktrees:$,skipped:l})},KA=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 Te(t,"origin/dev"):null,f=await Ch({cwd:t,worktreePath:r.path,branches:n}),y={entries:f,pushed:!1,pushAborted:!1,declined:!1};if(BA(f,s),c)return{...y,selected:n};let E=await WA({entries:f,toPlan:n,all:i,explicit:a!==void 0});E.length===o.length?h.addOption("--all",!0):h.addOption("--versions",E);let k=f.filter(T=>E.includes(T.branch)&&T.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: ${E.join(", ")}?`,{throwOnDecline:!0,plan:HA(f,E,s)})}catch(T){if(!St(T))throw T;return{...y,selected:E,declined:!0}}p||h.addOption("--yes",!0);let O=await VA({cwd:t,worktreePath:r.path,entries:f,selected:E,verify:l}),v=T=>f.filter(W=>E.includes(W.branch)&&T(W)).map(W=>W.branch),S=v(T=>T.status==="conflict"),R=v(T=>T.status==="merged"&&(O.verifyFailed?.has(T.branch)??!1)),$=u&&m&&S.length+R.length>0?await Zh({cwd:t,conflicted:S,verifyFailed:R,devSha:m,verify:l}):void 0;return{entries:f,selected:E,declined:!1,...O,handOffs:$}},HA=(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:lu(n.conflictPaths)}:{},...n.reason?{reason:n.reason}:{}})),skipped:r}),qA=(e,t)=>e.resolution?`# ${e.branch} \u2014 ${e.status}, left to resolve in ${e.resolution.worktreePath} (then --continue)
387
387
  `:`# ${e.branch} \u2014 ${e.status}
388
- ${OA(e.branch,t)}
389
- `,LA=(e,t)=>e!==void 0&&t?`${e}
390
- hand-off: ${t}`:e??t,BA=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 h=!!k.mergeSha,R=l?.has(k.branch)??!1,S=l?.get(k.branch),P=o&&h?"push-aborted":k.status,M=R?"verify-failed":P,$=u?.get(k.branch);return{branch:k.branch,status:M,mergeSha:k.mergeSha,conflictPaths:k.conflictPaths,pushed:m.has(k.branch),reason:LA(S,$?.reason)??k.reason,...$?.resolution?{resolution:$.resolution}:{}}}),v=f.filter(k=>!sd.has(k.status));for(let k of f){let h=t.find(R=>R.branch===k.branch);d.info({branch:k.branch,status:k.status,mergeSha:k.mergeSha,conflictCount:k.conflictPaths?.length??0,durationMs:h?.durationMs,pushed:k.pushed,msg:"merge-dev branch result"})}if(i||a)d.info(i?`
388
+ ${UA(e.branch,t)}
389
+ `,YA=(e,t)=>e!==void 0&&t?`${e}
390
+ hand-off: ${t}`:e??t,zA=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 O=!!k.mergeSha,v=l?.has(k.branch)??!1,S=l?.get(k.branch),R=o&&O?"push-aborted":k.status,$=v?"verify-failed":R,T=u?.get(k.branch);return{branch:k.branch,status:$,mergeSha:k.mergeSha,conflictPaths:k.conflictPaths,pushed:m.has(k.branch),reason:YA(S,T?.reason)??k.reason,...T?.resolution?{resolution:T.resolution}:{}}}),y=f.filter(k=>!cd.has(k.status));for(let k of f){let O=t.find(v=>v.branch===k.branch);d.info({branch:k.branch,status:k.status,mergeSha:k.mergeSha,conflictCount:k.conflictPaths?.length??0,durationMs:O?.durationMs,pushed:k.pushed,msg:"merge-dev branch result"})}if(i||a)d.info(i?`
391
391
  Operation cancelled \u2014 nothing was pushed.
392
392
  `:`
393
393
  \u{1F50D} Dry run \u2014 nothing was pushed.
394
- `);else if(v.length>0){d.info(`
395
- \u26A0\uFE0F ${v.length} branch(es) did not merge.
396
- `);for(let k of v)d.info(FA(k,c))}else d.info(`\u2705 All merges completed successfully!
397
- `);y.print();let E=a||i;return id({successfulMerges:E?0:f.filter(k=>sd.has(k.status)).length,failedMerges:E?0:v.length,failedBranches:E?[]:v.map(k=>k.branch),totalBranches:f.length,dryRun:a,atomicPush:{attempted:!a&&!i,aborted:o,abortedBy:s},results:f.map(k=>E?{...k,pushed:!1}:k),skipped:p})},ad=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:T.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:T.union([T.string(),T.array(T.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:T.boolean().optional().describe("Compute and print the merge plan without pushing anything."),verify:T.union([T.boolean(),T.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:T.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:T.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:T.boolean().optional().describe("Discard the selected resolution worktrees and their state. Excludes `keepConflicts`, `continue` and `dryRun`."),tree:T.union([T.string(),T.array(T.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:T.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{successfulMerges:T.number().describe("Number of branches that reached their desired state"),failedMerges:T.number().describe("Number of branches that did not"),failedBranches:T.array(T.string()).describe("List of branches that did not merge"),totalBranches:T.number().describe("Total number of branches processed"),dryRun:T.boolean().describe("True when nothing was pushed because this was a plan-only run"),atomicPush:T.object({attempted:T.boolean(),aborted:T.boolean(),abortedBy:T.string().optional()}).describe("Outcome of the single all-or-nothing push"),results:T.array(T.object({branch:T.string(),status:T.string(),mergeSha:T.string().optional(),conflictPaths:T.array(T.string()).optional(),pushed:T.boolean(),reason:T.string().optional(),resolution:T.object({worktreePath:T.string(),baseSha:T.string(),devSha:T.string(),conflictPaths:T.array(T.string()),editablePaths:T.array(T.string()).optional(),lockfileOnly:T.boolean(),rererePreResolved:T.array(T.string()),state:T.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:T.object({code:T.enum(["unmerged-paths","markers-remaining","out-of-scope-edit","verify-failed","verify-mutated-tree","parents-mismatch","git-too-old","tree-changed"]),paths:T.array(T.string()).optional(),detail:T.string()}).optional().describe("Why a `continue` run did not commit this resolution")})).describe("Per-branch terminal state"),skipped:T.array(T.object({branch:T.string(),reason:T.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:fa});import{z as ps}from"zod";import{$ as He}from"zx";var Mv=(e,t)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-t).trim()},Tr=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=Mv(t.stderr,500);o&&(r.stderr=o);let s=Mv(t.stdout,200);return s&&(r.stdout=s),r};var is=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 as=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 ge()?new O({status:"partial_failure",...n},1,s):new g(void 0,s)};import ga from"node:fs/promises";import{$ as ld}from"zx";var UA=new Set([".omc",".DS_Store"]),WA=new Set(["state","sessions"]),VA=2e3,Bv="check 'git worktree list' for the path; uncommitted changes block removal",GA=e=>new Promise(t=>{setTimeout(t,e)}),cd=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)},Fv=async e=>{try{return jv(await ga.realpath(e))}catch{return jv(e)}},JA=async e=>{let{projectRoot:t,worktreePath:r}=e;try{let n=await ot(t),o=await Fv(r);for(let s of n)if(await Fv(s.path)===o)return!0;return!1}catch{return!0}},KA=async e=>{let t;try{t=await ga.readdir(e)}catch(n){return{kind:cd(n)==="ENOENT"?"gone":"not-sweepable",entries:[]}}if(!t.every(n=>UA.has(n)))return{kind:"not-sweepable",entries:t};if(!t.includes(".omc"))return{kind:"sweepable",entries:t};try{return{kind:(await ga.readdir(`${e}/.omc`)).every(s=>WA.has(s))?"sweepable":"not-sweepable",entries:t}}catch(n){return{kind:cd(n)==="ENOENT"?"sweepable":"not-sweepable",entries:t}}},Lv=async e=>{try{return await ga.rm(e,{recursive:!0,force:!0}),"removed"}catch(t){return cd(t)==="ENOTEMPTY"?"busy":"failed"}},HA=async e=>{let{worktreePath:t,sleep:r}=e,n=await Lv(t);return n!=="busy"?n==="removed":(await r(VA),await Lv(t)==="removed")},cs=(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}},qA=async e=>{let{branch:t,worktreePath:r,projectRoot:n,error:o,sleep:s}=e;if(await JA({projectRoot:n,worktreePath:r}))return cs(t,o,Bv);let i=await KA(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 HA({worktreePath:r,sleep:s})?cs(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"})},YA=async e=>{try{return(await ld`git -C ${e} status --porcelain`).stdout.split(`
398
- `).filter(r=>r.trim().length>0)}catch{return[]}},zA=async e=>{let{branch:t,worktreeDir:r,projectRoot:n,orcaProbe:o,sleep:s}=e,i=`${r}/${t}`,a=await YA(i);if(a.length>0)return cs(t,new Error(`uncommitted changes in ${i}: ${a.slice(0,5).join(", ")}`),Bv);let c=await If(i,o);if(!c.closed&&"error"in c)return cs(t,c.error,"close the Orca terminals of this worktree manually (orca terminal close --terminal <handle>) and re-run");try{return await ld`git worktree remove ${i}`,{branch:t,status:"removed"}}catch(l){return qA({branch:t,worktreePath:i,projectRoot:n,error:l,sleep:s})}},Cr=async e=>{let{branches:t,worktreeDir:r,projectRoot:n,pruneFolder:o=!1,sleep:s=GA}=e,i=t.length>0?await Lt():"unreachable",a=await Promise.all(t.map(l=>zA({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 ld`git worktree prune`,c};var ls=async(e,t)=>{if(!(await we("release")).includes(e))return[];let n=await A(),o=`${n}${fe}`,{removed:s,failed:i}=await Cr({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 ud}from"zx";var us=async(e,t)=>{let r=await ud({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))]:[]}},Uv=async(e,t)=>(await ud({quiet:!0})`git commit-tree ${e} -p ${t} -m ${"infra-kit deliver preflight"}`).stdout.trim(),ds=(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`})},Wv=async e=>{let{releaseBranch:t,releaseType:r,releaseMerged:n,rcMerged:o}=e,s=`origin/${t}`;if(await ud({quiet:!0})`git fetch origin main dev ${n?[]:[t]}`,r==="hotfix"){let a="origin/main";if(!n){let c=await us("origin/main",s);ds(`merging ${t} into main`,c),a=await Uv(c.tree,"origin/main")}ds("syncing main back into dev",await us("origin/dev",a));return}let i="origin/dev";if(!n){let a=await us("origin/dev",s);ds(`merging ${t} into dev`,a),i=await Uv(a.tree,"origin/dev")}o?ds("syncing main back into dev",await us(i,"origin/main")):ds("merging dev into main (RC PR)",await us("origin/main",i))};var _n=async(e,t,r)=>{try{return await r()}catch(n){throw d.debug({err:Tr(n)},`Failed to ${e}`),new g(n,{operation:e,remediation:t})}},Gv=async e=>{let t=kc(e),r=await He`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},Vv=async()=>{let e=await He`gh pr list --head dev --base main --state open --json number,state,title,baseRefName,headRefName --limit 5`;return JSON.parse(e.stdout)[0]??null},XA=async e=>{let t=Ct(e),r=await Hl(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 an(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=Ao(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}},ZA=async()=>{let e=await V(),t=e.map(i=>i.branch),r=new Map(e.map(i=>[i.branch,i.type]));y.setInteractive();let n=await pe(),o=await Jt(me({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}},QA=async e=>{let{selectedReleaseBranch:t,releaseType:r,prNumber:n}=e,o=pt(r),s=await _i(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 _n(`merge release PR #${n} ${t} into ${o}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await He`gh pr merge ${n} --squash --admin --delete-branch`})},eO=async e=>{let t=re(e),r=kc(e),n=await Vv();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 _n(`retitle dev \u2192 main PR #${s} to "${r}"`,`update manually: gh pr edit ${s} --title "${r}"`,async()=>{await He`gh pr edit ${s} --title ${r}`})),s}await _n(`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 He`gh pr create --base main --head dev --title ${r} --body ""`});let o=await Vv();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},tO=async e=>{let t=re(e);if(await Gv(e)){d.info(`\u2713 RC PR for ${t} already merged into main \u2014 skipping`);return}let n=await eO(e);await _n(`merge RC PR #${n} (dev \u2192 main) for ${t}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await He`gh pr merge ${n} --squash --admin`})},rO=async()=>{He.quiet=!1,await _n("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await He`gh workflow run deploy-all.yml --ref main -f environment=prod`}),He.quiet=!0},nO=async()=>{await _n("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 He`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},oO=async e=>{try{await Xs(e)}catch(t){d.warn({err:Tr(t)},`Failed to delete local branch ${e} (non-blocking)`)}try{await Zs(e)}catch(t){d.warn({err:Tr(t)},`Failed to delete remote branch ${e} (non-blocking)`)}},sO=async e=>{let t=await Tt();if(!t){d.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let r=ce(e);await Yl({versionName:r},t)}catch(r){let n=Do(r)&&r.kind==="auth"?" \u2014 reissue the Atlassian API token and update JIRA_TOKEN":"";d.error({err:Tr(r)},`Failed to deliver Jira release (non-blocking)${n}`)}},ha=async e=>{let{version:t,confirmedCommand:r}=e;await Ne({operation:"deliver release"});let{selectedReleaseBranch:n,releaseType:o,prNumber:s}=t?await XA(t):await ZA(),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=re(i);if(y.addOption("--version",a),d.info(`Delivering ${i.kind==="name"?"named release":"version"} ${n}`),ge())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 Wv({releaseBranch:n,releaseType:o,releaseMerged:(await _i(s)).state==="MERGED",rcMerged:o!=="hotfix"&&await Gv(i)!==null}),await G(r,`Are you sure you want to deliver version ${n} to production?`),y.addOption("--yes",!0),He.quiet=!0;let l=`${await A()}${fe}`;await ls(n,{operation:`remove worktree for ${n} before merge`,remediation:`run manually: git worktree remove ${l}/${n} (use --force if uncommitted changes)`}),await QA({selectedReleaseBranch:n,releaseType:o,prNumber:s}),o!=="hotfix"&&await tO(i),await rO(),await nO(),await oO(n),He.quiet=!1,await sO(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}},dd=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:ps.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:ps.string().describe("The release branch that was delivered"),version:ps.string().describe("The version that was delivered"),type:ps.enum(["regular","hotfix"]).describe("Release type"),success:ps.boolean().describe("Whether the delivery was successful")},handler:ha});import{z as Ot}from"zod";import{$ as Cd}from"zx";import{z as gs}from"zod";import tw from"node:fs/promises";import wd from"node:path";import{DEPLOY_CONFIG_FILE as ya,deployConfigSchema as iO}from"@slip-stream-kit/config/internal";import aO from"node:fs/promises";import cO from"node:path";import{pathToFileURL as lO}from"node:url";import{z as uO}from"zod";var $r=async e=>{let t=cO.join(e,ya);try{await aO.access(t)}catch{return}let r=await import(lO(t).href);if(r.default===void 0)throw new Error(`${ya} at ${t} has no default export`);let n=iO.safeParse(r.default);if(!n.success)throw new Error(`Invalid ${ya} at ${t}:
400
- ${uO.prettifyError(n.error)}`);let o=[...pO(n.data),...dO(n.data)];if(o.length>0)throw new Error(`Invalid ${ya} at ${t}:
394
+ `);else if(y.length>0){d.info(`
395
+ \u26A0\uFE0F ${y.length} branch(es) did not merge.
396
+ `);for(let k of y)d.info(qA(k,c))}else d.info(`\u2705 All merges completed successfully!
397
+ `);h.print();let E=a||i;return ld({successfulMerges:E?0:f.filter(k=>cd.has(k.status)).length,failedMerges:E?0:y.length,failedBranches:E?[]:y.map(k=>k.branch),totalBranches:f.length,dryRun:a,atomicPush:{attempted:!a&&!i,aborted:o,abortedBy:s},results:f.map(k=>E?{...k,pushed:!1}:k),skipped:p})},ud=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:va});import{z as ms}from"zod";import{$ as He}from"zx";var Lv=(e,t)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-t).trim()},$r=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=Lv(t.stderr,500);o&&(r.stderr=o);let s=Lv(t.stdout,200);return s&&(r.stdout=s),r};var as=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 cs=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 D({status:"partial_failure",...n},1,s):new g(void 0,s)};import wa from"node:fs/promises";import{$ as pd}from"zx";var XA=new Set([".omc",".DS_Store"]),ZA=new Set(["state","sessions"]),QA=2e3,Vv="check 'git worktree list' for the path; uncommitted changes block removal",eO=e=>new Promise(t=>{setTimeout(t,e)}),dd=e=>typeof e=="object"&&e!==null?e.code:void 0,Bv=e=>{let t=e.length;for(;t>1&&e[t-1]==="/";)t-=1;return e.slice(0,t)},Uv=async e=>{try{return Bv(await wa.realpath(e))}catch{return Bv(e)}},tO=async e=>{let{projectRoot:t,worktreePath:r}=e;try{let n=await ot(t),o=await Uv(r);for(let s of n)if(await Uv(s.path)===o)return!0;return!1}catch{return!0}},rO=async e=>{let t;try{t=await wa.readdir(e)}catch(n){return{kind:dd(n)==="ENOENT"?"gone":"not-sweepable",entries:[]}}if(!t.every(n=>XA.has(n)))return{kind:"not-sweepable",entries:t};if(!t.includes(".omc"))return{kind:"sweepable",entries:t};try{return{kind:(await wa.readdir(`${e}/.omc`)).every(s=>ZA.has(s))?"sweepable":"not-sweepable",entries:t}}catch(n){return{kind:dd(n)==="ENOENT"?"sweepable":"not-sweepable",entries:t}}},Wv=async e=>{try{return await wa.rm(e,{recursive:!0,force:!0}),"removed"}catch(t){return dd(t)==="ENOTEMPTY"?"busy":"failed"}},nO=async e=>{let{worktreePath:t,sleep:r}=e,n=await Wv(t);return n!=="busy"?n==="removed":(await r(QA),await Wv(t)==="removed")},ls=(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}},oO=async e=>{let{branch:t,worktreePath:r,projectRoot:n,error:o,sleep:s}=e;if(await tO({projectRoot:n,worktreePath:r}))return ls(t,o,Vv);let i=await rO(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 nO({worktreePath:r,sleep:s})?ls(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"})},sO=async e=>{try{return(await pd`git -C ${e} status --porcelain`).stdout.split(`
398
+ `).filter(r=>r.trim().length>0)}catch{return[]}},iO=async e=>{let{branch:t,worktreeDir:r,projectRoot:n,orcaProbe:o,sleep:s}=e,i=`${r}/${t}`,a=await sO(i);if(a.length>0)return ls(t,new Error(`uncommitted changes in ${i}: ${a.slice(0,5).join(", ")}`),Vv);let c=await Mf(i,o);if(!c.closed&&"error"in c)return ls(t,c.error,"close the Orca terminals of this worktree manually (orca terminal close --terminal <handle>) and re-run");try{return await pd`git worktree remove ${i}`,{branch:t,status:"removed"}}catch(l){return oO({branch:t,worktreePath:i,projectRoot:n,error:l,sleep:s})}},Ar=async e=>{let{branches:t,worktreeDir:r,projectRoot:n,pruneFolder:o=!1,sleep:s=eO}=e,i=t.length>0?await Ut():"unreachable",a=await Promise.all(t.map(l=>iO({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 pd`git worktree prune`,c};var us=async(e,t)=>{if(!(await ke("release")).includes(e))return[];let n=await A(),o=`${n}${ge}`,{removed:s,failed:i}=await Ar({branches:[e],worktreeDir:o,projectRoot:n});if(!s.includes(e)){let a=i.find(c=>c.branch===e);throw new g(void 0,{...t,stderrExcerpt:a?.reason})}return s};import{$ as md}from"zx";var ds=async(e,t)=>{let r=await md({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))]:[]}},Gv=async(e,t)=>(await md({quiet:!0})`git commit-tree ${e} -p ${t} -m ${"infra-kit deliver preflight"}`).stdout.trim(),ps=(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`})},Jv=async e=>{let{releaseBranch:t,releaseType:r,releaseMerged:n,rcMerged:o}=e,s=`origin/${t}`;if(await md({quiet:!0})`git fetch origin main dev ${n?[]:[t]}`,r==="hotfix"){let a="origin/main";if(!n){let c=await ds("origin/main",s);ps(`merging ${t} into main`,c),a=await Gv(c.tree,"origin/main")}ps("syncing main back into dev",await ds("origin/dev",a));return}let i="origin/dev";if(!n){let a=await ds("origin/dev",s);ps(`merging ${t} into dev`,a),i=await Gv(a.tree,"origin/dev")}o?ps("syncing main back into dev",await ds(i,"origin/main")):ps("merging dev into main (RC PR)",await ds("origin/main",i))};var Mn=async(e,t,r)=>{try{return await r()}catch(n){throw d.debug({err:$r(n)},`Failed to ${e}`),new g(n,{operation:e,remediation:t})}},Hv=async e=>{let t=Sc(e),r=await He`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},Kv=async()=>{let e=await He`gh pr list --head dev --base main --state open --json number,state,title,baseRefName,headRefName --limit 5`;return JSON.parse(e.stdout)[0]??null},aO=async e=>{let t=At(e),r=await zl(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 cn(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=Oo(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}},cO=async()=>{let e=await G(),t=e.map(i=>i.branch),r=new Map(e.map(i=>[i.branch,i.type]));h.setInteractive();let n=await pe(),o=await Ht(me({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}},lO=async e=>{let{selectedReleaseBranch:t,releaseType:r,prNumber:n}=e,o=pt(r),s=await Li(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 Mn(`merge release PR #${n} ${t} into ${o}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await He`gh pr merge ${n} --squash --admin --delete-branch`})},uO=async e=>{let t=re(e),r=Sc(e),n=await Kv();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 Mn(`retitle dev \u2192 main PR #${s} to "${r}"`,`update manually: gh pr edit ${s} --title "${r}"`,async()=>{await He`gh pr edit ${s} --title ${r}`})),s}await Mn(`create RC PR (dev \u2192 main) for ${t}`,"run 'gh pr create --base main --head dev' manually to surface the underlying error (e.g. no commits between dev and main)",async()=>{await He`gh pr create --base main --head dev --title ${r} --body ""`});let o=await Kv();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},dO=async e=>{let t=re(e);if(await Hv(e)){d.info(`\u2713 RC PR for ${t} already merged into main \u2014 skipping`);return}let n=await uO(e);await Mn(`merge RC PR #${n} (dev \u2192 main) for ${t}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await He`gh pr merge ${n} --squash --admin`})},pO=async()=>{He.quiet=!1,await Mn("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await He`gh workflow run deploy-all.yml --ref main -f environment=prod`}),He.quiet=!0},mO=async()=>{await Mn("sync main back into dev","run manually: git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push",async()=>{await He`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},fO=async e=>{try{await ti(e)}catch(t){d.warn({err:$r(t)},`Failed to delete local branch ${e} (non-blocking)`)}try{await ri(e)}catch(t){d.warn({err:$r(t)},`Failed to delete remote branch ${e} (non-blocking)`)}},gO=async e=>{let t=await $t();if(!t){d.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let r=ce(e);await Zl({versionName:r},t)}catch(r){let n=Io(r)&&r.kind==="auth"?" \u2014 reissue the Atlassian API token and update JIRA_TOKEN":"";d.error({err:$r(r)},`Failed to deliver Jira release (non-blocking)${n}`)}},ka=async e=>{let{version:t,confirmedCommand:r}=e;await Ne({operation:"deliver release"});let{selectedReleaseBranch:n,releaseType:o,prNumber:s}=t?await aO(t):await cO(),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=re(i);if(h.addOption("--version",a),d.info(`Delivering ${i.kind==="name"?"named release":"version"} ${n}`),he())throw new D({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 Jv({releaseBranch:n,releaseType:o,releaseMerged:(await Li(s)).state==="MERGED",rcMerged:o!=="hotfix"&&await Hv(i)!==null}),await J(r,`Are you sure you want to deliver version ${n} to production?`),h.addOption("--yes",!0),He.quiet=!0;let l=`${await A()}${ge}`;await us(n,{operation:`remove worktree for ${n} before merge`,remediation:`run manually: git worktree remove ${l}/${n} (use --force if uncommitted changes)`}),await lO({selectedReleaseBranch:n,releaseType:o,prNumber:s}),o!=="hotfix"&&await dO(i),await pO(),await mO(),await fO(n),He.quiet=!1,await gO(i),d.info(`Successfully delivered ${n} to production!`),h.print();let u={releaseBranch:n,version:a,type:o,success:!0};return{content:b(JSON.stringify(u,null,2)),structuredContent:u}},fd=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:ms.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:ms.string().describe("The release branch that was delivered"),version:ms.string().describe("The version that was delivered"),type:ms.enum(["regular","hotfix"]).describe("Release type"),success:ms.boolean().describe("Whether the delivery was successful")},handler:ka});import{z as It}from"zod";import{$ as $d}from"zx";import{z as vs}from"zod";import ow from"node:fs/promises";import bd from"node:path";import{DEPLOY_CONFIG_FILE as ba,deployConfigSchema as hO}from"@slip-stream-kit/config/internal";import yO from"node:fs/promises";import vO from"node:path";import{pathToFileURL as wO}from"node:url";import{z as kO}from"zod";var yt=async e=>{let t=vO.join(e,ba);try{await yO.access(t)}catch{return}let r=await import(wO(t).href);if(r.default===void 0)throw new Error(`${ba} at ${t} has no default export`);let n=hO.safeParse(r.default);if(!n.success)throw new Error(`Invalid ${ba} at ${t}:
400
+ ${kO.prettifyError(n.error)}`);let o=[...RO(n.data),...bO(n.data)];if(o.length>0)throw new Error(`Invalid ${ba} at ${t}:
401
401
  ${o.join(`
402
- `)}`);return n.data},dO=e=>e.replaceV1!==!0?[]:Dc.filter(t=>!e.environments.includes(t)).map(t=>`\u2716 replaceV1: environments must include '${t}', which delivery dispatches deploy-all.yml with`),pO=e=>{let t=new Set([...e.environments,...Dc]);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 pd=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};var qv="b16ab9c88dc04a2237481f439da5e489ffda7844",Yv=`ArthurSaenz/infra-kit/.github/workflows/ik-deploy-service.yml@${qv}`,mO=`ArthurSaenz/infra-kit/.github/workflows/ik-install-deps.yml@${qv}`,wa="install-deps",Jv=25,Mn="# Generated by `infra-kit deploy-sync` from infra-kit.deploy.ts",ka="skip_terraform_deploy",zv={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"}}},Xv=(e,t)=>zv[e.replaceV1===!0?"v1":"pilot"][t],Zv=e=>Object.values(zv[e]).map(({file:t})=>`.github/workflows/${t}`),fd=Zv("pilot"),gd=Zv("v1"),va=e=>e.replace(/^_/,"").replace(/(?:-jobs)?\.ya?ml$/,""),fO=(e,t)=>Object.entries(e.services).flatMap(([r,n])=>{if(t==="all"&&n.deployAll===!1)return[];let o=e.environments.filter(s=>(n.envs?.includes(s)??!0)&&!(n.skipEnvs?.includes(s)??!1));return o.length===0?[]:[{name:r,service:n,gate:o.length===e.environments.length?void 0:o}]}),z=e=>`\${{ ${e} }}`,md=e=>z(`secrets[format('{0}_${e}', inputs.environment)]`),gO=e=>[wa,...e.terraform,...e.preDeploy],Qv=e=>e.map(t=>`(needs.${t}.result == 'success' || needs.${t}.result == 'skipped')`),hO=e=>[`needs.${wa}.result == 'success'`,...Qv(e.terraform),...e.preDeploy.map(t=>`needs.${t}.result == 'success'`)],yO=(e,t,r)=>{let n=[];return t==="selected"&&n.push(`inputs.${e.name}`),e.gate!==void 0&&n.push(`contains(fromJSON('${JSON.stringify(e.gate)}'), inputs.environment)`),n.push("!cancelled()",...hO(r)),z(n.join(" && "))},hd=e=>e.length===0?[]:[` needs: [ ${e.join(", ")} ]`],ew=e=>e===void 0?[]:[` if: ${e}`],yd=e=>[` uses: ./.github/workflows/${e}`," with:",` branch: ${z("github.ref")}`,` environment: ${z("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=z(`secrets.${i}`);return` ${i}=${a}`})];return[` uses: ${Yv}`," with:",` environment: ${z("inputs.environment")}`,` ref: ${z("github.ref")}`,` sha: ${z("github.sha")}`,` service: ${e.name}`,` infra-kit-version: ${L.version}`,...n,...o," secrets:",` aws-access-key-id: ${md("AWS_ACCESS_KEY_ID")}`,` aws-secret-access-key: ${md("AWS_SECRET_ACCESS_KEY")}`,` aws-region: ${md("AWS_REGION")}`,` serverless-access-key: ${z("secrets.SERVERLESS_ACCESS_KEY")}`,` slack-token: ${z("secrets.SLACK_TOKEN")}`,` slack-channel: ${z("secrets.SLACK_CHANNEL")}`,...s]},wO=(e,t,r,n)=>{let o=e.service.workflow===void 0?vO(e,n):yd(e.service.workflow);return["",` deploy-${e.name}:`,...hd(gO(r)),...ew(yO(e,t,r)),...o]},Kv=(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?Kv(ka,"Skip terraform deployment"):[],s=t==="all"?[]:r.flatMap(i=>{let a=i.gate===void 0?"":` (${i.gate.join(", ")} only)`;return Kv(i.name,`Deploy ${i.name}${a}`)});return["on:"," workflow_dispatch:"," inputs:",...n,...o,...s]},bO=e=>e.map(t=>z(`inputs.${t.name} && ''${t.name} '' || ''''`)).join(""),RO=(e,t,r)=>{let{title:n,concurrency:o}=Xv(e,t),s=(e.terraform??[]).length>0?z(`inputs.${ka} && '' \u2014 skip TF'' || ''''`):"",i=t==="selected"?` \u2014 ${bO(r)}`:"";return[`${Mn}: edit that file and re-run the command,`,"# a hand edit here is overwritten.",`name: '${n}'`,`run-name: '${n} [${z("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}-${z("inputs.environment")}`," # false: a cancelled run would also kill an in-flight terraform apply."," cancel-in-progress: false",""]},SO=e=>{let t=z(`!inputs.${ka}`);return["",` ${va(e)}:`,` if: ${t}`,...yd(e)]},EO=(e,t)=>{let r=t.length===0?void 0:z(["!cancelled()",...Qv(t)].join(" && "));return["",` ${va(e)}:`,...hd(t),...ew(r),...yd(e)]},PO=()=>["",` ${wa}:`,` uses: ${mO}`," with:",` ref: ${z("github.ref")}`,` sha: ${z("github.sha")}`," secrets:",` slack-token: ${z("secrets.SLACK_TOKEN")}`,` slack-channel: ${z("secrets.SLACK_CHANNEL")}`],xO=(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)}},TO=(e,t)=>[""," notify-success:",...hd(t),` if: ${z("!cancelled() && contains(needs.*.result, 'success') && !contains(needs.*.result, 'failure')")}`,` uses: ./.github/workflows/${e}`," secrets: inherit"],Hv=(e,t)=>{let r=fO(e,t),n=e.terraform??[],o=e.preDeploy??[],s={terraform:n.map(va),preDeploy:o.map(va)},{file:i}=Xv(e,t),a=1+(n.length>0?1:0)+(t==="selected"?r.length:0);if(a>Jv){let p=n.length>0?`environment, ${ka}`:"environment";throw new Error(`${i} would need ${a} dispatch inputs (${p} and one checkbox per service); GitHub allows ${Jv}. Fold services that always deploy together into one deploy script.`)}let c=r.map(p=>`deploy-${p.name}`);xO([wa,...s.terraform,...s.preDeploy,...c,...e.notifySuccess===void 0?[]:["notify-success"]],i);let u=`${[...RO(e,t,r),...kO(e,t,r),"","permissions:"," contents: read","","jobs:",...PO(),...n.flatMap(SO),...o.flatMap(p=>EO(p,s.terraform)),...r.flatMap(p=>wO(p,t,s,e)),...e.notifySuccess===void 0?[]:TO(e.notifySuccess,c)].join(`
402
+ `)}`);return n.data},bO=e=>e.replaceV1!==!0?[]:_c.filter(t=>!e.environments.includes(t)).map(t=>`\u2716 replaceV1: environments must include '${t}', which delivery dispatches deploy-all.yml with`),RO=e=>{let t=new Set([...e.environments,..._c]);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 fs=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};var Xv="b16ab9c88dc04a2237481f439da5e489ffda7844",Zv=`ArthurSaenz/infra-kit/.github/workflows/ik-deploy-service.yml@${Xv}`,SO=`ArthurSaenz/infra-kit/.github/workflows/ik-install-deps.yml@${Xv}`,Sa="install-deps",qv=25,jn="# Generated by `infra-kit deploy-sync` from infra-kit.deploy.ts",Ea="skip_terraform_deploy",Qv={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"}}},ew=(e,t)=>Qv[e.replaceV1===!0?"v1":"pilot"][t],tw=e=>Object.values(Qv[e]).map(({file:t})=>`.github/workflows/${t}`),hd=tw("pilot"),yd=tw("v1"),Ra=e=>e.replace(/^_/,"").replace(/(?:-jobs)?\.ya?ml$/,""),EO=(e,t)=>Object.entries(e.services).flatMap(([r,n])=>{if(t==="all"&&n.deployAll===!1)return[];let o=t==="all"&&Array.isArray(n.deployAll)?n.deployAll:void 0,s=e.environments.filter(i=>(n.envs?.includes(i)??!0)&&!(n.skipEnvs?.includes(i)??!1)&&(o?.includes(i)??!0));return s.length===0?[]:[{name:r,service:n,gate:s.length===e.environments.length?void 0:s}]}),z=e=>`\${{ ${e} }}`,gd=e=>z(`secrets[format('{0}_${e}', inputs.environment)]`),PO=e=>[Sa,...e.terraform,...e.preDeploy],rw=e=>e.map(t=>`(needs.${t}.result == 'success' || needs.${t}.result == 'skipped')`),xO=e=>[`needs.${Sa}.result == 'success'`,...rw(e.terraform),...e.preDeploy.map(t=>`needs.${t}.result == 'success'`)],TO=(e,t,r)=>{let n=[];return t==="selected"&&n.push(`inputs.${e.name}`),e.gate!==void 0&&n.push(`contains(fromJSON('${JSON.stringify(e.gate)}'), inputs.environment)`),n.push("!cancelled()",...xO(r)),z(n.join(" && "))},vd=e=>e.length===0?[]:[` needs: [ ${e.join(", ")} ]`],nw=e=>e===void 0?[]:[` if: ${e}`],wd=e=>[` uses: ./.github/workflows/${e}`," with:",` branch: ${z("github.ref")}`,` environment: ${z("inputs.environment")}`," secrets: inherit"],CO=(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=z(`secrets.${i}`);return` ${i}=${a}`})];return[` uses: ${Zv}`," with:",` environment: ${z("inputs.environment")}`,` ref: ${z("github.ref")}`,` sha: ${z("github.sha")}`,` service: ${e.name}`,` infra-kit-version: ${L.version}`,...n,...o," secrets:",` aws-access-key-id: ${gd("AWS_ACCESS_KEY_ID")}`,` aws-secret-access-key: ${gd("AWS_SECRET_ACCESS_KEY")}`,` aws-region: ${gd("AWS_REGION")}`,` serverless-access-key: ${z("secrets.SERVERLESS_ACCESS_KEY")}`,` slack-token: ${z("secrets.SLACK_TOKEN")}`,` slack-channel: ${z("secrets.SLACK_CHANNEL")}`,...s]},$O=(e,t,r,n)=>{let o=e.service.workflow===void 0?CO(e,n):wd(e.service.workflow);return["",` deploy-${e.name}:`,...vd(PO(r)),...nw(TO(e,t,r)),...o]},Yv=(e,t)=>["",` ${e}:`," type: boolean",` description: '${t}'`," required: false"," default: false"],AO=(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?Yv(Ea,"Skip terraform deployment"):[],s=t==="all"?[]:r.flatMap(i=>{let a=i.gate===void 0?"":` (${i.gate.join(", ")} only)`;return Yv(i.name,`Deploy ${i.name}${a}`)});return["on:"," workflow_dispatch:"," inputs:",...n,...o,...s]},OO=e=>e.map(t=>z(`inputs.${t.name} && ''${t.name} '' || ''''`)).join(""),DO=(e,t,r)=>{let{title:n,concurrency:o}=ew(e,t),s=(e.terraform??[]).length>0?z(`inputs.${Ea} && '' \u2014 skip TF'' || ''''`):"",i=t==="selected"?` \u2014 ${OO(r)}`:"";return[`${jn}: edit that file and re-run the command,`,"# a hand edit here is overwritten.",`name: '${n}'`,`run-name: '${n} [${z("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}-${z("inputs.environment")}`," # false: a cancelled run would also kill an in-flight terraform apply."," cancel-in-progress: false",""]},IO=e=>{let t=z(`!inputs.${Ea}`);return["",` ${Ra(e)}:`,` if: ${t}`,...wd(e)]},NO=(e,t)=>{let r=t.length===0?void 0:z(["!cancelled()",...rw(t)].join(" && "));return["",` ${Ra(e)}:`,...vd(t),...nw(r),...wd(e)]},_O=()=>["",` ${Sa}:`,` uses: ${SO}`," with:",` ref: ${z("github.ref")}`,` sha: ${z("github.sha")}`," secrets:",` slack-token: ${z("secrets.SLACK_TOKEN")}`,` slack-channel: ${z("secrets.SLACK_CHANNEL")}`],MO=(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)}},jO=(e,t)=>[""," notify-success:",...vd(t),` if: ${z("!cancelled() && contains(needs.*.result, 'success') && !contains(needs.*.result, 'failure')")}`,` uses: ./.github/workflows/${e}`," secrets: inherit"],zv=(e,t)=>{let r=EO(e,t),n=e.terraform??[],o=e.preDeploy??[],s={terraform:n.map(Ra),preDeploy:o.map(Ra)},{file:i}=ew(e,t),a=1+(n.length>0?1:0)+(t==="selected"?r.length:0);if(a>qv){let p=n.length>0?`environment, ${Ea}`:"environment";throw new Error(`${i} would need ${a} dispatch inputs (${p} and one checkbox per service); GitHub allows ${qv}. Fold services that always deploy together into one deploy script.`)}let c=r.map(p=>`deploy-${p.name}`);MO([Sa,...s.terraform,...s.preDeploy,...c,...e.notifySuccess===void 0?[]:["notify-success"]],i);let u=`${[...DO(e,t,r),...AO(e,t,r),"","permissions:"," contents: read","","jobs:",..._O(),...n.flatMap(IO),...o.flatMap(p=>NO(p,s.terraform)),...r.flatMap(p=>$O(p,t,s,e)),...e.notifySuccess===void 0?[]:jO(e.notifySuccess,c)].join(`
403
403
  `).replace(`jobs:
404
404
 
405
405
  `,`jobs:
406
406
  `)}
407
- `;return{path:`.github/workflows/${i}`,content:u}},vd=e=>[Hv(e,"all"),Hv(e,"selected")];var rw=".github/workflows",CO=/script_name:\s*(?<service>[a-z0-9-]+)/,$O=/uses:\s*\.\/\.github\/workflows\/_deploy-(?<service>[a-z0-9-]+)-jobs\.ya?ml/,AO=/inputs\.environment\s*==\s*'(?<env>[a-z0-9-]+)'/g,kd=async e=>{let t=wd.resolve(e,rw),r;try{r=await tw.readdir(t)}catch{return new Map}return nw(e,r.filter(n=>n.endsWith(".yml")||n.endsWith(".yaml")))},ms=async(e,t)=>nw(e,[t]),nw=async(e,t)=>{let r=wd.resolve(e,rw),n=new Map,o=!1;for(let s of t){let i;try{i=await tw.readFile(wd.resolve(r,s),"utf-8")}catch{continue}i.startsWith(Mn)?o=!0:DO(i,n)}return o&&ow(n,await OO(e)),n},OO=async e=>{try{let t=await $r(e);return t?.replaceV1===!0?pd(t):new Map}catch(t){return d.warn(`Deploy gates unavailable, nothing is refused before dispatch: ${t.message}`),new Map}},ow=(e,t)=>{for(let[r,n]of t)e.set(r,[...new Set([...e.get(r)??[],...n])])},DO=(e,t)=>{for(let r of e.split(/\n(?= {2}[\w-]+:)/i)){let n=CO.exec(r)?.groups?.service??$O.exec(r)?.groups?.service;if(n===void 0||r.trimStart().startsWith("#"))continue;let o=[...r.matchAll(AO)].map(s=>s.groups?.env??"");o.length!==0&&ow(t,new Map([[n,o]]))}},bd=(e,t)=>e===null?t??null:t===void 0?e:e.filter(r=>t.includes(r));import IO from"node:fs/promises";import NO from"node:path";import _O from"yaml";var MO=".github/workflows",jO="skip_terraform_deploy",fs=async(e,t)=>{let r=NO.resolve(e,MO,t),n;try{n=_O.parse(await IO.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!==jO).map(([i])=>i)};var sw="dev",Rd=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),iw=(e,t)=>e[t]===void 0,aw=(e,t)=>{let r=e[t];return typeof r=="string"&&r.length>0?r:void 0},Sd=async e=>{try{return await e}catch{return[]}},FO=async()=>{let e=await V();return $t(e.map(t=>t.branch))},LO=(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},Ar=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 Sd(FO());if(l.length===0)return null;let u=aw(c,"version");return gs.enum([...new Set([...l,sw])]).optional().describe(`Which release to deploy from. "${sw}" 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=Bt(await Sd(Ut(t)),await st());if(l.length===0)return null;let u=l.filter(ro),p=l.filter(f=>!ro(f)),m=aw(c,"env");return gs.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 Sd(fs(c,t));if(l.length===0)return null;let u=await ms(c,t);return gs.array(gs.enum(l)).optional().describe(`Services to deploy. Environment gates declared by ${t} \u2014 ${LO(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=>Rd(c)?r.some(l=>iw(c,l)):!1,buildRequestedSchema:async c=>{let l=Rd(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")&&iw(l,"services")){let p=await a();if(p===null)return o("services");u.services=p}return Object.keys(u).length===0?o("fields"):gs.object(u)},toArgs:(c,l)=>{let u={...Rd(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 BO from"@inquirer/select";var jn=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=>BO({message:"\u{1F9EA} Select environment",choices:e.map(n=>({name:n,value:n}))},r),{whenHeadless:"refuse"})};import UO from"@inquirer/confirm";var hs=async e=>{let{confirmedCommand:t,branch:r,env:n}=e;if(t)return!0;let o=`Deploy ${r} \u2192 ${n} via GitHub Actions?`;Z()&&ni(o,{branch:r,env:n}),y.setInteractive();let s=await _(i=>UO({message:o,default:!1},i),{whenHeadless:"refuse"});return s&&y.addOption("--yes",!0),s};import WO from"@inquirer/select";import VO from"node:process";var Ed=()=>!Z()&&VO.stdin.isTTY===!0,GO={ci:"Dispatch the GitHub workflow for a release ref",local:"Run devops/scripts/deploy-*.sh here, against your current checkout"},Pd=async()=>_(e=>WO({message:"\u{1F680} Where should this deploy run?",choices:Zt.filter(t=>t!=="local").map(t=>({name:t,value:t,description:GO[t]}))},e),{whenHeadless:"refuse"});var Zt=["ci","local"],JO={ci:["--version","--skip-terraform"],local:["--dry-run","--print-env"]},cw=e=>{if(!e){let r={operation:"resolve the deploy source",remediation:`pass --from with one of: ${Zt.join(", ")}`,stderrExcerpt:"--from is required \u2014 it decides whether this deploy runs in CI or on this machine"};throw Z()?new O({status:"argument_required",argument:"from",agentMode:j.source},2,r):new g(void 0,r)}let t=Zt.find(r=>r===e);if(!t)throw new g(void 0,{operation:"resolve the deploy source",remediation:`use one of: ${Zt.join(", ")}`,stderrExcerpt:`unknown --from value "${e}"`});return t},xd=(e,t)=>{let n=JO[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}`})},Td=async e=>e||!Ed()?cw(e):Pd();var ys=async e=>{if(e)return e==="dev"?"dev":Ct(e);y.setInteractive();let t=await V(),r=t.map(s=>s.branch),n=new Map(t.map(s=>[s.branch,s.type])),o=await pe();return Jt([{value:"dev",label:"dev"},...me({branches:r,descriptions:o,types:n})])};var lw="deploy-all.yml",uw=Ar({workflowFile:lw,fields:["version","env"],toolName:"gh-release-deploy-all"}),ba=async e=>{let{version:t,env:r,skipTerraform:n,confirmedCommand:o}=e;await it({provider:uw,params:e,operation:"launch deploy-all workflow",argument:p=>p[0]??"version"});let s=await ys(t),i=_o(s);y.addOption("--version",i);let a=await st(),c=Bt(await Ut(lw),a),l="";r?l=r:(y.setInteractive(),l=await jn(c,"launch deploy-all workflow")),y.addOption("--env",l),Gr(l,"launch deploy-all workflow",a),si({env:l,branch:s});let u=n??!1;if(u&&y.addOption("--skip-terraform",!0),!await hs({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{Cd.quiet=!0,await Cd`gh workflow run deploy-all.yml --ref ${s} -f environment=${l} ${u?["-f","skip_terraform_deploy=true"]:[]}`,Cd.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"})}},$d=C({name:"gh-release-deploy-all",formProvider:uw,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:Ot.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:Ot.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:Ot.boolean().optional().describe("Skip the terraform deployment stage."),confirm:Ot.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:Ot.string().describe("The release branch that was deployed"),version:Ot.string().describe("The version that was deployed"),environment:Ot.string().describe("The environment deployed to"),skipTerraformDeploy:Ot.boolean().describe("Whether terraform deployment was skipped"),success:Ot.boolean().describe("Whether the deployment was successful")},handler:ba});import KO from"@inquirer/checkbox";import{z as Me}from"zod";import{$ as Ad}from"zx";var Or="deploy-selected-services.yml",dw=Ar({workflowFile:Or,fields:["version","env","services"],toolName:"gh-release-deploy-selected"}),Ra=async e=>{let{version:t,env:r,services:n,skipTerraform:o,confirmedCommand:s}=e;await it({provider:dw,params:e,operation:"launch deploy-selected workflow",argument:S=>S[0]??"version"});let i=await ys(t),a=_o(i);y.addOption("--version",a);let c=await st(),l=Bt(await Ut(Or),c),u="";r?u=r:(y.setInteractive(),u=await jn(l,"launch deploy-selected workflow")),y.addOption("--env",u),Gr(u,"launch deploy-selected workflow",c),si({env:u,branch:i});let p=await A(),m=await fs(p,Or);if(m.length===0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${Or}`,stderrExcerpt:`no services found in .github/workflows/${Or}`});let f=[];if(n&&n.length>0?f=n:(y.setInteractive(),f=await _(S=>KO({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:m.map(P=>({name:P,value:P}))},S),{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 v=f.filter(S=>!m.includes(S));if(v.length>0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${m.join(", ")}`,stderrExcerpt:`invalid services: ${v.join(", ")}`});let E=await ms(p,Or),k=f.filter(S=>{let P=E.get(S);return P!==void 0&&!P.includes(u)});if(k.length>0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:k.map(S=>`${S} deploys only to: ${(E.get(S)??[]).join(", ")}`).join("; "),stderrExcerpt:`${Or} gates these services out of ${u}: ${k.join(", ")}`});let h=o??!1;h&&y.addOption("--skip-terraform",!0);let R=S=>{let P={releaseBranch:i,version:a,environment:u,services:f,skipTerraformDeploy:h,success:S};return{content:b(JSON.stringify(P,null,2)),structuredContent:P}};if(!await hs({confirmedCommand:s,branch:i,env:u}))return d.info("Deployment cancelled"),R(!1);try{Ad.quiet=!0;let S=f.flatMap(M=>["-f",`${M}=true`]);return await Ad`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${u} ${S} ${h?["-f","skip_terraform_deploy=true"]:[]}`,Ad.quiet=!1,d.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${u}, services: ${f.join(", ")}`),y.print(),R(!0)}catch(S){throw d.error({error:S},"\u274C Error launching workflow"),new g(S,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},Od=C({name:"gh-release-deploy-selected",requiresHumanConfirm:!0,formProvider:dw,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:Me.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:Me.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:Me.array(Me.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:Me.boolean().optional().describe("Skip the terraform deployment stage."),confirm:Me.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:Me.string().describe("The release branch that was deployed"),version:Me.string().describe("The version that was deployed"),environment:Me.string().describe("The environment deployed to"),services:Me.array(Me.string()).describe("The services that were deployed"),skipTerraformDeploy:Me.boolean().describe("Whether terraform deployment was skipped"),success:Me.boolean().describe("Whether the deployment was successful")},handler:Ra});import{z as Qt}from"zod";var Sa=async()=>{let t=(await V()).flatMap(i=>{let a=Q(i.branch);return a?[{version:re(a),jiraKey:ce(a),type:i.type,titleMismatch:i.titleMismatch}]:[]}),r=await ji(),n=Math.max(...t.map(i=>i.version.length)),o=t.map(i=>{let a=No(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:
407
+ `;return{path:`.github/workflows/${i}`,content:u}},kd=e=>[zv(e,"all"),zv(e,"selected")];var sw=".github/workflows",FO=/script_name:\s*(?<service>[a-z0-9-]+)/,LO=/uses:\s*\.\/\.github\/workflows\/_deploy-(?<service>[a-z0-9-]+)-jobs\.ya?ml/,BO=/inputs\.environment\s*==\s*'(?<env>[a-z0-9-]+)'/g,Rd=async e=>{let t=bd.resolve(e,sw),r;try{r=await ow.readdir(t)}catch{return new Map}return iw(e,r.filter(n=>n.endsWith(".yml")||n.endsWith(".yaml")))},gs=async(e,t)=>iw(e,[t]),iw=async(e,t)=>{let r=bd.resolve(e,sw),n=new Map,o=!1;for(let s of t){let i;try{i=await ow.readFile(bd.resolve(r,s),"utf-8")}catch{continue}i.startsWith(jn)?o=!0:WO(i,n)}return o&&aw(n,await UO(e)),n},UO=async e=>{try{let t=await yt(e);return t?.replaceV1===!0?fs(t):new Map}catch(t){return d.warn(`Deploy gates unavailable, nothing is refused before dispatch: ${t.message}`),new Map}},aw=(e,t)=>{for(let[r,n]of t)e.set(r,[...new Set([...e.get(r)??[],...n])])},WO=(e,t)=>{for(let r of e.split(/\n(?= {2}[\w-]+:)/i)){let n=FO.exec(r)?.groups?.service??LO.exec(r)?.groups?.service;if(n===void 0||r.trimStart().startsWith("#"))continue;let o=[...r.matchAll(BO)].map(s=>s.groups?.env??"");o.length!==0&&aw(t,new Map([[n,o]]))}},hs=(e,t)=>e===null?t??null:t===void 0?e:e.filter(r=>t.includes(r));import VO from"node:fs/promises";import GO from"node:path";import JO from"yaml";var KO=".github/workflows",HO="skip_terraform_deploy",ys=async(e,t)=>{let r=GO.resolve(e,KO,t),n;try{n=JO.parse(await VO.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!==HO).map(([i])=>i)};var cw="dev",Sd=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),lw=(e,t)=>e[t]===void 0,uw=(e,t)=>{let r=e[t];return typeof r=="string"&&r.length>0?r:void 0},Ed=async e=>{try{return await e}catch{return[]}},qO=async()=>{let e=await G();return Ot(e.map(t=>t.branch))},YO=(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},Or=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 Ed(qO());if(l.length===0)return null;let u=uw(c,"version");return vs.enum([...new Set([...l,cw])]).optional().describe(`Which release to deploy from. "${cw}" 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=Wt(await Ed(Vt(t)),await st());if(l.length===0)return null;let u=l.filter(no),p=l.filter(f=>!no(f)),m=uw(c,"env");return vs.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 Ed(ys(c,t));if(l.length===0)return null;let u=await gs(c,t);return vs.array(vs.enum(l)).optional().describe(`Services to deploy. Environment gates declared by ${t} \u2014 ${YO(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=>Sd(c)?r.some(l=>lw(c,l)):!1,buildRequestedSchema:async c=>{let l=Sd(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")&&lw(l,"services")){let p=await a();if(p===null)return o("services");u.services=p}return Object.keys(u).length===0?o("fields"):vs.object(u)},toArgs:(c,l)=>{let u={...Sd(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 zO from"@inquirer/select";var Fn=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=>zO({message:"\u{1F9EA} Select environment",choices:e.map(n=>({name:n,value:n}))},r),{whenHeadless:"refuse"})};import XO from"@inquirer/confirm";var ws=async e=>{let{confirmedCommand:t,branch:r,env:n}=e;if(t)return!0;let o=`Deploy ${r} \u2192 ${n} via GitHub Actions?`;Z()&&ai(o,{branch:r,env:n}),h.setInteractive();let s=await M(i=>XO({message:o,default:!1},i),{whenHeadless:"refuse"});return s&&h.addOption("--yes",!0),s};import ZO from"@inquirer/select";import QO from"node:process";var Pd=()=>!Z()&&QO.stdin.isTTY===!0,eD={ci:"Dispatch the GitHub workflow for a release ref",local:"Run devops/scripts/deploy-*.sh here, against your current checkout"},xd=async()=>M(e=>ZO({message:"\u{1F680} Where should this deploy run?",choices:er.filter(t=>t!=="local").map(t=>({name:t,value:t,description:eD[t]}))},e),{whenHeadless:"refuse"});var er=["ci","local"],tD={ci:["--version","--skip-terraform"],local:["--dry-run","--print-env"]},dw=e=>{if(!e){let r={operation:"resolve the deploy source",remediation:`pass --from with one of: ${er.join(", ")}`,stderrExcerpt:"--from is required \u2014 it decides whether this deploy runs in CI or on this machine"};throw Z()?new D({status:"argument_required",argument:"from",agentMode:j.source},2,r):new g(void 0,r)}let t=er.find(r=>r===e);if(!t)throw new g(void 0,{operation:"resolve the deploy source",remediation:`use one of: ${er.join(", ")}`,stderrExcerpt:`unknown --from value "${e}"`});return t},Td=(e,t)=>{let n=tD[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}`})},Cd=async e=>e||!Pd()?dw(e):xd();var ks=async e=>{if(e)return e==="dev"?"dev":At(e);h.setInteractive();let t=await G(),r=t.map(s=>s.branch),n=new Map(t.map(s=>[s.branch,s.type])),o=await pe();return Ht([{value:"dev",label:"dev"},...me({branches:r,descriptions:o,types:n})])};var pw="deploy-all.yml",mw=Or({workflowFile:pw,fields:["version","env"],toolName:"gh-release-deploy-all"}),Pa=async e=>{let{version:t,env:r,skipTerraform:n,confirmedCommand:o}=e;await it({provider:mw,params:e,operation:"launch deploy-all workflow",argument:p=>p[0]??"version"});let s=await ks(t),i=Mo(s);h.addOption("--version",i);let a=await st(),c=Wt(await Vt(pw),a),l="";r?l=r:(h.setInteractive(),l=await Fn(c,"launch deploy-all workflow")),h.addOption("--env",l),Jr(l,"launch deploy-all workflow",a),li({env:l,branch:s});let u=n??!1;if(u&&h.addOption("--skip-terraform",!0),!await ws({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{$d.quiet=!0,await $d`gh workflow run deploy-all.yml --ref ${s} -f environment=${l} ${u?["-f","skip_terraform_deploy=true"]:[]}`,$d.quiet=!1,d.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${s} and environment: ${l}`),h.print();let m={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:u,success:!0};return{content: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"})}},Ad=C({name:"gh-release-deploy-all",formProvider:mw,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:It.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:It.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:It.boolean().optional().describe("Skip the terraform deployment stage."),confirm:It.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:It.string().describe("The release branch that was deployed"),version:It.string().describe("The version that was deployed"),environment:It.string().describe("The environment deployed to"),skipTerraformDeploy:It.boolean().describe("Whether terraform deployment was skipped"),success:It.boolean().describe("Whether the deployment was successful")},handler:Pa});import rD from"@inquirer/checkbox";import{z as Me}from"zod";import{$ as Od}from"zx";var Dr="deploy-selected-services.yml",fw=Or({workflowFile:Dr,fields:["version","env","services"],toolName:"gh-release-deploy-selected"}),xa=async e=>{let{version:t,env:r,services:n,skipTerraform:o,confirmedCommand:s}=e;await it({provider:fw,params:e,operation:"launch deploy-selected workflow",argument:S=>S[0]??"version"});let i=await ks(t),a=Mo(i);h.addOption("--version",a);let c=await st(),l=Wt(await Vt(Dr),c),u="";r?u=r:(h.setInteractive(),u=await Fn(l,"launch deploy-selected workflow")),h.addOption("--env",u),Jr(u,"launch deploy-selected workflow",c),li({env:u,branch:i});let p=await A(),m=await ys(p,Dr);if(m.length===0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${Dr}`,stderrExcerpt:`no services found in .github/workflows/${Dr}`});let f=[];if(n&&n.length>0?f=n:(h.setInteractive(),f=await M(S=>rD({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:m.map(R=>({name:R,value:R}))},S),{whenHeadless:"refuse"})),h.addOption("--services",f),f.length===0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${m.join(", ")}`,stderrExcerpt:"no services selected"});let y=f.filter(S=>!m.includes(S));if(y.length>0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${m.join(", ")}`,stderrExcerpt:`invalid services: ${y.join(", ")}`});let E=await gs(p,Dr),k=f.filter(S=>{let R=E.get(S);return R!==void 0&&!R.includes(u)});if(k.length>0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:k.map(S=>`${S} deploys only to: ${(E.get(S)??[]).join(", ")}`).join("; "),stderrExcerpt:`${Dr} gates these services out of ${u}: ${k.join(", ")}`});let O=o??!1;O&&h.addOption("--skip-terraform",!0);let v=S=>{let R={releaseBranch:i,version:a,environment:u,services:f,skipTerraformDeploy:O,success:S};return{content:b(JSON.stringify(R,null,2)),structuredContent:R}};if(!await ws({confirmedCommand:s,branch:i,env:u}))return d.info("Deployment cancelled"),v(!1);try{Od.quiet=!0;let S=f.flatMap($=>["-f",`${$}=true`]);return await Od`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${u} ${S} ${O?["-f","skip_terraform_deploy=true"]:[]}`,Od.quiet=!1,d.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${u}, services: ${f.join(", ")}`),h.print(),v(!0)}catch(S){throw d.error({error:S},"\u274C Error launching workflow"),new g(S,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},Dd=C({name:"gh-release-deploy-selected",requiresHumanConfirm:!0,formProvider:fw,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:Me.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:Me.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:Me.array(Me.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:Me.boolean().optional().describe("Skip the terraform deployment stage."),confirm:Me.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:Me.string().describe("The release branch that was deployed"),version:Me.string().describe("The version that was deployed"),environment:Me.string().describe("The environment deployed to"),services:Me.array(Me.string()).describe("The services that were deployed"),skipTerraformDeploy:Me.boolean().describe("Whether terraform deployment was skipped"),success:Me.boolean().describe("Whether the deployment was successful")},handler:xa});import{z as tr}from"zod";var Ta=async()=>{let t=(await G()).flatMap(i=>{let a=Q(i.branch);return a?[{version:re(a),jiraKey:ce(a),type:i.type,titleMismatch:i.titleMismatch}]:[]}),r=await Ui(),n=Math.max(...t.map(i=>i.version.length)),o=t.map(i=>{let a=_o(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
408
  `),d.info(`
409
409
  ${o.join(`
410
410
  `)}
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}},Dd=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:Qt.array(Qt.object({version:Qt.string().describe("Release version"),type:Qt.enum(["regular","hotfix"]).describe("Release type"),description:Qt.string().nullable().describe("Jira version description"),releaseDate:Qt.string().nullable().describe("Planned release date of the Jira version (yyyy-mm-dd)"),titleMismatch:Qt.boolean().describe("The PR title names a different release type than its base branch")})).describe("List of all release branches"),count:Qt.number().describe("Number of release branches")},handler:Sa});import HO from"node:process";var vs="local-deploy";var Id=e=>({...e}),Nd=e=>{let{env:t,branch:r,sha:n,isClean:o,ambient:s=HO.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:vs},contract:i,stripped:c}},Ea=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 aD from"@inquirer/checkbox";import cD from"@inquirer/confirm";import lD from"@inquirer/select";import{spawn as uD}from"node:child_process";import dD from"node:process";import{z as te}from"zod";import{$ as ks}from"zx";import{$ as ws}from"zx";var qO=async e=>{let t=ws.quiet;ws.quiet=!0;try{let r=`/${e}/environment`,n=await ws`aws sts get-caller-identity --query Account --output text`,o=await ws`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{ws.quiet=t}},pw=(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`})},mw=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"})},fw=(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`})},_d=async e=>{let{env:t,project:r,isShared:n,isClean:o,runningEnvs:s,protectedEnvAccess:i}=e;Gr(t,`deploy to "${t}"`,i),fw(t,s),mw({env:t,isShared:n,isClean:o});let a=await qO(r);return pw(t,a),{identity:a}};import gw from"node:fs/promises";import Pa from"node:path";var YO="devops/scripts",zO=/^deploy-(?<service>[a-z0-9-]+)\.sh$/,XO=/skip_unless_env_enabled\s+"[^"]*"\s+"[^"]*"\s+"(?<envs>[^"]*)"/,ZO=/aws\s+ssm\s+get-parameter\s+--name[=\s]+(?<arg>[^\s)]+)/,QO=/aws\s+ssm\s+get-parameter\s+--name[=\s]+["']?\/(?<prefix>[\w.-]+)\/environment["']?(?![\w./-])/,Md=async e=>{let t=Pa.resolve(e,YO),r;try{r=await gw.readdir(t)}catch{return[]}let n=await kd(e);return(await Promise.all(r.map(s=>({entry:s,match:zO.exec(s)})).filter(s=>s.match!==null).map(async({entry:s,match:i})=>{let a=Pa.resolve(t,s),c=i?.groups?.service??"",l=tD(await eD(a));return{name:c,scriptPath:a,allowedEnvs:bd(rD(l),n.get(c)),ssmPrefix:oD(l)}}))).sort((s,i)=>s.name.localeCompare(i.name))},eD=async e=>{try{return await gw.readFile(e,"utf-8")}catch{return""}},tD=e=>e.split(`
413
- `).map((t,r)=>({line:r+1,text:t})).filter(({text:t})=>!t.trimStart().startsWith("#")),rD=e=>{let t=e.reduce((n,{text:o})=>n??XO.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},nD=e=>{let t=e.replaceAll(/["']/g,"");return t.includes("$")&&(t.includes("/environment")||t.startsWith("$"))},oD=e=>{for(let{line:t,text:r}of e){let n=QO.exec(r)?.groups?.prefix;if(n!==void 0)return n;let o=ZO.exec(r)?.groups?.arg;if(o!==void 0&&nD(o))return{unparseable:{line:t,text:r.trim()}}}return null},sD=e=>{let t=new Map;for(let r of e)typeof r.ssmPrefix=="string"&&t.set(r.ssmPrefix,[...t.get(r.ssmPrefix)??[],Pa.basename(r.scriptPath)]);return t},iD=e=>{let t=e.flatMap(r=>{if(r.ssmPrefix===null||typeof r.ssmPrefix=="string")return[];let{line:n,text:o}=r.ssmPrefix.unparseable;return[`${Pa.basename(r.scriptPath)}:${n}: ${o}`]});if(t.length!==0)throw new g(void 0,{operation:"resolve the SSM project prefix",remediation:"write the parameter name as a literal `/<project>/environment` so infra-kit can preflight it",stderrExcerpt:t.join("; ")})},hw=e=>{iD(e);let t=sD(e),[r,...n]=t.keys();if(r===void 0)throw new g(void 0,{operation:"resolve the SSM project prefix",remediation:'add `aws ssm get-parameter --name "/<project>/environment"` to at least one devops/scripts/deploy-*.sh',stderrExcerpt:`none of ${e.length} deploy scripts reads /<project>/environment`});if(n.length>0){let o=[...t.entries()].sort(([,s],[,i])=>s.length-i.length).map(([s,i])=>`${s}: ${i.join(", ")}`).join("; ");throw new g(void 0,{operation:"resolve the SSM project prefix",remediation:"make every deploy script read the same /<project>/environment parameter",stderrExcerpt:`${t.size} different prefixes across ${e.length} deploy scripts \u2014 ${o}`})}return r},xa=(e,t)=>e.allowedEnvs===null||e.allowedEnvs.includes(t),jd=(e,t)=>e.filter(r=>xa(r,t));var Ld="deploy-all.yml",vw="/bin/sh",pD=async()=>{let e=ks.quiet;ks.quiet=!0;try{let t=await ks`gh run list --workflow=${Ld} --status=in_progress --json displayTitle`;return JSON.parse(t.stdout).flatMap(n=>/\[(?<env>[a-z0-9-]+)\]/.exec(n.displayTitle??"")?.groups?.env??[])}catch{return[]}finally{ks.quiet=e}},mD=async(e,t)=>{let r=e.map(o=>({name:o.name,value:o.name})),n=await _(o=>aD({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},fD=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 Z()&&ni(i,{env:t,services:n,accountId:o,shared:r}),r?_(a=>lD({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"})},gD=(e,t,r)=>new Promise((n,o)=>{let s=uD(vw,[e.scriptPath],{cwd:r,env:t,stdio:"inherit"});s.on("error",o),s.on("close",i=>{n(i??1)})}),hD=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 gD(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}},yD=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&&!xa(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))},Fd=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:Id(o.contract),strippedVars:o.stripped,dryRun:a,success:c};return{content:b(JSON.stringify(l,null,2)),structuredContent:l}},vD=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(),mD(r,o))},ww=async(e,t)=>{let{env:r,service:n,confirmedCommand:o,dryRun:s,printEnv:i}=e,a=await A(),c=await Md(a);if(c.length===0)throw new g(void 0,{operation:"discover deployable services",remediation:"run this from a repo that has devops/scripts/deploy-*.sh",stderrExcerpt:`no deploy scripts found under ${a}/devops/scripts`});let l=hw(c);await it({provider:Bd[t],params:e,operation:"deploy locally",argument:"env"});let u=await st(),p=Bt(await Ut(Ld),u),m=r??"";m||(y.setInteractive(),m=await jn(p,"deploy locally")),y.addOption("--env",m);let f=jd(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 v=await vD({selection:t,eligible:f,service:n,env:m}),E=yD({names:v,services:c,env:m});if(t==="selected")for(let Ce of v)y.addOption("--service",Ce);let k=ro(m),h=await Ur(),R=(await ks`git rev-parse HEAD`.quiet()).stdout.trim(),S=await Qm(),P=Nd({env:m,branch:h,sha:R,isClean:S});i&&d.info(`Deploy contract for ${m}:
414
- ${Ea(P)}`);let $=(await _d({env:m,project:l,isShared:k,isClean:S,runningEnvs:await pD(),protectedEnvAccess:u})).identity.accountId;if(s)return d.info([`Would deploy to "${m}" (AWS account ${$}) from this machine`,`Preflight parameter: /${l}/environment`,Ea(P),"Commands:",...E.map(Ce=>` ${vw} ${Ce.scriptPath}`),"","Dry run: preflight and contract only \u2014 says nothing about whether the deploy would succeed."].join(`
415
- `)),Fd({env:m,accountId:$,names:v,built:P,deployed:[],failed:[],dryRun:!0,success:!0});if(!o&&!await fD({env:m,isShared:k,names:v,accountId:$}))return d.info("Deployment cancelled"),Fd({env:m,accountId:$,names:v,built:P,deployed:[],failed:[],dryRun:!1,success:!1});P.stripped.length>0&&d.info(`Stripped ambient VITE_* from the build env: ${P.stripped.join(", ")}`);let{deployed:J,failed:K}=await hD({chosen:E,childEnv:P.childEnv,cwd:a,env:m});return K.length>0&&(d.error(`Partial deploy to "${m}": succeeded [${J.join(", ")||"none"}], failed [${K.join(", ")}]. There is no rollback \u2014 redeploy the previous commit to restore it.`),dD.exitCode=1),y.print(),Fd({env:m,accountId:$,names:v,built:P,deployed:J,failed:K,dryRun:!1,success:K.length===0})},kw=async e=>ww(e,"all"),bw=async e=>ww(e,"selected"),Rw='Runs the repo\'s own devops/scripts/deploy-*.sh on THIS machine instead of dispatching CI. Supplies the build contract (VITE_DOMAIN_ENV/BRANCH/COMMIT) that the workflow YAML normally provides and that the scripts do not set themselves, and refuses unless the requested environment matches the AWS account the shell is authenticated to. "prod" is refused by default \u2014 it is delivered, not deployed \u2014 and is reachable only if this project sets `protectedEnvs` in infra-kit.json; "cli-only" allows it in a terminal but still refuses it here. Services the environment forbids are refused, matching the workflow\'s own per-service gates. Use dryRun first.',Sw={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.")},Ew={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")},yw=e=>Ar({workflowFile:Ld,fields:["env"],toolName:e}),Bd={all:yw("local-deploy-all"),selected:yw("local-deploy-selected")},Ud=C({name:"local-deploy-all",description:`Deploy EVERY service enabled for an environment, from this machine. ${Rw}`,requiresHumanConfirm:!0,formProvider:Bd.all,inputSchema:Sw,outputSchema:Ew,handler:kw}),Wd=C({name:"local-deploy-selected",description:`Deploy a NAMED SUBSET of services from this machine. ${Rw}`,requiresHumanConfirm:!0,formProvider:Bd.selected,inputSchema:{...Sw,service:te.array(te.string()).min(1).describe('Service names as in devops/scripts/deploy-<name>.sh, e.g. ["client-be"]. Required for MCP.')},outputSchema:Ew,handler:bw});import bD from"@inquirer/confirm";import Ta from"@inquirer/input";import Cw from"@inquirer/select";import Gd from"node:process";import{z as q}from"zod";import{z as bs}from"zod";var Fn=async(e,t)=>new Promise(r=>{let n=setTimeout(()=>{r(null)},t);e.then(o=>{clearTimeout(n),r(o)},()=>{clearTimeout(n),r(null)})});var Tw=2500,Pw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),xw=e=>typeof e=="string"&&e.trim()!==""?e.trim():void 0,wD=async()=>{let e=await Xo();return{regular:In(e,"regular"),hotfix:In(e,"hotfix")}},kD=(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).`,Vd=(e={})=>{let t=e.hintBudgetMs??Tw;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=>Pw(r)&&(r.releases===void 0||Array.isArray(r.releases)&&r.releases.length===0),buildRequestedSchema:async()=>{let r=await Fn(wD(),t);return bs.object({type:bs.enum(["regular","hotfix"]).describe('Release type. "regular" branches off dev and bumps the minor; "hotfix" branches off main and bumps the patch.'),release:bs.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. ${kD(r,t)}`),description:bs.string().optional().describe("Optional. Becomes the Jira fix version description and feeds the PR body. Blank means none."),releaseDate:bs.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=xw(r.description),a=xw(r.releaseDate),c=oa(o);return{...Pw(n)?n:{},releases:[{...c,type:s,...i===void 0?{}:{description:i},...a===void 0?{}:{releaseDate:a}}]}}}};var RD='"1.2.5" or "next"',Jd=(e,t)=>{try{return Fu(e,t)}catch(r){throw r instanceof Rr?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 Ym?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}},SD=async(e,t)=>{let r=In(e,t),n=r?` [${r}]`:"",o=(await _(i=>Ta({message:` Version (e.g. ${RD})${n}: `},i),{whenHeadless:"refuse"})).trim(),s=o===""?r??"":o;return s===""&&(d.error("No version provided. Exiting..."),Gd.exit(1)),s},ED=async()=>{let e=(await _(t=>Ta({message:' Name (kebab-case, e.g. "checkout-redesign"): '},t),{whenHeadless:"refuse"})).trim();e===""&&(d.error("No name provided. Exiting..."),Gd.exit(1));try{zs(e)}catch(t){let r=t instanceof Error?t.message:String(t);d.error(`${r} Exiting...`),Gd.exit(1)}return e},PD=async()=>(await _(e=>Ta({message:" Release date (yyyy-mm-dd, optional, press Enter to skip): ",validate:zo},e),{whenHeadless:"refuse"})).trim(),xD=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=>Cw({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=>Cw({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 ED();l=Jd([{name:m,type:c}],[])[0]}else{let m=await SD(await n(),c);l=Jd([{version:m,type:c}],r)[0],l.id.kind==="version"&&r.push(Yt(`v${l.id.raw}`))}let u=(await _(m=>Ta({message:" Description (optional, press Enter to skip): "},m),{whenHeadless:"refuse"})).trim(),p=await PD();o.push({...l,...u!==""?{description:u}:{},...p!==""?{releaseDate:p}:{}}),s=await _(m=>bD({message:"Add another release?",default:!1},m),{whenHeadless:"refuse"})}return o},TD=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 ")},$w=e=>{for(let t of e)y.addOption("--release",ju(t))},CD=async(e,t)=>{if(e&&e.length>0){let n=Lu(e)?await t():[],o=Jd(e,n);return $w(o),o}if(ge())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 xD(t);return $w(r),r},$D=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"})},AD=async(e,t)=>{let r=e.map(TD).join(`
416
- - `);await G(t,`Create the following ${e.length} release(s)?
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}},Id=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:tr.array(tr.object({version:tr.string().describe("Release version"),type:tr.enum(["regular","hotfix"]).describe("Release type"),description:tr.string().nullable().describe("Jira version description"),releaseDate:tr.string().nullable().describe("Planned release date of the Jira version (yyyy-mm-dd)"),titleMismatch:tr.boolean().describe("The PR title names a different release type than its base branch")})).describe("List of all release branches"),count:tr.number().describe("Number of release branches")},handler:Ta});import nD from"node:process";var bs="local-deploy";var Nd=e=>({...e}),_d=e=>{let{env:t,branch:r,sha:n,isClean:o,ambient:s=nD.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:bs},contract:i,stripped:c}},Ca=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 wD from"@inquirer/checkbox";import kD from"@inquirer/confirm";import bD from"@inquirer/select";import{spawn as RD}from"node:child_process";import Ud from"node:process";import{z as te}from"zod";import{$ as Es}from"zx";import{$ as Rs}from"zx";var oD=async e=>{let t=Rs.quiet;Rs.quiet=!0;try{let r=`/${e}/environment`,n=await Rs`aws sts get-caller-identity --query Account --output text`,o=await Rs`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{Rs.quiet=t}},gw=(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`})},hw=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"})},yw=(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`})},Md=async e=>{let{env:t,project:r,isShared:n,isClean:o,runningEnvs:s,protectedEnvAccess:i}=e;Jr(t,`deploy to "${t}"`,i),yw(t,s),hw({env:t,isShared:n,isClean:o});let a=await oD(r);return gw(t,a),{identity:a}};import jd from"node:fs/promises";import Ss from"node:path";var kw="devops/scripts",sD=/^deploy-(?<service>[a-z0-9-]+)\.sh$/,iD=/skip_unless_env_enabled\s+"[^"]*"\s+"[^"]*"\s+"(?<envs>[^"]*)"/,aD=/aws\s+ssm\s+get-parameter\s+--name[=\s]+(?<arg>[^\s)]+)/,cD=/aws\s+ssm\s+get-parameter\s+--name[=\s]+["']?\/(?<prefix>[\w.-]+)\/environment["']?(?![\w./-])/,lD=/(["'`])\/(?<prefix>[\w.-]+)\/environment\1/,uD=/`[^`]*\$\{[^`]*\/environment[^`]*`/,vw={commentPrefixes:["#"],literalPrefix:e=>cD.exec(e)?.groups?.prefix,isUnparseable:e=>{let t=aD.exec(e)?.groups?.arg;return t!==void 0&&gD(t)}},ww={commentPrefixes:["//","/*","*"],literalPrefix:e=>lD.exec(e)?.groups?.prefix,isUnparseable:e=>uD.test(e)},Fd=async e=>{let t=await yt(e),r=await Rd(e);return(t===void 0?await dD(e,r):await pD(e,t,r)).sort((o,s)=>o.name.localeCompare(s.name))},dD=async(e,t)=>{let r=Ss.resolve(e,kw),n;try{n=await jd.readdir(r)}catch{return[]}return Promise.all(n.flatMap(o=>{let s=sD.exec(o)?.groups?.service;return s===void 0?[]:[bw(s,Ss.resolve(r,o),t)]}))},bw=async(e,t,r)=>{let n=Sw(await Rw(t),vw);return{name:e,scriptPath:t,runner:"sh",allowedEnvs:hs(fD(n),r.get(e)),ssmPrefix:Ew(n,vw)}},pD=async(e,t,r)=>{let n=fs(t);return(await Promise.all(Object.entries(t.services).map(async([s,i])=>{if(i.deploy===void 0){let l=Ss.resolve(e,kw,`deploy-${s}.sh`);if(!await mD(l))return null;let u=await bw(s,l,r);return{...u,allowedEnvs:hs(u.allowedEnvs,n.get(s))}}let a=Ss.resolve(e,i.deploy),c=Sw(await Rw(a),ww);return{name:s,scriptPath:a,runner:"deploy-run",allowedEnvs:hs(n.get(s)??null,r.get(s)),ssmPrefix:Ew(c,ww)}}))).filter(s=>s!==null)},mD=async e=>{try{return await jd.access(e),!0}catch{return!1}},Rw=async e=>{try{return await jd.readFile(e,"utf-8")}catch{return""}},Sw=(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))}),fD=e=>{let t=e.reduce((n,{text:o})=>n??iD.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},gD=e=>{let t=e.replaceAll(/["']/g,"");return t.includes("$")&&(t.includes("/environment")||t.startsWith("$"))},Ew=(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},Pw=e=>{let t=Ss.basename(e.scriptPath);return e.runner==="sh"?t:`${e.name} (${t})`},hD=e=>{let t=new Map;for(let r of e)typeof r.ssmPrefix=="string"&&t.set(r.ssmPrefix,[...t.get(r.ssmPrefix)??[],Pw(r)]);return t},yD=e=>{let t=e.flatMap(r=>{if(r.ssmPrefix===null||typeof r.ssmPrefix=="string")return[];let{line:n,text:o}=r.ssmPrefix.unparseable;return[`${Pw(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("; ")})},vD=e=>{yD(e);let t=hD(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},xw=async(e,t)=>(await yt(e))?.project??vD(t),$a=(e,t)=>e.allowedEnvs===null||e.allowedEnvs.includes(t),Ld=(e,t)=>e.filter(r=>$a(r,t));var Wd="deploy-all.yml",SD="/bin/sh",ED=async()=>{let e=Es.quiet;Es.quiet=!0;try{let t=await Es`gh run list --workflow=${Wd} --status=in_progress --json displayTitle`;return JSON.parse(t.stdout).flatMap(n=>/\[(?<env>[a-z0-9-]+)\]/.exec(n.displayTitle??"")?.groups?.env??[])}catch{return[]}finally{Es.quiet=e}},PD=async(e,t)=>{let r=e.map(o=>({name:o.name,value:o.name})),n=await M(o=>wD({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},xD=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 Z()&&ai(i,{env:t,services:n,accountId:o,shared:r}),r?M(a=>bD({message:i,choices:[{name:"No, cancel",value:!1},{name:`Yes, deploy to ${t}`,value:!0}]},a),{whenHeadless:"refuse"}):M(a=>kD({message:i,default:!1},a),{whenHeadless:"refuse"})},Cw=e=>e.runner==="sh"?[SD,[e.scriptPath]]:[Ud.execPath,[Ud.argv[1]??"","deploy-run",e.name]],TD=(e,t,r)=>new Promise((n,o)=>{let[s,i]=Cw(e),a=RD(s,i,{cwd:r,env:t,stdio:"inherit"});a.on("error",o),a.on("close",c=>{n(c??1)})}),CD=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 TD(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}},$D=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&&!$a(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))},Bd=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:Nd(o.contract),strippedVars:o.stripped,dryRun:a,success:c};return{content:b(JSON.stringify(l,null,2)),structuredContent:l}},AD=async e=>{let{selection:t,eligible:r,service:n,env:o}=e;return t==="all"?r.map(s=>s.name):n&&n.length>0?n:(h.setInteractive(),PD(r,o))},$w=async(e,t)=>{let{env:r,service:n,confirmedCommand:o,dryRun:s,printEnv:i}=e,a=await A(),c=await Fd(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 xw(a,c);await it({provider:Vd[t],params:e,operation:"deploy locally",argument:"env"});let u=await st(),p=Wt(await Vt(Wd),u),m=r??"";m||(h.setInteractive(),m=await Fn(p,"deploy locally")),h.addOption("--env",m);let f=Ld(c,m);if(f.length===0)throw new g(void 0,{operation:`deploy to "${m}"`,remediation:"pick an environment these services allow",stderrExcerpt:`no service on disk is enabled for "${m}"`});let y=await AD({selection:t,eligible:f,service:n,env:m}),E=$D({names:y,services:c,env:m});if(t==="selected")for(let H of y)h.addOption("--service",H);let k=no(m),O=await Wr(),v=(await Es`git rev-parse HEAD`.quiet()).stdout.trim(),S=await rf(),R=_d({env:m,branch:O,sha:v,isClean:S});i&&d.info(`Deploy contract for ${m}:
414
+ ${Ca(R)}`);let T=(await Md({env:m,project:l,isShared:k,isClean:S,runningEnvs:await ED(),protectedEnvAccess:u})).identity.accountId;if(s)return d.info([`Would deploy to "${m}" (AWS account ${T}) from this machine`,`Preflight parameter: /${l}/environment`,Ca(R),"Commands:",...E.map(H=>` ${Cw(H).flat().join(" ")}`),"","Dry run: preflight and contract only \u2014 says nothing about whether the deploy would succeed."].join(`
415
+ `)),Bd({env:m,accountId:T,names:y,built:R,deployed:[],failed:[],dryRun:!0,success:!0});if(!o&&!await xD({env:m,isShared:k,names:y,accountId:T}))return d.info("Deployment cancelled"),Bd({env:m,accountId:T,names:y,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:W,failed:fe}=await CD({chosen:E,childEnv:R.childEnv,cwd:a,env:m});return fe.length>0&&(d.error(`Partial deploy to "${m}": succeeded [${W.join(", ")||"none"}], failed [${fe.join(", ")}]. There is no rollback \u2014 redeploy the previous commit to restore it.`),Ud.exitCode=1),h.print(),Bd({env:m,accountId:T,names:y,built:R,deployed:W,failed:fe,dryRun:!1,success:fe.length===0})},Aw=async e=>$w(e,"all"),Ow=async e=>$w(e,"selected"),Dw='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.',Iw={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.")},Nw={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")},Tw=e=>Or({workflowFile:Wd,fields:["env"],toolName:e}),Vd={all:Tw("local-deploy-all"),selected:Tw("local-deploy-selected")},Gd=C({name:"local-deploy-all",description:`Deploy EVERY service enabled for an environment, from this machine. ${Dw}`,requiresHumanConfirm:!0,formProvider:Vd.all,inputSchema:Iw,outputSchema:Nw,handler:Aw}),Jd=C({name:"local-deploy-selected",description:`Deploy a NAMED SUBSET of services from this machine. ${Dw}`,requiresHumanConfirm:!0,formProvider:Vd.selected,inputSchema:{...Iw,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:Nw,handler:Ow});import ID from"@inquirer/confirm";import Aa from"@inquirer/input";import Fw from"@inquirer/select";import Hd from"node:process";import{z as q}from"zod";import{z as Ps}from"zod";var Ln=async(e,t)=>new Promise(r=>{let n=setTimeout(()=>{r(null)},t);e.then(o=>{clearTimeout(n),r(o)},()=>{clearTimeout(n),r(null)})});var jw=2500,_w=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Mw=e=>typeof e=="string"&&e.trim()!==""?e.trim():void 0,OD=async()=>{let e=await Zo();return{regular:Nn(e,"regular"),hotfix:Nn(e,"hotfix")}},DD=(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).`,Kd=(e={})=>{let t=e.hintBudgetMs??jw;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=>_w(r)&&(r.releases===void 0||Array.isArray(r.releases)&&r.releases.length===0),buildRequestedSchema:async()=>{let r=await Ln(OD(),t);return Ps.object({type:Ps.enum(["regular","hotfix"]).describe('Release type. "regular" branches off dev and bumps the minor; "hotfix" branches off main and bumps the patch.'),release:Ps.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. ${DD(r,t)}`),description:Ps.string().optional().describe("Optional. Becomes the Jira fix version description and feeds the PR body. Blank means none."),releaseDate:Ps.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=Mw(r.description),a=Mw(r.releaseDate),c=ca(o);return{..._w(n)?n:{},releases:[{...c,type:s,...i===void 0?{}:{description:i},...a===void 0?{}:{releaseDate:a}}]}}}};var ND='"1.2.5" or "next"',qd=(e,t)=>{try{return Uu(e,t)}catch(r){throw r instanceof Er?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 Zm?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}},_D=async(e,t)=>{let r=Nn(e,t),n=r?` [${r}]`:"",o=(await M(i=>Aa({message:` Version (e.g. ${ND})${n}: `},i),{whenHeadless:"refuse"})).trim(),s=o===""?r??"":o;return s===""&&(d.error("No version provided. Exiting..."),Hd.exit(1)),s},MD=async()=>{let e=(await M(t=>Aa({message:' Name (kebab-case, e.g. "checkout-redesign"): '},t),{whenHeadless:"refuse"})).trim();e===""&&(d.error("No name provided. Exiting..."),Hd.exit(1));try{ei(e)}catch(t){let r=t instanceof Error?t.message:String(t);d.error(`${r} Exiting...`),Hd.exit(1)}return e},jD=async()=>(await M(e=>Aa({message:" Release date (yyyy-mm-dd, optional, press Enter to skip): ",validate:Xo},e),{whenHeadless:"refuse"})).trim(),FD=async e=>{h.setInteractive();let t=null,r=[],n=async()=>(t===null&&(t=await e(),r.push(...t)),r),o=[],s=!0;for(;s;){let i=o.length+1,a=await M(m=>Fw({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(m=>Fw({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 MD();l=qd([{name:m,type:c}],[])[0]}else{let m=await _D(await n(),c);l=qd([{version:m,type:c}],r)[0],l.id.kind==="version"&&r.push(Xt(`v${l.id.raw}`))}let u=(await M(m=>Aa({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(m=>ID({message:"Add another release?",default:!1},m),{whenHeadless:"refuse"})}return o},LD=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 ")},Lw=e=>{for(let t of e)h.addOption("--release",Bu(t))},BD=async(e,t)=>{if(e&&e.length>0){let n=Wu(e)?await t():[],o=qd(e,n);return Lw(o),o}if(he())throw new D({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 FD(t);return Lw(r),r},UD=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"})},WD=async(e,t)=>{let r=e.map(LD).join(`
416
+ - `);await J(t,`Create the following ${e.length} release(s)?
417
417
  - ${r}
418
- `),y.addOption("--yes",!0)},OD=async e=>{let{entry:t,jiraConfig:r}=e,n=re(t.id),o=t.id.kind==="version"?`v${t.id.raw}`:t.id.name;try{await on({operation:`create release ${o}`});let s=await Xl(t.type),i=await Zl({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=Do(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}}}},DD=(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.`)},Aw=Vd(),Ca=async e=>{let{releases:t,confirmedCommand:r}=e;await Ne({operation:"create release"}),await it({provider:Aw,params:e,operation:"create release",argument:"release"});let n=await pn(),o=null,i=await CD(t,async()=>(o===null&&(o=await Xo()),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"});$D(i),await To({operation:"create release",base:pt(i[0].type)}),await AD(i,!!r);let a=[],c=[];for(let u of i){let{result:p,failure:m}=await OD({entry:u,jiraConfig:n});p&&a.push(p),m&&c.push(m)}DD(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}},Kd=C({name:"release-create",requiresHumanConfirm:!0,formProvider:Aw,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: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:Au.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:Ca});import Ow from"@inquirer/input";import{z as qe}from"zod";var Dw=["description","releaseDate"],ID=async()=>{let e=await V(),t=e.map(s=>s.branch),r=new Map(e.map(s=>[s.branch,s.type])),n=await pe(),o=await Jt(me({branches:t,descriptions:n,types:r}));return{branch:o,type:r.get(o)||"regular"}},ND=async e=>{let r=(await V()).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},_D=async e=>{let t=e===""?"(no current description)":`current: "${e}"`,n=(await _(o=>Ow({message:` New description ${t} (press Enter to keep current): `},o),{whenHeadless:{refuse:"description"}})).trim();return n===""?e:n},MD=async e=>{let t=e===null?"(no current date)":`current: ${e}`,n=(await _(o=>Ow({message:` Release date yyyy-mm-dd ${t} (press Enter to keep current): `,validate:zo},o),{whenHeadless:{refuse:"releaseDate"}})).trim();return n===""?e:br(n)},jD=e=>{if(e!==void 0)return e===""?null:e},FD=async e=>(y.setInteractive(),{description:await _D(e.description),releaseDate:await MD(e.releaseDate)}),Hd=e=>e??"(none)",LD=(e,t,r)=>e==="description"?` description: "${t.description}" \u2192 "${r.description}"`:` release date: ${Hd(t.releaseDate)} \u2192 ${Hd(r.releaseDate)}`,$a=async e=>{let{version:t,description:r,releaseDate:n,confirmedCommand:o}=e,s=jD(n),i=await pn(),a;t?(a=Ct(t),await ND(a)):(y.setInteractive(),a=(await ID()).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=re(c);y.addOption("--version",l);let u=ce(c),p=await xt(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&&Z())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 v=f?{description:r??m.description,releaseDate:s===void 0?m.releaseDate:s}:await FD(m),E=Dw.filter(M=>v[M]!==m[M]),k=E.includes("description"),h=E.includes("releaseDate"),R=hr(i,p),S=M=>{let $={version:l,branch:a,jiraVersionUrl:R,previousDescription:m.description,newDescription:v.description,previousReleaseDate:m.releaseDate,newReleaseDate:v.releaseDate,changedFields:E,changed:M};return{content:b(JSON.stringify($,null,2)),structuredContent:$}};if(E.length===0)return d.info(`No change \u2014 ${u} already has description "${m.description}" and release date ${Hd(m.releaseDate)}`),y.print(),S(!1);k&&y.addOption("--description",v.description),h&&y.addOption("--release-date",v.releaseDate??"");let P=E.map(M=>LD(M,m,v));return await G(o,`Update ${u}?
421
- ${P.join(`
418
+ `),h.addOption("--yes",!0)},VD=async e=>{let{entry:t,jiraConfig:r}=e,n=re(t.id),o=t.id.kind==="version"?`v${t.id.raw}`:t.id.name;try{await sn({operation:`create release ${o}`});let s=await eu(t.type),i=await tu({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=Io(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}}}},GD=(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.`)},Bw=Kd(),Oa=async e=>{let{releases:t,confirmedCommand:r}=e;await Ne({operation:"create release"}),await it({provider:Bw,params:e,operation:"create release",argument:"release"});let n=await mn(),o=null,i=await BD(t,async()=>(o===null&&(o=await Zo()),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"});UD(i),await Co({operation:"create release",base:pt(i[0].type)}),await WD(i,!!r);let a=[],c=[];for(let u of i){let{result:p,failure:m}=await VD({entry:u,jiraConfig:n});p&&a.push(p),m&&c.push(m)}GD(i.length,a.length,c.length),h.print();let l={createdBranches:a.map(u=>u.branchName),successCount:a.length,failureCount:c.length,releases:a,failedReleases:c};return{content:b(JSON.stringify(l,null,2)),structuredContent:l}},Yd=C({name:"release-create",requiresHumanConfirm:!0,formProvider:Bw,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: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:Iu.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:Oa});import Uw from"@inquirer/input";import{z as qe}from"zod";var Ww=["description","releaseDate"],JD=async()=>{let e=await G(),t=e.map(s=>s.branch),r=new Map(e.map(s=>[s.branch,s.type])),n=await pe(),o=await Ht(me({branches:t,descriptions:n,types:r}));return{branch:o,type:r.get(o)||"regular"}},KD=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},HD=async e=>{let t=e===""?"(no current description)":`current: "${e}"`,n=(await M(o=>Uw({message:` New description ${t} (press Enter to keep current): `},o),{whenHeadless:{refuse:"description"}})).trim();return n===""?e:n},qD=async e=>{let t=e===null?"(no current date)":`current: ${e}`,n=(await M(o=>Uw({message:` Release date yyyy-mm-dd ${t} (press Enter to keep current): `,validate:Xo},o),{whenHeadless:{refuse:"releaseDate"}})).trim();return n===""?e:Sr(n)},YD=e=>{if(e!==void 0)return e===""?null:e},zD=async e=>(h.setInteractive(),{description:await HD(e.description),releaseDate:await qD(e.releaseDate)}),zd=e=>e??"(none)",XD=(e,t,r)=>e==="description"?` description: "${t.description}" \u2192 "${r.description}"`:` release date: ${zd(t.releaseDate)} \u2192 ${zd(r.releaseDate)}`,Da=async e=>{let{version:t,description:r,releaseDate:n,confirmedCommand:o}=e,s=YD(n),i=await mn(),a;t?(a=At(t),await KD(a)):(h.setInteractive(),a=(await JD()).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=re(c);h.addOption("--version",l);let u=ce(c),p=await Ct(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&&Z())throw new D({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 y=f?{description:r??m.description,releaseDate:s===void 0?m.releaseDate:s}:await zD(m),E=Ww.filter($=>y[$]!==m[$]),k=E.includes("description"),O=E.includes("releaseDate"),v=vr(i,p),S=$=>{let T={version:l,branch:a,jiraVersionUrl:v,previousDescription:m.description,newDescription:y.description,previousReleaseDate:m.releaseDate,newReleaseDate:y.releaseDate,changedFields:E,changed:$};return{content:b(JSON.stringify(T,null,2)),structuredContent:T}};if(E.length===0)return d.info(`No change \u2014 ${u} already has description "${m.description}" and release date ${zd(m.releaseDate)}`),h.print(),S(!1);k&&h.addOption("--description",y.description),O&&h.addOption("--release-date",y.releaseDate??"");let R=E.map($=>XD($,m,y));return await J(o,`Update ${u}?
421
+ ${R.join(`
422
422
  `)}
423
- `),y.addOption("--yes",!0),await dn({versionId:p.id,...k?{description:v.description}:{},...h?{releaseDate:v.releaseDate}:{}},i),k&&await Ii({branch:a,body:Oo(R,v.description)}),d.info(`\u2705 Updated ${E.join(" and ")} for ${u}`),d.info(`\u{1F517} Jira Version: ${R}`),d.info(`\u{1F517} PR branch: ${a}
424
- `),y.print(),S(!0)},qd=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:qe.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:qe.string().optional().describe("New description. Empty string clears the description."),releaseDate:Ou.optional().describe("New planned release date (yyyy-mm-dd). Empty string clears the date.")},outputSchema:{version:qe.string().describe("Release version"),branch:qe.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:qe.string().describe("Jira fix version URL"),previousDescription:qe.string().describe("The description before the update"),newDescription:qe.string().describe("The description after the update"),previousReleaseDate:qe.string().nullable().describe("The planned release date before the update, or null"),newReleaseDate:qe.string().nullable().describe("The planned release date after the update, or null"),changedFields:qe.array(qe.enum(Dw)).describe("The fields whose value actually changed"),changed:qe.boolean().describe("Whether anything actually changed")},handler:$a});import{z as ae}from"zod";import{$ as zd}from"zx";import{z as Iw}from"zod";var Mw=2500,Aa="release-remove",Nw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),BD=e=>e.version===void 0||e.version==="",UD=async()=>{try{return{outcome:"listed",prs:await V()}}catch(e){return e instanceof g&&e.operation===$o?{outcome:"empty"}:{outcome:"failed"}}},_w=(e,t)=>(e===null?d.info({msg:`Tool execution form enumeration timed out (gh pr list, ${t/1e3} s): ${Aa}`}):e.outcome==="failed"?d.info({msg:`Tool execution form enumeration failed (gh pr list): ${Aa}`}):d.info({msg:`Tool execution form options empty (open release PRs): ${Aa}`}),null),WD=(e,t)=>{let r=new Map(e.map(n=>[n.branch,n.type]));return Fi(e.map(n=>n.branch)).map(({branch:n,id:o,label:s})=>{let i=t?.get(ce(o)),a=i===void 0?"":` \u2014 ${i}`;return{label:s,prose:`${s} [${r.get(n)??"regular"}]${a}`}})},VD=(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): ${Aa}`}),`Open release PRs right now: ${n}. Jira descriptions could not be fetched within ${r/1e3} s. `)},Yd=(e={})=>{let t=e.fetchBudgetMs??Mw;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=>Nw(r)&&BD(r),buildRequestedSchema:async()=>{let[r,n]=await Promise.all([Fn(UD(),t),Fn(pe(),t)]);if(r===null||r.outcome!=="listed")return _w(r,t);let o=WD(r.prs,n);return o.length===0?_w({outcome:"empty"},t):Iw.object({version:Iw.enum(o.map(s=>s.label)).describe(`The ONE release to tear down. ${VD(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:{...Nw(n)?n:{},version:r.version}}};var jw=["worktree","pr","local-branch","remote-branch","jira"],Bw={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"},Dr="remove a release",tt=e=>{throw d.warn({operation:e.operation},`\u26D4 ${e.stderrExcerpt??e.operation}`),new g(void 0,e)},Fw=(e,t)=>{throw d.warn({operation:t.operation},`\u26D4 ${t.stderrExcerpt??t.operation}`),new O({...e,agentMode:j.source},2,t)},GD=e=>{ge()&&(e.version||Fw({status:"argument_required",argument:"version"},{operation:Dr,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&&Fw({status:"refused"},{operation:Dr,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"}))},Uw=e=>{e.pr?.state==="MERGED"&&tt({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`})},JD=(e,t)=>{if(t.skipJira||(e.jiraConfig||tt({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)&&tt({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||tt({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)`}))},KD=e=>{if(e.worktreePresent||e.pr!==null||e.localTipSha!==null||e.remoteTipSha!==null||e.jira)return;tt({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"})},HD=e=>{!e.worktreeDirty||e.worktreeDirty.length===0||tt({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(", ")}`})},qD=async e=>(await zd`git -C ${e} status --porcelain`).stdout.split(`
425
- `).map(r=>r.trimEnd()).filter(r=>r.length>0),YD=async e=>{try{let{terminals:t}=await Df(e);return t.filter(r=>r.connected).length}catch(t){return d.debug({error:t,worktreePath:e},"release remove: orca terminal probe failed"),0}},zD=async e=>{let t=await oi([e]);if(t!==null)throw d.warn({operation:Dr},`\u26D4 this command runs inside an Orca terminal of ${t}`),new O({status:"refused",reason:"orca_caller_inside_target",agentMode:j.source},2,{operation:Dr,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`})},XD=async(e,t)=>{let r={jiraConfig:null,jira:null,moveIssuesTo:null};if(t.skipJira)return r;let n=await Tt();if(!n)return r;let o=await xt(ce(e),n),s=t.moveIssuesTo?await ZD(t.moveIssuesTo,n):null;if(!o)return{jiraConfig:n,jira:null,moveIssuesTo:s};let i=await Mi(o.id,n);return{jiraConfig:n,moveIssuesTo:s,jira:{version:o,fixCount:i.issuesFixedCount,affectsCount:i.issuesAffectedCount,url:hr(n,o)}}},ZD=async(e,t)=>{let r=await xt(e,t);return r||tt({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}"`})},QD=async(e,t)=>{let r=Q(e);r||tt({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}${fe}`}/${e}`,[i,a,c,l]=await Promise.all([we("release"),an(e),xe(n,`refs/heads/${e}`),Wr(n,e)]),u=i.includes(e);return u&&await zD(s),{...await XD(r,t),branch:e,id:r,label:re(r),baseBranch:a?.baseRefName??pt("regular"),worktreePath:s,worktreePresent:u,orcaTerminalCount:u?await YD(s):0,worktreeDirty:u?await qD(s):null,localTipSha:c,remoteTipSha:l,pr:a}},Lw=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}),eI=(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}`},tI=(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: ${eI(e,t)}`];return e.orcaTerminalCount>0&&n.push(` \u2022 ${e.orcaTerminalCount} Orca terminal(s) in ${e.worktreePath} will be closed`),n.join(`
426
- `)},Oa=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 Rs(e,t,r){try{let n=await r(),o=rI(n);return t.push({step:e}),d.info({step:e,outcome:o},`\u2705 ${Bw[e]} \u2014 ${o}`),n}catch(n){throw new Oa(e,n)}}var nI=(e,t)=>t.step==="local-branch"&&e.localTipSha?`local-branch (was ${e.localTipSha.slice(0,7)})`:t.step,oI=e=>{let{plan:t,step:r,done:n,cause:o}=e,s=n.map(p=>nI(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 ${jw.indexOf(r)+1} of ${jw.length} (${Bw[r]})`,remediation:u?`${u} \u2014 ${l}`:l})},sI=async e=>(await ls(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",iI=async e=>{let t=await an(e.branch);if(Uw({...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 zd`gh pr close ${String(t.number)} --comment ${r}`,{outcome:"closed",number:t.number}},aI=async e=>(await Ur()===e.branch&&await zd`git switch ${e.baseBranch}`,await Xs(e.branch),await tf(e.branch)?tt({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 Zs(e.branch),e.remoteTipSha?"deleted":"absent"),lI=async(e,t,r)=>{let n=await Mi(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}\``;tt({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}`})},uI=async(e,t)=>t.skipJira?"skipped":!e.jira||!e.jiraConfig?"absent":(await lI(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 zl({versionId:e.jira.version.id,moveFixIssuesTo:e.moveIssuesTo?.id,moveAffectedIssuesTo:e.moveIssuesTo?.id},e.jiraConfig),"removed"),dI=(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}),pI=async(e,t,r)=>{let n=await Rs("worktree",r,()=>sI(e)),o=await Rs("pr",r,()=>iI(e));d.info({branch:e.branch,localTipSha:e.localTipSha,remoteTipSha:e.remoteTipSha},"\u{1F516} branch tips before deletion");let s=await Rs("local-branch",r,()=>aI(e)),i=await Rs("remote-branch",r,()=>cI(e)),a=await Rs("jira",r,()=>uI(e,t));return{worktree:n,pr:o,localBranch:s,remoteBranch:i,jira:a}},mI=async(e,t)=>{let r=[];try{return dI(e,await pI(e,t,r))}catch(n){throw n instanceof Oa?oI({plan:e,step:n.step,done:r,cause:n.reason}):n}},fI=async e=>{if(e)return Ct(e);y.setInteractive();let[t,r]=await Promise.all([pe(),V()]),n=r.map(s=>s.branch);n.length===0&&tt({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 Jt(me({branches:n,descriptions:t,types:o}))}catch(s){throw Ae(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"})}},Ww=Yd(),Da=async e=>{let{confirmedCommand:t,version:r,moveIssuesTo:n,skipJira:o}=e;await Ne({operation:Dr}),await H(),await it({provider:Ww,params:e,operation:Dr,argument:"version"}),GD(e);try{let s=await QD(await fI(r),e);d.debug({plan:Lw(s)},"release remove: resolved plan"),Uw(s),JD(s,e),KD(s),await To({operation:`remove release ${s.label}`,base:s.baseBranch}),HD(s),y.addOption("--version",s.label),n&&y.addOption("--move-issues-to",n),o&&y.addOption("--skip-jira",!0),await G(t,tI(s,!!o),{throwOnDecline:!0,plan:{...Lw(s),skipJira:!!o}}),t||y.addOption("--yes",!0);let i=await mI(s,e);return y.print(),{content:b(JSON.stringify(i,null,2)),structuredContent:i}}catch(s){throw Ae(s)||bt(s)||s instanceof g?s:(d.error({err:Tr(s)},"\u274C Error removing release"),new g(s,{operation:Dr,remediation:"check `gh auth status`, `git worktree list` and the Jira credentials, then re-run"}))}},Xd=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:Ww,inputSchema:{version:ae.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:ae.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:ae.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{branch:ae.string().describe("The release branch that was targeted"),version:ae.string().describe('The release label (e.g. "1.2.5")'),baseBranch:ae.string().describe("The branch HEAD was moved to before the local delete"),worktree:ae.enum(["removed","absent"]).describe("Whether a git worktree was removed or none existed"),pr:ae.enum(["closed","already-closed","absent"]).describe("What happened to the release pull request"),prNumber:ae.number().nullable().describe("The pull request number, or null when none exists"),localBranch:ae.enum(["deleted","absent"]).describe("Whether a local branch was deleted or none existed"),localTipSha:ae.string().nullable().describe("The local tip before deletion \u2014 the handle that restores the branch"),remoteBranch:ae.enum(["deleted","absent"]).describe("Whether the origin branch was deleted or none existed"),remoteTipSha:ae.string().nullable().describe("The origin tip before deletion"),jira:ae.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:ae.object({id:ae.string(),name:ae.string(),url:ae.string()}).nullable().describe("The fix version this release owned, captured before removal \u2014 the id is the only handle that survives it")},handler:Da});import{spawn as vI}from"node:child_process";import wI from"node:fs";import{homedir as kI}from"node:os";import Na from"node:process";import Ia from"node:fs";import Ln from"node:path";var gI=e=>{try{return Ia.statSync(e).isFile()?Ia.readFileSync(e,"utf8"):null}catch{return null}},hI=e=>{try{return Ia.realpathSync(e)}catch{return e}},yI=(e,t)=>{let o=t(Ln.join(e,".git"))?.split(`
427
- `).map(c=>c.trim()).find(c=>c.startsWith("gitdir:"))?.slice(7).trim();if(!o)return e;let s=Ln.resolve(e,o),i=`${Ln.sep}.git${Ln.sep}worktrees${Ln.sep}`,a=s.lastIndexOf(i);return a===-1?e:s.slice(0,a)},Vw=(e={})=>{let t=e.listInstallations??xc,r=e.exists??Ia.existsSync,n=e.readGitFile??gI,o=e.realpath??hI,s=new Map;for(let i of t()){if(i.projectPath===null)continue;let a=yI(i.projectPath,n);if(!r(Ln.join(a,"infra-kit.json")))continue;let c=o(a);s.has(c)||s.set(c,a)}return[...s.values()].sort()};var bI=180*1e3,RI=900*1e3,SI=4*1024*1024,EI=2e3,PI=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=vI(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&&Na.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<SI&&(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)},EI).unref()})}),xI=({cwd:e,timeoutMs:t})=>PI({command:Na.execPath,args:[Na.argv[1]??"","setup","--unattended","--json"],cwd:e,env:xf(Na.env),timeoutMs:t}),TI=e=>{wI.writeFileSync(kn(),e,{mode:384})},CI=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}},$I=new RegExp("\x1B\\[[0-9;]*m","g"),AI=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($I,"").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},OI=(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}},Gw=async(e,t,r,n)=>{let o=n-r.clock(),s=e===null?"infra-kit setup":Xi(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(bI,o)}),a=i.error===null?CI(i.stdout):null;return a===null?{root:e,status:"failed",notes:[`${AI(i)} \u2014 run: ${s}`]}:{root:e,...OI(a,i.status)}}catch(i){return{root:e,status:"failed",notes:[`${i instanceof Error?i.message:String(i)} \u2014 run: ${s}`]}}},DI=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}})},II=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(`
423
+ `),h.addOption("--yes",!0),await pn({versionId:p.id,...k?{description:y.description}:{},...O?{releaseDate:y.releaseDate}:{}},i),k&&await ji({branch:a,body:Do(v,y.description)}),d.info(`\u2705 Updated ${E.join(" and ")} for ${u}`),d.info(`\u{1F517} Jira Version: ${v}`),d.info(`\u{1F517} PR branch: ${a}
424
+ `),h.print(),S(!0)},Xd=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:qe.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:qe.string().optional().describe("New description. Empty string clears the description."),releaseDate:Nu.optional().describe("New planned release date (yyyy-mm-dd). Empty string clears the date.")},outputSchema:{version:qe.string().describe("Release version"),branch:qe.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:qe.string().describe("Jira fix version URL"),previousDescription:qe.string().describe("The description before the update"),newDescription:qe.string().describe("The description after the update"),previousReleaseDate:qe.string().nullable().describe("The planned release date before the update, or null"),newReleaseDate:qe.string().nullable().describe("The planned release date after the update, or null"),changedFields:qe.array(qe.enum(Ww)).describe("The fields whose value actually changed"),changed:qe.boolean().describe("Whether anything actually changed")},handler:Da});import{z as ae}from"zod";import{$ as Qd}from"zx";import{z as Vw}from"zod";var Kw=2500,Ia="release-remove",Gw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ZD=e=>e.version===void 0||e.version==="",QD=async()=>{try{return{outcome:"listed",prs:await G()}}catch(e){return e instanceof g&&e.operation===Ao?{outcome:"empty"}:{outcome:"failed"}}},Jw=(e,t)=>(e===null?d.info({msg:`Tool execution form enumeration timed out (gh pr list, ${t/1e3} s): ${Ia}`}):e.outcome==="failed"?d.info({msg:`Tool execution form enumeration failed (gh pr list): ${Ia}`}):d.info({msg:`Tool execution form options empty (open release PRs): ${Ia}`}),null),eI=(e,t)=>{let r=new Map(e.map(n=>[n.branch,n.type]));return Wi(e.map(n=>n.branch)).map(({branch:n,id:o,label:s})=>{let i=t?.get(ce(o)),a=i===void 0?"":` \u2014 ${i}`;return{label:s,prose:`${s} [${r.get(n)??"regular"}]${a}`}})},tI=(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): ${Ia}`}),`Open release PRs right now: ${n}. Jira descriptions could not be fetched within ${r/1e3} s. `)},Zd=(e={})=>{let t=e.fetchBudgetMs??Kw;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=>Gw(r)&&ZD(r),buildRequestedSchema:async()=>{let[r,n]=await Promise.all([Ln(QD(),t),Ln(pe(),t)]);if(r===null||r.outcome!=="listed")return Jw(r,t);let o=eI(r.prs,n);return o.length===0?Jw({outcome:"empty"},t):Vw.object({version:Vw.enum(o.map(s=>s.label)).describe(`The ONE release to tear down. ${tI(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:{...Gw(n)?n:{},version:r.version}}};var Hw=["worktree","pr","local-branch","remote-branch","jira"],zw={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"},Ir="remove a release",tt=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 D({...e,agentMode:j.source},2,t)},rI=e=>{he()&&(e.version||qw({status:"argument_required",argument:"version"},{operation:Ir,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:Ir,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"}))},Xw=e=>{e.pr?.state==="MERGED"&&tt({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`})},nI=(e,t)=>{if(t.skipJira||(e.jiraConfig||tt({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)&&tt({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||tt({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)`}))},oI=e=>{if(e.worktreePresent||e.pr!==null||e.localTipSha!==null||e.remoteTipSha!==null||e.jira)return;tt({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"})},sI=e=>{!e.worktreeDirty||e.worktreeDirty.length===0||tt({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(", ")}`})},iI=async e=>(await Qd`git -C ${e} status --porcelain`).stdout.split(`
425
+ `).map(r=>r.trimEnd()).filter(r=>r.length>0),aI=async e=>{try{let{terminals:t}=await _f(e);return t.filter(r=>r.connected).length}catch(t){return d.debug({error:t,worktreePath:e},"release remove: orca terminal probe failed"),0}},cI=async e=>{let t=await ci([e]);if(t!==null)throw d.warn({operation:Ir},`\u26D4 this command runs inside an Orca terminal of ${t}`),new D({status:"refused",reason:"orca_caller_inside_target",agentMode:j.source},2,{operation:Ir,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`})},lI=async(e,t)=>{let r={jiraConfig:null,jira:null,moveIssuesTo:null};if(t.skipJira)return r;let n=await $t();if(!n)return r;let o=await Ct(ce(e),n),s=t.moveIssuesTo?await uI(t.moveIssuesTo,n):null;if(!o)return{jiraConfig:n,jira:null,moveIssuesTo:s};let i=await Bi(o.id,n);return{jiraConfig:n,moveIssuesTo:s,jira:{version:o,fixCount:i.issuesFixedCount,affectsCount:i.issuesAffectedCount,url:vr(n,o)}}},uI=async(e,t)=>{let r=await Ct(e,t);return r||tt({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}"`})},dI=async(e,t)=>{let r=Q(e);r||tt({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}${ge}`}/${e}`,[i,a,c,l]=await Promise.all([ke("release"),cn(e),Te(n,`refs/heads/${e}`),Vr(n,e)]),u=i.includes(e);return u&&await cI(s),{...await lI(r,t),branch:e,id:r,label:re(r),baseBranch:a?.baseRefName??pt("regular"),worktreePath:s,worktreePresent:u,orcaTerminalCount:u?await aI(s):0,worktreeDirty:u?await iI(s):null,localTipSha:c,remoteTipSha:l,pr:a}},Yw=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}),pI=(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}`},mI=(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: ${pI(e,t)}`];return e.orcaTerminalCount>0&&n.push(` \u2022 ${e.orcaTerminalCount} Orca terminal(s) in ${e.worktreePath} will be closed`),n.join(`
426
+ `)},Na=class extends Error{constructor(r,n){super(`step ${r} failed`,{cause:n});this.step=r;this.reason=n;this.name="StepFailure"}step;reason},fI=e=>typeof e=="string"?e:e.outcome;async function xs(e,t,r){try{let n=await r(),o=fI(n);return t.push({step:e}),d.info({step:e,outcome:o},`\u2705 ${zw[e]} \u2014 ${o}`),n}catch(n){throw new Na(e,n)}}var gI=(e,t)=>t.step==="local-branch"&&e.localTipSha?`local-branch (was ${e.localTipSha.slice(0,7)})`:t.step,hI=e=>{let{plan:t,step:r,done:n,cause:o}=e,s=n.map(p=>gI(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 ${Hw.indexOf(r)+1} of ${Hw.length} (${zw[r]})`,remediation:u?`${u} \u2014 ${l}`:l})},yI=async e=>(await us(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",vI=async e=>{let t=await cn(e.branch);if(Xw({...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 Qd`gh pr close ${String(t.number)} --comment ${r}`,{outcome:"closed",number:t.number}},wI=async e=>(await Wr()===e.branch&&await Qd`git switch ${e.baseBranch}`,await ti(e.branch),await of(e.branch)?tt({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"),kI=async e=>(await ri(e.branch),e.remoteTipSha?"deleted":"absent"),bI=async(e,t,r)=>{let n=await Bi(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}\``;tt({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}`})},RI=async(e,t)=>t.skipJira?"skipped":!e.jira||!e.jiraConfig?"absent":(await bI(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 Ql({versionId:e.jira.version.id,moveFixIssuesTo:e.moveIssuesTo?.id,moveAffectedIssuesTo:e.moveIssuesTo?.id},e.jiraConfig),"removed"),SI=(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}),EI=async(e,t,r)=>{let n=await xs("worktree",r,()=>yI(e)),o=await xs("pr",r,()=>vI(e));d.info({branch:e.branch,localTipSha:e.localTipSha,remoteTipSha:e.remoteTipSha},"\u{1F516} branch tips before deletion");let s=await xs("local-branch",r,()=>wI(e)),i=await xs("remote-branch",r,()=>kI(e)),a=await xs("jira",r,()=>RI(e,t));return{worktree:n,pr:o,localBranch:s,remoteBranch:i,jira:a}},PI=async(e,t)=>{let r=[];try{return SI(e,await EI(e,t,r))}catch(n){throw n instanceof Na?hI({plan:e,step:n.step,done:r,cause:n.reason}):n}},xI=async e=>{if(e)return At(e);h.setInteractive();let[t,r]=await Promise.all([pe(),G()]),n=r.map(s=>s.branch);n.length===0&&tt({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 Ht(me({branches:n,descriptions:t,types:o}))}catch(s){throw Ae(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"})}},Zw=Zd(),_a=async e=>{let{confirmedCommand:t,version:r,moveIssuesTo:n,skipJira:o}=e;await Ne({operation:Ir}),await K(),await it({provider:Zw,params:e,operation:Ir,argument:"version"}),rI(e);try{let s=await dI(await xI(r),e);d.debug({plan:Yw(s)},"release remove: resolved plan"),Xw(s),nI(s,e),oI(s),await Co({operation:`remove release ${s.label}`,base:s.baseBranch}),sI(s),h.addOption("--version",s.label),n&&h.addOption("--move-issues-to",n),o&&h.addOption("--skip-jira",!0),await J(t,mI(s,!!o),{throwOnDecline:!0,plan:{...Yw(s),skipJira:!!o}}),t||h.addOption("--yes",!0);let i=await PI(s,e);return h.print(),{content:b(JSON.stringify(i,null,2)),structuredContent:i}}catch(s){throw Ae(s)||St(s)||s instanceof g?s:(d.error({err:$r(s)},"\u274C Error removing release"),new g(s,{operation:Ir,remediation:"check `gh auth status`, `git worktree list` and the Jira credentials, then re-run"}))}},ep=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:Zw,inputSchema:{version:ae.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:ae.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:ae.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{branch:ae.string().describe("The release branch that was targeted"),version:ae.string().describe('The release label (e.g. "1.2.5")'),baseBranch:ae.string().describe("The branch HEAD was moved to before the local delete"),worktree:ae.enum(["removed","absent"]).describe("Whether a git worktree was removed or none existed"),pr:ae.enum(["closed","already-closed","absent"]).describe("What happened to the release pull request"),prNumber:ae.number().nullable().describe("The pull request number, or null when none exists"),localBranch:ae.enum(["deleted","absent"]).describe("Whether a local branch was deleted or none existed"),localTipSha:ae.string().nullable().describe("The local tip before deletion \u2014 the handle that restores the branch"),remoteBranch:ae.enum(["deleted","absent"]).describe("Whether the origin branch was deleted or none existed"),remoteTipSha:ae.string().nullable().describe("The origin tip before deletion"),jira:ae.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:ae.object({id:ae.string(),name:ae.string(),url:ae.string()}).nullable().describe("The fix version this release owned, captured before removal \u2014 the id is the only handle that survives it")},handler:_a});import{spawn as AI}from"node:child_process";import OI from"node:fs";import{homedir as DI}from"node:os";import ja from"node:process";import Ma from"node:fs";import Bn from"node:path";var TI=e=>{try{return Ma.statSync(e).isFile()?Ma.readFileSync(e,"utf8"):null}catch{return null}},CI=e=>{try{return Ma.realpathSync(e)}catch{return e}},$I=(e,t)=>{let o=t(Bn.join(e,".git"))?.split(`
427
+ `).map(c=>c.trim()).find(c=>c.startsWith("gitdir:"))?.slice(7).trim();if(!o)return e;let s=Bn.resolve(e,o),i=`${Bn.sep}.git${Bn.sep}worktrees${Bn.sep}`,a=s.lastIndexOf(i);return a===-1?e:s.slice(0,a)},Qw=(e={})=>{let t=e.listInstallations??$c,r=e.exists??Ma.existsSync,n=e.readGitFile??TI,o=e.realpath??CI,s=new Map;for(let i of t()){if(i.projectPath===null)continue;let a=$I(i.projectPath,n);if(!r(Bn.join(a,"infra-kit.json")))continue;let c=o(a);s.has(c)||s.set(c,a)}return[...s.values()].sort()};var II=180*1e3,NI=900*1e3,_I=4*1024*1024,MI=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=AI(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&&ja.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<_I&&(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)},MI).unref()})}),FI=({cwd:e,timeoutMs:t})=>jI({command:ja.execPath,args:[ja.argv[1]??"","setup","--unattended","--json"],cwd:e,env:$f(ja.env),timeoutMs:t}),LI=e=>{OI.writeFileSync(bn(),e,{mode:384})},BI=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}},UI=new RegExp("\x1B\\[[0-9;]*m","g"),WI=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(UI,"").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},VI=(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}},ek=async(e,t,r,n)=>{let o=n-r.clock(),s=e===null?"infra-kit setup":ta(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(II,o)}),a=i.error===null?BI(i.stdout):null;return a===null?{root:e,status:"failed",notes:[`${WI(i)} \u2014 run: ${s}`]}:{root:e,...VI(a,i.status)}}catch(i){return{root:e,status:"failed",notes:[`${i instanceof Error?i.message:String(i)} \u2014 run: ${s}`]}}},GI=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}})},JI=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
429
  `)}
430
- `},NI=e=>({version:e.version??L.version,home:e.home??kI(),clock:e.clock??Date.now,acquireLock:e.acquireLock??(()=>$c({lockPath:dy()})),readRecord:e.readRecord??bn,writeRecord:e.writeRecord??py,discoverProjects:e.discoverProjects??(()=>Vw()),runSetupChild:e.runSetupChild??xI,writeLog:e.writeLog??TI}),_I=e=>{try{return{projects:e.discoverProjects(),error:null}}catch(t){return{projects:[],error:t instanceof Error?t.message:String(t)}}},MI=async e=>{let t=e.readRecord(),r=e.clock();if(!gy(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+RI,s=await Gw(null,e.home,e,o),i=_I(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 Gw(l,l,e,o));let c={version:e.version,attempts:n,startedMs:r,finishedMs:e.clock(),runs:DI(a)};e.writeRecord(c);try{e.writeLog(II(c))}catch{}return"ran"},Jw=async(e={})=>{try{let t=NI(e),r=t.acquireLock();if(r===null)return"already-running";try{return await MI(t)}finally{r()}}catch{return"not-due"}},Zd=async(e={})=>{let t=await Jw(e);return{content:b(JSON.stringify({outcome:t})),structuredContent:{outcome:t}}};import{spawnSync as BI}from"node:child_process";import{homedir as UI}from"node:os";import WI from"node:process";var jI=e=>{let t=new Set(e.steps.map(r=>r[0]));return t.has("brew")?"homebrew":t.has("npm")?"npm":null},FI=e=>{let t=[];return e.needsSudo&&t.push("needs-sudo"),e.fetchesNetworkScript&&t.push("fetches-network-script"),t},LI=(e,t)=>{let r=jI(e);if(r===null)return[];let n=[];return t.present.includes(r)||n.push("manager-absent"),t.owner!==null&&t.owner!==r&&n.push("manager-mismatch"),n},Ss=(e,t)=>{let r=[...FI(e),...LI(e,t)];return r.length===0?{executable:!0}:{executable:!1,reasons:r}},Es=e=>e.steps.map(Be);var VI=["NONINTERACTIVE","CI","INTERACTIVE","HAVE_SUDO_ACCESS","SUDO_ASKPASS"],GI=e=>{let t={...$m(e)};for(let r of VI)delete t[r];return t},Qd=(e,t,r={})=>{let n=r.spawnSync??BI,o=r.env??WI.env,s=(r.agentMode??ge)(),i=Es(e),a=Ss(e,t);return a.executable?s?{ran:!1,commands:i,refusedBecause:["agent-mode"]}:HI({recipe:e,spawn:n,env:o,commands:i,notify:r.notify??JI}):{ran:!1,commands:i,refusedBecause:a.reasons}},JI=e=>{d.info(e)},Hw=64,KI=Hw*1024*1024,HI=({recipe:e,spawn:t,env:r,commands:n,notify:o})=>{let s=GI(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:KI,cwd:UI(),env:s}),l=QI(c);if(l!==null)return{ran:!0,ok:!1,commands:n,failedStep:n[i],detail:l}}return{ran:!0,ok:!0,commands:n}},qI=5,YI=/^(?:error|fatal|warning: failed|[a-z-]{0,20} ERR!)[:\s]/i,Kw=e=>e==null?[]:String(e).split(`
431
- `).map(t=>t.trim()).filter(t=>t.length>0),zI=e=>{let t=Kw(e.stderr),r=Kw(e.stdout),n=[...t,...r].filter(s=>YI.test(s)),o=t.length>0?t:r;return(n.length>0?n:o).slice(-qI).join(" / ")},XI="ENOBUFS",ZI=e=>e.error?.code===XI,QI=e=>{if(ZI(e))return`terminated after exceeding the ${Hw} 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=zI(e),r=t===""?"":`: ${t}`;return`exited ${e.status??"unknown"}${r}`};var eN=e=>{let t=[];return e.some(n=>n.id==="brew"&&n.present)&&t.push("homebrew"),t.push("npm"),t},tN=e=>{let t=Ke(e.id);return e.present?t.updateFor(e.binRealPath):t.bootstrapInstall},rN=(e,t)=>{let r=tN(e),n={...t,owner:e.present?e.manager:null};if(r===null)return{state:e,action:"none",recipe:null,executable:!1,refusedBecause:[],commands:[],context:n};let o=Ss(r,n);return{state:e,action:e.present?"update":"install",recipe:r,executable:o.executable,refusedBecause:o.executable?[]:o.reasons,commands:Es(r),context:n}},_a=async(e=kr,t=Ko())=>{let r=await qo(kr,t),n={owner:null,present:eN(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 ep=(e,t)=>({...Ps(e),action:"skipped",commands:e.commands,detail:t}),Ps=e=>({id:e.state.id,before:{present:e.state.present,onPath:e.state.onPath,version:e.state.version,manager:e.state.manager}}),qw=(e,t)=>e.action==="none"?ep(e,`nothing to do: ${e.state.manager} installs are not managed from here`):t==="update"&&e.action==="install"?ep(e,"not installed, and --update only updates \u2014 drop the flag to install it"):e.executable?null:{...Ps(e),action:"refused",commands:e.commands,detail:`refused (${e.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},nN=(e,t)=>t.ran?t.ok?{...Ps(e),action:e.action==="install"?"installed":"updated",commands:t.commands,detail:e.action==="install"?"installed":"updated"}:{...Ps(e),action:"failed",commands:t.commands,detail:`${t.failedStep??"a step"} ${t.detail??"failed"}`}:{...Ps(e),action:"refused",commands:t.commands,detail:`refused (${t.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},tp=async e=>{let t=e.run??Qd,{plans:r}=await _a(e.ids,e.probeDeps),n=[];for(let o of r){let s=qw(o,e.mode);if(s!==null){n.push(s);continue}n.push(nN(o,t(o.recipe,o.context)))}return n},rp=async(e,t)=>{let{plans:r}=await _a(e,t);return r.map(n=>qw(n,"converge")??ep(n,`would ${n.action} \u2014 nothing was run (--skip-tools)`))};import wN from"node:process";import{z as N}from"zod";var np={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},oN=Object.keys(np).sort((e,t)=>np[e]-np[t]),Yw={skipped:0,ok:1,changed:2,manual:3,warn:4,fail:5},zw=new Set(["manual","warn","fail"]),op=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 Ue(e)}},sN=e=>e.reduce((t,r)=>Yw[r]>Yw[t]?r:t,"skipped"),Zw=e=>e.message.trim(),iN=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 "),Xw=e=>e.message===Tn,aN=(e,t)=>{let[r]=e;return e.length===1&&r!==void 0?Zw(r):e.length>1?iN(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=>op(i.outcome)),n=t.filter(i=>zw.has(op(i.outcome))).map(Zw),o=t.filter(i=>!zw.has(op(i.outcome))&&!Xw(i)),s={name:e,status:sN(r),message:aN(o,t.some(Xw))};return n.length>0?{...s,notes:n}:s},lN=e=>({label:"Local setup",rows:oN.map(t=>cN(t,e.filter(r=>r.step===t)))}),uN=(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 Ue(e.action)}},dN=(e,t)=>{let r=uN(e,t),n={name:e.id,status:r,message:e.detail};return r==="manual"&&e.commands.length>0?{...n,notes:[...e.commands]}:n},pN=(e,t)=>({label:t.skipTools?"Tools (probe: nothing installed)":"Tools",rows:e.map(r=>dN(r,t))}),mN=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 Ue(e)}},fN=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 Ue(e)}},gN=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 Ue(e)}},hN=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 Ue(e.outcome)}},yN=(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 Ue(e)}},vN=e=>({label:"Portless service",rows:[{name:"link",status:mN(e.link),message:gN(e.link)},{name:"node",status:fN(e.node.outcome),message:hN(e.node)},yN(e.service,e.command)]}),Qw=(e,t)=>[lN(e.init),pN(e.tools,t),vN(e.portless)],ek=e=>e.some(t=>t.rows.some(r=>r.status==="fail"));var kN=()=>{let{link:e,node:t}=qs();return{link:e,node:t,target:{home:e.home,isGlobal:e.isGlobal,processStartTime:()=>null}}},bN=async e=>{let t=Jm(e.link).outcome,r=Gm(e.node),n=Hs(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 gv(e.target,n);if(o==="converged")return{link:t,node:r,service:o,command:null};let i=Nt(n,{home:e.link.home,exists:e.target.exists,execPath:e.target.execPath,stableNode:s});return{link:t,node:r,service:o,command:i}},rk="--unattended cannot be combined with --tools or --update: an unattended run installs and updates nothing (it implies --skip-tools).",nk="--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.",RN=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(rk);if(o&&(e.tools!==void 0||r))throw new Error(nk);return{ids:e.tools??t??kr,mode:r?"update":"converge",skipTools:o}},tk=(e,t)=>e instanceof xn?e.step:t.at(-1)?.step??"zshrc",SN=async()=>{let e=[];try{await Ru(t=>{e.push(t)})}catch(t){e.push({step:tk(t,e),outcome:"failed",message:`The ${tk(t,e)} step failed: ${t instanceof Error?t.message:String(t)}`,level:"warn"})}return e},EN=(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}`}))},PN=async(e,t)=>{try{return e.skipTools?await rp(e.ids,t.probeDeps):await tp({ids:e.ids,mode:e.mode,probeDeps:t.probeDeps,run:t.run})}catch(r){return EN(e.ids,r)}},xN=e=>({step:e.step,outcome:e.outcome,message:e.message}),Ma=async(e={})=>{let t=RN(e);Xe.withheld=e.unattended===!0;let r=await SN(),n=await PN(t,e),o=await bN(e.portlessDeps??kN()),s=Qw({init:r,tools:n,portless:o},{skipTools:t.skipTools});dt({title:"infra-kit setup",sections:s},{ascii:e.ascii}),d.info(Tn),ek(s)&&(wN.exitCode=1);let i={init:r.map(xN),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}},TN=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")}),CN=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")}),$N=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")}),AN={init:N.array(TN).describe("One entry per init step, in the order they ran"),tools:N.array(CN).describe("One result per requested dependency"),portlessService:$N.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)")},ON={tools:N.array(N.enum(kr)).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.")},sp=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:ON,outputSchema:AN,requiresHumanConfirm:!0,handler:e=>Ma({tools:e.tools,update:e.mode==="update",skipTools:e.skipTools})});import{existsSync as sk}from"node:fs";import ik from"node:path";import WN from"node:process";import{z as Dt}from"zod";import{createHash as DN}from"node:crypto";import{readFileSync as IN}from"node:fs";var Ir=e=>DN("sha256").update(IN(e)).digest("hex");import{readFileSync as LN,writeFileSync as BN}from"node:fs";import Ba from"node:path";import{z as yt}from"zod";var oe="vendor",NN=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack"]),_N=new Set([".sync-manifest.json",".eslintcache","log.txt","routeTree.gen.ts"]),MN=[".tsbuildinfo"],ip=e=>NN.has(e),ap=e=>_N.has(e)?!0:MN.some(t=>e.endsWith(t)),ja=e=>{let t=e.split("/"),r=t.pop()??"";return t.some(o=>ip(o))||ap(r)};import{readdirSync as jN}from"node:fs";import cp from"node:path";var FN=e=>e.split(cp.sep).join("/"),Fa=e=>{let t=[],r=n=>{for(let o of jN(n,{withFileTypes:!0})){let s=cp.join(n,o.name);if(o.isDirectory()){if(ip(o.name))continue;r(s);continue}ap(o.name)||t.push(FN(cp.relative(e,s)))}};return r(e),t.sort()};var Ye=".sync-manifest.json",La=1,UN=yt.object({schemaVersion:yt.number().optional(),source:yt.string(),commit:yt.string(),syncedAt:yt.string(),fileCount:yt.number(),files:yt.record(yt.string(),yt.string())}),lp=e=>(e.schemaVersion??La)>La,ok=(e,t)=>{let r={},n=t?[...new Set(t)].sort():Fa(e);for(let o of n)try{r[o]=Ir(Ba.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},xs=e=>{let t=Ba.join(e,Ye),r;try{r=LN(t,"utf8")}catch{throw new Error(`Missing ${Ye} at ${t}`)}let n=UN.safeParse(JSON.parse(r));if(!n.success)throw new Error(`Invalid ${Ye} at ${t}: ${yt.prettifyError(n.error)}`);return n.data},up=(e,t,r)=>{let n=ok(e,r),o={schemaVersion:La,source:t.source,commit:t.commit,syncedAt:new Date().toISOString(),fileCount:Object.keys(n).length,files:n};return BN(Ba.join(e,Ye),`${JSON.stringify(o,null,2)}
432
- `),o},dp=(e,t)=>{let r=Object.fromEntries(Object.entries(t.files).filter(([c])=>!ja(c))),n=Fa(e),o=[],s=[];for(let c of n){if(!(c in r)){s.push(c);continue}Ir(Ba.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 pp=30,mp=(e,t)=>{if(t.length!==0){d.info(`
433
- ${e} (${t.length}):`);for(let r of t.slice(0,pp))d.info(` ${r}`);t.length>pp&&d.info(` \u2026and ${t.length-pp} more`)}},Ua=async(e={})=>{let t=e.cwd??await A(),r=ik.join(t,oe),n={modified:[],added:[],removed:[],fileCount:0};if(!sk(r)){d.info(`\u2139\uFE0F No ${oe}/ folder found \u2014 nothing to check.`);let u={status:"skipped",ok:!0,...n};return{content:b(JSON.stringify(u,null,2)),structuredContent:u}}if(!sk(ik.join(r,Ye))){d.error(`\u274C Missing ${oe}/${Ye}. 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=xs(r);if(lp(o)){d.error(`\u274C ${oe}/${Ye} 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}=dp(r,o),c=s.length>0||i.length>0||a.length>0;c?(d.error(`\u274C ${oe}/ has drifted from ${oe}/${Ye}.`),d.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),mp("Modified",s),mp("Added (not in manifest)",i),mp("Removed (in manifest, now missing)",a)):d.info(`\u2705 ${oe}/ 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}},VN={status:Dt.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:Dt.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:Dt.number(),modified:Dt.array(Dt.string()),added:Dt.array(Dt.string()),removed:Dt.array(Dt.string())},fp=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:VN,handler:()=>Ua({cwd:WN.cwd()})});import ak from"node:process";import{z as Ts}from"zod";var ck=async e=>{try{return await e()}catch{return null}},Wa=async()=>{let e=L.version;d.info(e);let t=await ck(A),r=t===null?null:await ck(()=>$e(t)),n={version:e,cwd:ak.cwd(),repoRoot:t,mainRepoRoot:r,projectDir:ak.env.CLAUDE_PROJECT_DIR||null};return{content:b(JSON.stringify(n,null,2)),structuredContent:n}},gp=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:Ts.string().describe("Installed infra-kit CLI version (from package.json)"),cwd:Ts.string().describe("The working directory of this process"),repoRoot:Ts.string().nullable().describe("git toplevel of cwd \u2014 the worktree itself in a linked worktree; null when git cannot answer"),mainRepoRoot:Ts.string().nullable().describe("The main checkout a linked worktree belongs to (equals repoRoot outside worktrees); null with repoRoot"),projectDir:Ts.string().nullable().describe("CLAUDE_PROJECT_DIR as Claude Code set it for this process, or null")},handler:Wa});import bk from"@inquirer/confirm";import YN from"node:path";import{z as U}from"zod";import{$ as $s}from"zx";import GN from"@inquirer/input";import uk from"@inquirer/select";import{$ as er}from"zx";var Cs="dev",JN="main",hp="feature/",dk=["new","local","remote"],Va=e=>{let t=e.trim().replace(/^feature\//,"").toLowerCase().replaceAll(/\s+/g,"-");return`${hp}${t}`},pk=async()=>{let e=await er({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},KN=2,yp=async()=>{let e=await er({nothrow:!0,quiet:!0})`git ls-remote --exit-code origin refs/heads/${Cs}`;if(e.exitCode===0)return Cs;if(e.exitCode!==KN)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 ${Cs} exists`});return await pk()??Cs},mk=async e=>{let t=e?.trim();return t?t===Cs||t===JN||t===await pk()?t:Pe(ve(t)):yp()},fk=async()=>_(e=>uk({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"}}),gk=async()=>_(e=>GN({message:"Feature name (becomes feature/<name>):",required:!0,validate:t=>Va(t)===hp?"Enter a name":!0},e),{whenHeadless:{refuse:"feature"}}),hk=async(e,t)=>e.length===0?t:_(r=>uk({message:"Base branch:",default:t,choices:[t,...e].map(n=>({name:n,value:n}))},r),{whenHeadless:{value:t}}),HN=async e=>{let t=await er({nothrow:!0,quiet:!0})`git check-ref-format --branch ${e}`;if(e===hp||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`})},lk=async e=>(await er({nothrow:!0,quiet:!0})`git fetch origin ${e}`).exitCode===0,qN=async e=>(await er({nothrow:!0,quiet:!0})`git show-ref --verify --quiet refs/heads/${e}`).exitCode===0,yk=async e=>{let{names:t,base:r}=e,n=[...new Set(t.map(Va))];for(let s of n)await HN(s);if(!await lk(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 qN(s)?o.push({branch:s,base:r,source:"local"}):await lk(s)?o.push({branch:s,base:r,source:"remote"}):o.push({branch:s,base:r,source:"new"});return o},vk=async(e,t)=>{let{branch:r,base:n,source:o}=e;o==="local"?await er`git worktree add ${t} ${r}`:o==="remote"?await er`git worktree add --track -b ${r} ${t} origin/${r}`:await er`git worktree add --no-track -b ${r} ${t} origin/${n}`},wk=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 As="create worktrees",zN=["already_open","orca_unreachable","orca_absent","orca_worktree_not_selectable","orca_error"],vp=()=>({orcaOpened:[],orcaSkipped:[],orcaHidden:[]}),Ga=async e=>{let{confirmedCommand:t,githubDesktop:r,orca:n}=e;await Ne({operation:As}),XN(e);try{let o=await A(),s=`${o}${fe}`;await kk(`${s}/${Lr.release}`),await kk(`${s}/${Lr.feature}`);let i=await ZN(e),a=i==="feature"?await e_(e):await QN(e);if(a===null){d.info("\u2139\uFE0F No open release branches found"),y.print();let R={kind:i,createdWorktrees:[],count:0,features:[],...vp()};return{content:b(JSON.stringify(R,null,2)),structuredContent:R}}let c=await H(),l=await t_(r,c),u=await r_(n,c),p=await $e(o),m=YN.basename(p),f=u?await n_({explicit:n!==void 0,mainRepoRoot:p}):null;await G(t,o_(f,m,a.previewLines)),t||y.addOption("--yes",!0);let v=f?await s_(f,p):null,E=await u_(a.targets,s);if(d_(E),l)for(let R of E)await $s`github ${s}/${R}`,await $s`sleep 5`;let k=v?await a_({registration:v,createdWorktrees:E,worktreeDir:s,mainRepoRoot:p,repoName:m,config:c}):vp();c_(k),y.print();let h={kind:i,createdWorktrees:E,count:E.length,features:a.features.filter(R=>E.includes(R.branch)),...k};return{content:b(JSON.stringify(h,null,2)),structuredContent:h}}catch(o){throw Ae(o)||o instanceof O?o:(d.debug({err:o},"Error managing worktrees"),new g(o,{operation:As,remediation:o instanceof g&&o.remediation||"verify branches don't already exist as worktrees: 'git worktree list'"}))}},XN=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:As,remediation:"pass either --versions/--all (release worktrees) or --feature [--base] (feature worktrees)",stderrExcerpt:"--feature/--base cannot be combined with --versions/--all"})},ZN=async e=>e.feature!==void 0||e.base!==void 0?"feature":e.all||e.versions!==void 0?"release":(y.setInteractive(),fk()),QN=async e=>{let{all:t,versions:r}=e,n=await we("release"),o=[];if(r)o=r.split(",").map(a=>Pe(ve(a.trim())));else{let a=await V(),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 pe();o=await Kt(me({branches:c,descriptions:u,types:l}),{required:!0})}}t?y.addOption("--all",!0):y.addOption("--versions",$t(o));let{branchesToCreate:s}=l_({selectedReleaseBranches:o,currentWorktrees:n});return{targets:s.map(a=>({branch:a,add:c=>$s`git worktree add ${c} ${a}`})),features:[],previewLines:[]}},e_=async e=>{let r=e.feature?.split(",").filter(l=>l.trim()!=="")??[],n=e.base;if(r.length===0&&(y.setInteractive(),r=[await gk()],n===void 0)){let l=(await V()).map(u=>u.branch);n=await hk(l,await yp())}let o=await mk(n),s=await yk({names:r,base:o});y.addOption("--feature",s.map(l=>l.branch.replace(/^feature\//,"")).join(",")),y.addOption("--base",o);let i=await we("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=>vk(l,u)})),features:a,previewLines:a.map(wk)}},t_=async(e,t)=>{let r=t.worktrees?.openInGithubDesktop,n=e??r??await _(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},r_=async(e,t)=>{let r=t.worktrees?.openInOrca,n=e??r??await _(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},Rk=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"},n_=async e=>{let{explicit:t,mainRepoRoot:r}=e,n=await Lt();if(n!=="ready"){let{reason:s,text:i}=Rk(n);if(t)throw d.warn({operation:As},`\u26D4 --orca was passed but ${i}`),new O({status:"refused",reason:s,agentMode:j.source},2,{operation:As,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 Nf(r);return{probe:n,registered:o.registered,visibility:o.visibility}},o_=(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
- `)},s_=async(e,t)=>{if(e.probe!=="ready")return{kind:"skip",reason:Rk(e.probe).reason};if(e.registered)return{kind:"ready",visibility:e.visibility};try{let{visibility:r}=await _f(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 Vr?r.code:void 0}}},i_=e=>`Orca \u2192 ${e} \u2192 "hidden worktrees" card \u2192 Show, or Settings \u2192 General \u2192 Workspace \u2192 external-worktree sources`,a_=async e=>{let{registration:t,createdWorktrees:r,worktreeDir:n,mainRepoRoot:o,repoName:s,config:i}=e,a=vp();if(t.kind==="skip"){for(let p of r)a.orcaSkipped.push({branch:p,reason:t.reason,code:t.code});return a}let c=gf(i),l=r.length===1&&t.visibility!=="hide",u=jf();for(let p of r){let m=`${n}/${p}`;try{let{layout:f}=await Ff({cwd:m,title:Lf({branch:p}),focus:l,layout:"full",panes:c,poll:u});await Mf(o,m)?a.orcaOpened.push({branch:p,layout:f}):a.orcaHidden.push({branch:p,path:m,fix:i_(s)})}catch(f){d.warn({error:f,branch:p},`\u26A0\uFE0F Failed to open Orca terminals for ${p}`),f instanceof Vr&&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 Vr?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}`)}},kk=async e=>{await $s`mkdir -p ${e}`},l_=e=>{let{selectedReleaseBranches:t,currentWorktrees:r}=e,n=r.filter(s=>Br(s));return{branchesToCreate:t.filter(s=>!n.includes(s))}},u_=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},d_=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")},wp=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:U.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:U.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:U.boolean().optional().describe('Add worktrees for every open release branch. Either "all" or "versions" must be provided for MCP calls (the interactive picker is unavailable without a TTY). Ignored if "versions" is provided.'),versions:U.string().optional().describe('Comma-separated release versions or names to target (e.g. "1.2.5, 1.2.6" or "checkout-redesign, 1.2.5"). Either "versions" or all=true must be provided for MCP calls. Overrides "all" when set.'),githubDesktop:U.boolean().optional().describe('Open each created worktree in GitHub Desktop. Resolution order: this flag \u2192 "worktrees.openInGithubDesktop" from infra-kit config \u2192 interactive prompt (CLI) / false (MCP, no TTY).'),orca:U.boolean().optional().describe('Open each created worktree in Orca: one terminal tab per worktree, laid out per "worktrees.orca.layout" (default "two-columns": left | right; or "three-pane": left split top/bottom + full-height right). Resolution order: this flag \u2192 "worktrees.openInOrca" from infra-kit config \u2192 interactive prompt (CLI, default yes) / false (MCP, no TTY). Passed explicitly, an Orca that is absent or not running is refused before any worktree is created (orca_absent / orca_unreachable); resolved from config it degrades to orcaSkipped with that reason.')},outputSchema:{kind:U.enum(["release","feature"]).describe("Which kind of worktree the run created"),features:U.array(U.object({branch:U.string(),base:U.string(),source:U.enum(dk)})).describe('Created feature worktrees: source "new" = cut from origin/<base>; "local" / "remote" = an existing branch checked out as-is (base not applied)'),createdWorktrees:U.array(U.string()).describe("List of created git worktree branches"),count:U.number().describe("Number of git worktrees created"),orcaOpened:U.array(U.object({branch:U.string(),layout:U.enum(["full","single-pane"])})).describe("Created worktrees that got an Orca terminal tab on a row the sidebar shows, with the layout applied"),orcaSkipped:U.array(U.object({branch:U.string(),reason:U.enum(zN),code:U.string().optional()})).describe("Created worktrees NOT opened in Orca and why: orca_absent / orca_unreachable (config-derived ask, Orca down), orca_worktree_not_selectable (Orca had not scanned the fresh worktree yet), orca_error (code carries the Orca error code)"),orcaHidden:U.array(U.object({branch:U.string(),path:U.string(),fix:U.string()})).describe("Created worktrees whose Orca terminals opened on a row the sidebar HIDES (the repo hides external worktrees); fix names the in-app steps to reveal it")},handler:Ga});import{z as tr}from"zod";var Ja=async()=>{await H();let[e,t]=await Promise.all([we("release"),we("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 p_(e):[],n=[];r.length>0&&n.push(`\u{1F33F} Active worktrees:
430
+ `},KI=e=>({version:e.version??L.version,home:e.home??DI(),clock:e.clock??Date.now,acquireLock:e.acquireLock??(()=>Dc({lockPath:fy()})),readRecord:e.readRecord??Rn,writeRecord:e.writeRecord??gy,discoverProjects:e.discoverProjects??(()=>Qw()),runSetupChild:e.runSetupChild??FI,writeLog:e.writeLog??LI}),HI=e=>{try{return{projects:e.discoverProjects(),error:null}}catch(t){return{projects:[],error:t instanceof Error?t.message:String(t)}}},qI=async e=>{let t=e.readRecord(),r=e.clock();if(!vy(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+NI,s=await ek(null,e.home,e,o),i=HI(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 ek(l,l,e,o));let c={version:e.version,attempts:n,startedMs:r,finishedMs:e.clock(),runs:GI(a)};e.writeRecord(c);try{e.writeLog(JI(c))}catch{}return"ran"},tk=async(e={})=>{try{let t=KI(e),r=t.acquireLock();if(r===null)return"already-running";try{return await qI(t)}finally{r()}}catch{return"not-due"}},tp=async(e={})=>{let t=await tk(e);return{content:b(JSON.stringify({outcome:t})),structuredContent:{outcome:t}}};import{spawnSync as ZI}from"node:child_process";import{homedir as QI}from"node:os";import eN from"node:process";var YI=e=>{let t=new Set(e.steps.map(r=>r[0]));return t.has("brew")?"homebrew":t.has("npm")?"npm":null},zI=e=>{let t=[];return e.needsSudo&&t.push("needs-sudo"),e.fetchesNetworkScript&&t.push("fetches-network-script"),t},XI=(e,t)=>{let r=YI(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},Ts=(e,t)=>{let r=[...zI(e),...XI(e,t)];return r.length===0?{executable:!0}:{executable:!1,reasons:r}},Cs=e=>e.steps.map(Be);var tN=["NONINTERACTIVE","CI","INTERACTIVE","HAVE_SUDO_ACCESS","SUDO_ASKPASS"],rN=e=>{let t={...Dm(e)};for(let r of tN)delete t[r];return t},rp=(e,t,r={})=>{let n=r.spawnSync??ZI,o=r.env??eN.env,s=(r.agentMode??he)(),i=Cs(e),a=Ts(e,t);return a.executable?s?{ran:!1,commands:i,refusedBecause:["agent-mode"]}:sN({recipe:e,spawn:n,env:o,commands:i,notify:r.notify??nN}):{ran:!1,commands:i,refusedBecause:a.reasons}},nN=e=>{d.info(e)},nk=64,oN=nk*1024*1024,sN=({recipe:e,spawn:t,env:r,commands:n,notify:o})=>{let s=rN(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:oN,cwd:QI(),env:s}),l=dN(c);if(l!==null)return{ran:!0,ok:!1,commands:n,failedStep:n[i],detail:l}}return{ran:!0,ok:!0,commands:n}},iN=5,aN=/^(?:error|fatal|warning: failed|[a-z-]{0,20} ERR!)[:\s]/i,rk=e=>e==null?[]:String(e).split(`
431
+ `).map(t=>t.trim()).filter(t=>t.length>0),cN=e=>{let t=rk(e.stderr),r=rk(e.stdout),n=[...t,...r].filter(s=>aN.test(s)),o=t.length>0?t:r;return(n.length>0?n:o).slice(-iN).join(" / ")},lN="ENOBUFS",uN=e=>e.error?.code===lN,dN=e=>{if(uN(e))return`terminated after exceeding the ${nk} 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=cN(e),r=t===""?"":`: ${t}`;return`exited ${e.status??"unknown"}${r}`};var pN=e=>{let t=[];return e.some(n=>n.id==="brew"&&n.present)&&t.push("homebrew"),t.push("npm"),t},mN=e=>{let t=Ke(e.id);return e.present?t.updateFor(e.binRealPath):t.bootstrapInstall},fN=(e,t)=>{let r=mN(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=Ts(r,n);return{state:e,action:e.present?"update":"install",recipe:r,executable:o.executable,refusedBecause:o.executable?[]:o.reasons,commands:Cs(r),context:n}},Fa=async(e=Rr,t=Ho())=>{let r=await Yo(Rr,t),n={owner:null,present:pN(r)},o=Du(e),s=new Map(r.map(a=>[a.id,a]));return{plans:o.filter(a=>e.includes(a)).map(a=>fN(s.get(a),n)),context:n}};var np=(e,t)=>({...$s(e),action:"skipped",commands:e.commands,detail:t}),$s=e=>({id:e.state.id,before:{present:e.state.present,onPath:e.state.onPath,version:e.state.version,manager:e.state.manager}}),ok=(e,t)=>e.action==="none"?np(e,`nothing to do: ${e.state.manager} installs are not managed from here`):t==="update"&&e.action==="install"?np(e,"not installed, and --update only updates \u2014 drop the flag to install it"):e.executable?null:{...$s(e),action:"refused",commands:e.commands,detail:`refused (${e.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},gN=(e,t)=>t.ran?t.ok?{...$s(e),action:e.action==="install"?"installed":"updated",commands:t.commands,detail:e.action==="install"?"installed":"updated"}:{...$s(e),action:"failed",commands:t.commands,detail:`${t.failedStep??"a step"} ${t.detail??"failed"}`}:{...$s(e),action:"refused",commands:t.commands,detail:`refused (${t.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},op=async e=>{let t=e.run??rp,{plans:r}=await Fa(e.ids,e.probeDeps),n=[];for(let o of r){let s=ok(o,e.mode);if(s!==null){n.push(s);continue}n.push(gN(o,t(o.recipe,o.context)))}return n},sp=async(e,t)=>{let{plans:r}=await Fa(e,t);return r.map(n=>ok(n,"converge")??np(n,`would ${n.action} \u2014 nothing was run (--skip-tools)`))};import ON from"node:process";import{z as _}from"zod";var ip={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},hN=Object.keys(ip).sort((e,t)=>ip[e]-ip[t]),sk={skipped:0,ok:1,changed:2,manual:3,warn:4,fail:5},ik=new Set(["manual","warn","fail"]),ap=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 Ue(e)}},yN=e=>e.reduce((t,r)=>sk[r]>sk[t]?r:t,"skipped"),ck=e=>e.message.trim(),vN=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 "),ak=e=>e.message===Cn,wN=(e,t)=>{let[r]=e;return e.length===1&&r!==void 0?ck(r):e.length>1?vN(e):t?"activate with the last line below":"see below"},kN=(e,t)=>{if(t.length===0)return{name:e,status:"skipped",message:"did not run"};let r=t.map(i=>ap(i.outcome)),n=t.filter(i=>ik.has(ap(i.outcome))).map(ck),o=t.filter(i=>!ik.has(ap(i.outcome))&&!ak(i)),s={name:e,status:yN(r),message:wN(o,t.some(ak))};return n.length>0?{...s,notes:n}:s},bN=e=>({label:"Local setup",rows:hN.map(t=>kN(t,e.filter(r=>r.step===t)))}),RN=(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 Ue(e.action)}},SN=(e,t)=>{let r=RN(e,t),n={name:e.id,status:r,message:e.detail};return r==="manual"&&e.commands.length>0?{...n,notes:[...e.commands]}:n},EN=(e,t)=>({label:t.skipTools?"Tools (probe: nothing installed)":"Tools",rows:e.map(r=>SN(r,t))}),PN=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 Ue(e)}},xN=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 Ue(e)}},TN=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 Ue(e)}},CN=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 Ue(e.outcome)}},$N=(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 Ue(e)}},AN=e=>({label:"Portless service",rows:[{name:"link",status:PN(e.link),message:TN(e.link)},{name:"node",status:xN(e.node.outcome),message:CN(e.node)},$N(e.service,e.command)]}),lk=(e,t)=>[bN(e.init),EN(e.tools,t),AN(e.portless)],uk=e=>e.some(t=>t.rows.some(r=>r.status==="fail"));var DN=()=>{let{link:e,node:t}=Zs();return{link:e,node:t,target:{home:e.home,isGlobal:e.isGlobal,processStartTime:()=>null}}},IN=async e=>{let t=qm(e.link).outcome,r=Hm(e.node),n=Xs(e.link.home,e.target.exists)??e.link.resolveBin();if(n===null)return{link:t,node:r,service:"skipped",command:null};let{state:o,stableNode:s}=await vv(e.target,n);if(o==="converged")return{link:t,node:r,service:o,command:null};let i=Mt(n,{home:e.link.home,exists:e.target.exists,execPath:e.target.execPath,stableNode:s});return{link:t,node:r,service:o,command:i}},pk="--unattended cannot be combined with --tools or --update: an unattended run installs and updates nothing (it implies --skip-tools).",mk="--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.",NN=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(pk);if(o&&(e.tools!==void 0||r))throw new Error(mk);return{ids:e.tools??t??Rr,mode:r?"update":"converge",skipTools:o}},dk=(e,t)=>e instanceof Tn?e.step:t.at(-1)?.step??"zshrc",_N=async()=>{let e=[];try{await Pu(t=>{e.push(t)})}catch(t){e.push({step:dk(t,e),outcome:"failed",message:`The ${dk(t,e)} step failed: ${t instanceof Error?t.message:String(t)}`,level:"warn"})}return e},MN=(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 sp(e.ids,t.probeDeps):await op({ids:e.ids,mode:e.mode,probeDeps:t.probeDeps,run:t.run})}catch(r){return MN(e.ids,r)}},FN=e=>({step:e.step,outcome:e.outcome,message:e.message}),La=async(e={})=>{let t=NN(e);Xe.withheld=e.unattended===!0;let r=await _N(),n=await jN(t,e),o=await IN(e.portlessDeps??DN()),s=lk({init:r,tools:n,portless:o},{skipTools:t.skipTools});dt({title:"infra-kit setup",sections:s},{ascii:e.ascii}),d.info(Cn),uk(s)&&(ON.exitCode=1);let i={init:r.map(FN),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}},LN=_.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")}),BN=_.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")}),UN=_.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")}),WN={init:_.array(LN).describe("One entry per init step, in the order they ran"),tools:_.array(BN).describe("One result per requested dependency"),portlessService:UN.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)")},VN={tools:_.array(_.enum(Rr)).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.")},cp=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:VN,outputSchema:WN,requiresHumanConfirm:!0,handler:e=>La({tools:e.tools,update:e.mode==="update",skipTools:e.skipTools})});import{existsSync as gk}from"node:fs";import hk from"node:path";import e_ from"node:process";import{z as Nt}from"zod";import{createHash as GN}from"node:crypto";import{readFileSync as JN}from"node:fs";var Nr=e=>GN("sha256").update(JN(e)).digest("hex");import{readFileSync as XN,writeFileSync as ZN}from"node:fs";import Va from"node:path";import{z as vt}from"zod";var oe="vendor",KN=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".vitest",".output",".source",".nitro",".tanstack"]),HN=new Set([".sync-manifest.json",".eslintcache","log.txt","routeTree.gen.ts"]),qN=[".tsbuildinfo"],lp=e=>KN.has(e),up=e=>HN.has(e)?!0:qN.some(t=>e.endsWith(t)),Ba=e=>{let t=e.split("/"),r=t.pop()??"";return t.some(o=>lp(o))||up(r)};import{readdirSync as YN}from"node:fs";import dp from"node:path";var zN=e=>e.split(dp.sep).join("/"),Ua=e=>{let t=[],r=n=>{for(let o of YN(n,{withFileTypes:!0})){let s=dp.join(n,o.name);if(o.isDirectory()){if(lp(o.name))continue;r(s);continue}up(o.name)||t.push(zN(dp.relative(e,s)))}};return r(e),t.sort()};var Ye=".sync-manifest.json",Wa=1,QN=vt.object({schemaVersion:vt.number().optional(),source:vt.string(),commit:vt.string(),syncedAt:vt.string(),fileCount:vt.number(),files:vt.record(vt.string(),vt.string())}),pp=e=>(e.schemaVersion??Wa)>Wa,fk=(e,t)=>{let r={},n=t?[...new Set(t)].sort():Ua(e);for(let o of n)try{r[o]=Nr(Va.join(e,o))}catch(s){let i=s instanceof Error?s.message:String(s);throw new Error(`Cannot hash vendor file "${o}" (broken symlink or unreadable file): ${i}`)}return r},As=e=>{let t=Va.join(e,Ye),r;try{r=XN(t,"utf8")}catch{throw new Error(`Missing ${Ye} at ${t}`)}let n=QN.safeParse(JSON.parse(r));if(!n.success)throw new Error(`Invalid ${Ye} at ${t}: ${vt.prettifyError(n.error)}`);return n.data},mp=(e,t,r)=>{let n=fk(e,r),o={schemaVersion:Wa,source:t.source,commit:t.commit,syncedAt:new Date().toISOString(),fileCount:Object.keys(n).length,files:n};return ZN(Va.join(e,Ye),`${JSON.stringify(o,null,2)}
432
+ `),o},fp=(e,t)=>{let r=Object.fromEntries(Object.entries(t.files).filter(([c])=>!Ba(c))),n=Ua(e),o=[],s=[];for(let c of n){if(!(c in r)){s.push(c);continue}Nr(Va.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 gp=30,hp=(e,t)=>{if(t.length!==0){d.info(`
433
+ ${e} (${t.length}):`);for(let r of t.slice(0,gp))d.info(` ${r}`);t.length>gp&&d.info(` \u2026and ${t.length-gp} more`)}},Ga=async(e={})=>{let t=e.cwd??await A(),r=hk.join(t,oe),n={modified:[],added:[],removed:[],fileCount:0};if(!gk(r)){d.info(`\u2139\uFE0F No ${oe}/ folder found \u2014 nothing to check.`);let u={status:"skipped",ok:!0,...n};return{content:b(JSON.stringify(u,null,2)),structuredContent:u}}if(!gk(hk.join(r,Ye))){d.error(`\u274C Missing ${oe}/${Ye}. 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=As(r);if(pp(o)){d.error(`\u274C ${oe}/${Ye} 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}=fp(r,o),c=s.length>0||i.length>0||a.length>0;c?(d.error(`\u274C ${oe}/ has drifted from ${oe}/${Ye}.`),d.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),hp("Modified",s),hp("Added (not in manifest)",i),hp("Removed (in manifest, now missing)",a)):d.info(`\u2705 ${oe}/ 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}},t_={status:Nt.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:Nt.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:Nt.number(),modified:Nt.array(Nt.string()),added:Nt.array(Nt.string()),removed:Nt.array(Nt.string())},yp=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:t_,handler:()=>Ga({cwd:e_.cwd()})});import yk from"node:process";import{z as Os}from"zod";var vk=async e=>{try{return await e()}catch{return null}},Ja=async()=>{let e=L.version;d.info(e);let t=await vk(A),r=t===null?null:await vk(()=>$e(t)),n={version:e,cwd:yk.cwd(),repoRoot:t,mainRepoRoot:r,projectDir:yk.env.CLAUDE_PROJECT_DIR||null};return{content:b(JSON.stringify(n,null,2)),structuredContent:n}},vp=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:Os.string().describe("Installed infra-kit CLI version (from package.json)"),cwd:Os.string().describe("The working directory of this process"),repoRoot:Os.string().nullable().describe("git toplevel of cwd \u2014 the worktree itself in a linked worktree; null when git cannot answer"),mainRepoRoot:Os.string().nullable().describe("The main checkout a linked worktree belongs to (equals repoRoot outside worktrees); null with repoRoot"),projectDir:Os.string().nullable().describe("CLAUDE_PROJECT_DIR as Claude Code set it for this process, or null")},handler:Ja});import Ok from"@inquirer/confirm";import a_ from"node:path";import{z as U}from"zod";import{$ as Is}from"zx";import r_ from"@inquirer/input";import kk from"@inquirer/select";import{$ as rr}from"zx";var Ds="dev",n_="main",wp="feature/",bk=["new","local","remote"],Ka=e=>{let t=e.trim().replace(/^feature\//,"").toLowerCase().replaceAll(/\s+/g,"-");return`${wp}${t}`},Rk=async()=>{let e=await rr({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},o_=2,kp=async()=>{let e=await rr({nothrow:!0,quiet:!0})`git ls-remote --exit-code origin refs/heads/${Ds}`;if(e.exitCode===0)return Ds;if(e.exitCode!==o_)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 ${Ds} exists`});return await Rk()??Ds},Sk=async e=>{let t=e?.trim();return t?t===Ds||t===n_||t===await Rk()?t:xe(we(t)):kp()},Ek=async()=>M(e=>kk({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"}}),Pk=async()=>M(e=>r_({message:"Feature name (becomes feature/<name>):",required:!0,validate:t=>Ka(t)===wp?"Enter a name":!0},e),{whenHeadless:{refuse:"feature"}}),xk=async(e,t)=>e.length===0?t:M(r=>kk({message:"Base branch:",default:t,choices:[t,...e].map(n=>({name:n,value:n}))},r),{whenHeadless:{value:t}}),s_=async e=>{let t=await rr({nothrow:!0,quiet:!0})`git check-ref-format --branch ${e}`;if(e===wp||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`})},wk=async e=>(await rr({nothrow:!0,quiet:!0})`git fetch origin ${e}`).exitCode===0,i_=async e=>(await rr({nothrow:!0,quiet:!0})`git show-ref --verify --quiet refs/heads/${e}`).exitCode===0,Tk=async e=>{let{names:t,base:r}=e,n=[...new Set(t.map(Ka))];for(let s of n)await s_(s);if(!await wk(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 i_(s)?o.push({branch:s,base:r,source:"local"}):await wk(s)?o.push({branch:s,base:r,source:"remote"}):o.push({branch:s,base:r,source:"new"});return o},Ck=async(e,t)=>{let{branch:r,base:n,source:o}=e;o==="local"?await rr`git worktree add ${t} ${r}`:o==="remote"?await rr`git worktree add --track -b ${r} ${t} origin/${r}`:await rr`git worktree add --no-track -b ${r} ${t} origin/${n}`},$k=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 Ns="create worktrees",c_=["already_open","orca_unreachable","orca_absent","orca_worktree_not_selectable","orca_error"],bp=()=>({orcaOpened:[],orcaSkipped:[],orcaHidden:[]}),Ha=async e=>{let{confirmedCommand:t,githubDesktop:r,orca:n}=e;await Ne({operation:Ns}),l_(e);try{let o=await A(),s=`${o}${ge}`;await Ak(`${s}/${Br.release}`),await Ak(`${s}/${Br.feature}`);let i=await u_(e),a=i==="feature"?await p_(e):await d_(e);if(a===null){d.info("\u2139\uFE0F No open release branches found"),h.print();let v={kind:i,createdWorktrees:[],count:0,features:[],...bp()};return{content:b(JSON.stringify(v,null,2)),structuredContent:v}}let c=await K(),l=await m_(r,c),u=await f_(n,c),p=await $e(o),m=a_.basename(p),f=u?await g_({explicit:n!==void 0,mainRepoRoot:p}):null;await J(t,h_(f,m,a.previewLines)),t||h.addOption("--yes",!0);let y=f?await y_(f,p):null,E=await R_(a.targets,s);if(S_(E),l)for(let v of E)await Is`github ${s}/${v}`,await Is`sleep 5`;let k=y?await w_({registration:y,createdWorktrees:E,worktreeDir:s,mainRepoRoot:p,repoName:m,config:c}):bp();k_(k),h.print();let O={kind:i,createdWorktrees:E,count:E.length,features:a.features.filter(v=>E.includes(v.branch)),...k};return{content:b(JSON.stringify(O,null,2)),structuredContent:O}}catch(o){throw Ae(o)||o instanceof D?o:(d.debug({err:o},"Error managing worktrees"),new g(o,{operation:Ns,remediation:o instanceof g&&o.remediation||"verify branches don't already exist as worktrees: 'git worktree list'"}))}},l_=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:Ns,remediation:"pass either --versions/--all (release worktrees) or --feature [--base] (feature worktrees)",stderrExcerpt:"--feature/--base cannot be combined with --versions/--all"})},u_=async e=>e.feature!==void 0||e.base!==void 0?"feature":e.all||e.versions!==void 0?"release":(h.setInteractive(),Ek()),d_=async e=>{let{all:t,versions:r}=e,n=await ke("release"),o=[];if(r)o=r.split(",").map(a=>xe(we(a.trim())));else{let a=await G(),c=a.map(l=>l.branch);if(c.length===0)return null;if(t)o=c;else{h.setInteractive();let l=new Map(a.map(p=>[p.branch,p.type])),u=await pe();o=await qt(me({branches:c,descriptions:u,types:l}),{required:!0})}}t?h.addOption("--all",!0):h.addOption("--versions",Ot(o));let{branchesToCreate:s}=b_({selectedReleaseBranches:o,currentWorktrees:n});return{targets:s.map(a=>({branch:a,add:c=>Is`git worktree add ${c} ${a}`})),features:[],previewLines:[]}},p_=async e=>{let r=e.feature?.split(",").filter(l=>l.trim()!=="")??[],n=e.base;if(r.length===0&&(h.setInteractive(),r=[await Pk()],n===void 0)){let l=(await G()).map(u=>u.branch);n=await xk(l,await kp())}let o=await Sk(n),s=await Tk({names:r,base:o});h.addOption("--feature",s.map(l=>l.branch.replace(/^feature\//,"")).join(",")),h.addOption("--base",o);let i=await ke("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=>Ck(l,u)})),features:a,previewLines:a.map($k)}},m_=async(e,t)=>{let r=t.worktrees?.openInGithubDesktop,n=e??r??await M(o=>Ok({message:"Open created worktrees in GitHub Desktop?"},o),{whenHeadless:{value:!1}});return e===void 0&&r===void 0&&h.setInteractive(),h.addOption(n?"--github-desktop":"--no-github-desktop",!0),n},f_=async(e,t)=>{let r=t.worktrees?.openInOrca,n=e??r??await M(o=>Ok({message:"Open created worktrees in Orca?",default:!0},o),{whenHeadless:{value:!1}});return e===void 0&&r===void 0&&h.setInteractive(),h.addOption(n?"--orca":"--no-orca",!0),n},Dk=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"},g_=async e=>{let{explicit:t,mainRepoRoot:r}=e,n=await Ut();if(n!=="ready"){let{reason:s,text:i}=Dk(n);if(t)throw d.warn({operation:Ns},`\u26D4 --orca was passed but ${i}`),new D({status:"refused",reason:s,agentMode:j.source},2,{operation:Ns,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 jf(r);return{probe:n,registered:o.registered,visibility:o.visibility}},h_=(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
+ `)},y_=async(e,t)=>{if(e.probe!=="ready")return{kind:"skip",reason:Dk(e.probe).reason};if(e.registered)return{kind:"ready",visibility:e.visibility};try{let{visibility:r}=await Ff(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 Gr?r.code:void 0}}},v_=e=>`Orca \u2192 ${e} \u2192 "hidden worktrees" card \u2192 Show, or Settings \u2192 General \u2192 Workspace \u2192 external-worktree sources`,w_=async e=>{let{registration:t,createdWorktrees:r,worktreeDir:n,mainRepoRoot:o,repoName:s,config:i}=e,a=bp();if(t.kind==="skip"){for(let p of r)a.orcaSkipped.push({branch:p,reason:t.reason,code:t.code});return a}let c=vf(i),l=r.length===1&&t.visibility!=="hide",u=Bf();for(let p of r){let m=`${n}/${p}`;try{let{layout:f}=await Uf({cwd:m,title:Wf({branch:p}),focus:l,layout:"full",panes:c,poll:u});await Lf(o,m)?a.orcaOpened.push({branch:p,layout:f}):a.orcaHidden.push({branch:p,path:m,fix:v_(s)})}catch(f){d.warn({error:f,branch:p},`\u26A0\uFE0F Failed to open Orca terminals for ${p}`),f instanceof Gr&&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 Gr?f.code:void 0})}}return a},k_=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}`)}},Ak=async e=>{await Is`mkdir -p ${e}`},b_=e=>{let{selectedReleaseBranches:t,currentWorktrees:r}=e,n=r.filter(s=>Ur(s));return{branchesToCreate:t.filter(s=>!n.includes(s))}},R_=async(e,t)=>{let r=await Promise.allSettled(e.map(async o=>{let s=`${t}/${o.branch}`;return await o.add(s),await Is({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},S_=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")},Rp=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:U.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:U.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:U.boolean().optional().describe('Add worktrees for every open release branch. Either "all" or "versions" must be provided for MCP calls (the interactive picker is unavailable without a TTY). Ignored if "versions" is provided.'),versions:U.string().optional().describe('Comma-separated release versions or names to target (e.g. "1.2.5, 1.2.6" or "checkout-redesign, 1.2.5"). Either "versions" or all=true must be provided for MCP calls. Overrides "all" when set.'),githubDesktop:U.boolean().optional().describe('Open each created worktree in GitHub Desktop. Resolution order: this flag \u2192 "worktrees.openInGithubDesktop" from infra-kit config \u2192 interactive prompt (CLI) / false (MCP, no TTY).'),orca:U.boolean().optional().describe('Open each created worktree in Orca: one terminal tab per worktree, laid out per "worktrees.orca.layout" (default "two-columns": left | right; or "three-pane": left split top/bottom + full-height right). Resolution order: this flag \u2192 "worktrees.openInOrca" from infra-kit config \u2192 interactive prompt (CLI, default yes) / false (MCP, no TTY). Passed explicitly, an Orca that is absent or not running is refused before any worktree is created (orca_absent / orca_unreachable); resolved from config it degrades to orcaSkipped with that reason.')},outputSchema:{kind:U.enum(["release","feature"]).describe("Which kind of worktree the run created"),features:U.array(U.object({branch:U.string(),base:U.string(),source:U.enum(bk)})).describe('Created feature worktrees: source "new" = cut from origin/<base>; "local" / "remote" = an existing branch checked out as-is (base not applied)'),createdWorktrees:U.array(U.string()).describe("List of created git worktree branches"),count:U.number().describe("Number of git worktrees created"),orcaOpened:U.array(U.object({branch:U.string(),layout:U.enum(["full","single-pane"])})).describe("Created worktrees that got an Orca terminal tab on a row the sidebar shows, with the layout applied"),orcaSkipped:U.array(U.object({branch:U.string(),reason:U.enum(c_),code:U.string().optional()})).describe("Created worktrees NOT opened in Orca and why: orca_absent / orca_unreachable (config-derived ask, Orca down), orca_worktree_not_selectable (Orca had not scanned the fresh worktree yet), orca_error (code carries the Orca error code)"),orcaHidden:U.array(U.object({branch:U.string(),path:U.string(),fix:U.string()})).describe("Created worktrees whose Orca terminals opened on a row the sidebar HIDES (the repo hides external worktrees); fix names the in-app steps to reveal it")},handler:Ha});import{z as nr}from"zod";var qa=async()=>{await K();let[e,t]=await Promise.all([ke("release"),ke("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 E_(e):[],n=[];r.length>0&&n.push(`\u{1F33F} Active worktrees:
435
435
 
436
- ${m_(r).join(`
436
+ ${P_(r).join(`
437
437
  `)}`),t.length>0&&n.push(`\u{1F9EA} Feature worktrees:
438
438
 
439
439
  ${t.join(`
440
440
  `)}`),d.info(n.join(`
441
441
 
442
- `));let o={worktrees:r,count:r.length,features:t};return{content:b(JSON.stringify(o,null,2)),structuredContent:o}},p_=async e=>{let[t,r]=await Promise.all([V(),pe()]),n=new Map(t.map(o=>[o.branch,o.type]));return e.flatMap(o=>{let s=Q(o);if(!s)return[];let i=re(s),a=n.get(o)||"regular",c=r.get(ce(s))||null;return[{version:i,type:a,description:c}]})},m_=e=>{let t=Math.max(...e.map(r=>r.version.length));return e.map(r=>{let n=No(r.version,r.type,t);return r.description?`${n} ${r.description}`:n})},kp=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:tr.array(tr.object({version:tr.string().describe("Release version"),type:tr.enum(["regular","hotfix"]).describe("Release type"),description:tr.string().nullable().describe("Jira version description")})).describe("Release worktrees with details"),count:tr.number().describe("Number of release worktrees"),features:tr.array(tr.string()).describe("Branches of feature worktrees (feature/<name>)")},handler:Ja});import{z as ze}from"zod";import f_ from"node:fs/promises";import{$ as g_}from"zx";var Ek="remove this worktree",h_=2,y_=3,Ka=async e=>{try{return await f_.realpath(e)}catch{return e}},Nr=(e,t)=>{throw new g(void 0,{operation:Ek,remediation:e,stderrExcerpt:t})},v_=e=>{if(e.startsWith("feature/"))return["--feature",e.slice(8)];let[t]=$t([e]);return Br(e)&&t?["--versions",t]:Nr("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`)},w_=async()=>{let e=await Ka(await A()),t=await Ka(await $e(e));e===t&&Nr("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 ot(t))await Ka(o.path)===e&&(r=o.branch);if(!r)return Nr("check out a branch in this worktree first",`no branch is checked out at ${e}`);let n=await Ka(`${t}${fe}/${r}`);return n!==e&&Nr("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:v_(r)}},Sk=async e=>(await g_({quiet:!0})`git -C ${e} status --porcelain`).stdout.split(`
443
- `).filter(r=>r.trim().length>0),k_=async e=>{let[t,r]=await Promise.all([Sk(e.worktreePath),Sk(e.mainRoot)]);t.length>0&&Nr("commit or stash your changes (`git stash -u`), then retry",`uncommitted changes: ${t.join(", ")}`),r.length>0&&Nr(`commit or stash the changes in the main checkout ${e.mainRoot}, then retry`,`the main checkout has uncommitted changes: ${r.join(", ")}`);let n=await Lt();n!=="ready"&&Nr(`run \`infra-kit worktrees remove ${Be(e.targetArgs)}\` from the main checkout ${e.mainRoot}`,`--self hands the removal to an Orca terminal, and Orca is ${n}`)},b_=async e=>{let t=Be(["infra-kit","worktrees","remove",...e.targetArgs,"--yes"]),r=`sleep ${h_}; ${t} && { sleep ${y_}; exit; }`;try{return(await Of(["terminal","create","--worktree",`path:${e.mainRoot}`,"--title",`ik: remove ${e.branch}`,"--command",r])).terminal.handle}catch(n){throw n instanceof Vr?new g(n,{operation:Ek,remediation:`run \`infra-kit worktrees remove ${Be(e.targetArgs)}\` from the main checkout ${e.mainRoot}`,stderrExcerpt:n.message}):n}},Pk=async e=>{let t=await w_();await k_(t),y.addOption("--self",!0),await G(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 b_(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 R_=e=>{if(ge()){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"})}},S_=(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(", ")}`})},E_=async(e,t)=>{let r=await oi(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`})},P_=e=>e?e.split(",").map(t=>Pe(ve(t.trim()))):[],x_=e=>e?e.split(",").filter(t=>t.trim()!=="").map(Va):[],T_=e=>{let t=e.filter(n=>n.startsWith("feature/")),r=e.filter(n=>!t.includes(n));r.length>0&&y.addOption("--versions",$t(r)),t.length>0&&y.addOption("--feature",t.map(n=>n.replace(/^feature\//,"")).join(","))},Ha=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 Pk(t)}await Ne({operation:"remove worktrees"}),await H(),R_({all:r,versions:n,feature:o});try{let[i,a]=await Promise.all([we("release"),we("feature")]),c=[...i,...a];if(c.length===0){d.info("\u2139\uFE0F No active worktrees to remove"),y.print();let v={removedWorktrees:[],failedWorktrees:[],count:0};return{content:b(JSON.stringify(v,null,2)),structuredContent:v}}let l=await A(),u=`${l}${fe}`,p=[];if(r)p=c;else if(n||o)p=[...P_(n),...x_(o)];else{y.setInteractive();let[v,E]=await Promise.all([pe(),V()]),k=new Map(E.map(h=>[h.branch,h.type]));p=await Kt([...me({branches:i,descriptions:v,types:k}),...a.map(h=>({value:h,label:h,type:"feature"}))],{required:!0})}S_(p,c);let m=p.length===c.length;m?y.addOption("--all",!0):T_(p),await E_(u,p),await G(t,"Are you sure you want to proceed with these worktree changes?"),t||y.addOption("--yes",!0);let f=await Cr({branches:p,worktreeDir:u,projectRoot:l,pruneFolder:m});return is(f),y.print(),as({result:f,operation:"remove worktrees"})}catch(i){throw Ae(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"}))}},bp=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:ze.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:ze.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:ze.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{removedWorktrees:ze.array(ze.string()).describe("List of removed git worktree branches"),failedWorktrees:ze.array(ze.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:ze.number().describe("Number of git worktrees removed"),handedOff:ze.object({branch:ze.string(),worktreePath:ze.string(),terminal:ze.string()}).optional().describe("--self only: the worktree whose removal now runs in an Orca tab of the main checkout")},handler:Ha});import{z as Os}from"zod";var qa=async e=>{let{confirmedCommand:t}=e;await Ne({operation:"sync worktrees"}),await H();try{let r=await we("release"),n=await A(),o=`${n}${fe}`,s=await Di();await G(t,"Are you sure you want to proceed with these worktree changes?"),t||y.addOption("--yes",!0);let{branchesToRemove:i}=C_({releasePRsList:s,currentWorktrees:r}),a=await Cr({branches:i,worktreeDir:o,projectRoot:n});return is(a),y.print(),as({result:a,operation:"sync worktrees"})}catch(r){throw Ae(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"}))}},C_=e=>{let{releasePRsList:t,currentWorktrees:r}=e;return{branchesToRemove:r.filter(s=>Br(s)).filter(s=>!t.includes(s))}},Rp=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:Os.array(Os.string()).describe("List of removed worktree branches"),failedWorktrees:Os.array(Os.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:Os.number().describe("Number of worktrees removed during sync")},handler:qa});var Sp=[{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"}],Sr=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["dev"],longRunning:!0},{cliName:"dev-status",menuGroup:"develop",mcpTool:Ml,mcpExposed:!0,mutating:!1,groupPath:["dev-status"]},{cliName:"e2e",menuGroup:"develop",mcpTool:ed,mcpExposed:!1,mutating:!0,groupPath:["e2e"]},{cliName:"merge-dev",menuGroup:"release",mcpTool:ad,mcpExposed:!0,mutating:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:Dd,mcpExposed:!0,mutating:!1,groupPath:["release","list"]},{cliName:"release-create",menuGroup:"release",mcpTool:Kd,mcpExposed:!0,mutating:!0,groupPath:["release","create"]},{cliName:"release-edit",menuGroup:"release",mcpTool:qd,mcpExposed:!0,mutating:!0,groupPath:["release","edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:$d,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:Od,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:dd,mcpExposed:!1,mutating:!0,humanOnly:!0,groupPath:["release","deliver"]},{cliName:"release-remove",menuGroup:"release",mcpTool:Xd,mcpExposed:!0,mutating:!0,groupPath:["release","remove"]},{cliName:"local-deploy-all",menuGroup:null,mcpTool:Ud,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-all"]},{cliName:"local-deploy-selected",menuGroup:null,mcpTool:Wd,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-selected"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:wp,mcpExposed:!0,mutating:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:kp,mcpExposed:!0,mutating:!1,groupPath:["worktrees","list"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:bp,mcpExposed:!0,mutating:!0,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:Rp,mcpExposed:!0,mutating:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:nd,mcpExposed:!0,mutating:!1,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:Gf,mcpExposed:!0,mutating:!1,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:jc,mcpExposed:!0,mutating:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:rd,mcpExposed:!0,mutating:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:od,mcpExposed:!0,mutating:!1,groupPath:["env-token-list"]},{cliName:"config-get",menuGroup:"configuration",mcpTool:Nl,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:fp,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:sp,mcpExposed:!0,mutating:!0,groupPath:["setup"]},{cliName:"doctor",menuGroup:"setup",mcpTool:Wu,mcpExposed:!0,mutating:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:Sl,mcpExposed:!0,mutating:!1,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:gp,mcpExposed:!0,mutating:!1,groupPath:["version"]},{cliName:"change-stats",menuGroup:null,mcpTool:Ol,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 Ep=e=>Sr.filter(t=>t.menuGroup===e),Pp=e=>Sr.some(t=>t.longRunning===!0&&t.groupPath.join(" ")===e);var $_=(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},xk=e=>Sp.flatMap(({key:t,label:r})=>Ep(t).flatMap(n=>{let o=$_(e,n.groupPath);return o?[{name:n.groupPath.join(" "),description:o.description(),group:r}]:[]}));import xp from"node:process";var A_="MODULE_TYPELESS_PACKAGE_JSON",O_=(e,t)=>typeof e=="object"&&e!==null?e.code:t,Tk=!1,Tp=()=>{if(Tk)return;Tk=!0;let e=xp.emitWarning.bind(xp);xp.emitWarning=((t,...r)=>{O_(r[0],r[1])!==A_&&e(t,...r)})};import{Command as Bj,InvalidArgumentError as Ab,Option as Cb}from"commander";import{resolve as Uj}from"node:path";import je from"node:process";import{cd as Wj}from"zx";import Ck from"node:process";import{$ as D_}from"zx";var Cp=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 ne(i.path)}))),r=t.at(-1)?.exists===!0,n=await Go(e.userProject,r),o=r?Jo(n):"";d.info(`Project name: ${e.projectName}
442
+ `));let o={worktrees:r,count:r.length,features:t};return{content:b(JSON.stringify(o,null,2)),structuredContent:o}},E_=async e=>{let[t,r]=await Promise.all([G(),pe()]),n=new Map(t.map(o=>[o.branch,o.type]));return e.flatMap(o=>{let s=Q(o);if(!s)return[];let i=re(s),a=n.get(o)||"regular",c=r.get(ce(s))||null;return[{version:i,type:a,description:c}]})},P_=e=>{let t=Math.max(...e.map(r=>r.version.length));return e.map(r=>{let n=_o(r.version,r.type,t);return r.description?`${n} ${r.description}`:n})},Sp=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:nr.array(nr.object({version:nr.string().describe("Release version"),type:nr.enum(["regular","hotfix"]).describe("Release type"),description:nr.string().nullable().describe("Jira version description")})).describe("Release worktrees with details"),count:nr.number().describe("Number of release worktrees"),features:nr.array(nr.string()).describe("Branches of feature worktrees (feature/<name>)")},handler:qa});import{z as ze}from"zod";import x_ from"node:fs/promises";import{$ as T_}from"zx";var Nk="remove this worktree",C_=2,$_=3,Ya=async e=>{try{return await x_.realpath(e)}catch{return e}},_r=(e,t)=>{throw new g(void 0,{operation:Nk,remediation:e,stderrExcerpt:t})},A_=e=>{if(e.startsWith("feature/"))return["--feature",e.slice(8)];let[t]=Ot([e]);return Ur(e)&&t?["--versions",t]:_r("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`)},O_=async()=>{let e=await Ya(await A()),t=await Ya(await $e(e));e===t&&_r("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 ot(t))await Ya(o.path)===e&&(r=o.branch);if(!r)return _r("check out a branch in this worktree first",`no branch is checked out at ${e}`);let n=await Ya(`${t}${ge}/${r}`);return n!==e&&_r("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:A_(r)}},Ik=async e=>(await T_({quiet:!0})`git -C ${e} status --porcelain`).stdout.split(`
443
+ `).filter(r=>r.trim().length>0),D_=async e=>{let[t,r]=await Promise.all([Ik(e.worktreePath),Ik(e.mainRoot)]);t.length>0&&_r("commit or stash your changes (`git stash -u`), then retry",`uncommitted changes: ${t.join(", ")}`),r.length>0&&_r(`commit or stash the changes in the main checkout ${e.mainRoot}, then retry`,`the main checkout has uncommitted changes: ${r.join(", ")}`);let n=await Ut();n!=="ready"&&_r(`run \`infra-kit worktrees remove ${Be(e.targetArgs)}\` from the main checkout ${e.mainRoot}`,`--self hands the removal to an Orca terminal, and Orca is ${n}`)},I_=async e=>{let t=Be(["infra-kit","worktrees","remove",...e.targetArgs,"--yes"]),r=`sleep ${C_}; ${t} && { sleep ${$_}; exit; }`;try{return(await Nf(["terminal","create","--worktree",`path:${e.mainRoot}`,"--title",`ik: remove ${e.branch}`,"--command",r])).terminal.handle}catch(n){throw n instanceof Gr?new g(n,{operation:Nk,remediation:`run \`infra-kit worktrees remove ${Be(e.targetArgs)}\` from the main checkout ${e.mainRoot}`,stderrExcerpt:n.message}):n}},_k=async e=>{let t=await O_();await D_(t),h.addOption("--self",!0),await J(e,`Remove ${t.branch} at ${t.worktreePath} and close every Orca tab in it (this terminal included)?`),e||h.addOption("--yes",!0);let r=await I_(t);d.info(`\u27A1\uFE0F Removal of ${t.branch} handed off to Orca (main checkout tab "ik: remove ${t.branch}")`),h.print();let n={branch:t.branch,worktreePath:t.worktreePath,terminal:r};return{content:b(JSON.stringify({status:"handed_off",...n},null,2)),structuredContent:{removedWorktrees:[],failedWorktrees:[],count:0,handedOff:n}}};var N_=e=>{if(he()){if(e.all)throw new D({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 D({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"})}},__=(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(", ")}`})},M_=async(e,t)=>{let r=await ci(t.map(n=>`${e}/${n}`));if(r!==null)throw new D({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=>xe(we(t.trim()))):[],F_=e=>e?e.split(",").filter(t=>t.trim()!=="").map(Ka):[],L_=e=>{let t=e.filter(n=>n.startsWith("feature/")),r=e.filter(n=>!t.includes(n));r.length>0&&h.addOption("--versions",Ot(r)),t.length>0&&h.addOption("--feature",t.map(n=>n.replace(/^feature\//,"")).join(","))},za=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 _k(t)}await Ne({operation:"remove worktrees"}),await K(),N_({all:r,versions:n,feature:o});try{let[i,a]=await Promise.all([ke("release"),ke("feature")]),c=[...i,...a];if(c.length===0){d.info("\u2139\uFE0F No active worktrees to remove"),h.print();let y={removedWorktrees:[],failedWorktrees:[],count:0};return{content:b(JSON.stringify(y,null,2)),structuredContent:y}}let l=await A(),u=`${l}${ge}`,p=[];if(r)p=c;else if(n||o)p=[...j_(n),...F_(o)];else{h.setInteractive();let[y,E]=await Promise.all([pe(),G()]),k=new Map(E.map(O=>[O.branch,O.type]));p=await qt([...me({branches:i,descriptions:y,types:k}),...a.map(O=>({value:O,label:O,type:"feature"}))],{required:!0})}__(p,c);let m=p.length===c.length;m?h.addOption("--all",!0):L_(p),await M_(u,p),await J(t,"Are you sure you want to proceed with these worktree changes?"),t||h.addOption("--yes",!0);let f=await Ar({branches:p,worktreeDir:u,projectRoot:l,pruneFolder:m});return as(f),h.print(),cs({result:f,operation:"remove worktrees"})}catch(i){throw Ae(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"}))}},Ep=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:ze.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:ze.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:ze.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{removedWorktrees:ze.array(ze.string()).describe("List of removed git worktree branches"),failedWorktrees:ze.array(ze.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:ze.number().describe("Number of git worktrees removed"),handedOff:ze.object({branch:ze.string(),worktreePath:ze.string(),terminal:ze.string()}).optional().describe("--self only: the worktree whose removal now runs in an Orca tab of the main checkout")},handler:za});import{z as _s}from"zod";var Xa=async e=>{let{confirmedCommand:t}=e;await Ne({operation:"sync worktrees"}),await K();try{let r=await ke("release"),n=await A(),o=`${n}${ge}`,s=await Mi();await J(t,"Are you sure you want to proceed with these worktree changes?"),t||h.addOption("--yes",!0);let{branchesToRemove:i}=B_({releasePRsList:s,currentWorktrees:r}),a=await Ar({branches:i,worktreeDir:o,projectRoot:n});return as(a),h.print(),cs({result:a,operation:"sync worktrees"})}catch(r){throw Ae(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"}))}},B_=e=>{let{releasePRsList:t,currentWorktrees:r}=e;return{branchesToRemove:r.filter(s=>Ur(s)).filter(s=>!t.includes(s))}},Pp=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:_s.array(_s.string()).describe("List of removed worktree branches"),failedWorktrees:_s.array(_s.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:_s.number().describe("Number of worktrees removed during sync")},handler:Xa});var xp=[{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"}],Pr=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["dev"],longRunning:!0},{cliName:"dev-status",menuGroup:"develop",mcpTool:Ll,mcpExposed:!0,mutating:!1,groupPath:["dev-status"]},{cliName:"e2e",menuGroup:"develop",mcpTool:nd,mcpExposed:!1,mutating:!0,groupPath:["e2e"]},{cliName:"merge-dev",menuGroup:"release",mcpTool:ud,mcpExposed:!0,mutating:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:Id,mcpExposed:!0,mutating:!1,groupPath:["release","list"]},{cliName:"release-create",menuGroup:"release",mcpTool:Yd,mcpExposed:!0,mutating:!0,groupPath:["release","create"]},{cliName:"release-edit",menuGroup:"release",mcpTool:Xd,mcpExposed:!0,mutating:!0,groupPath:["release","edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:Ad,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:Dd,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:fd,mcpExposed:!1,mutating:!0,humanOnly:!0,groupPath:["release","deliver"]},{cliName:"release-remove",menuGroup:"release",mcpTool:ep,mcpExposed:!0,mutating:!0,groupPath:["release","remove"]},{cliName:"local-deploy-all",menuGroup:null,mcpTool:Gd,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-all"]},{cliName:"local-deploy-selected",menuGroup:null,mcpTool:Jd,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-selected"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:Rp,mcpExposed:!0,mutating:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:Sp,mcpExposed:!0,mutating:!1,groupPath:["worktrees","list"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:Ep,mcpExposed:!0,mutating:!0,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:Pp,mcpExposed:!0,mutating:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:id,mcpExposed:!0,mutating:!1,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:Hf,mcpExposed:!0,mutating:!1,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:Bc,mcpExposed:!0,mutating:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:sd,mcpExposed:!0,mutating:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:ad,mcpExposed:!0,mutating:!1,groupPath:["env-token-list"]},{cliName:"config-get",menuGroup:"configuration",mcpTool:jl,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:yp,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:cp,mcpExposed:!0,mutating:!0,groupPath:["setup"]},{cliName:"doctor",menuGroup:"setup",mcpTool:Ju,mcpExposed:!0,mutating:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:xl,mcpExposed:!0,mutating:!1,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:vp,mcpExposed:!0,mutating:!1,groupPath:["version"]},{cliName:"change-stats",menuGroup:null,mcpTool:Nl,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 Tp=e=>Pr.filter(t=>t.menuGroup===e),Cp=e=>Pr.some(t=>t.longRunning===!0&&t.groupPath.join(" ")===e);var U_=(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},Mk=e=>xp.flatMap(({key:t,label:r})=>Tp(t).flatMap(n=>{let o=U_(e,n.groupPath);return o?[{name:n.groupPath.join(" "),description:o.description(),group:r}]:[]}));import $p from"node:process";var W_="MODULE_TYPELESS_PACKAGE_JSON",V_=(e,t)=>typeof e=="object"&&e!==null?e.code:t,jk=!1,Ap=()=>{if(jk)return;jk=!0;let e=$p.emitWarning.bind($p);$p.emitWarning=((t,...r)=>{V_(r[0],r[1])!==W_&&e(t,...r)})};import{Command as Zj,InvalidArgumentError as Bb,Option as Fb}from"commander";import{resolve as Qj}from"node:path";import je from"node:process";import{cd as eF}from"zx";import Fk from"node:process";import{$ as G_}from"zx";var Op=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 ne(i.path)}))),r=t.at(-1)?.exists===!0,n=await Jo(e.userProject,r),o=r?Ko(n):"";d.info(`Project name: ${e.projectName}
444
444
  `),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}},$p=async()=>{let e=await ee(),t=Ck.env.EDITOR||Ck.env.VISUAL||"vi",r=await yn(e);r.createdConfig&&d.info(vn(r)),d.info(`Opening ${w(e.userProject)} in ${t} (per-machine override \u2014 every key except "mcp")`),await D_({stdio:"inherit"})`${t} ${e.userProject}`,Mt();let n={path:e.userProject,editor:t};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}};var Ap=async({key:e,global:t})=>{Ci(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 ${Ro[r]} (${w(n)})`:`${e} is not set in the ${Ro[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 Ik from"node:fs/promises";import Ds from"node:path";import V_ from"node:process";import{pathToFileURL as G_}from"node:url";import{execFile as I_,spawn as N_}from"node:child_process";import nr from"node:fs/promises";import __ from"node:os";import rr from"node:path";import $k from"node:process";import{promisify as M_}from"node:util";var j_=M_(I_),Ak="3.39.0",F_=10*1024*1024,L_=960,B_=60,Op=(e,t=500)=>e.length>t?`${e.slice(0,t)}\u2026`:e,U_=e=>{try{let{FunctionError:t}=JSON.parse(e);return t===void 0?void 0:`FunctionError=${t}`}catch{return`unparseable invoke metadata: ${Op(e)}`}},Bn=class extends Error{constructor(t){super(t),this.name="DeploySkipped"}},W_=(e,t,r)=>new Promise((n,o)=>{let s=N_(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}`))})}),za={run:W_,capture:async(e,t,r)=>{let{stdout:n}=await j_(e,t,{...r,maxBuffer:F_});return n},sleep:e=>new Promise(t=>{setTimeout(t,e)}),random:Math.random,log:e=>{$k.stdout.write(`${e}
446
- `)}},Ya=e=>({AWS_RETRY_MODE:"adaptive",AWS_MAX_ATTEMPTS:"10",...e,AWS_PAGER:""}),Ok=async e=>{let t=JSON.parse(await nr.readFile(rr.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},Ip=async e=>{let t=await nr.readdir(e,{withFileTypes:!0});await Promise.all(t.filter(r=>r.isDirectory()).map(r=>{let n=rr.join(e,r.name);return r.name==="node_modules"?nr.rm(n,{recursive:!0,force:!0}):Ip(n)}))},Dp=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 nr.readFile(rr.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`)},Np=({root:e,service:t,scriptDir:r,env:n=$k.env,deps:o=za})=>{let s=async(h,R,S,P={})=>{o.log(`COMMAND: ${[R,...S].join(" ")}`);try{await o.run(R,S,{cwd:P.cwd??e,env:P.env??n})}catch(M){throw new Error(`${h} failed: ${M.message}`)}},i=async(h,R,S={})=>{let{attempts:P=8,initialDelaySeconds:M=3,maxDelaySeconds:$=60}=S,J=async K=>{try{return await R()}catch(Ce){if(K>=P)throw new Error(`${h} failed after ${P} attempts: ${Ce.message}`);let js=Math.min($,M*2**(K-1)),Fs=Math.round((js/2+o.random()*js/2)*10)/10;return o.log(`Attempt ${K}/${P} failed. Retrying in ${Fs}s...`),await o.sleep(Fs*1e3),J(K+1)}};return J(1)},a=async(h,R,S=n)=>{o.log(`COMMAND: aws ${R.join(" ")}`),await i(h,()=>o.run("aws",R,{cwd:e,env:Ya(S)}))},c=async(h,R={})=>{await s(`aws ${h.slice(0,2).join(" ")}`,"aws",h,{cwd:R.cwd,env:Ya(R.env??n)})},l=async h=>{let R=await Promise.all(h.map(async S=>{try{let P=await o.capture("aws",["ssm","get-parameter","--name",S,"--query","Parameter.Value","--output","text"],{cwd:e,env:Ya(n)});return[S,P.trim()]}catch(P){throw new Error(`SSM parameter ${S}: ${P instanceof Error?P.message:String(P)}`)}}));return Object.fromEntries(R)},u=async h=>{let R=[`turbo@${await Ok(e)}`,...h?[`serverless@${Ak}`]:[]];await s("Install tools","pnpm",["add","-g",...R])},p=async(h,R)=>{let S=rr.join(e,"out"),P={...n,...R.buildEnv},M=R.buildTask??P.TURBO_BUILD_TASK??"build";return await nr.rm(S,{recursive:!0,force:!0}),await s(`Prune to ${h}`,"turbo",["prune",h],{env:P}),await s("Install dependencies","pnpm",["install"],{cwd:S,env:P}),await s(`Build ${h}`,"pnpm",["exec","turbo",M,`--filter=${h}`,"--env-mode=loose"],{cwd:S,env:P}),R.installProd&&(o.log("COMMAND: remove every node_modules under ./out"),await Ip(S),await s("Install production dependencies","pnpm",["install","--frozen-lockfile","--node-linker=hoisted","--prod"],{cwd:S,env:P}),await s("Show node_modules size","du",["-sm","./node_modules/"],{cwd:S})),S},m=async(h,R,S)=>{if(R!==void 0){o.log(`Running ${h} hooks...`);try{await R(S)}catch(P){throw new Error(`${h} hooks failed: ${P.message}`)}o.log(`${h} hooks completed successfully`)}},f=async h=>{let{app:R,appPath:S}=await Dp(e,r,h);await u(!0);let P={...n,...h.buildEnv},M=await p(R,{installProd:!0,buildTask:h.buildTask,buildEnv:h.buildEnv}),$={stage:h.stage,outDir:M,appDir:rr.join(M,S)};await m("Pre-deployment",h.preDeploy,$),await s("Deploy with Serverless","serverless",["deploy","--stage",h.stage,"--force"],{cwd:$.appDir,env:P}),h.restApiId===void 0?o.log(`Skipping API Gateway deployment for ${R}: no restApiId.`):await a("Create API Gateway deployment",["apigateway","create-deployment","--rest-api-id",h.restApiId,"--stage-name","api"],P),await m("Post-deployment",h.postDeploy,$)},v=async h=>{let{app:R,appPath:S}=await Dp(e,r,h);await u(!1);let P={...n,...h.buildEnv},M=await p(R,{installProd:!1,buildTask:h.buildTask,buildEnv:h.buildEnv}),$={stage:h.stage,outDir:M,appDir:rr.join(M,S)},J=`s3://${h.bucket}${h.destPath??""}`,K=h.sourcePath??"./dist";await s("Sync to S3","aws",["s3","sync",K,J,...h.syncFlags??[],"--only-show-errors"],{cwd:$.appDir,env:Ya(P)}),await a("Invalidate CloudFront",["cloudfront","create-invalidation","--distribution-id",h.cloudfrontId,"--paths",h.invalidationPath??"/*"],P),await m("Post-deployment",h.postDeploy,$)},E=async(h,R,S)=>{let P=await nr.mkdtemp(rr.join(__.tmpdir(),"infra-kit-lambda-")),M=rr.join(P,"response.json"),$=["lambda","invoke","--function-name",h.functionName,...S===void 0?[]:["--region",S],"--cli-binary-format","raw-in-base64-out","--payload",h.payload??R,"--cli-read-timeout",String(L_),"--cli-connect-timeout",String(B_),M],J=Date.now();o.log(`COMMAND: aws ${$.join(" ")}`);try{let K=await o.capture("aws",$,{cwd:e,env:{...n,AWS_PAGER:""}}).then(U_,hc=>`aws CLI failed: ${Op(hc instanceof Error?hc.message:String(hc))}`),Ce=await nr.readFile(M,"utf-8").catch(()=>""),js=((Date.now()-J)/1e3).toFixed(1),Fs=K!==void 0&&Ce?`; response: ${Op(Ce)}`:"";return{outcome:`${h.functionName} (${js}s)`,failure:K===void 0?void 0:K+Fs}}finally{await nr.rm(P,{recursive:!0,force:!0})}};return{root:e,service:t,ssm:l,aws:c,run:(h,R,S={})=>o.run(h,R,{cwd:S.cwd??e,env:S.env??n}),capture:(h,R,S={})=>o.capture(h,R,{cwd:S.cwd??e,env:S.env??n}),retry:i,skip:h=>{throw new Bn(h)},pruneAndBuild:p,deployBackendApi:f,deployFrontendUi:v,invokeLambdas:async h=>{let{region:R,payload:S="{}",blocking:P=[],steps:M=[]}=h;for(let $ of P){let{outcome:J,failure:K}=await E($,S,R);if(K!==void 0)throw new Error(`Lambda ${J} failed: ${K}`);o.log(`Lambda ${J} OK`)}for(let $ of M){let J=await Promise.all($.map(K=>E(K,S,R).catch(Ce=>({outcome:K.functionName,failure:String(Ce)}))));for(let{outcome:K,failure:Ce}of J)o.log(Ce===void 0?`Lambda ${K} OK`:`Warning: Lambda ${K} failed, continuing: ${Ce}`)}}}};var Dk=e=>({content:b(JSON.stringify(e,null,2)),structuredContent:e}),J_=async(e,t)=>{let r=Ds.join(e,"devops","scripts",`deploy-${t}.sh`);try{await Ik.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},K_=e=>`::add-mask::${e.replaceAll("%","%25").replaceAll("\r","%0D").replaceAll(`
447
- `,"%0A")}`,H_=(e,t)=>{let r=(e??"").split(`
448
- `).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(K_(n));return Object.fromEntries(r)},q_=async e=>{try{await Ik.access(e)}catch{throw new g(void 0,{operation:`run ${Ds.basename(e)}`,remediation:"create it, or fix the deploy path in infra-kit.deploy.ts",stderrExcerpt:`${e} does not exist`})}let t=await import(G_(e).href);if(typeof t.default!="function")throw new g(void 0,{operation:`run ${Ds.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},_p=async e=>{let{service:t,env:r=V_.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(ge()&&r.INFRA_KIT_DEPLOY_VIA!==vs)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 A(),o=e.deps??za,{INFRA_KIT_EXTRA_ENV:s,...i}=r,a={...i,...H_(s,o.log)},c=(await $r(n))?.services[t]?.deploy;if(c===void 0)await o.run("sh",[await J_(n,t)],{cwd:n,env:a});else{let l=await q_(Ds.join(n,c)),u=Np({root:n,service:t,scriptDir:Ds.dirname(c),env:a,deps:o});try{await l(u)}catch(p){if(!(p instanceof Bn))throw p;return d.info(`\u23ED\uFE0F ${t} skipped: ${p.message}`),Dk({status:"skipped",service:t,reason:p.message})}}return d.info(`\u2705 ${t} deployed`),Dk({status:"deployed",service:t})};import{DEPLOY_CONFIG_FILE as Is}from"@slip-stream-kit/config/internal";import Za from"node:fs/promises";import Qa from"node:path";var Mp=async e=>{try{return await Za.readFile(e,"utf-8")}catch{return}},Xa=e=>({content:b(JSON.stringify(e,null,2)),structuredContent:e}),Y_={created:"missing",updated:"differs",unchanged:"matches",removed:"no longer generated"},Nk=async(e,t)=>(await Promise.all(t.map(async n=>{let o=Qa.join(e,n);return(await Mp(o))?.startsWith(Mn)?[{path:n,absolute:o}]:[]}))).flat(),z_=async(e,t)=>t.replaceV1!==!0?[]:(await Nk(e,fd)).map(r=>({...r,status:"removed"})),X_=async(e,t)=>{let n=(await Promise.all(Object.entries(t.services).map(async([o,s])=>s.deploy===void 0?[]:await Mp(Qa.join(e,s.deploy))===void 0?[`${o}: ${s.deploy}`]:[]))).flat();if(n.length>0)throw new Error(`Deploy scripts named in ${Is} do not exist: ${n.join(", ")}`)},Z_=async(e,t)=>{if(t.replaceV1===!0)return;let r=await Nk(e,gd);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 ${Is} 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 A(),r=await $r(t);if(r===void 0)return(e.check?d.info.bind(d):d.error.bind(d))(`No ${Is} at ${t}, nothing to generate.`),Xa({status:"missing-config",ok:!!e.check,files:[]});await Z_(t,r),await X_(t,r);let n=await Promise.all(vd(r).map(async a=>{let c=Qa.join(t,a.path),l=await Mp(c),u="unchanged";return l===void 0?u="created":l!==a.content&&(u="updated"),{...a,absolute:c,status:u}})),o=await z_(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 ${Is}.`),Xa({status:"unchanged",ok:!0,files:i});if(e.check){d.error(`\u274C Deploy workflows differ from ${Is}; run \`infra-kit deploy-sync\` and commit:`);for(let a of s)d.error(` ${a.path} (${Y_[a.status]})`);return Xa({status:"drift",ok:!1,files:i})}for(let a of s){if(a.status==="removed"){await Za.rm(a.absolute),d.info(`\u{1F5D1}\uFE0F Removed ${a.path}`);continue}await Za.mkdir(Qa.dirname(a.absolute),{recursive:!0}),await Za.writeFile(a.absolute,a.content),d.info(`\u270F\uFE0F ${a.status==="created"?"Created":"Updated"} ${a.path}`)}return Xa({status:"written",ok:!0,files:i})};var _k="https://dashboard.doppler.com/workplace/projects",Q_=(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}"): ${_k}/${e}`],Fp=async({env:e})=>{let r=!!(await Ze())?.envs[e];await Pf(e);let n=await cr(),o=await Ft();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 Q_(n,e))d.warn(i);let s={env:e,removed:r,storePath:o,revokeUrl:`${_k}/${n}`};return{content:b(JSON.stringify(s,null,2)),structuredContent:s}};import eM from"@inquirer/confirm";import tM from"@inquirer/input";import rM from"@inquirer/password";import nM from"@inquirer/select";import oM from"node:fs/promises";import vt from"node:process";import{$ as ec}from"zx";var sM=async({stdin:e,fromEnv:t})=>{if(e)return{token:await Mk(),source:"stdin"};if(t){let n=vt.env[t];if(!n)throw new Error(`${t} is not set (or is empty) \u2014 nothing to store.`);return{token:n,source:"env"}}if(!vt.stdin.isTTY){let n=await Mk();if(n)return{token:n,source:"stdin"};if(!Z())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=>rM({message:"Paste the Doppler service token (input is hidden)",mask:!0},n),{output:vt.stderr,whenHeadless:{refuse:"stdin"}})).trim(),source:"prompt"}},Mk=async()=>{let e=[];vt.stdin.setEncoding("utf8");for await(let t of vt.stdin)e.push(t);return e.join("").trim()},Lp="DOPPLER_CONFIG",iM=3e4,aM=async(e,t,r)=>{let n=ec.quiet;ec.quiet=!0;let o;try{o=(await ec({env:no(e)})`doppler secrets download --no-file --format json --project ${t} --config ${r}`.timeout(iM)).stdout}catch(s){throw cM(s,r)}finally{ec.quiet=n}return Mc(o)},cM=(e,t)=>{let r=qm(e)??(e instanceof Error?e.message:String(e));if(Tf(r)!=="auth")return e instanceof Error?e:new Error(String(e));let n=Cf(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(`
449
- `))},lM=e=>[`Could not verify this token's scope: the Doppler payload for "${e}" carries no ${Lp}.`,"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(`
450
- `),Fk=async(e,t,r,n)=>{let o=await aM(e,t,r);_c(o,r);let s=o.some(([i])=>i===Lp);if(!s&&!n)throw new Error(lM(r));return s},jk="\0new-env",uM=async()=>{if(Z()||!vt.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([Uf(),Ze()]),r=Math.max(0,...e.map(({env:s})=>s.length));y.setInteractive();let n=await _(s=>nM({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:jk}]},s),{output:vt.stderr,whenHeadless:"refuse"});return n!==jk?n:(await _(s=>tM({message:"Doppler config name",validate:i=>/^\S+$/.test(i.trim())||"Enter a config name without spaces"},s),{output:vt.stderr,whenHeadless:"refuse"})).trim()},dM=async(e,t,r)=>_(n=>eM({message:`Replace the "${e}" token ${Te(t)} with ${Te(r)}?`,default:!0},n),{output:vt.stderr,whenHeadless:"refuse"}),pM=(e,t,r,n)=>{switch(t){case"stored":return`Stored the "${e}" service token (${Te(r)})`;case"replaced":return`Replaced the "${e}" service token ${Te(n??"")} \u2192 ${Te(r)}`;case"unchanged":return`The "${e}" service token is already ${Te(r)} \u2014 nothing to write`;case"kept":return`Kept the existing "${e}" service token ${Te(n??"")} \u2014 nothing was written`;default:return Ue(t)}},Bp=async({env:e,stdin:t,fromEnv:r,force:n})=>{let o=await cr(),s=e??await uM(),{token:i,source:a}=await sM({stdin:t,fromEnv:r});if(!i)throw new Error("No token provided \u2014 nothing was written.");let c=await Fk(i,o,s,n),l=(await Ze())?.envs[s],u;l===i?u="unchanged":l!==void 0&&a==="prompt"&&!await dM(s,l,i)?u="kept":(await Tc({[s]:i}),u=l===void 0?"stored":"replaced");let p=await Ft();d.info(`${pM(s,u,i,l)} in ${w(p)} (mode 0600).`),c||d.warn(`Scope was NOT verified (no ${Lp} in the payload) \u2014 accepted because --force was given.`);let m={env:s,status:u,source:a,redactedToken:Te(i),previousRedactedToken:l===void 0?null:Te(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,Lk=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},fM=e=>(e instanceof Error?e.message:String(e)).split(`
451
- `)[0]??"",gM=(e,t)=>e===void 0?"stored":e===t?"unchanged":"replaced",hM=async(e,t,r,n)=>{let o=Te(e.token);try{let s=await Fk(e.token,t,e.env,n);return{env:e.env,status:gM(r,e.token),redactedToken:o,scopeVerified:s}}catch(s){return{env:e.env,status:"failed",redactedToken:o,scopeVerified:!1,error:fM(s)}}},Up=async({fromFile:e,force:t})=>{let r=await cr(),n=Lk(await oM.readFile(e,"utf8")),o=await Ze(),s=await Promise.all(n.map(p=>hM(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 Tc(i);let a=await Ft(),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&&(vt.exitCode=1);let u={storePath:a,rows:s,failedCount:l};return{content:b(JSON.stringify(u,null,2)),structuredContent:u}};var Wp=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 Td(n);if(r&&y.addOption("--from",p),xd(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"?ba({version:o,env:s,skipTerraform:a,confirmedCommand:c}):Ra({version:o,env:s,services:i,skipTerraform:a,confirmedCommand:c})},Vp=async e=>Wp(e,"all"),Gp=async e=>Wp(e,"selected"),tc=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.`),Wp({...e,from:"local"},t,!1)};import{VENDOR_CONFIG_FILE as Uk}from"@slip-stream-kit/config/internal";import Jp from"node:fs/promises";import Un from"node:path";import Bk from"node:process";import{pathToFileURL as yM}from"node:url";var Wk="~/projects",Kp=async(e={})=>{if(e.init){await wM(e.cwd);return}await vM()},vM=async()=>{let e=Sn(),t=await ne(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."),Bk.exitCode=1;return}let{workspaceDir:r,source:n,targets:o}=await Yi(),s=En(r),i=await ne(s),a=Un.join(s,n),c=await ne(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=Un.join(s,u),m=await ne(p);m||(l=!1);let f=m?"[\u2713]":"[ ]",v=m?"":" (not found \u2014 clone or remove)";d.info(` ${f} ${u} ${w(p)}${v}`)}l||(Bk.exitCode=1)},wM=async e=>{let t=Sn();if(await ne(t)){d.info(`Factory config already exists at ${w(t)} \u2014 leaving it untouched.`);return}let r=e??await A(),n=await kM(r);await Jp.mkdir(Un.dirname(t),{recursive:!0}),await Jp.writeFile(t,bM(Un.basename(r),n),"utf-8"),d.info(`\u2713 Created ${w(t)}`),n.length>0&&d.info(` Seeded ${n.length} target(s) from the source ${Uk}.`),d.info(` Edit \`workspaceDir\` (placeholder: ${Wk}) to point at where your repos live.`),d.info(` \`source\` is seeded with ${Un.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.")},kM=async e=>{try{let t=Un.join(e,Uk),r=await Jp.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[]},bM=(e,t)=>`${JSON.stringify({workspaceDir:Wk,source:e,targets:t},null,2)}
452
- `;import{existsSync as $j}from"node:fs";import Aj from"node:fs/promises";import hb from"node:path";import yb from"node:process";import{z as Oj}from"zod";import{chmodSync as $M,copyFileSync as AM,lstatSync as OM,mkdirSync as Zk,readdirSync as DM,readlinkSync as IM,rmSync as NM,rmdirSync as Qk,symlinkSync as _M,unlinkSync as MM,writeFileSync as jM}from"node:fs";import Se from"node:path";import{lstatSync as RM,readlinkSync as Vk}from"node:fs";import SM from"node:path";var EM=new Set(["ENOENT","ENOTDIR"]),rc=e=>{let t;try{t=RM(e)}catch(r){if(EM.has(r.code??""))return null;throw r}return t.isSymbolicLink()?{kind:"link",text:Vk(e)}:t.isFile()?{kind:"file",executable:(t.mode&64)!==0,sha:Ir(e)}:{kind:"other"}},Gk=(e,t)=>{let r=SM.join(e,t.path),n=t.mode==="120000"?{kind:"link",text:Vk(r)}:{kind:"file",executable:t.mode==="100755",sha:Ir(r)};return{...t,fingerprint:n}},Jk=(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 PM}from"zx";var X=async(e,t,r={})=>{let{input:n,allowFailure:o=!1}=r,s=await PM({cwd:e,quiet:!0,input:n,nothrow:o})`git ${t}`;return s.exitCode===0?s.stdout:""},nc=e=>e.slice(0,7),rt=e=>e.split("\0").filter(t=>t.length>0);import xM from"node:path";var Hp=`${oe}/`,or=`${oe}/README.md`,Ns=`${oe}/${Ye}`,Hk=e=>e.startsWith(Hp),Kk=e=>{let t=xM.posix.normalize(e);return t.endsWith("/")?t.slice(0,-1):t},qk=e=>{let t=Kk(e.path),r=e.target===void 0?t:Kk(e.target);return{path:t,target:r,vendored:Hk(r),module:e.module??null}},Yk=e=>e.copy.map(qk),_s=(e,t)=>t.length===0?!1:e.split("/").some(r=>t.includes(r)),Ms=(e,t)=>e.filter(r=>!_s(r.path,t)),oc=(e,t)=>e===t.path?t.target:`${t.target}${e.slice(t.path.length)}`,Wn=e=>[...new Set(e)].sort(),zk=e=>e.startsWith(Hp)?e.slice(Hp.length):null;var sc=e=>`# vendor/ \u2014 mirrored from ${e}
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}},Dp=async()=>{let e=await ee(),t=Fk.env.EDITOR||Fk.env.VISUAL||"vi",r=await vn(e);r.createdConfig&&d.info(wn(r)),d.info(`Opening ${w(e.userProject)} in ${t} (per-machine override \u2014 every key except "mcp")`),await G_({stdio:"inherit"})`${t} ${e.userProject}`,Ft();let n={path:e.userProject,editor:t};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}};var Ip=async({key:e,global:t})=>{Di(e,"config-unset");let r=t?"global":"project",{file:n,previous:o,changed:s}=await Ii(r,e,a=>e in a?Object.fromEntries(Object.entries(a).filter(([c])=>c!==e)):null);d.info(s?`Removed ${e} from the ${So[r]} (${w(n)})`:`${e} is not set in the ${So[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 Vk from"node:fs/promises";import Ms from"node:path";import tM from"node:process";import{pathToFileURL as rM}from"node:url";import{execFile as J_,spawn as K_}from"node:child_process";import sr from"node:fs/promises";import H_ from"node:os";import or from"node:path";import Lk from"node:process";import{promisify as q_}from"node:util";var Y_=q_(J_),Bk="3.39.0",z_=10*1024*1024,X_=960,Z_=60,Np=(e,t=500)=>e.length>t?`${e.slice(0,t)}\u2026`:e,Q_=e=>{try{let{FunctionError:t}=JSON.parse(e);return t===void 0?void 0:`FunctionError=${t}`}catch{return`unparseable invoke metadata: ${Np(e)}`}},Un=class extends Error{constructor(t){super(t),this.name="DeploySkipped"}},eM=(e,t,r)=>new Promise((n,o)=>{let s=K_(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}`))})}),Qa={run:eM,capture:async(e,t,r)=>{let{stdout:n}=await Y_(e,t,{...r,maxBuffer:z_});return n},sleep:e=>new Promise(t=>{setTimeout(t,e)}),random:Math.random,log:e=>{Lk.stdout.write(`${e}
446
+ `)}},Za=e=>({AWS_RETRY_MODE:"adaptive",AWS_MAX_ATTEMPTS:"10",...e,AWS_PAGER:""}),Uk=async e=>{let t=JSON.parse(await sr.readFile(or.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},Mp=async e=>{let t=await sr.readdir(e,{withFileTypes:!0});await Promise.all(t.filter(r=>r.isDirectory()).map(r=>{let n=or.join(e,r.name);return r.name==="node_modules"?sr.rm(n,{recursive:!0,force:!0}):Mp(n)}))},_p=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 sr.readFile(or.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`)},jp=({root:e,service:t,project:r,scriptDir:n,env:o=Lk.env,deps:s=Qa})=>{let i=async(v,S,R,$={})=>{s.log(`COMMAND: ${[S,...R].join(" ")}`);try{await s.run(S,R,{cwd:$.cwd??e,env:$.env??o})}catch(T){throw new Error(`${v} failed: ${T.message}`)}},a=async(v,S,R={})=>{let{attempts:$=8,initialDelaySeconds:T=3,maxDelaySeconds:W=60}=R,fe=async H=>{try{return await S()}catch(kt){if(H>=$)throw new Error(`${v} failed after ${$} attempts: ${kt.message}`);let Us=Math.min(W,T*2**(H-1)),Ws=Math.round((Us/2+s.random()*Us/2)*10)/10;return s.log(`Attempt ${H}/${$} failed. Retrying in ${Ws}s...`),await s.sleep(Ws*1e3),fe(H+1)}};return fe(1)},c=async(v,S,R=o)=>{s.log(`COMMAND: aws ${S.join(" ")}`),await a(v,()=>s.run("aws",S,{cwd:e,env:Za(R)}))},l=async(v,S={})=>{await i(`aws ${v.slice(0,2).join(" ")}`,"aws",v,{cwd:S.cwd,env:Za(S.env??o)})},u=async v=>{let S=await Promise.all(v.map(async R=>{try{let $=await s.capture("aws",["ssm","get-parameter","--name",R,"--query","Parameter.Value","--output","text"],{cwd:e,env:Za(o)});return[R,$.trim()]}catch($){throw new Error(`SSM parameter ${R}: ${$ instanceof Error?$.message:String($)}`)}}));return Object.fromEntries(S)},p=async v=>{let S=[`turbo@${await Uk(e)}`,...v?[`serverless@${Bk}`]:[]];await i("Install tools","pnpm",["add","-g",...S])},m=async(v,S)=>{let R=or.join(e,"out"),$={...o,...S.buildEnv},T=S.buildTask??$.TURBO_BUILD_TASK??"build";return await sr.rm(R,{recursive:!0,force:!0}),await i(`Prune to ${v}`,"turbo",["prune",v],{env:$}),await i("Install dependencies","pnpm",["install"],{cwd:R,env:$}),await i(`Build ${v}`,"pnpm",["exec","turbo",T,`--filter=${v}`,"--env-mode=loose"],{cwd:R,env:$}),S.installProd&&(s.log("COMMAND: remove every node_modules under ./out"),await Mp(R),await i("Install production dependencies","pnpm",["install","--frozen-lockfile","--node-linker=hoisted","--prod"],{cwd:R,env:$}),await i("Show node_modules size","du",["-sm","./node_modules/"],{cwd:R})),R},f=async(v,S,R)=>{if(S!==void 0){s.log(`Running ${v} hooks...`);try{await S(R)}catch($){throw new Error(`${v} hooks failed: ${$.message}`)}s.log(`${v} hooks completed successfully`)}},y=async v=>{let{app:S,appPath:R}=await _p(e,n,v);await p(!0);let $={...o,...v.buildEnv},T=await m(S,{installProd:!0,buildTask:v.buildTask,buildEnv:v.buildEnv}),W={stage:v.stage,outDir:T,appDir:or.join(T,R)};await f("Pre-deployment",v.preDeploy,W),await i("Deploy with Serverless","serverless",["deploy","--stage",v.stage,"--force"],{cwd:W.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 f("Post-deployment",v.postDeploy,W)},E=async v=>{let{app:S,appPath:R}=await _p(e,n,v);await p(!1);let $={...o,...v.buildEnv},T=await m(S,{installProd:!1,buildTask:v.buildTask,buildEnv:v.buildEnv}),W={stage:v.stage,outDir:T,appDir:or.join(T,R)},fe=`s3://${v.bucket}${v.destPath??""}`,H=v.sourcePath??"./dist";await i("Sync to S3","aws",["s3","sync",H,fe,...v.syncFlags??[],"--only-show-errors"],{cwd:W.appDir,env:Za($)}),await c("Invalidate CloudFront",["cloudfront","create-invalidation","--distribution-id",v.cloudfrontId,"--paths",v.invalidationPath??"/*"],$),await f("Post-deployment",v.postDeploy,W)},k=async(v,S,R)=>{let $=await sr.mkdtemp(or.join(H_.tmpdir(),"infra-kit-lambda-")),T=or.join($,"response.json"),W=["lambda","invoke","--function-name",v.functionName,...R===void 0?[]:["--region",R],"--cli-binary-format","raw-in-base64-out","--payload",v.payload??S,"--cli-read-timeout",String(X_),"--cli-connect-timeout",String(Z_),T],fe=Date.now();s.log(`COMMAND: aws ${W.join(" ")}`);try{let H=await s.capture("aws",W,{cwd:e,env:{...o,AWS_PAGER:""}}).then(Q_,wc=>`aws CLI failed: ${Np(wc instanceof Error?wc.message:String(wc))}`),kt=await sr.readFile(T,"utf-8").catch(()=>""),Us=((Date.now()-fe)/1e3).toFixed(1),Ws=H!==void 0&&kt?`; response: ${Np(kt)}`:"";return{outcome:`${v.functionName} (${Us}s)`,failure:H===void 0?void 0:H+Ws}}finally{await sr.rm($,{recursive:!0,force:!0})}};return{root:e,service:t,project:r,ssm:u,aws:l,run:(v,S,R={})=>s.run(v,S,{cwd:R.cwd??e,env:R.env??o}),capture:(v,S,R={})=>s.capture(v,S,{cwd:R.cwd??e,env:R.env??o}),retry:a,skip:v=>{throw new Un(v)},pruneAndBuild:m,deployBackendApi:y,deployFrontendUi:E,invokeLambdas:async v=>{let{region:S,payload:R="{}",blocking:$=[],steps:T=[]}=v;for(let W of $){let{outcome:fe,failure:H}=await k(W,R,S);if(H!==void 0)throw new Error(`Lambda ${fe} failed: ${H}`);s.log(`Lambda ${fe} OK`)}for(let W of T){let fe=await Promise.all(W.map(H=>k(H,R,S).catch(kt=>({outcome:H.functionName,failure:String(kt)}))));for(let{outcome:H,failure:kt}of fe)s.log(kt===void 0?`Lambda ${H} OK`:`Warning: Lambda ${H} failed, continuing: ${kt}`)}}}};var Wk=e=>({content:b(JSON.stringify(e,null,2)),structuredContent:e}),nM=async(e,t)=>{let r=Ms.join(e,"devops","scripts",`deploy-${t}.sh`);try{await Vk.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},oM=e=>`::add-mask::${e.replaceAll("%","%25").replaceAll("\r","%0D").replaceAll(`
447
+ `,"%0A")}`,sM=(e,t)=>{let r=(e??"").split(`
448
+ `).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(oM(n));return Object.fromEntries(r)},iM=async e=>{try{await Vk.access(e)}catch{throw new g(void 0,{operation:`run ${Ms.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 ${Ms.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},Fp=async e=>{let{service:t,env:r=tM.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!==bs)throw new D({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 A(),o=e.deps??Qa,{INFRA_KIT_EXTRA_ENV:s,...i}=r,a={...i,...sM(s,o.log)},c=await yt(n),l=c?.services[t]?.deploy;if(l===void 0)await o.run("sh",[await nM(n,t)],{cwd:n,env:a});else{let u=await iM(Ms.join(n,l)),p=jp({root:n,service:t,project:c?.project,scriptDir:Ms.dirname(l),env:a,deps:o});try{await u(p)}catch(m){if(!(m instanceof Un))throw m;return d.info(`\u23ED\uFE0F ${t} skipped: ${m.message}`),Wk({status:"skipped",service:t,reason:m.message})}}return d.info(`\u2705 ${t} deployed`),Wk({status:"deployed",service:t})};import{DEPLOY_CONFIG_FILE as js}from"@slip-stream-kit/config/internal";import tc from"node:fs/promises";import rc from"node:path";var Lp=async e=>{try{return await tc.readFile(e,"utf-8")}catch{return}},ec=e=>({content:b(JSON.stringify(e,null,2)),structuredContent:e}),aM={created:"missing",updated:"differs",unchanged:"matches",removed:"no longer generated"},Gk=async(e,t)=>(await Promise.all(t.map(async n=>{let o=rc.join(e,n);return(await Lp(o))?.startsWith(jn)?[{path:n,absolute:o}]:[]}))).flat(),cM=async(e,t)=>t.replaceV1!==!0?[]:(await Gk(e,hd)).map(r=>({...r,status:"removed"})),lM=async(e,t)=>{let n=(await Promise.all(Object.entries(t.services).map(async([o,s])=>s.deploy===void 0?[]:await Lp(rc.join(e,s.deploy))===void 0?[`${o}: ${s.deploy}`]:[]))).flat();if(n.length>0)throw new Error(`Deploy scripts named in ${js} do not exist: ${n.join(", ")}`)},uM=async(e,t)=>{if(t.replaceV1===!0)return;let r=await Gk(e,yd);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 ${js} no longer sets. Restore the hand-written v1 workflows from git history (or set replaceV1 again) before syncing.`)},Bp=async(e={})=>{let t=e.cwd??await A(),r=await yt(t);if(r===void 0)return(e.check?d.info.bind(d):d.error.bind(d))(`No ${js} at ${t}, nothing to generate.`),ec({status:"missing-config",ok:!!e.check,files:[]});await uM(t,r),await lM(t,r);let n=await Promise.all(kd(r).map(async a=>{let c=rc.join(t,a.path),l=await Lp(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 ${js}.`),ec({status:"unchanged",ok:!0,files:i});if(e.check){d.error(`\u274C Deploy workflows differ from ${js}; run \`infra-kit deploy-sync\` and commit:`);for(let a of s)d.error(` ${a.path} (${aM[a.status]})`);return ec({status:"drift",ok:!1,files:i})}for(let a of s){if(a.status==="removed"){await tc.rm(a.absolute),d.info(`\u{1F5D1}\uFE0F Removed ${a.path}`);continue}await tc.mkdir(rc.dirname(a.absolute),{recursive:!0}),await tc.writeFile(a.absolute,a.content),d.info(`\u270F\uFE0F ${a.status==="created"?"Created":"Updated"} ${a.path}`)}return ec({status:"written",ok:!0,files:i})};var Jk="https://dashboard.doppler.com/workplace/projects",dM=(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}"): ${Jk}/${e}`],Up=async({env:e})=>{let r=!!(await Ze())?.envs[e];await Cf(e);let n=await ur(),o=await Bt();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 dM(n,e))d.warn(i);let s={env:e,removed:r,storePath:o,revokeUrl:`${Jk}/${n}`};return{content:b(JSON.stringify(s,null,2)),structuredContent:s}};import pM from"@inquirer/confirm";import mM from"@inquirer/input";import fM from"@inquirer/password";import gM from"@inquirer/select";import hM from"node:fs/promises";import wt from"node:process";import{$ as nc}from"zx";var yM=async({stdin:e,fromEnv:t})=>{if(e)return{token:await Kk(),source:"stdin"};if(t){let n=wt.env[t];if(!n)throw new Error(`${t} is not set (or is empty) \u2014 nothing to store.`);return{token:n,source:"env"}}if(!wt.stdin.isTTY){let n=await Kk();if(n)return{token:n,source:"stdin"};if(!Z())throw new Error("stdin is not a terminal and carried no token \u2014 pipe one in (`op read \u2026 | infra-kit env-token-set <env>`) or pass --from-env <VAR>.")}return h.setInteractive(),{token:(await M(n=>fM({message:"Paste the Doppler service token (input is hidden)",mask:!0},n),{output:wt.stderr,whenHeadless:{refuse:"stdin"}})).trim(),source:"prompt"}},Kk=async()=>{let e=[];wt.stdin.setEncoding("utf8");for await(let t of wt.stdin)e.push(t);return e.join("").trim()},Wp="DOPPLER_CONFIG",vM=3e4,wM=async(e,t,r)=>{let n=nc.quiet;nc.quiet=!0;let o;try{o=(await nc({env:oo(e)})`doppler secrets download --no-file --format json --project ${t} --config ${r}`.timeout(vM)).stdout}catch(s){throw kM(s,r)}finally{nc.quiet=n}return Lc(o)},kM=(e,t)=>{let r=Xm(e)??(e instanceof Error?e.message:String(e));if(Af(r)!=="auth")return e instanceof Error?e:new Error(String(e));let n=Of(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(`
449
+ `))},bM=e=>[`Could not verify this token's scope: the Doppler payload for "${e}" carries no ${Wp}.`,"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(`
450
+ `),qk=async(e,t,r,n)=>{let o=await wM(e,t,r);Fc(o,r);let s=o.some(([i])=>i===Wp);if(!s&&!n)throw new Error(bM(r));return s},Hk="\0new-env",RM=async()=>{if(Z()||!wt.stdin.isTTY)throw new D({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([Gf(),Ze()]),r=Math.max(0,...e.map(({env:s})=>s.length));h.setInteractive();let n=await M(s=>gM({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:Hk}]},s),{output:wt.stderr,whenHeadless:"refuse"});return n!==Hk?n:(await M(s=>mM({message:"Doppler config name",validate:i=>/^\S+$/.test(i.trim())||"Enter a config name without spaces"},s),{output:wt.stderr,whenHeadless:"refuse"})).trim()},SM=async(e,t,r)=>M(n=>pM({message:`Replace the "${e}" token ${Ce(t)} with ${Ce(r)}?`,default:!0},n),{output:wt.stderr,whenHeadless:"refuse"}),EM=(e,t,r,n)=>{switch(t){case"stored":return`Stored the "${e}" service token (${Ce(r)})`;case"replaced":return`Replaced the "${e}" service token ${Ce(n??"")} \u2192 ${Ce(r)}`;case"unchanged":return`The "${e}" service token is already ${Ce(r)} \u2014 nothing to write`;case"kept":return`Kept the existing "${e}" service token ${Ce(n??"")} \u2014 nothing was written`;default:return Ue(t)}},Vp=async({env:e,stdin:t,fromEnv:r,force:n})=>{let o=await ur(),s=e??await RM(),{token:i,source:a}=await yM({stdin:t,fromEnv:r});if(!i)throw new Error("No token provided \u2014 nothing was written.");let c=await qk(i,o,s,n),l=(await Ze())?.envs[s],u;l===i?u="unchanged":l!==void 0&&a==="prompt"&&!await SM(s,l,i)?u="kept":(await Ac({[s]:i}),u=l===void 0?"stored":"replaced");let p=await Bt();d.info(`${EM(s,u,i,l)} in ${w(p)} (mode 0600).`),c||d.warn(`Scope was NOT verified (no ${Wp} in the payload) \u2014 accepted because --force was given.`);let m={env:s,status:u,source:a,redactedToken:Ce(i),previousRedactedToken:l===void 0?null:Ce(l),storePath:p,scopeVerified:c};return h.print(),{content:b(JSON.stringify(m,null,2)),structuredContent:m}},PM=e=>/^(["']).*\1$/.test(e)?e.slice(1,-1):e,Yk=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?PM(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},xM=e=>(e instanceof Error?e.message:String(e)).split(`
451
+ `)[0]??"",TM=(e,t)=>e===void 0?"stored":e===t?"unchanged":"replaced",CM=async(e,t,r,n)=>{let o=Ce(e.token);try{let s=await qk(e.token,t,e.env,n);return{env:e.env,status:TM(r,e.token),redactedToken:o,scopeVerified:s}}catch(s){return{env:e.env,status:"failed",redactedToken:o,scopeVerified:!1,error:xM(s)}}},Gp=async({fromFile:e,force:t})=>{let r=await ur(),n=Yk(await hM.readFile(e,"utf8")),o=await Ze(),s=await Promise.all(n.map(p=>CM(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 Ac(i);let a=await Bt(),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&&(wt.exitCode=1);let u={storePath:a,rows:s,failedCount:l};return{content:b(JSON.stringify(u,null,2)),structuredContent:u}};var Jp=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 Cd(n);if(r&&h.addOption("--from",p),Td(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"?Pa({version:o,env:s,skipTerraform:a,confirmedCommand:c}):xa({version:o,env:s,services:i,skipTerraform:a,confirmedCommand:c})},Kp=async e=>Jp(e,"all"),Hp=async e=>Jp(e,"selected"),oc=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.`),Jp({...e,from:"local"},t,!1)};import{VENDOR_CONFIG_FILE as Xk}from"@slip-stream-kit/config/internal";import qp from"node:fs/promises";import Wn from"node:path";import zk from"node:process";import{pathToFileURL as $M}from"node:url";var Zk="~/projects",Yp=async(e={})=>{if(e.init){await OM(e.cwd);return}await AM()},AM=async()=>{let e=En(),t=await ne(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."),zk.exitCode=1;return}let{workspaceDir:r,source:n,targets:o}=await Qi(),s=Pn(r),i=await ne(s),a=Wn.join(s,n),c=await ne(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=Wn.join(s,u),m=await ne(p);m||(l=!1);let f=m?"[\u2713]":"[ ]",y=m?"":" (not found \u2014 clone or remove)";d.info(` ${f} ${u} ${w(p)}${y}`)}l||(zk.exitCode=1)},OM=async e=>{let t=En();if(await ne(t)){d.info(`Factory config already exists at ${w(t)} \u2014 leaving it untouched.`);return}let r=e??await A(),n=await DM(r);await qp.mkdir(Wn.dirname(t),{recursive:!0}),await qp.writeFile(t,IM(Wn.basename(r),n),"utf-8"),d.info(`\u2713 Created ${w(t)}`),n.length>0&&d.info(` Seeded ${n.length} target(s) from the source ${Xk}.`),d.info(` Edit \`workspaceDir\` (placeholder: ${Zk}) to point at where your repos live.`),d.info(` \`source\` is seeded with ${Wn.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.")},DM=async e=>{try{let t=Wn.join(e,Xk),r=await qp.stat(t),s=(await import(`${$M(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[]},IM=(e,t)=>`${JSON.stringify({workspaceDir:Zk,source:e,targets:t},null,2)}
452
+ `;import{existsSync as Uj}from"node:fs";import Wj from"node:fs/promises";import xb from"node:path";import Tb from"node:process";import{z as Vj}from"zod";import{chmodSync as UM,copyFileSync as WM,lstatSync as VM,mkdirSync as cb,readdirSync as GM,readlinkSync as JM,rmSync as KM,rmdirSync as lb,symlinkSync as HM,unlinkSync as qM,writeFileSync as YM}from"node:fs";import Ee from"node:path";import{lstatSync as NM,readlinkSync as Qk}from"node:fs";import _M from"node:path";var MM=new Set(["ENOENT","ENOTDIR"]),sc=e=>{let t;try{t=NM(e)}catch(r){if(MM.has(r.code??""))return null;throw r}return t.isSymbolicLink()?{kind:"link",text:Qk(e)}:t.isFile()?{kind:"file",executable:(t.mode&64)!==0,sha:Nr(e)}:{kind:"other"}},eb=(e,t)=>{let r=_M.join(e,t.path),n=t.mode==="120000"?{kind:"link",text:Qk(r)}:{kind:"file",executable:t.mode==="100755",sha:Nr(r)};return{...t,fingerprint:n}},tb=(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 jM}from"zx";var X=async(e,t,r={})=>{let{input:n,allowFailure:o=!1}=r,s=await jM({cwd:e,quiet:!0,input:n,nothrow:o})`git ${t}`;return s.exitCode===0?s.stdout:""},ic=e=>e.slice(0,7),rt=e=>e.split("\0").filter(t=>t.length>0);import FM from"node:path";var zp=`${oe}/`,ir=`${oe}/README.md`,Fs=`${oe}/${Ye}`,nb=e=>e.startsWith(zp),rb=e=>{let t=FM.posix.normalize(e);return t.endsWith("/")?t.slice(0,-1):t},ob=e=>{let t=rb(e.path),r=e.target===void 0?t:rb(e.target);return{path:t,target:r,vendored:nb(r),module:e.module??null}},sb=e=>e.copy.map(ob),Ls=(e,t)=>t.length===0?!1:e.split("/").some(r=>t.includes(r)),Bs=(e,t)=>e.filter(r=>!Ls(r.path,t)),ac=(e,t)=>e===t.path?t.target:`${t.target}${e.slice(t.path.length)}`,Vn=e=>[...new Set(e)].sort(),ib=e=>e.startsWith(zp)?e.slice(zp.length):null;var cc=e=>`# vendor/ \u2014 mirrored from ${e}
453
453
 
454
454
  **DO NOT EDIT files in this folder here.**
455
455
 
@@ -460,19 +460,19 @@ fail \`ik vendor check\` in CI.
460
460
  To change a vendored package, edit it in \`${e}\` and re-run the sync there.
461
461
 
462
462
  See \`.sync-manifest.json\` for the source commit and per-file checksums.
463
- `;var TM=new Set(["100644","100755","120000"]),CM=(e,t)=>{let r=new Map;for(let n of rt(e)){let o=n.indexOf(" "),s=n.slice(0,n.indexOf(" ")),i=n.slice(o+1);o<0||!TM.has(s)||_s(i,t)||r.set(i,{path:i,mode:s})}return[...r.values()]},qp=async(e,t,r)=>{let n=await X(e,["--literal-pathspecs","ls-files","-z","-s","--",t]);return CM(n,r)},Xk=async e=>rt(await X(e,["--literal-pathspecs","ls-files","-z","--",oe]));var Vn=e=>["git","-C",e.root,"--literal-pathspecs","checkout","HEAD","--",...e.recoveryPaths],eb=e=>{let t=rc(e);t!==null&&(t.kind==="other"?Qk(e):MM(e))},FM=(e,t,r)=>{let n=Se.join(e,r.source),o=Se.join(t,r.target);if(Zk(Se.dirname(o),{recursive:!0}),eb(o),r.mode==="120000"){_M(IM(n),o);return}AM(n,o),$M(o,r.mode==="100755"?493:420)},LM=async(e,t)=>{let r=new Set;for(let n of rt(await X(e,["ls-files","-z"]))){if(t.has(n))continue;let o=Se.posix.dirname(n);for(;o!==".";)r.add(o),o=Se.posix.dirname(o)}return r},BM=async(e,t)=>{if(t.length===0)return;let r=await LM(e,new Set(t)),n=[...new Set(t.map(o=>Se.dirname(Se.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)&&!(!OM(s,{throwIfNoEntry:!1})?.isDirectory()||DM(s).length>0||r.has(Se.relative(e,s).split(Se.sep).join("/")));)Qk(s),s=Se.dirname(s)}},tb=(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,or,...s].map(zk).filter(a=>a!==null&&!ja(a));return Wn(i)},rb=async(e,t,r,n)=>{let o=Se.join(e,oe);Zk(o,{recursive:!0}),jM(Se.join(e,or),sc(t.name));let s=tb(r,await Xk(e),n);up(o,{source:t.name,commit:t.headSha},s)},Yp=async({source:e,plan:t,onBeforeFirstWrite:r})=>{if(t.status!=="changed")return{touched:[],manifestWritten:!1};r?.(Vn(t));let n=Se.resolve(t.root),o=t.entries.flatMap(a=>a.deletes);for(let a of o)eb(Se.join(n,a));await BM(n,o);for(let a of t.entries)a.pruned&&a.deletes.length>0&&NM(Se.join(n,a.target),{recursive:!0,force:!0});let s=t.entries.flatMap(a=>a.writes);for(let a of s)FM(e.root,n,a);let i=s.map(a=>a.target);return t.writeVendorMeta?(await rb(n,e,t.entries,o),{touched:Wn([...o,...i,or,Ns]),manifestWritten:!0}):{touched:Wn([...o,...i]),manifestWritten:!1}},zp=async(e,t)=>(await rb(e,t,[],[]),[or,Ns]);var Xp=(e,t)=>`[ROOT] vendor: sync from ${e}@${nc(t)}`,UM=e=>{let{stdout:t,stderr:r}=e;return[t,r].filter(o=>typeof o=="string"&&o.trim().length>0).join(`
464
- `).trim()||String(e)},Zp=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 X(e,["--literal-pathspecs","add","-A",...o],{input:n}),await X(e,["--literal-pathspecs","commit","--only","-m",r,...o],{input:n}),{ok:!0}}catch(s){return{ok:!1,output:UM(s)}}};var nb=20,WM=20,em=(e,t)=>e.length<=t?[...e]:[...e.slice(0,t),`\u2026and ${e.length-t} more`],Qp=(e,t,r)=>{let{entry:n}=e,o=new Set(t.tracked),s=[],i=[];for(let u of Ms(e.files,r)){let p=oc(u.path,n);if(s.push(p),Jk(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=Ms(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}},_r=(e,t,r,n=[])=>({name:e.name,root:e.root,status:t,message:r,notes:n,warnings:[],entries:[],writeVendorMeta:!1,recoveryPaths:[]}),tm=(e,t)=>e.entries.filter((r,n)=>t[n]!=="release").map(r=>r.entry.target),VM=(e,t,r,n)=>{let o=["git","-C",t.root,"--literal-pathspecs","status","--",...tm(e,r)];return _r(t,"fail",`blocked: ${n.length} uncommitted path(s) under synced paths`,[...em(n,nb),Be(o)])},GM=(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=nc(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}`,...em(e.lines,WM)],warnings:[]}},JM=e=>{let{added:t,modified:r,removed:n}=e.counts;return t+r+n===0?null:`${e.target}: ${t} added, ${r} modified, ${n} removed`},KM=e=>{let t=r=>e.reduce((n,o)=>n+o.counts[r],0);return`${t("added")} added, ${t("modified")} modified, ${t("removed")} removed`},HM=(e,t,r)=>{let n=e.flatMap(o=>[...o.writes.filter(i=>i.change==="modified").map(i=>i.target),...o.deletes]);return Wn([...n,...r?t.headVendorMeta:[]])},qM=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`),YM=(e,t)=>{let r=t.entries.map(f=>f.scope);if(t.dirty.length>0)return VM(e,t,r,t.dirty);if(t.pruneConflicts.length>0)return _r(t,"fail","blocked: a module this repo dropped is still a dependency",[...em(t.pruneConflicts,nb)]);let n=e.entries.flatMap((f,v)=>{let E=t.entries[v]??{target:f.entry.target,scope:"sync",tracked:[],onDisk:{}};return E.scope==="release"?[]:E.scope==="sync"?[Qp(f,E,e.exclude)]:[{...Qp({...f,files:[]},E,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={..._r(t,"ok","up to date"),branch:t.branch,entries:n,writeVendorMeta:o};if(!s&&!i)return a;let c=GM(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(JM).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:`${KM(n)} on ${t.branch}`,notes:[...u,...m,...qM(t),...i?["vendor/README.md and manifest rewritten"]:[],...c.notes],warnings:[...l,...c.warnings],recoveryPaths:HM(n,t,o)}},ic=(e,t)=>{switch(t.kind){case"missing":return _r(t,"skipped",`not checked out at ${t.root}`);case"source":return _r(t,"skipped","this is the source repo");case"not-git":return _r(t,"fail",`not a git repo: ${t.reason}`);case"bad-selection":return _r(t,"fail",`vendorTarget: ${t.reason}`);case"repo":return YM(e,t)}};import{existsSync as nj,readFileSync as oj,realpathSync as ac}from"node:fs";import cc from"node:path";import{readFileSync as ob}from"node:fs";import Gn from"node:path";var zM=["dependencies","devDependencies","peerDependencies","optionalDependencies"],XM=e=>{let t=e.flatMap(({entry:r})=>r.module===null?[]:[r.module]);return[...new Set(t)].sort()},sb=(e,t)=>{if(t.kind==="invalid")return{reason:t.reason};let r=XM(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")},ib=e=>{try{return JSON.parse(ob(e,"utf8"))}catch{return null}},ZM=(e,t)=>t.files.flatMap(r=>{let n=Gn.posix.relative(t.entry.path,r.path);if(Gn.posix.basename(n)!=="package.json"||n.split("/").length>2)return[];let o=ib(Gn.join(e,r.path))?.name;return typeof o=="string"?[o]:[]}),QM=e=>zM.flatMap(t=>{let r=e[t];return r!==null&&typeof r=="object"?Object.keys(r):[]}),ab=(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},ej=["*.sh","*.yml","*.yaml"],tj=(e,t,r)=>{let n=QM(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"&&ab(i,r)&&n.push(`${e} script "${s}" runs ${r}`);return n},rj=async(e,t,r)=>{let n=["grep","-z","-l","-F","-e",t,"--",...ej];return rt(await X(e,n,{allowFailure:!0})).filter(s=>r(s)&&ab(ob(Gn.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 ZM(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=rt(await X(t,["ls-files","-z","--","*package.json"])).filter(c=>Gn.posix.basename(c)==="package.json"&&s(c)),a=[];for(let[c,l]of n){let u=i.flatMap(p=>{let m=ib(Gn.join(t,p));return m===null?[]:tj(p,m,c)});u.push(...await rj(t,c,s));for(let p of u)a.push(`${p}: add "${l}" to vendorTarget.modules or stop using it`)}return a.sort()};var rm=async(e,t)=>{let r=t.exclude??[],n=(await X(e,["rev-parse","HEAD"])).trim(),o=await $e(e),s=await Promise.all(Yk(t).map(async i=>{let a=await qp(e,i.path,r);return{entry:i,files:a.map(c=>Gk(e,c))}}));return{root:e,selfRoots:[...new Set([ac(e),ac(o)])],name:cc.basename(o),headSha:n,entries:s,exclude:r}},lc=e=>{let t=rt(e)[Symbol.iterator](),r=[];for(let n of t)r.push(n.slice(3)),/^[RC]|^.[RC]/u.test(n)&&t.next();return r},sj=async(e,t,r)=>{let n=tm(e,t);if(n.length===0)return[];let o=await X(r,["--literal-pathspecs","status","--porcelain","-z","--untracked-files=all","--",...n]);return lc(o).filter(s=>!_s(s,e.exclude))},ij=async(e,t,r)=>Promise.all(e.entries.map(async({entry:n,files:o},s)=>{let i=t[s],a=await qp(r,n.target,e.exclude),c={},l=i==="sync"?o:[];for(let u of Ms(l,e.exclude)){let p=oc(u.path,n);c[p]=rc(cc.join(r,p))}return{target:n.target,scope:i,tracked:a.map(u=>u.path),onDisk:c}})),aj=async e=>{try{return rt(await X(e,["--literal-pathspecs","ls-tree","-z","--name-only","HEAD","--",or,Ns]))}catch{return[]}},cj=e=>{try{let{commit:t,source:r}=xs(cc.join(e,oe));return{commit:t,source:r}}catch{return null}},lj=async(e,t,r)=>{if(r===null)return{kind:"unknown-sha"};if(await xe(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 X(e.root,["--literal-pathspecs","log","--oneline",`${r}..HEAD`,"--",...n])).split(`
465
- `).filter(i=>i.length>0);return{kind:"log",sha:r,lines:s}},uj=(e,t)=>{try{return oj(cc.join(e,or),"utf8")===sc(t)}catch{return!1}},dj=async e=>{try{return{toplevel:(await X(e,["rev-parse","--show-toplevel"])).trim()}}catch(t){return{reason:String(t.stderr??t).trim().split(`
466
- `)[0]??"git rev-parse failed"}}},pj=async e=>{try{return(await X(e,["rev-parse","--abbrev-ref","HEAD"])).trim()}catch{return"HEAD"}},uc=async(e,t)=>{if(!nj(t.root))return{...t,kind:"missing"};let r=ac(t.root);if(e.selfRoots.includes(r))return{...t,kind:"source"};let n=await dj(t.root);if("reason"in n)return{...t,kind:"not-git",reason:n.reason};if(ac(n.toplevel)!==r)return{...t,kind:"not-git",reason:`it sits inside the repo at ${n.toplevel}`};let o=sb(e.entries,t.selection??{kind:"all"});if("reason"in o)return{...t,kind:"bad-selection",reason:o.reason};let s=cj(t.root),i=s?.commit??null,[a,c,l,u,p]=await Promise.all([pj(t.root),sj(e,o,t.root),ij(e,o,t.root),aj(t.root),lj(e,o,i)]),m=l.flatMap((f,v)=>f.scope==="prune"&&f.tracked.length>0?[{facts:e.entries[v],target:f.target}]:[]);return{...t,kind:"repo",branch:a,dirty:c,entries:l,headVendorMeta:u,readmeCurrent:uj(t.root,e.name),manifestPresent:s!==null,manifestSource:s?.source??null,changelog:p,pruneConflicts:await cb(e.root,t.root,m)}};var mj=20,fj=(e,t)=>!t.commit||e.status!=="changed"||e.branch===void 0?e.notes:[...e.notes,`--commit lands on ${e.branch}`],gj=(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:",Be(Vn(r))]};let o=e.applied?`wrote ${r.message}`:r.message;return{name:n,status:r.status,message:o,notes:t.mode==="applied"?r.notes:fj(r,t)}},hj=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(`
467
- `).slice(0,mj)},yj=(e,t)=>{let r=e.plan.warnings.map(n=>({name:"changelog",status:"warn",message:n}));return{label:e.plan.name,rows:[gj(e,t),...r,...e.commit?[hj(e.commit)]:[]]}},vj={preview:"infra-kit vendor sync (preview)",check:"infra-kit vendor sync --check",applied:"infra-kit vendor sync"},nm=(e,t,r)=>{let n=r.mode==="preview"?["re-run with --yes from a real terminal to apply"]:[];return{title:vj[r.mode],sections:[{label:"source",rows:[...e]},...t.map(o=>yj(o,r))],hints:n}},lb=e=>e.sections.some(t=>t.rows.some(r=>r.status==="fail")),ub=(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,om=async(e,t)=>(await X(e,t,{allowFailure:!0})).trim(),kj=async e=>lc(await X(e,["status","--porcelain","-z","--untracked-files=normal"])),bj=async e=>(await om(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"]},Rj=async e=>{let[t,r]=await Promise.all([om(e,["symbolic-ref","--quiet","--short","refs/remotes/origin/HEAD"]),om(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}`}},db=async e=>{let t=await kj(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([bj(e),Rj(e)]);return[{name:"working tree",status:"ok",message:"clean"},...r.filter(n=>n!==null)]};import xj from"node:path";import{readFileSync as Sj}from"node:fs";import Ej from"node:path";import{z as Pj}from"zod";var pb=e=>{let t;try{t=Sj(Ej.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=pf.safeParse(r);return n.success?{kind:"modules",modules:n.data.modules}:{kind:"invalid",reason:Pj.prettifyError(n.error)}};var mb=(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=En(e.workspaceDir);return(t.length>0?e.targets.filter(s=>t.includes(s)):e.targets).map(s=>{let i=xj.join(n,s);return{name:s,root:i,selection:pb(i)}})},Tj="rewrite vendor/README.md and vendor/.sync-manifest.json from the tracked vendor/ files",Cj=async(e,t)=>{let r=await uc(e,t),n=ic(e,r);return r.kind!=="repo"||n.status==="fail"?n:{...n,status:"changed",message:`${Tj} on ${r.branch}`,notes:[],warnings:[],branch:r.branch,entries:[],writeVendorMeta:!0,recoveryPaths:r.headVendorMeta}},fb=async(e,t,r)=>Promise.all(t.map(async n=>r?Cj(e,n):ic(e,await uc(e,n))));var vb="sync vendored files",Dj=e=>{let t=hb.join(En(e.workspaceDir),e.source);if($j(t))return t;throw new O({status:"refused",reason:"source-missing",source:t},1,{operation:vb,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'})},sm=(e,t)=>new O({status:"refused",reason:"not-a-vendor-source"},1,{operation:vb,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`}),Ij=async e=>{let t=hb.join(e,"infra-kit.json"),r;try{r=JSON.parse(await Aj.readFile(t,"utf8"))}catch(s){throw sm(t,`is unreadable: ${s instanceof Error?s.message:String(s)}`)}let n=r?.vendorSource;if(n==null)throw sm(t,"has no vendorSource block");let o=df.safeParse(n);if(!o.success)throw sm(t,`has an invalid vendorSource: ${Oj.prettifyError(o.error)}`);return o.data},gb=(e,t)=>{yb.stderr.write(`${e.name}: if this run dies, restore the tracked paths with:
463
+ `;var LM=new Set(["100644","100755","120000"]),BM=(e,t)=>{let r=new Map;for(let n of rt(e)){let o=n.indexOf(" "),s=n.slice(0,n.indexOf(" ")),i=n.slice(o+1);o<0||!LM.has(s)||Ls(i,t)||r.set(i,{path:i,mode:s})}return[...r.values()]},Xp=async(e,t,r)=>{let n=await X(e,["--literal-pathspecs","ls-files","-z","-s","--",t]);return BM(n,r)},ab=async e=>rt(await X(e,["--literal-pathspecs","ls-files","-z","--",oe]));var Gn=e=>["git","-C",e.root,"--literal-pathspecs","checkout","HEAD","--",...e.recoveryPaths],ub=e=>{let t=sc(e);t!==null&&(t.kind==="other"?lb(e):qM(e))},zM=(e,t,r)=>{let n=Ee.join(e,r.source),o=Ee.join(t,r.target);if(cb(Ee.dirname(o),{recursive:!0}),ub(o),r.mode==="120000"){HM(JM(n),o);return}WM(n,o),UM(o,r.mode==="100755"?493:420)},XM=async(e,t)=>{let r=new Set;for(let n of rt(await X(e,["ls-files","-z"]))){if(t.has(n))continue;let o=Ee.posix.dirname(n);for(;o!==".";)r.add(o),o=Ee.posix.dirname(o)}return r},ZM=async(e,t)=>{if(t.length===0)return;let r=await XM(e,new Set(t)),n=[...new Set(t.map(o=>Ee.dirname(Ee.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)&&!(!VM(s,{throwIfNoEntry:!1})?.isDirectory()||GM(s).length>0||r.has(Ee.relative(e,s).split(Ee.sep).join("/")));)lb(s),s=Ee.dirname(s)}},db=(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,ir,...s].map(ib).filter(a=>a!==null&&!Ba(a));return Vn(i)},pb=async(e,t,r,n)=>{let o=Ee.join(e,oe);cb(o,{recursive:!0}),YM(Ee.join(e,ir),cc(t.name));let s=db(r,await ab(e),n);mp(o,{source:t.name,commit:t.headSha},s)},Zp=async({source:e,plan:t,onBeforeFirstWrite:r})=>{if(t.status!=="changed")return{touched:[],manifestWritten:!1};r?.(Gn(t));let n=Ee.resolve(t.root),o=t.entries.flatMap(a=>a.deletes);for(let a of o)ub(Ee.join(n,a));await ZM(n,o);for(let a of t.entries)a.pruned&&a.deletes.length>0&&KM(Ee.join(n,a.target),{recursive:!0,force:!0});let s=t.entries.flatMap(a=>a.writes);for(let a of s)zM(e.root,n,a);let i=s.map(a=>a.target);return t.writeVendorMeta?(await pb(n,e,t.entries,o),{touched:Vn([...o,...i,ir,Fs]),manifestWritten:!0}):{touched:Vn([...o,...i]),manifestWritten:!1}},Qp=async(e,t)=>(await pb(e,t,[],[]),[ir,Fs]);var em=(e,t)=>`[ROOT] vendor: sync from ${e}@${ic(t)}`,QM=e=>{let{stdout:t,stderr:r}=e;return[t,r].filter(o=>typeof o=="string"&&o.trim().length>0).join(`
464
+ `).trim()||String(e)},tm=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 X(e,["--literal-pathspecs","add","-A",...o],{input:n}),await X(e,["--literal-pathspecs","commit","--only","-m",r,...o],{input:n}),{ok:!0}}catch(s){return{ok:!1,output:QM(s)}}};var mb=20,ej=20,nm=(e,t)=>e.length<=t?[...e]:[...e.slice(0,t),`\u2026and ${e.length-t} more`],rm=(e,t,r)=>{let{entry:n}=e,o=new Set(t.tracked),s=[],i=[];for(let u of Bs(e.files,r)){let p=ac(u.path,n);if(s.push(p),tb(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=Bs(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}},Mr=(e,t,r,n=[])=>({name:e.name,root:e.root,status:t,message:r,notes:n,warnings:[],entries:[],writeVendorMeta:!1,recoveryPaths:[]}),om=(e,t)=>e.entries.filter((r,n)=>t[n]!=="release").map(r=>r.entry.target),tj=(e,t,r,n)=>{let o=["git","-C",t.root,"--literal-pathspecs","status","--",...om(e,r)];return Mr(t,"fail",`blocked: ${n.length} uncommitted path(s) under synced paths`,[...nm(n,mb),Be(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=ic(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}`,...nm(e.lines,ej)],warnings:[]}},nj=e=>{let{added:t,modified:r,removed:n}=e.counts;return t+r+n===0?null:`${e.target}: ${t} added, ${r} modified, ${n} removed`},oj=e=>{let t=r=>e.reduce((n,o)=>n+o.counts[r],0);return`${t("added")} added, ${t("modified")} modified, ${t("removed")} removed`},sj=(e,t,r)=>{let n=e.flatMap(o=>[...o.writes.filter(i=>i.change==="modified").map(i=>i.target),...o.deletes]);return Vn([...n,...r?t.headVendorMeta:[]])},ij=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`),aj=(e,t)=>{let r=t.entries.map(f=>f.scope);if(t.dirty.length>0)return tj(e,t,r,t.dirty);if(t.pruneConflicts.length>0)return Mr(t,"fail","blocked: a module this repo dropped is still a dependency",[...nm(t.pruneConflicts,mb)]);let n=e.entries.flatMap((f,y)=>{let E=t.entries[y]??{target:f.entry.target,scope:"sync",tracked:[],onDisk:{}};return E.scope==="release"?[]:E.scope==="sync"?[rm(f,E,e.exclude)]:[{...rm({...f,files:[]},E,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={...Mr(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(nj).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:`${oj(n)} on ${t.branch}`,notes:[...u,...m,...ij(t),...i?["vendor/README.md and manifest rewritten"]:[],...c.notes],warnings:[...l,...c.warnings],recoveryPaths:sj(n,t,o)}},lc=(e,t)=>{switch(t.kind){case"missing":return Mr(t,"skipped",`not checked out at ${t.root}`);case"source":return Mr(t,"skipped","this is the source repo");case"not-git":return Mr(t,"fail",`not a git repo: ${t.reason}`);case"bad-selection":return Mr(t,"fail",`vendorTarget: ${t.reason}`);case"repo":return aj(e,t)}};import{existsSync as gj,readFileSync as hj,realpathSync as uc}from"node:fs";import dc from"node:path";import{readFileSync as fb}from"node:fs";import Jn from"node:path";var cj=["dependencies","devDependencies","peerDependencies","optionalDependencies"],lj=e=>{let t=e.flatMap(({entry:r})=>r.module===null?[]:[r.module]);return[...new Set(t)].sort()},gb=(e,t)=>{if(t.kind==="invalid")return{reason:t.reason};let r=lj(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")},hb=e=>{try{return JSON.parse(fb(e,"utf8"))}catch{return null}},uj=(e,t)=>t.files.flatMap(r=>{let n=Jn.posix.relative(t.entry.path,r.path);if(Jn.posix.basename(n)!=="package.json"||n.split("/").length>2)return[];let o=hb(Jn.join(e,r.path))?.name;return typeof o=="string"?[o]:[]}),dj=e=>cj.flatMap(t=>{let r=e[t];return r!==null&&typeof r=="object"?Object.keys(r):[]}),yb=(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},pj=["*.sh","*.yml","*.yaml"],mj=(e,t,r)=>{let n=dj(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"&&yb(i,r)&&n.push(`${e} script "${s}" runs ${r}`);return n},fj=async(e,t,r)=>{let n=["grep","-z","-l","-F","-e",t,"--",...pj];return rt(await X(e,n,{allowFailure:!0})).filter(s=>r(s)&&yb(fb(Jn.join(e,s),"utf8"),t)).map(s=>`${s} uses ${t}`)},vb=async(e,t,r)=>{let n=new Map;for(let{facts:c}of r)for(let l of uj(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=rt(await X(t,["ls-files","-z","--","*package.json"])).filter(c=>Jn.posix.basename(c)==="package.json"&&s(c)),a=[];for(let[c,l]of n){let u=i.flatMap(p=>{let m=hb(Jn.join(t,p));return m===null?[]:mj(p,m,c)});u.push(...await fj(t,c,s));for(let p of u)a.push(`${p}: add "${l}" to vendorTarget.modules or stop using it`)}return a.sort()};var sm=async(e,t)=>{let r=t.exclude??[],n=(await X(e,["rev-parse","HEAD"])).trim(),o=await $e(e),s=await Promise.all(sb(t).map(async i=>{let a=await Xp(e,i.path,r);return{entry:i,files:a.map(c=>eb(e,c))}}));return{root:e,selfRoots:[...new Set([uc(e),uc(o)])],name:dc.basename(o),headSha:n,entries:s,exclude:r}},pc=e=>{let t=rt(e)[Symbol.iterator](),r=[];for(let n of t)r.push(n.slice(3)),/^[RC]|^.[RC]/u.test(n)&&t.next();return r},yj=async(e,t,r)=>{let n=om(e,t);if(n.length===0)return[];let o=await X(r,["--literal-pathspecs","status","--porcelain","-z","--untracked-files=all","--",...n]);return pc(o).filter(s=>!Ls(s,e.exclude))},vj=async(e,t,r)=>Promise.all(e.entries.map(async({entry:n,files:o},s)=>{let i=t[s],a=await Xp(r,n.target,e.exclude),c={},l=i==="sync"?o:[];for(let u of Bs(l,e.exclude)){let p=ac(u.path,n);c[p]=sc(dc.join(r,p))}return{target:n.target,scope:i,tracked:a.map(u=>u.path),onDisk:c}})),wj=async e=>{try{return rt(await X(e,["--literal-pathspecs","ls-tree","-z","--name-only","HEAD","--",ir,Fs]))}catch{return[]}},kj=e=>{try{let{commit:t,source:r}=As(dc.join(e,oe));return{commit:t,source:r}}catch{return null}},bj=async(e,t,r)=>{if(r===null)return{kind:"unknown-sha"};if(await Te(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 X(e.root,["--literal-pathspecs","log","--oneline",`${r}..HEAD`,"--",...n])).split(`
465
+ `).filter(i=>i.length>0);return{kind:"log",sha:r,lines:s}},Rj=(e,t)=>{try{return hj(dc.join(e,ir),"utf8")===cc(t)}catch{return!1}},Sj=async e=>{try{return{toplevel:(await X(e,["rev-parse","--show-toplevel"])).trim()}}catch(t){return{reason:String(t.stderr??t).trim().split(`
466
+ `)[0]??"git rev-parse failed"}}},Ej=async e=>{try{return(await X(e,["rev-parse","--abbrev-ref","HEAD"])).trim()}catch{return"HEAD"}},mc=async(e,t)=>{if(!gj(t.root))return{...t,kind:"missing"};let r=uc(t.root);if(e.selfRoots.includes(r))return{...t,kind:"source"};let n=await Sj(t.root);if("reason"in n)return{...t,kind:"not-git",reason:n.reason};if(uc(n.toplevel)!==r)return{...t,kind:"not-git",reason:`it sits inside the repo at ${n.toplevel}`};let o=gb(e.entries,t.selection??{kind:"all"});if("reason"in o)return{...t,kind:"bad-selection",reason:o.reason};let s=kj(t.root),i=s?.commit??null,[a,c,l,u,p]=await Promise.all([Ej(t.root),yj(e,o,t.root),vj(e,o,t.root),wj(t.root),bj(e,o,i)]),m=l.flatMap((f,y)=>f.scope==="prune"&&f.tracked.length>0?[{facts:e.entries[y],target:f.target}]:[]);return{...t,kind:"repo",branch:a,dirty:c,entries:l,headVendorMeta:u,readmeCurrent:Rj(t.root,e.name),manifestPresent:s!==null,manifestSource:s?.source??null,changelog:p,pruneConflicts:await vb(e.root,t.root,m)}};var Pj=20,xj=(e,t)=>!t.commit||e.status!=="changed"||e.branch===void 0?e.notes:[...e.notes,`--commit lands on ${e.branch}`],Tj=(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:",Be(Gn(r))]};let o=e.applied?`wrote ${r.message}`:r.message;return{name:n,status:r.status,message:o,notes:t.mode==="applied"?r.notes:xj(r,t)}},Cj=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(`
467
+ `).slice(0,Pj)},$j=(e,t)=>{let r=e.plan.warnings.map(n=>({name:"changelog",status:"warn",message:n}));return{label:e.plan.name,rows:[Tj(e,t),...r,...e.commit?[Cj(e.commit)]:[]]}},Aj={preview:"infra-kit vendor sync (preview)",check:"infra-kit vendor sync --check",applied:"infra-kit vendor sync"},im=(e,t,r)=>{let n=r.mode==="preview"?["re-run with --yes from a real terminal to apply"]:[];return{title:Aj[r.mode],sections:[{label:"source",rows:[...e]},...t.map(o=>$j(o,r))],hints:n}},wb=e=>e.sections.some(t=>t.rows.some(r=>r.status==="fail")),kb=(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 Oj=20,am=async(e,t)=>(await X(e,t,{allowFailure:!0})).trim(),Dj=async e=>pc(await X(e,["status","--porcelain","-z","--untracked-files=normal"])),Ij=async e=>(await am(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"]},Nj=async e=>{let[t,r]=await Promise.all([am(e,["symbolic-ref","--quiet","--short","refs/remotes/origin/HEAD"]),am(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}`}},bb=async e=>{let t=await Dj(e);if(t.length>0){let n=t.slice(0,Oj),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([Ij(e),Nj(e)]);return[{name:"working tree",status:"ok",message:"clean"},...r.filter(n=>n!==null)]};import Fj from"node:path";import{readFileSync as _j}from"node:fs";import Mj from"node:path";import{z as jj}from"zod";var Rb=e=>{let t;try{t=_j(Mj.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=gf.safeParse(r);return n.success?{kind:"modules",modules:n.data.modules}:{kind:"invalid",reason:jj.prettifyError(n.error)}};var Sb=(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=Pn(e.workspaceDir);return(t.length>0?e.targets.filter(s=>t.includes(s)):e.targets).map(s=>{let i=Fj.join(n,s);return{name:s,root:i,selection:Rb(i)}})},Lj="rewrite vendor/README.md and vendor/.sync-manifest.json from the tracked vendor/ files",Bj=async(e,t)=>{let r=await mc(e,t),n=lc(e,r);return r.kind!=="repo"||n.status==="fail"?n:{...n,status:"changed",message:`${Lj} on ${r.branch}`,notes:[],warnings:[],branch:r.branch,entries:[],writeVendorMeta:!0,recoveryPaths:r.headVendorMeta}},Eb=async(e,t,r)=>Promise.all(t.map(async n=>r?Bj(e,n):lc(e,await mc(e,n))));var Cb="sync vendored files",Gj=e=>{let t=xb.join(Pn(e.workspaceDir),e.source);if(Uj(t))return t;throw new D({status:"refused",reason:"source-missing",source:t},1,{operation:Cb,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'})},cm=(e,t)=>new D({status:"refused",reason:"not-a-vendor-source"},1,{operation:Cb,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`}),Jj=async e=>{let t=xb.join(e,"infra-kit.json"),r;try{r=JSON.parse(await Wj.readFile(t,"utf8"))}catch(s){throw cm(t,`is unreadable: ${s instanceof Error?s.message:String(s)}`)}let n=r?.vendorSource;if(n==null)throw cm(t,"has no vendorSource block");let o=ff.safeParse(n);if(!o.success)throw cm(t,`has an invalid vendorSource: ${Vj.prettifyError(o.error)}`);return o.data},Pb=(e,t)=>{Tb.stderr.write(`${e.name}: if this run dies, restore the tracked paths with:
468
468
  ${Be(t)}
469
- `)},Nj=async(e,t,r)=>r?(gb(t,Vn(t)),zp(t.root,e)):(await Yp({source:e,plan:t,onBeforeFirstWrite:o=>{gb(t,o)}})).touched,_j=async(e,t,r)=>{if(t.status!=="changed")return{plan:t,applied:!1};let n;try{n=await Nj(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 Zp(t.root,n,Xp(e.name,e.headSha));return{plan:t,applied:!0,commit:o}},Mj=async(e,t,r)=>{let n=[];for(let o of t)n.push(await _j(e,o,r));return n},wb=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})),im=({mode:e,report:t,outcomes:r,source:n,print:o})=>{o&&dt(t);let s=r.map(a=>a.plan);return{structuredContent:{mode:e,source:{root:n.root,name:n.name,headSha:n.headSha},targets:wb(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:lb(t),report:t.sections}}},jj=async e=>{let t=await Yi(),r=Dj(t),n=await db(r),o=await Ij(r),s=mb(t,e.targets??[]),i=await rm(r,o),a=await fb(i,s,!!e.manifestOnly);return{source:i,sourceRows:n,plans:a}},am=async(e={})=>{let{source:t,sourceRows:r,plans:n}=await jj(e),o=n.map(m=>({plan:m,applied:!1})),s={commit:e.commit,manifestOnly:e.manifestOnly},i=e.check?"check":"preview",a=nm(r,o,{...s,mode:i}),c=!n.some(m=>m.status==="changed");if(e.check||c)return im({mode:i,report:a,outcomes:o,source:t,print:!0});let l=!e.confirmedCommand&&!Z();if(l&&!yb.stdin.isTTY)return dt(a),im({mode:"preview",report:a,outcomes:o,source:t,print:!1});l&&dt({...a,hints:[]}),await G(e.confirmedCommand,`Sync vendored files from ${t.name} into these targets?`,{plan:wb(n),throwOnDecline:!0});let u=await Mj(t,n,e),p=nm(r,u,{...s,mode:"applied"});if(l){let m=u.filter(f=>f.applied).map(f=>f.plan.name);dt(ub(a,p,m))}return im({mode:"applied",report:p,outcomes:u,source:t,print:!l})};var dc=(e,t=!0)=>({line:e,reproducible:t});import pc from"node:fs";import Fj from"node:os";import Lj from"node:path";import Sb from"node:process";var mc="INFRA_KIT_SESSION_REPORT",cm=null,kb=!1,bb=[],Eb=(e=Sb.env)=>{kb||(cm=e[mc]??null,kb=!0,delete e[mc])};var Pb=(e,t)=>{if(!cm)return;let r=e.summary??(bb.length>0?[...bb]:void 0),n={...e,...r?{summary:r}:{}},o=t?.write??((s,i)=>{pc.writeFileSync(s,i)});try{o(cm,JSON.stringify(n))}catch{}},Rb=0,xb=e=>{let t=e?.tmpdir?.()??Fj.tmpdir(),r=e?.pid??Sb.pid;return Rb+=1,Lj.join(t,`infra-kit-session-${r}-${Rb}.json`)},Tb=(e,t)=>{if(!(t?.exists??(i=>pc.existsSync(i)))(e))return null;let n=t?.read??(i=>pc.readFileSync(i,"utf-8")),o=t?.unlink??(i=>pc.unlinkSync(i)),s;try{s=n(e)}catch{return null}finally{try{o(e)}catch{}}try{return JSON.parse(s)}catch{return null}};var lm=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)lm(r)};var um=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)um(r)};var Vj=(e,t)=>[...t,e],Gj=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 $h(()=>fa({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&&(je.exitCode=1)}),$b=e=>(je.stdout.write(`${e.structuredContent.filePath}
470
- `),D(e)),Jj=e=>e.description("List all release branches").action(async()=>{D(await Sa())}),Kj=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".',Vj,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let n=t.release.map(Mu),o=n.length>0?n:void 0;D(await Ca({releases:o,confirmedCommand:t.yes}))}),Hj=e=>{if(e==="")return e;try{return br(e)}catch(t){throw t instanceof On?new Ab(t.message):t}},qj=e=>{let t=Number(e);if(!Number.isInteger(t)||t<=0)throw new Ab("Expected a positive whole number of days.");return t},Yj=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)',Hj).option("-y, --yes","Skip confirmation prompt").action(async t=>{D(await $a({version:t.version,description:t.description,releaseDate:t.releaseDate,confirmedCommand:t.yes}))}),Ob=e=>e.option("-f, --from <where>",`Where the deploy runs: ${Zt.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"),zj=e=>Ob(e).description("Deploy every service to any environment, in CI or from this machine").action(async t=>{D(await Vp({from:t.from,version:t.version,env:t.env,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),Xj=e=>Ob(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 Gp({from:t.from,version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),Zj=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 ha({version:t.version,confirmedCommand:t.yes}))}),Qj=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 Da({version:t.version,moveIssuesTo:t.moveIssuesTo,skipJira:t.skipJira,confirmedCommand:t.yes}))}),eF=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{D(await qa({confirmedCommand:t.yes}))}),tF=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 Ga({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature,base:t.base,githubDesktop:t.githubDesktop,orca:t.orca}))}),rF=e=>e.description("List all git worktrees with detailed information").action(async()=>{D(await Ja())}),nF=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 Ha({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature,self:t.self}))}),oF=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 Kp({init:t.init}))}),sF=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await Ua();D(t),t.structuredContent.ok||(je.exitCode=1)}),iF=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 am({targets:t,confirmedCommand:r.yes,check:r.check,commit:r.commit,manifestOnly:r.manifestOnly})}catch(a){if(!bt(a))throw a;d.info("Operation cancelled.");return}D(n);let{failed:o,changed:s,mode:i}=n.structuredContent;(o||i==="check"&&s)&&(je.exitCode=1)}),aF=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{D(await Cp())}),cF=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{D(await $p())}),lF=new Set(["version"]),fc=e=>{let t=[];for(let r=e;r&&r.parent;r=r.parent)t.unshift(r.name());return t.join(" ")},dm=()=>{let e=new Bj().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");Gj(t.command("merge-dev")),Jj(t.command("list")),Kj(t.command("create")),Yj(t.command("edit")),zj(t.command("deploy-all")),Xj(t.command("deploy-selected")),Zj(t.command("deliver")),Qj(t.command("remove"));let r=e.command("worktrees").description("Git worktree management commands");tF(r.command("add")),rF(r.command("list")),nF(r.command("remove")),eF(r.command("sync"));let n=e.command("config").description("Manage infra-kit configuration files");aF(n.command("path")),cF(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 Ai({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 Il({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 Ap({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 tc({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 tc({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)"),je.exitCode=1;return}let c=await Si({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)&&(je.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 _p({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||(je.exitCode=1)});let i=e.command("vendor").description("Mirror and verify the vendored starter files");sF(i.command("check")),oF(i.command("config")),iF(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 sa({fix:!!a.fix});ir.enabled||Vl(c.structuredContent.checks,{ascii:!!a.ascii}),c.structuredContent.checks.some(u=>u.name==="plugin installed"&&u.status==="fail")&&(je.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=!!(je.stdout.isTTY&&je.stdin.isTTY);await l({...c,appName:a},u,ir.enabled)}),e.command("dev-status").description("Show what `infra-kit dev` currently has running (reads dev-context fragments; starts nothing)").action(async()=>{D(await Oi())}),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 la({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 Cb("--unattended","Background run: no tool installs, no writes to git-tracked files").hideHelp()).addOption(new Cb("--auto","Unattended setup for the machine and every infra-kit project, once per version").hideHelp()).action(async a=>{if(a.auto){D(await Zd());return}D(await Ma({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 Wa())}),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 ${bo})`,qj).action(async a=>{D(await Ti({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 pa())}),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 Vf())}),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=>{$b(await Nc({config:a.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{$b(await da())}),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 Up({fromFile:c.fromFile,force:c.force}));return}D(await Bp({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 ma({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 Fp({env:a}))});for(let a of e.commands)Hm(a);return lm(e),um(e),e.hook("preAction",async(a,c)=>{let{C:l}=e.opts();l!==void 0&&Wj(Uj(je.cwd(),l)),y.start(fc(c)),ir.enabled=!!c.optsWithGlobals().json,ir.enabled&&(d.level="warn"),j.source=Ys({env:je.env,stdinIsTTY:je.stdin.isTTY===!0,flag:!!c.optsWithGlobals().agent}),lF.has(fc(c))||await hu()}),e.hook("postAction",(a,c)=>{let l=fc(c);if(Pp(l))return;let p=y.snapshot()?.formattedOptions??"",m=p?` ${p}`:"",f=`infra-kit ${l}${m}`;Pb({equivalent:dc(f,!0)})}),e};import uF from"node:process";var dF={exit:uF.exit,emit:D,logger:d},Db=(e,t=dF)=>Ae(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 pm=(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 pF from"node:fs";import mm from"node:path";import Jn from"node:process";var _b=new Set([...uf,Hn,"XDG_CACHE_HOME","CLAUDE_PROJECT_DIR","CLAUDE_PLUGIN_ROOT"]),Mb=null,gc=new Set,fm=null,Ib=!1;var Nb=e=>{try{return pF.statSync(e)}catch{return null}},mF=()=>{if(Ib)return null;try{return Fr()}catch{return Ib=!0,d.debug(`session-env: ${Hn} unset \u2014 no overlay`),null}},fF=e=>{let t=mm.join(e,Mr),r=mm.join(e,Ls),n=Nb(t),o=Nb(r);return n&&!(o&&o.mtimeMs>n.mtimeMs)?Em(mm.join(e,Bs),Jn.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"}},gF=e=>e.kind==="load"?{kind:"load",vars:Rm(e.file),signature:e.signature}:e.kind==="clear"?{kind:"clear",unset:Sm(e.file),signature:e.signature}:e;var hF=()=>{let e=mF();if(e===null)return{kind:"no-session"};let t=fF(e);return t.signature===fm?null:gF(t)},yF=()=>{for(let e of gc){let t=Mb[e];t===void 0?delete Jn.env[e]:Jn.env[e]=t}gc.clear()},vF=(e,t,r)=>{if(_b.has(t)){e.skipped.push(t);return}Jn.env[t]=r,gc.add(t),e.set.push(t)},wF=(e,t)=>{if(_b.has(t)){e.skipped.push(t);return}delete Jn.env[t],gc.add(t),e.unset.push(t)},kF=e=>{let t={set:[],unset:[],skipped:[]};if(e.kind==="load")for(let[r,n]of Object.entries(e.vars))vF(t,r,n);if(e.kind==="clear")for(let r of e.unset)wF(t,r);return t},bF=e=>e.kind==="load"?`load, ${Object.keys(e.vars).length} vars`:e.kind,gm=(e=hF())=>{if(Mb??={...Jn.env},e===null||e.kind==="no-session"||e.signature===fm)return{set:[],unset:[],changed:!1};yF();let{set:t,unset:r,skipped:n}=kF(e);return fm=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(", ")}] (${bF(e)})`),{set:t,unset:r,changed:!0}};import{chalkStderr as WF}from"chalk";import{spawn as VF}from"node:child_process";import Fe from"node:process";import{Chalk as RF}from"chalk";var Kn=new RF({level:1}),nt={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."},SF={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"}},jb={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},Fb={unicode:"\u2500",ascii:"-"},EF=3,hm=e=>e,PF={ok:e=>Kn.green(e),findings:e=>Kn.yellow(e),failed:e=>Kn.red(e),cancelled:e=>Kn.gray(e)},vm=e=>e?{dim:t=>Kn.dim(t),bold:t=>Kn.bold(t)}:{dim:hm,bold:hm},xF=(e,t)=>e?PF[t]:hm,ym=e=>[...e].length,TF=(e,t)=>{if(t==null)return e;let r=Math.max(0,t-1);return ym(e)<=r?e:[...e].slice(0,r).join("")},Lb=e=>{let t=vm(e.color===!0).dim,r=SF[e.canSuspend?"suspend":"plain"],n=e.ascii===!0?r.ascii:r.unicode;return t(TF(n,e.width))},Bb=(e,t={})=>{let r=vm(t.color===!0);return`${r.dim(nt.reproPrefix.trim())} ${r.bold(e)}`},CF=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,$F=(e,t)=>e==="findings"?t!=null?`${t} ${nt.findingsSuffix}`:nt.findingsPlain:{ok:nt.ok,failed:nt.failed,cancelled:nt.cancelled}[e],AF=(e,t,r,n)=>{if(t==null)return"";let o=t-2-e;return o<EF?"":` ${n(r.repeat(o))}`},Ub=e=>{let t=e.color===!0,r=vm(t),n=xF(t,e.outcome),o=e.ascii===!0,s=e.equivalent.reproducible?nt.reproPrefix:nt.nonReproPrefix,i=o?jb[e.outcome].ascii:jb[e.outcome].unicode,a=$F(e.outcome,e.findingsCount),c=[CF(e.durationMs)],l=e.summary?.[0]?.split(`
471
- `)[0];l!=null&&l.length>0&&c.push(l);let u=`${i} ${a}`,p=`${nt.sep}${c.join(nt.sep)}`,m=ym(u)+ym(p),f=AF(m,e.width,o?Fb.ascii:Fb.unicode,r.dim),v=[`${n(u)}${r.dim(p)}${f}`];return e.showEquivalent!==!1&&v.unshift(`${r.dim(s.trim())} ${r.bold(e.equivalent.line)}`),e.envNotice===!0&&v.push(r.dim(nt.envNotice)),v.join(`
472
- `)};var OF=new Set([130,143]),Wb=(e,t,r,n=!1)=>r?t!=null||e===0?"ok":"findings":n&&e!=null&&OF.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import DF from"node:process";var IF={3:"quit",4:"quit",26:"suspend",27:"quit"},NF=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":IF[t]??"continue"},_F=150,MF="\r\x1B[2K",jF=`\r
473
- `,Vb=(e,t)=>{Gb(e),e.stdin.on("data",t),e.listener=t},Gb=e=>{e.listener!==null&&(e.stdin.off("data",e.listener),e.listener=null)},Jb=(e,t)=>{kf(),e.stdin.setRawMode(!0),e.stdin.isPaused()&&e.stdin.resume(),Vb(e,t)},Kb=e=>{e.hintOnScreen&&(e.hintOnScreen=!1,e.deps.write(MF)),Gb(e),e.stdin.isTTY===!0&&e.stdin.isRaw===!0&&e.stdin.setRawMode(!1),bf()},FF=e=>{e.settled||(e.settled=!0,Kb(e))},Hb=(e,t)=>{let r=Lb({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},LF=async e=>{await new Promise(t=>{setTimeout(t,e)})},BF=(e,t,r)=>{Kb(e),t(),Jb(e,r),Hb(e,jF)},UF=async e=>new Promise(t=>{let r=n=>{let o=NF(n),s=e.deps.suspend;if(o==="quit"){t("quit");return}if(o==="suspend"&&s!==void 0){BF(e,s,r);return}t("palette")};Vb(e,r),Hb(e,"")}),qb=async(e,t)=>{if(e.quitRequested())return"quit";let r=t.stdin??DF.stdin;if(r.isTTY!==!0)return"palette";let n={deps:t,stdin:r,listener:null,hintOnScreen:!1,settled:!1};try{return Jb(n,()=>{}),e.armed(),await LF(t.drainMs??_F),await UF(n)}finally{FF(n)}};import Yb from"node:process";var sr={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},zb=(e,t)=>{let r=t?.write??(s=>{Yb.stderr.write(s)}),n=t?.stdin??Yb.stdin,o=[sr.saveCursor,sr.scrollRegion,sr.restoreCursor,sr.column,sr.sgr,sr.cursor,sr.wrap];e.entersAltScreen===!0&&o.push(sr.primaryBuffer),r(o.join("")),n.isTTY===!0&&n.isRaw===!0&&n.setRawMode?.(!1)};var Xb=e=>`infra-kit ${e.groupPath.join(" ")}`,GF=()=>{JF();let e=Fe.stderr.columns;return e!=null&&e>0?e:void 0},JF=()=>{let e=Fe.stderr;typeof e._refreshSize=="function"&&e._refreshSize()},KF=e=>new Promise(t=>{e.on("exit",(r,n)=>{t({code:r,signal:n})}),e.on("error",()=>{t({code:1,signal:null})})}),HF=async(e,t,r)=>{let n=xb(),o={...t.env,[mc]:n,INFRA_KIT_NO_AUTO_UPDATE:"1"},s=t.now(),i={code:1,signal:null};r();try{let p=t.spawn(Fe.execPath,[t.cliPath,...e.groupPath],{stdio:"inherit",env:o});i=await KF(p)}catch{i={code:1,signal:null}}finally{t.resetTerminal({entersAltScreen:e.entersAltScreen})}let a=Tb(n),c=Wb(i.code,i.signal,a!=null,e.longRunning),l=Xb(e),u=a?.equivalent??dc(l,!0);return Ub({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)})},qF=1e3,YF=(e,t)=>e!=null&&t-e<=qF,wm=e=>{e.resetTerminal(),e.exit(0)},zF=(e,t)=>{let r=null,n=!1,o=()=>{let c=e();if(c==="child"){r=t.now();return}c!=="pause"&&wm(t)},s=()=>{let c=e();if(c==="palette"){wm(t);return}if(!YF(r,t.now())){if(c==="pause"){wm(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}},Zb=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),XF=Fe.platform==="win32"?void 0:()=>{Rf()},ZF=(e,t)=>r=>qb(r,{write:e,columns:t.columns,ascii:t.ascii,color:t.color,suspend:XF}),Qb=async(e,t)=>{let r={spawn:t.spawn??VF,now:t.now??(()=>Date.now()),env:t.env??Fe.env,cliPath:t.cliPath,ascii:t.ascii??!(Fe.stdout.isTTY&&Fe.env.TERM!=="dumb"),color:t.color??WF.level>0,columns:t.columns??GF,resetTerminal:t.resetTerminal??(u=>{zb(u)})},n=t.write??(u=>Fe.stderr.write(u)),o="palette",s=t.signals??{register:(u,p)=>{Fe.on(u,p)},unregister:(u,p)=>{Fe.off(u,p)},exit:u=>{Fe.exit(u)},raise:u=>{Fe.kill(Fe.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:zF(()=>o,s),c={armed:()=>{o="pause"},quitRequested:()=>a.quitRequested()},l=t.afterRun??ZF(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=Bb(Xb(p),{color:r.color});n(`
469
+ `)},Kj=async(e,t,r)=>r?(Pb(t,Gn(t)),Qp(t.root,e)):(await Zp({source:e,plan:t,onBeforeFirstWrite:o=>{Pb(t,o)}})).touched,Hj=async(e,t,r)=>{if(t.status!=="changed")return{plan:t,applied:!1};let n;try{n=await Kj(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 tm(t.root,n,em(e.name,e.headSha));return{plan:t,applied:!0,commit:o}},qj=async(e,t,r)=>{let n=[];for(let o of t)n.push(await Hj(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})),lm=({mode:e,report:t,outcomes:r,source:n,print:o})=>{o&&dt(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:wb(t),report:t.sections}}},Yj=async e=>{let t=await Qi(),r=Gj(t),n=await bb(r),o=await Jj(r),s=Sb(t,e.targets??[]),i=await sm(r,o),a=await Eb(i,s,!!e.manifestOnly);return{source:i,sourceRows:n,plans:a}},um=async(e={})=>{let{source:t,sourceRows:r,plans:n}=await Yj(e),o=n.map(m=>({plan:m,applied:!1})),s={commit:e.commit,manifestOnly:e.manifestOnly},i=e.check?"check":"preview",a=im(r,o,{...s,mode:i}),c=!n.some(m=>m.status==="changed");if(e.check||c)return lm({mode:i,report:a,outcomes:o,source:t,print:!0});let l=!e.confirmedCommand&&!Z();if(l&&!Tb.stdin.isTTY)return dt(a),lm({mode:"preview",report:a,outcomes:o,source:t,print:!1});l&&dt({...a,hints:[]}),await J(e.confirmedCommand,`Sync vendored files from ${t.name} into these targets?`,{plan:$b(n),throwOnDecline:!0});let u=await qj(t,n,e),p=im(r,u,{...s,mode:"applied"});if(l){let m=u.filter(f=>f.applied).map(f=>f.plan.name);dt(kb(a,p,m))}return lm({mode:"applied",report:p,outcomes:u,source:t,print:!l})};var fc=(e,t=!0)=>({line:e,reproducible:t});import gc from"node:fs";import zj from"node:os";import Xj from"node:path";import Ib from"node:process";var hc="INFRA_KIT_SESSION_REPORT",dm=null,Ab=!1,Ob=[],Nb=(e=Ib.env)=>{Ab||(dm=e[hc]??null,Ab=!0,delete e[hc])};var _b=(e,t)=>{if(!dm)return;let r=e.summary??(Ob.length>0?[...Ob]:void 0),n={...e,...r?{summary:r}:{}},o=t?.write??((s,i)=>{gc.writeFileSync(s,i)});try{o(dm,JSON.stringify(n))}catch{}},Db=0,Mb=e=>{let t=e?.tmpdir?.()??zj.tmpdir(),r=e?.pid??Ib.pid;return Db+=1,Xj.join(t,`infra-kit-session-${r}-${Db}.json`)},jb=(e,t)=>{if(!(t?.exists??(i=>gc.existsSync(i)))(e))return null;let n=t?.read??(i=>gc.readFileSync(i,"utf-8")),o=t?.unlink??(i=>gc.unlinkSync(i)),s;try{s=n(e)}catch{return null}finally{try{o(e)}catch{}}try{return JSON.parse(s)}catch{return null}};var pm=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)pm(r)};var mm=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)mm(r)};var tF=(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 Dh(()=>va({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&&(je.exitCode=1)}),Lb=e=>(je.stdout.write(`${e.structuredContent.filePath}
470
+ `),I(e)),nF=e=>e.description("List all release branches").action(async()=>{I(await Ta())}),oF=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".',tF,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let n=t.release.map(Lu),o=n.length>0?n:void 0;I(await Oa({releases:o,confirmedCommand:t.yes}))}),sF=e=>{if(e==="")return e;try{return Sr(e)}catch(t){throw t instanceof Dn?new Bb(t.message):t}},iF=e=>{let t=Number(e);if(!Number.isInteger(t)||t<=0)throw new Bb("Expected a positive whole number of days.");return t},aF=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)',sF).option("-y, --yes","Skip confirmation prompt").action(async t=>{I(await Da({version:t.version,description:t.description,releaseDate:t.releaseDate,confirmedCommand:t.yes}))}),Ub=e=>e.option("-f, --from <where>",`Where the deploy runs: ${er.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"),cF=e=>Ub(e).description("Deploy every service to any environment, in CI or from this machine").action(async t=>{I(await Kp({from:t.from,version:t.version,env:t.env,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),lF=e=>Ub(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 Hp({from:t.from,version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),uF=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 ka({version:t.version,confirmedCommand:t.yes}))}),dF=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 _a({version:t.version,moveIssuesTo:t.moveIssuesTo,skipJira:t.skipJira,confirmedCommand:t.yes}))}),pF=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{I(await Xa({confirmedCommand:t.yes}))}),mF=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 Ha({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature,base:t.base,githubDesktop:t.githubDesktop,orca:t.orca}))}),fF=e=>e.description("List all git worktrees with detailed information").action(async()=>{I(await qa())}),gF=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 za({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature,self:t.self}))}),hF=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 Yp({init:t.init}))}),yF=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await Ga();I(t),t.structuredContent.ok||(je.exitCode=1)}),vF=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 um({targets:t,confirmedCommand:r.yes,check:r.check,commit:r.commit,manifestOnly:r.manifestOnly})}catch(a){if(!St(a))throw a;d.info("Operation cancelled.");return}I(n);let{failed:o,changed:s,mode:i}=n.structuredContent;(o||i==="check"&&s)&&(je.exitCode=1)}),wF=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{I(await Op())}),kF=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{I(await Dp())}),bF=new Set(["version"]),yc=e=>{let t=[];for(let r=e;r&&r.parent;r=r.parent)t.unshift(r.name());return t.join(" ")},fm=()=>{let e=new Zj().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")),nF(t.command("list")),oF(t.command("create")),aF(t.command("edit")),cF(t.command("deploy-all")),lF(t.command("deploy-selected")),uF(t.command("deliver")),dF(t.command("remove"));let r=e.command("worktrees").description("Git worktree management commands");mF(r.command("add")),fF(r.command("list")),gF(r.command("remove")),pF(r.command("sync"));let n=e.command("config").description("Manage infra-kit configuration files");wF(n.command("path")),kF(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 Ni({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 Ml({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 Ip({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 oc({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 oc({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)"),je.exitCode=1;return}let c=await Ti({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)&&(je.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 Fp({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 Bp({check:a.check});I(c),c.structuredContent.ok||(je.exitCode=1)});let i=e.command("vendor").description("Mirror and verify the vendored starter files");yF(i.command("check")),hF(i.command("config")),vF(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 la({fix:!!a.fix});cr.enabled||Kl(c.structuredContent.checks,{ascii:!!a.ascii}),c.structuredContent.checks.some(u=>u.name==="plugin installed"&&u.status==="fail")&&(je.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=!!(je.stdout.isTTY&&je.stdin.isTTY);await l({...c,appName:a},u,cr.enabled)}),e.command("dev-status").description("Show what `infra-kit dev` currently has running (reads dev-context fragments; starts nothing)").action(async()=>{I(await _i())}),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 ma({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 Fb("--unattended","Background run: no tool installs, no writes to git-tracked files").hideHelp()).addOption(new Fb("--auto","Unattended setup for the machine and every infra-kit project, once per version").hideHelp()).action(async a=>{if(a.auto){I(await tp());return}I(await La({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 Ja())}),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 ${Ro})`,iF).action(async a=>{I(await Oi({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 ha())}),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 Kf())}),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=>{Lb(await jc({config:a.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{Lb(await ga())}),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 Gp({fromFile:c.fromFile,force:c.force}));return}I(await Vp({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 ya({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 Up({env:a}))});for(let a of e.commands)zm(a);return pm(e),mm(e),e.hook("preAction",async(a,c)=>{let{C:l}=e.opts();l!==void 0&&eF(Qj(je.cwd(),l)),h.start(yc(c)),cr.enabled=!!c.optsWithGlobals().json,cr.enabled&&(d.level="warn"),j.source=Qs({env:je.env,stdinIsTTY:je.stdin.isTTY===!0,flag:!!c.optsWithGlobals().agent}),bF.has(yc(c))||await wu()}),e.hook("postAction",(a,c)=>{let l=yc(c);if(Cp(l))return;let p=h.snapshot()?.formattedOptions??"",m=p?` ${p}`:"",f=`infra-kit ${l}${m}`;_b({equivalent:fc(f,!0)})}),e};import RF from"node:process";var SF={exit:RF.exit,emit:I,logger:d},Wb=(e,t=SF)=>Ae(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 gm=(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 EF from"node:fs";import hm from"node:path";import Kn from"node:process";var Jb=new Set([...mf,qn,"XDG_CACHE_HOME","CLAUDE_PROJECT_DIR","CLAUDE_PLUGIN_ROOT"]),Kb=null,vc=new Set,ym=null,Vb=!1;var Gb=e=>{try{return EF.statSync(e)}catch{return null}},PF=()=>{if(Vb)return null;try{return Lr()}catch{return Vb=!0,d.debug(`session-env: ${qn} unset \u2014 no overlay`),null}},xF=e=>{let t=hm.join(e,jr),r=hm.join(e,Vs),n=Gb(t),o=Gb(r);return n&&!(o&&o.mtimeMs>n.mtimeMs)?Tm(hm.join(e,Gs),Kn.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"}},TF=e=>e.kind==="load"?{kind:"load",vars:Pm(e.file),signature:e.signature}:e.kind==="clear"?{kind:"clear",unset:xm(e.file),signature:e.signature}:e;var CF=()=>{let e=PF();if(e===null)return{kind:"no-session"};let t=xF(e);return t.signature===ym?null:TF(t)},$F=()=>{for(let e of vc){let t=Kb[e];t===void 0?delete Kn.env[e]:Kn.env[e]=t}vc.clear()},AF=(e,t,r)=>{if(Jb.has(t)){e.skipped.push(t);return}Kn.env[t]=r,vc.add(t),e.set.push(t)},OF=(e,t)=>{if(Jb.has(t)){e.skipped.push(t);return}delete Kn.env[t],vc.add(t),e.unset.push(t)},DF=e=>{let t={set:[],unset:[],skipped:[]};if(e.kind==="load")for(let[r,n]of Object.entries(e.vars))AF(t,r,n);if(e.kind==="clear")for(let r of e.unset)OF(t,r);return t},IF=e=>e.kind==="load"?`load, ${Object.keys(e.vars).length} vars`:e.kind,vm=(e=CF())=>{if(Kb??={...Kn.env},e===null||e.kind==="no-session"||e.signature===ym)return{set:[],unset:[],changed:!1};$F();let{set:t,unset:r,skipped:n}=DF(e);return ym=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(", ")}] (${IF(e)})`),{set:t,unset:r,changed:!0}};import{chalkStderr as eL}from"chalk";import{spawn as tL}from"node:child_process";import Fe from"node:process";import{Chalk as NF}from"chalk";var Hn=new NF({level:1}),nt={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."},_F={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"}},Hb={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},qb={unicode:"\u2500",ascii:"-"},MF=3,wm=e=>e,jF={ok:e=>Hn.green(e),findings:e=>Hn.yellow(e),failed:e=>Hn.red(e),cancelled:e=>Hn.gray(e)},bm=e=>e?{dim:t=>Hn.dim(t),bold:t=>Hn.bold(t)}:{dim:wm,bold:wm},FF=(e,t)=>e?jF[t]:wm,km=e=>[...e].length,LF=(e,t)=>{if(t==null)return e;let r=Math.max(0,t-1);return km(e)<=r?e:[...e].slice(0,r).join("")},Yb=e=>{let t=bm(e.color===!0).dim,r=_F[e.canSuspend?"suspend":"plain"],n=e.ascii===!0?r.ascii:r.unicode;return t(LF(n,e.width))},zb=(e,t={})=>{let r=bm(t.color===!0);return`${r.dim(nt.reproPrefix.trim())} ${r.bold(e)}`},BF=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,UF=(e,t)=>e==="findings"?t!=null?`${t} ${nt.findingsSuffix}`:nt.findingsPlain:{ok:nt.ok,failed:nt.failed,cancelled:nt.cancelled}[e],WF=(e,t,r,n)=>{if(t==null)return"";let o=t-2-e;return o<MF?"":` ${n(r.repeat(o))}`},Xb=e=>{let t=e.color===!0,r=bm(t),n=FF(t,e.outcome),o=e.ascii===!0,s=e.equivalent.reproducible?nt.reproPrefix:nt.nonReproPrefix,i=o?Hb[e.outcome].ascii:Hb[e.outcome].unicode,a=UF(e.outcome,e.findingsCount),c=[BF(e.durationMs)],l=e.summary?.[0]?.split(`
471
+ `)[0];l!=null&&l.length>0&&c.push(l);let u=`${i} ${a}`,p=`${nt.sep}${c.join(nt.sep)}`,m=km(u)+km(p),f=WF(m,e.width,o?qb.ascii:qb.unicode,r.dim),y=[`${n(u)}${r.dim(p)}${f}`];return e.showEquivalent!==!1&&y.unshift(`${r.dim(s.trim())} ${r.bold(e.equivalent.line)}`),e.envNotice===!0&&y.push(r.dim(nt.envNotice)),y.join(`
472
+ `)};var VF=new Set([130,143]),Zb=(e,t,r,n=!1)=>r?t!=null||e===0?"ok":"findings":n&&e!=null&&VF.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import GF from"node:process";var JF={3:"quit",4:"quit",26:"suspend",27:"quit"},KF=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":JF[t]??"continue"},HF=150,qF="\r\x1B[2K",YF=`\r
473
+ `,Qb=(e,t)=>{eR(e),e.stdin.on("data",t),e.listener=t},eR=e=>{e.listener!==null&&(e.stdin.off("data",e.listener),e.listener=null)},tR=(e,t)=>{Sf(),e.stdin.setRawMode(!0),e.stdin.isPaused()&&e.stdin.resume(),Qb(e,t)},rR=e=>{e.hintOnScreen&&(e.hintOnScreen=!1,e.deps.write(qF)),eR(e),e.stdin.isTTY===!0&&e.stdin.isRaw===!0&&e.stdin.setRawMode(!1),Ef()},zF=e=>{e.settled||(e.settled=!0,rR(e))},nR=(e,t)=>{let r=Yb({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},XF=async e=>{await new Promise(t=>{setTimeout(t,e)})},ZF=(e,t,r)=>{rR(e),t(),tR(e,r),nR(e,YF)},QF=async e=>new Promise(t=>{let r=n=>{let o=KF(n),s=e.deps.suspend;if(o==="quit"){t("quit");return}if(o==="suspend"&&s!==void 0){ZF(e,s,r);return}t("palette")};Qb(e,r),nR(e,"")}),oR=async(e,t)=>{if(e.quitRequested())return"quit";let r=t.stdin??GF.stdin;if(r.isTTY!==!0)return"palette";let n={deps:t,stdin:r,listener:null,hintOnScreen:!1,settled:!1};try{return tR(n,()=>{}),e.armed(),await XF(t.drainMs??HF),await QF(n)}finally{zF(n)}};import sR from"node:process";var ar={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},iR=(e,t)=>{let r=t?.write??(s=>{sR.stderr.write(s)}),n=t?.stdin??sR.stdin,o=[ar.saveCursor,ar.scrollRegion,ar.restoreCursor,ar.column,ar.sgr,ar.cursor,ar.wrap];e.entersAltScreen===!0&&o.push(ar.primaryBuffer),r(o.join("")),n.isTTY===!0&&n.isRaw===!0&&n.setRawMode?.(!1)};var aR=e=>`infra-kit ${e.groupPath.join(" ")}`,rL=()=>{nL();let e=Fe.stderr.columns;return e!=null&&e>0?e:void 0},nL=()=>{let e=Fe.stderr;typeof e._refreshSize=="function"&&e._refreshSize()},oL=e=>new Promise(t=>{e.on("exit",(r,n)=>{t({code:r,signal:n})}),e.on("error",()=>{t({code:1,signal:null})})}),sL=async(e,t,r)=>{let n=Mb(),o={...t.env,[hc]:n,INFRA_KIT_NO_AUTO_UPDATE:"1"},s=t.now(),i={code:1,signal:null};r();try{let p=t.spawn(Fe.execPath,[t.cliPath,...e.groupPath],{stdio:"inherit",env:o});i=await oL(p)}catch{i={code:1,signal:null}}finally{t.resetTerminal({entersAltScreen:e.entersAltScreen})}let a=jb(n),c=Zb(i.code,i.signal,a!=null,e.longRunning),l=aR(e),u=a?.equivalent??fc(l,!0);return Xb({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)})},iL=1e3,aL=(e,t)=>e!=null&&t-e<=iL,Rm=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"&&Rm(t)},s=()=>{let c=e();if(c==="palette"){Rm(t);return}if(!aL(r,t.now())){if(c==="pause"){Rm(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}},cR=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),lL=Fe.platform==="win32"?void 0:()=>{Pf()},uL=(e,t)=>r=>oR(r,{write:e,columns:t.columns,ascii:t.ascii,color:t.color,suspend:lL}),lR=async(e,t)=>{let r={spawn:t.spawn??tL,now:t.now??(()=>Date.now()),env:t.env??Fe.env,cliPath:t.cliPath,ascii:t.ascii??!(Fe.stdout.isTTY&&Fe.env.TERM!=="dumb"),color:t.color??eL.level>0,columns:t.columns??rL,resetTerminal:t.resetTerminal??(u=>{iR(u)})},n=t.write??(u=>Fe.stderr.write(u)),o="palette",s=t.signals??{register:(u,p)=>{Fe.on(u,p)},unregister:(u,p)=>{Fe.off(u,p)},exit:u=>{Fe.exit(u)},raise:u=>{Fe.kill(Fe.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??uL(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=zb(aR(p),{color:r.color});n(`
474
474
  ${m}
475
- `),a.childStarted();let f=await HF(p,r,()=>{o="child"});if(n(`
475
+ `),a.childStarted();let f=await sL(p,r,()=>{o="child"});if(n(`
476
476
  ${f}
477
- `),await l(c)==="quit")return}}finally{a.dispose()}};Tp();Eb();var nR=dm(),tR=async(e=Le.argv)=>{gm(),vf(e);try{await nR.parseAsync(e)}catch(t){Db(t)}},nL=()=>{try{if(Le.env.INFRA_KIT_NO_LOCATION_WARN||Le.argv.includes("--json"))return;Cm({selfRealPath:tL(rR(import.meta.url)),cwd:Le.cwd(),env:Le.env,realpath:Ee,home:rL(),exists:eL})&&d.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};nL();Km((e,t)=>{d.debug(e,t)});vu(L.version);var oR=()=>xk(nR.commands),oL=async()=>{let e=oR(),t=null;try{if(Le.stdout.isTTY&&Le.stdin.isTTY){let{runCommandPalette:r}=await import("./boot-ST2534PA.js");t=await r(e)}else{let r=pm(e.map(o=>[o.name,o.description])),n=e.flatMap((o,s)=>[...e[s-1]?.group===o.group?[]:[new eR(" "),new eR(`\u2014 ${o.group} \u2014`)],{name:r[s]??o.name,value:o.name}]);t=await _(o=>QF({message:"Select a command to run",choices:n},o),{output:Le.stderr})}}catch(r){if(!Ae(r))throw r}return t},sL=async()=>{let{runCommandPalette:e}=await import("./boot-ST2534PA.js"),t=rR(import.meta.url),r=new Map(Sr.map(n=>[n.groupPath.join(" "),n]));await Qb(oR(),{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(Le.argv.length<=2){let e={stdoutIsTTY:!!Le.stdout.isTTY,stdinIsTTY:!!Le.stdin.isTTY,stderrIsTTY:!!Le.stderr.isTTY};if(Zb(Le.env,e))await sL();else{let t=await oL();t&&await tR(["node","infra-kit",...t.split(" ")])}}else await tR();
477
+ `),await l(c)==="quit")return}}finally{a.dispose()}};Ap();Nb();var mR=fm(),dR=async(e=Le.argv)=>{vm(),bf(e);try{await mR.parseAsync(e)}catch(t){Wb(t)}},gL=()=>{try{if(Le.env.INFRA_KIT_NO_LOCATION_WARN||Le.argv.includes("--json"))return;Om({selfRealPath:mL(pR(import.meta.url)),cwd:Le.cwd(),env:Le.env,realpath:Pe,home:fL(),exists:pL})&&d.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};gL();Ym((e,t)=>{d.debug(e,t)});bu(L.version);var fR=()=>Mk(mR.commands),hL=async()=>{let e=fR(),t=null;try{if(Le.stdout.isTTY&&Le.stdin.isTTY){let{runCommandPalette:r}=await import("./boot-ST2534PA.js");t=await r(e)}else{let r=gm(e.map(o=>[o.name,o.description])),n=e.flatMap((o,s)=>[...e[s-1]?.group===o.group?[]:[new uR(" "),new uR(`\u2014 ${o.group} \u2014`)],{name:r[s]??o.name,value:o.name}]);t=await M(o=>dL({message:"Select a command to run",choices:n},o),{output:Le.stderr})}}catch(r){if(!Ae(r))throw r}return t},yL=async()=>{let{runCommandPalette:e}=await import("./boot-ST2534PA.js"),t=pR(import.meta.url),r=new Map(Pr.map(n=>[n.groupPath.join(" "),n]));await lR(fR(),{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(Le.argv.length<=2){let e={stdoutIsTTY:!!Le.stdout.isTTY,stdinIsTTY:!!Le.stdin.isTTY,stderrIsTTY:!!Le.stderr.isTTY};if(cR(Le.env,e))await yL();else{let t=await hL();t&&await dR(["node","infra-kit",...t.split(" ")])}}else await dR();
478
478
  //# sourceMappingURL=cli.js.map